XSS is a type of injection in which an attacker injects malicious code into a trusted website. The attacker often initiates this attack by sending a malicious link to the user and enticing the user to click on it. If the website lacks the proper sanitization of input data, the malicious link executes the malicious code chosen by an attacker on the user’s system. The malicious code is designed to steal any sensitive data of the user such as the user’s active session cookie.
Types of XSS attacks
There are three types of XSS attacks that are defined as follows:
Reflected XSS is of non-persistent type. It occurs when input given by users is immediately returned by a web application in any form of response, either partially or completely, and without permanently storing it.
Stored XSS is of persistent type. It occurs when input provided by the user is stored on the target server such as in the database and the user receives that data within its later HTTP responses in an unsafe way.
Dom-Based XSS is of non-persistent type. It occurs when vulnerabilities exist in client-side code rather than server-side code. Web applications read the malicious code directly from the query string.
How to prevent XSS attacks?
There are multiple precautions that you should take to prevent the XSS attack.
1. Sanitize inputs: Input sanitization can be done in three ways:
- Whitelist sanitizing: It allows only valid characters and code strings.
- Blacklist sanitizing: It removes the unnecessary characters from input such as extra white spaces, tabs, etc.
- Escape sanitizing: It rejects invalid data requests and strips the input in order not to be seen as codes.
2. Encode output data: If the HTTP response is going to contain the user-controllable data then the output must be encoded to ensure that it can not be interpreted as active content.
3. Add appropriate response headers: Adding appropriate response headers will help in preventing XSS attacks through the HTTP responses. Setting Content-Type and X-Content-Type-Options headers will ensure that the browser interprets the response in the way you intend.
4. Content Security Policy(CSP): A content security policy eliminates the chances of an XSS attack by specifying the domains that the browser should trust to be valid sources of executable scripts. Configuring CSP involves adding the Content-Security-Policy response header as follows:
Where a policy is a string containing the policy directives that describe your Content Security Policy. For example, a website administrator wants to allow content that comes from the site's own origin.
Content-Security-Policy: default-src 'self'
In this blog, we discussed XSS attacks, their types, and how can we defend our web application against them. If you want help in eliminating this vulnerability, you can get in touch with PLG Works, that’s us.