Cross-Site Scripting & CSRF
Overview
XSS injects malicious script into a trusted site so it runs in another user's browser; CSRF tricks an already-logged-in browser into firing an unwanted request. Both abuse the trust between a user's browser and a site they're authenticated to.
Key concepts
- Stored, reflected, and DOM-based XSS
- Output encoding, CSP, secure cookies
- CSRF relies on existing authentication
How it works
Cross-Site Scripting (XSS)
XSS injects malicious script into a trusted website. The script runs in another user's browser and may access information tied to that user's session.
| Type | How it works |
|---|---|
| Stored XSS | Malicious script is saved by the application and later shown to users. |
| Reflected XSS | Malicious script is included in a request and immediately reflected back in the response. |
| DOM-based XSS | Malicious script changes the page through insecure client-side JavaScript processing. |
Preventing XSS
- Validate and sanitize user input.
- Encode output before displaying user-controlled data in a webpage.
- Use secure web-development frameworks.
- Use content security policies to restrict which scripts can run.
- Mark cookies as secure and HTTP-only when appropriate.
Cross-Site Request Forgery (CSRF)
CSRF tricks a logged-in user's browser into sending an unwanted request to a trusted website. It relies on the fact that the user is already authenticated to the targeted application — the attacker doesn't need to see the response, just needs the action to fire.