How to save application from Cross site scripting attack

Cross site scripting also known as XSS attack generally found in web application

Cross site scripting allows user to insert client side script like javascript or vbscript in to the webpage form or to the page content itself.

Example of XSS attack

Example-1: Suppose there is a registration form in a webpage, After entering all valid data you will be redirected to a listing page.This is general user point of view how web application flows.

Then how attacker thinks.A attacker wants to enter all valid data with adding some client side script like javascript into an textbox of the registration page.So what will happen next.As of web application flow ,as i said ,After successful registation the user will be redirected to the listing page.As the attacker enter some client side script to the registration page.All data will be saved in the database and in the listing page a alert message will popup and say 12356789.

“><script>alert(12356789)</script>

 

Example-2: Then next type of attack is attacker is entering the special chars to the registration page where it is needed.

like the username of the registation page user entered the name as bikash#@%kumar . which is invalid.

 

How to save application from XSS attack

To deal with this type of problem,we need to remove the client side script from the user enter registration form value.

Solution-1:In php there are several function to avoid XSS attack,we need to user these following functions to remove any unwanted script or data entered by the user in the registation page

  • htmlentities()
  • strip_tags()
  • utf8_decode()

$user_name = strip_tags($_POST[‘user_name’]);

$user_name = htmlentities($_POST[‘user_name’]);

 

Solution-2: Filtering user entered data .Remove special chars from a string where special chars are not allowed.

You can use following function like str_replace().

$user_name = str_replace(array(‘%’,’$’,’#’),””,$_POST[‘user_name’]);