What is XSS
Cross-Site Scripting (XSS) is a type of security vulnerability typically found in web applications. XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.
Types of XSS
There are three main types of XSS attacks:
- Stored XSS: Also known as persistent XSS, the attack occurs when the data provided by the attacker is saved by the server, and then permanently displayed on "normal" pages returned to other users.
- Reflected XSS: In this type, the user's request is immediately returned by the server in an error message, search result, or any other response that includes some or all of the input provided by the user as part of the request, without that data being made safe to render in the browser, and without permanently storing the user provided data.
- DOM-Based XSS: This type of XSS attack occurs when the client-side script writes user-provided data to the Document Object Model (DOM). The data is subsequently read from the DOM by the client-side script and output to the browser. If the data is incorrectly handled, an attacker can inject a payload that will be stored as part of the DOM and executed when the data is read back from the DOM.
XSS Attack Techniques
There are several techniques that attackers use to exploit XSS vulnerabilities:
- HTML Injection: This technique involves injecting malicious HTML code into a website, which is then executed by the victim's browser.
- JavaScript Injection: This technique involves injecting malicious JavaScript code into a website, which is then executed by the victim's browser.
- Document.cookie: This technique involves capturing the victim's cookies, which may contain sensitive information such as login credentials.
Preventing XSS
Preventing XSS involves input validation, output encoding, and setting the HttpOnly flag for cookies. Input validation involves checking user input against a set of rules (a whitelist) and rejecting any inputs that do not meet these rules. Output encoding involves converting user input into a safe form where the input is displayed to users. Setting the HttpOnly flag for cookies prevents client-side scripts from accessing them, protecting them from theft.