Cross-site Scripting (XSS) is a client-side code injection attack. The attacker aims to execute malicious scripts in a web browser of the victim by including malicious code in a legitimate web page or web application. The actual attack occurs when the victim visits the web page or web application that executes the malicious code. The web page or web application becomes a vehicle to deliver the malicious script to the user’s browser. Vulnerable vehicles that are commonly used for Cross-site Scripting attacks are forums, message boards, and web pages that allow comments.
In Reflected XSS, an attacker sends the victim a link to the target application through email, social media, etc. This link has a script embedded within it which executes when visiting the target site.
In Stored XSS, the attacker is able to plant a persistent script in the target website which will execute when anyone visits it.
With DOM Based XSS, no HTTP request is required, the script is injected as a result of modifying the DOM of the target site in the client side code in the victim’s browser and is then executed.
To keep yourself safe from XSS, you must sanitize your input. Your application code should never output data received as input directly to the browser without checking it for malicious code. Our examples are going to based on PHP since it’s the most used web technology.
Some prevention techniques are the use of google code against XSS. Download the library here and implement the code with a sample below:
$data = AntiXSS::setFilter($data, "white", "string"); //For strings
$data = AntiXSS::setFilter($data, "white", "number"); //For numbers
$data = AntiXSS::setFilter($data, "black"); //Filter against all
If your application processes high amount of html and rich media, you can download the htmlpurifier and implement it by using a sample code below:
$c> $config->set('HTML.Allowed', 'p,b,a[href],i'); // basic formatting and links
$HTML_Secure = new HTMLPurifier($config);
// Use HTML Purifier to prevent XSS in this user's profile
The internet provides other ways of protecting yourself against XSS.