Cross-Site Scripting (XSS)
when a website runs an attacker's script in your browser
Cross-site scripting happens when a website includes untrusted input in its pages without making it safe, so an attacker's JavaScript runs in a victim's browser as if it came from the trusted site.[1]
Why that is serious
Scripts that run on a site's page can usually read what the user sees, make requests as the user, read non-protected cookies and modify the page. Attackers use this to steal sessions, perform actions on the victim's behalf, show fake login boxes or spread further.
The three types
- Reflected: the malicious input is in a request (often a crafted link) and bounces straight back in the response. The victim must be lured into clicking.
- Stored: the input is saved, for example in a comment or profile, and served to everyone who views it. This is the most dangerous kind because no lure is needed.
- DOM-based: the flaw is in the page's own JavaScript, which writes untrusted data into the page in an unsafe way.
How to prevent it
- Encode output for the place it lands. Turn special characters into harmless text depending on whether the data goes into HTML, an attribute, JavaScript or a URL. Modern frameworks do this by default, which is why it is risky to bypass their escaping.[2]
- Avoid dangerous sinks such as
innerHTML,document.writeandevalwith untrusted data. PrefertextContent. - Sanitize rich content with a well-maintained library if you must allow some HTML.
- Content Security Policy (CSP): a response header that restricts which scripts may run. It limits the damage when other defenses fail.
- Cookie flags:
HttpOnlystops scripts reading session cookies, andSameSitelimits cross-site sending. - Validate input as a supporting layer, not as the main defense.
XSS versus CSRF
They sound alike but differ. XSS makes the victim's browser run attacker code on a trusted site. CSRF tricks the victim's browser into sending a request the user did not intend. Different fixes apply: output encoding and CSP for XSS, anti-CSRF tokens and SameSite cookies for CSRF.
Sources
Test yourself
My notes
Private — saved only on this device, never sent anywhere.