7. Cross-site scripting (XSS)
A web application includes untrusted data in a new web page without proper validation.
What it is
XSS allows malicious code to be added to a web page or app (e.g., via user comments or form submissions used to define the subsequent action). Since HTML mixes control statements, formatting, and requested content into the web page’s source code, it allows an opportunity for unsanitized code to be used in the resulting page. XSS is the second most prevalent issue in the OWASP Top 10 and is found in around two-thirds of all applications.
How it works
When a web page or app utilizes user-entered content as part of a resulting page without checking for bad input, a malicious user could enter content that includes HTML entities.
Why it’s bad
Attackers can change the behavior of an app, direct data to their systems, and corrupt or overwrite existing data.
Countermeasures
Use frameworks that automatically escape XSS by design. Learn the limitations of each framework's XSS protection and appropriately handle the use cases which are not covered.
Escape untrusted HTTP request data based on the context in the HTML output (e.g., body, attribute, JavaScript, CSS, or URL) to resolve reflected and stored XSS vulnerabilities.
Apply context-sensitive encoding when modifying the browser document on the client side acts against DOM XSS.
Enable a Content Security Policy (CSP) against XSS. It is effective if no other vulnerabilities exist that allow placing a malicious code file (e.g., compromised CDN, an unsecured file system on the server).
XSS example 1
Reflected XSS: The application or API includes unvalidated and unescaped user input as part of HTML output.
The attacker executes arbitrary HTML and JavaScript in the victim’s browser. Typically, the user needs to interact with a compromised link that points to an attacker-controlled page, such as malicious watering hole websites or advertisements.
XSS example 2
Stored XSS: Often considered a high or critical risk, the application or API stores unsanitized user input that is viewed later by another user or an administrator.
XSS example 3
DOM XSS: JavaScript frameworks, single-page applications, and APIs that dynamically include attacker controllable data to a page.
DOM-based XSS is a variant of both stored (i.e., persistent) and reflected XSS. As web applications become more advanced, an increasing amount of HTML is generated by JavaScript on the client-side rather than by the server. Even with completely secure server-side code, the client-side code unsafely includes a user input in a DOM update after the page has loaded.