Skip to main content
+994 55 300 09 92 Free consultation +15%
−20%Save your seat
Back to the blogWeb security

How does an XSS attack work?

You type a piece of code into a site’s search box instead of a word, and the page runs it. That’s Cross-Site Scripting, or XSS for short: one of the most common flaws in web applications.

What XSS is

XSS happens when an application sends input from a user back to the page without checking and sanitising it. The browser treats that input as code, not text, and runs it. Because the code runs as the site itself, it can reach the site’s cookies, the data on the page and requests made in the user’s name.

The three main types

  • Reflected XSS. The malicious code arrives inside the request, for example in a link, and is sent straight back in the response. The victim has to click a specially crafted link.
  • Stored XSS. The code is saved in the database, for example in a comment or profile bio, and runs for everyone who opens the page. The most dangerous type.
  • DOM-based XSS. The problem isn’t on the server but in the browser’s JavaScript: a script writes data from the URL or another source straight into the page.

A simple example

Imagine a search page shows the word you typed like this: Results: [your word]. Instead of a word you type <script>alert(1)</script> and a pop-up appears. That means the page runs what you type as code. If an attacker writes code that sends the cookie to their own server instead of alert, the victim’s session can be taken over.

What can happen

  • The session is stolen and the account taken over.
  • Actions in the user’s name: changing a password, sending messages.
  • Showing a fake sign-in form and collecting passwords.
  • Changing how the page looks.

How to defend against it

  • Encode output for its context. HTML, attributes, JavaScript and URLs each have their own rules.
  • Use the built-in mechanisms. Modern frameworks sanitise text automatically; don’t bypass them with things like innerHTML.
  • Set a Content Security Policy. CSP tells the browser which scripts are allowed to run.
  • Make cookies HttpOnly. Scripts can’t read such cookies.

How to learn it

The best way to understand XSS is to find it yourself in an authorised lab. In our Red Teaming course we learn web flaws first in theory, then through hands-on tasks. See the programme.

Only try what you read here on systems you are authorised to test.

FƏFəxri ƏlizadəRed Teaming trainer, Chronos.

Start learning hands-on.

Book a free consultation and get 20% off.

Get a free consultation