XSS (cross site scripting)

The article "Ensuring website safety" is provided by Sophos Plc and SophosLabs.

December 2007

This type of attacks aimed at the sites that display the data input by the user. Instead of trying to gain control over the database by entering malicious code, an attacker tries aims at the code of the site itself, inserting malicious segments into it.

Many sites store usernames in the database and display them when the users are logged in. An attacker can create a fake account and place malicious code in the name field. Such attacks usually use malicious Javascript scripts that download content from another site. It is assumed that the database stores the username, but in fact in this case it stores malicious code. This code is executed if the site displays the username at the top of the page. Under certain conditions, such code can do almost anything. The threat becomes quite real. Still, developers often forget about it. Recently, many popular sites have become victims of XSS attacks, including MySpace, Facebook, Google, Mail, VKontakte.


Consider the following PHP code:

$firstname = $_POST["firstname"]; echo "Your name: $firstname";

After the username is entered in the web form, the site displays a corresponding message on the page. If you enter “Chris”, the message will look like this: “Your name: Chris”.

What happens if I enter the following instead of the name: “<script>alert (‘You just got hacked!’) ;</script>”?

Unfortunately, XSS attacks are often difficult to prevent. You have to filter input and output data, as well as all fields that can be changed by users. This includes data received from GET and POST requests, as well as queries returned from the database.

A number of PHP packages help filter the output, for example, CodeIgniter [15]. Also, PHP has a built-in htmlspecialchars function which can be used to filter the output data.