A3 – Preventing cross-site scripting

Cross-site scripting, as seen previously, happens when the data shown to the user is not correctly encoded and the browser interprets it as a script code and executes it. This also has an input validation factor, as a malicious code is usually inserted through input variables.

In this recipe, we will cover the input validation and output encoding required for developers to prevent XSS vulnerabilities in their applications.

How to do it...

  1. The first sign of an application being vulnerable to XSS is that in the page it reflects the exact input given by the user. So, try not to use user-given information to build output text.
  2. When you need to put user-provided data in the output page, validate such data to prevent the insertion of any type of code. We already saw how to do that in the A1 – Preventing injection attacks recipe.
  3. If, for some reason, the user is allowed to input special characters or code fragments, sanitize or properly encode the text before inserting it in the output.
  4. For sanitization, in PHP, filter_var can be used; for example, if you want to have only e-mail valid characters in the string:
    <?php
    $email = "john(.doe)@exa//mple.com";
    $email = filter_var($email, FILTER_SANITIZE_EMAIL);
    echo $email;
    ?>

    For encoding, you can use htmlspecialchars in PHP:

    <?php
    $str = "The JavaScript HTML tags are <script> for opening, and </script>  for closing.";
    echo htmlspecialchars($str);
    ?>
  5. In .NET, for 4.5 and later implementations, the System.Web.Security.AntiXss namespace provides the necessary tools. For .NET Framework 4 and prior, we can use the Web Protection library: http://wpl.codeplex.com/.
  6. Also, to prevent stored XSS, encode or sanitize every piece of information before storing it and retrieving it from the database.
  7. Don't overlook headers, titles, CSS, and script sections of the page, as they are susceptible of being exploited too.

How it works...

Apart from a proper input validation and not using user inputs as output information, sanitization and encoding are key aspects in preventing XSS.

Sanitization means removing the characters that are not allowed from the string; this is useful when no special characters should exist in input strings.

Encoding converts special characters to their HTML code representations; for example, "&" to "&amp;" or "<" to "&lt;". Some applications allow the use of special characters in input strings; for them sanitization is not an option, so they should encode the inputs before inserting them into the page and storing them in the database.

See also

OWASP has an XSS prevention cheat sheet that is worth reading:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.36.194