Cross-Site Scripting (XSS)
Imagine a website that allows you to write a comment, and when someone else views it, your comment runs code in their browser. That’s basically what XSS is.
What is XSS?
XSS is a vulnerability that lets attackers inject JavaScript code into a website. When the site shows this code to other users, their browsers will run it, even if it’s malicious.
How XSS Happens
- The website accepts input from users (like comments or search boxes).
- The input is displayed later to other users, but without checking or cleaning it first.
- If someone adds a script (like
<script>alert("XSS")</script>
) and the site shows it as-is, that script runs in the viewer’s browser.
Real-Life Example
Let’s say you leave this comment: <script>alert("Hello from Ahmed!")</script>
.
If the site doesn’t protect itself, other users will see a pop-up.
That’s a very basic example, but attackers can do worse: steal cookies,
redirect to fake login pages, or control your actions.
Types of XSS
- Stored XSS: The malicious code is saved on the server (like in a comment), and shown to every visitor.
- Reflected XSS: The code comes from a URL or form and is shown immediately (like in search results).
- DOM-Based XSS: The browser itself builds the page using the input, and the JavaScript is injected directly in the DOM.
Why Is It Dangerous?
- Attackers can steal login tokens (cookies).
- They can force users to perform actions without permission (CSRF-like).
- They can hijack accounts or trick users.
How To Prevent XSS
- Always escape user input when showing it in HTML.
- Use a security library or framework that handles escaping automatically.
- Use Content Security Policy (CSP) to block inline scripts.
- Don’t trust anything coming from the user, even if it looks safe.
Key Idea
XSS is not about the hacker doing something complicated. It’s about the developer trusting user input too much. And when the browser runs that input like it’s safe, attackers take over.