Cross-site Scripting (XSS) is a type of Computer security vulnerability typically found in web application. XSS enables attackers to inject client side script in to web pages. Attacker may send malicious code to the the unsuspecting user(normally end user). The end user’s browser has no way to know that the script should be trusted, and will execute the script. The malicious code may access any cookies, session tokens or other information. This script can even rewrite the content of the HTML page. XSS attack is similar to SQL Injection. Normally we inject SQL queries in SQL Injection, but here in XSS we inject script(Client side script ex: JavaScript) to the remote server.
There are two types of Cross Site Scripting
Non-Persistent
Persistent
Here we are going to look Non-Persistent XSS attack.
Non-Persistent
The non-persistent cross site scripting is the most common type, and mainly used in HTTP query parameters or in HTML form submissions.
Let us the example :
index.php
<html> <body> <?php $name = $_GET['name']; echo 'Welcome'. $name.' </br>'; echo "<a href='https://www.google.co.in'>Click Here</a>"; ?> </body> </html>
The attacker will craft the URL as follows and send it to the end user.
index.php?name=name<script>alert('name')</script>
When the end user runs the above URL alert box will be displayed in user’s browser. This piece of alert script will not do any harm, but malicious code does.
Let us see how to change the content of the HTML page using the same attack. Take the same example and run the below URL.
index.php?name=<script>window.onload = function() {var link=document.getElementsByTagName("a");link[0].href="http://boopathi.me/";}</script>
The above code will change the actual URL. The above script gets all the anchor tag in the current page and store it in array, then it will only change the first URL. Normally this function will call during the page load itself. Mostly attacker will not use the URL in human readable format he usually encode the URL and send it to the end users.
How to protect from this attack
Usually this depends on developers hand. Let me show the same example without the vulnerability.
<html> <body> <?php $name = $_GET['name']; $name = stripslashes($name); $name = mysql_escape_string($name); echo 'Welcome'. $name.' </br>'; echo "<a href='www.google.co.in'>Click Here</a>"; ?> </body> </html>
When attacker tries to attack the above code using alert script, nothing happens. It just print the name only.
In the above code I used two PHP functions
stripslashes(str)Avoid \ in string this function will avoid back slash in the given string.
mysql_escape_string(str)Avoid scripts in this URL, Normally it will Escape the string, but in this case it will avoid scripts
If you found this post interesting Share: