Cross-Site Scripting (XSS): Complete Guide with Examples and Prevention
Cross-Site Scripting (XSS) is a type of web
security vulnerability in which attackers inject malicious scripts into web
pages that are delivered to unsuspecting users. These scripts are typically
written in JavaScript, though they can also include HTML or other client-side
code. When executed in the user’s browser, XSS allows attackers to steal
cookies, hijack sessions, perform phishing attacks, deface websites, or
redirect users to malicious sites. Unlike SQL Injection, which targets the
database, XSS primarily targets the end-user
and client side of web applications.
XSS vulnerabilities usually arise when web
applications fail to properly validate,
sanitize, or encode user input before rendering it in a web page.
There are three main types of XSS: Stored
XSS, Reflected XSS, and
DOM-based XSS. Stored XSS occurs
when malicious input is permanently saved on the server, such as in forum
posts, comments, or user profiles. When other users view the page, the
malicious script executes automatically. For example, if a comment field allows
<script>alert('Hacked');</script>,
a visitor viewing the comment will see a popup alert, or worse, have their
session token stolen. Reflected XSS happens when malicious input is immediately
reflected back in the server response, often via a crafted URL. For instance,
visiting a link like https://example.com/search?q=<script>alert('XSS')</script>
can trigger the script in the victim’s browser if the input is rendered without
encoding. DOM-based XSS occurs entirely on the client side, when JavaScript
code manipulates the Document Object Model (DOM) using unsanitized input, such
as document.write(location.hash),
allowing attackers to inject scripts via URL fragments or input fields.
The consequences of XSS attacks can range from
annoying pop-ups to severe security breaches. Attackers can steal cookies and session tokens, impersonate
users, capture login credentials, or deface websites. On e-commerce, banking,
or social networking platforms, XSS can lead to financial loss, data leaks, and
reputational damage. The severity of XSS depends on the attacker's access, the
sensitivity of the data, and the web application’s functionality.
Preventing XSS requires a multi-layered
approach. Input validation
ensures that only expected types of data are accepted, while output encoding escapes characters like <,
>,
",
and '
to prevent execution in HTML, JavaScript, or CSS contexts. Developers should
avoid using unsafe functions like innerHTML, document.write, or eval
with user input. Implementing Content
Security Policy (CSP) headers can also limit which scripts are allowed
to execute. Modern frameworks such as React, Angular, and Vue automatically
escape output in templates, reducing the risk of XSS. Regular security testing,
including automated scanners and manual penetration testing, is critical to
identify and fix XSS vulnerabilities before attackers exploit them.
Examples
of XSS Attacks:
1.
Stored XSS (Forum
Comment)
A comment field accepts:
<script>alert('Hacked');</script>
Every user who
views the comment sees the alert, or malicious scripts can steal session
cookies.
2.
Reflected XSS
(Search Page)
A URL like:
https://example.com/search?q=<script>alert('XSS')</script>
Causes the alert to
execute when the page reflects the q parameter without encoding.
3.
DOM-Based XSS
(Client-Side)
JavaScript code:
document.getElementById("output").innerHTML = location.hash;
Visiting https://example.com/#<script>alert('DOM
XSS')</script> executes the script in the browser.
Preventive
Code Examples:
·
JavaScript
Escaping
function escapeHTML(str) {
return str.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
document.getElementById("output").innerText = escapeHTML(userInput);
·
Using
React (Auto-Escaping)
const Comment = ({ text }) => <p>{text}</p>; // React automatically escapes input
·
CSP Header
Example
Content-Security-Policy: default-src 'self'; script-src 'self';
❓
Frequently Asked Questions (FAQs)
Q1: What
is XSS in simple terms?
A: XSS occurs when an attacker injects scripts into web pages viewed by other
users, allowing the attacker to run malicious code in the victim’s browser.
Q2: How
is XSS different from SQL Injection?
A: SQL Injection targets databases to manipulate data, while XSS targets users’
browsers and sessions.
Q3: Can
XSS steal my password?
A: Yes. XSS can steal session cookies or capture keystrokes, which can include
passwords if users are logged in.
Q4: Are
all web applications vulnerable to XSS?
A: Any application that displays user input without proper validation or
encoding can be vulnerable.
Q5: How
can I prevent XSS?
A: Use input validation, output encoding, safe frameworks, Content Security
Policy, and avoid unsafe JavaScript functions.
Q6: Can
XSS be exploited on mobile apps or APIs?
A: Yes. Any application that renders HTML or executes client-side scripts using
untrusted data can be vulnerable.
XSS remains one of the most common and
dangerous web vulnerabilities, but with proper input validation, output
encoding, secure frameworks, and defense-in-depth strategies, developers can
significantly reduce risk and protect users.

0 Comments