Monday, December 7, 2009

Preventing Cross Scripting Attacks with PHP

This post will discuss Cross Scripting attacks to your HTML forms; what are they and how to prevent them. HTML is simply plain text, like the bold tag, which is given special meaning by web browsers. As such, visitors to your web site could easily place HTML in their form data, like in the comments field in an email form.

What could be the problem? Well, many dynamic Web applications take information submitted by a user, store it in a database, and re-display that information on another page. For example, a message board or forum are two examples. If a user were to enter HTML code in their form data, this code could throw off the layout and and appearance of your site.

In addition, suppose a user placed Javascript into your web form. Javascript is also plain text, but text that has special meaning, which is executable code within a browser. If such code was entered into a form and re-displayed in the browser, it could create popup windows, steal cookies, or redirect the browser to another page. This is known as a Cross Scripting or XSS attack.

PHP includes several functions for handling HTML and other code found within strings, thus preventing XSS attacks.  These include:

  • htmlspecialchars(), which turns &, ', ", <, > into empty  HTML formats
  • htmlentities(), which turns all applicable characters into their HTML element format.
  • strip_tags(), which removes all HTML and PHP tags.
These  functions are listed from the least disruptive to the most.  A couple of examples of the syntax is shown below:

  //Check for the form submission and compare original data with what was submitted.
   if (isset($_POST['submitted'])) {
  {$_POST['data']}
  //To keep submitted information from messing up a page or hacking the web browser.     
  htmlentities($_POST['data'])
  //The strip_tags function completely removes any javascript, HTML, or PHP tags and is the most effective
   way to prevent XSS attacks.
   strip_tags($_POST['data'])
    }
Unrelated to security but quite useful is the nl2br() function. It turns every return(such as those entered into a text area) into an HTML br tag.

No comments:

Post a Comment

Get your own Widget