Home » , , , » Prevent Cross Site Scripting aka XSS attacks

Prevent Cross Site Scripting aka XSS attacks


Cross Site Scripting also called as xss attack it is one of the most common web vulnerabilities today, after making a tutorial on sql injection i thought that making a tutorial on preventing cross site scripting would be useful to readers.

First of all what is XSS (not CSS)

It is a web application bug on non filtered user input like search or comment box.
When an attacker has the possibility to inject some code into the page and on site reload that code does not show, it is called Non Persistent xss attack and when the code is saved on a database and loaded into the page that that is a high security risk.
He could insert an malicious script to steal user cookies or even further so how can we prevent xss at all.

Let's take an simple example of an vulnerable php script:
<?php
if(isset($_GET['search'])){
echo 'You searched for'.$_GET['search'];
}
else{
?><form action="" method="get">
<input type="text" name="search" value="search.."><br>
<input type="submit"></form>
}
?>

Basically this script is vulnerable
We can use this php functions:

  • htmlspecialchars
  • htmlentities
There are a few other we could use like is_int, is_numeric, (int)$data used when we are expecting the user to enter only numbers, also we can use preg_match, eregi which we can use for example to check if email is valid etc..

So here it is the implementation of htmlspecialchars
<?php
if(isset($_GET['search'])){
echo 'You searched for'.htmlspecialchars($_GET['search']);
}
else{
?><form action="" method="get">
<input type="text" name="search" value="search.."><br>
<input type="submit"></form>
}
?>

htmlspecialchars does not filter all characters like htmlentities does but that does not mean that it contain bugs.
Also i would like to mention that never using javascript for filtering user input, consider it only as a gui part handled by php, maybe most of you know this either.
I also recommend reading this other web security articles

0 תגובות:

Post a Comment

Follow by Email