5.4. Preventing Cross-Site Scripting

Cross-site scripting (or XSS for short) is a big buzzword in security circles, and it seems like every few days a new XSS exploit is found. In this section, we demystify the hype and explain exactly how XSS attacks work, and how to prevent them.

5.4.1. How an XSS attack works

The cross-site scripting model has a lot of variations, but essentially, it involves a malicious user entering a script into a form input area. When that data is used in the application, the script is run and bad things happen. For example, http://blog.example.com allows anonymous visitors to post comments. Joe BadGuy visits the site and puts the following code into the comments form:

<script language = "PHP">
   eval('rm -rf /');
</script>

The next time the site is loaded, the user that the Web server runs as goes and deletes everything that the operating system allows it to delete. Three little lines of code, and your application is gone. Hope you made backups!

Of course, if you had prevented the script from running the eval() function, this bad guy would be thwarted anyway. You can deactivate a function in the php.ini file, as follows:

disable_functions eval

Another variation on this theme involves entering code into a form that, when it appears in the browser, does something to another user's local system. The code might steal session information, set cookies, or even ...

Get PHP & MySQL® Web Development All-in-One Desk Reference for Dummies® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.