Preventing Cross Site Scripting (XSS) In Your Code

Cross-Site Scripting (XSS) is a vulnerablity where an attacker can put their own code on your site. Often javascript is used so I’ll use it here in my examples.

Here’s a code example:


<html>
<head><title>XSS Example</title></head>
<body>
<?php
if (!empty($_GET['name'])) {
$name = $_GET['name'];
echo "Hello $name!\n";
}
?>
<br />
<form action="#" method="get">
My name is <input name="name" value="" size="20" />
<br />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Looks harmless, doesn’t it? If you type in “bob” then it’ll say “Hello bob!” to you. How cute!

OK, so what if my name is “<script>alert(‘boo!’);</script>”? Now I get a popup window in my browser. This isn’t malicious, but if people can execute abitrary code on your site then just trust me that it’s a Very Bad Thing and that these things add up.

If I can entice a user to click on a link, say “http://myhost/xssform.php?name=<script>alert(‘boo!’)%3B<%2Fscript>” then I could use javascript to steal their cookies and pretend to be them. And it looks like your fault (which it is, partially).

If the server is storing data and displaying it to other users then it gets worse. I’ll use code I used previously in my article on SQL injection. The article touched briefly on the need to encode any output which users have entered. The example is in PHP but every language should have a simple way to encode HTML characters.

Same as before you’ll have to set up a database.

Here are the source files. “dbform.php” is the un-fixed and insecure version. “dbform2.php” is fixed.

OK, this revolves around this line of code which outputs comments made by visitors to the website. Here’s the unfixed version first:


echo $row['comment_text'] . "<br />\n";

and here is the fixed version:


echo htmlspecialchars($row['comment_text']) . "<br />\n";

So what’s so special? Well the second version encodes the output. So HTML characters like “<” are encoded (in this case to “&lt;”). Otherwise a user can inject HTML into the page.

Try this on “dbform.php” and you’ll get a link which throws up a popup when clicked (needs javascript to work):


<a href=javascript:alert("xss");>hi</a>

If you’re thinking “big deal” then try typing this (also needs javascript to work) into the add comment box:


<script>window.location="http://www.google.com";</script>

Type that into the comments box and the comment appears in the page and immediately redirects the browser to another site. OK, so this is google but what if it was a malware site?

Now every single user that visits the page gets redirected.

Share this:
Share this page via Email Share this page via Stumble Upon Share this page via Digg this Share this page via Facebook Share this page via Twitter

Leave a Comment