Description
XSS occurs when a web application handles untrusted input incorrectly while generating a page, allowing malicious script to run in the user's browser.
Potential impact
- Malicious script may steal user data or bypass application protections.
- Sensitive page data or script-accessible cookies may be exposed.
HttpOnlycookies do not by themselves stop actions performed with the victim's permissions. - An attacker may execute arbitrary code within the browser context.
Remediation
- Encode values at the final output step for the actual context, such as HTML text, attributes or JavaScript. HTML text escaping does not replace JavaScript encoding or URL validation. Prefer auto-escaped templates where possible.
- Use Content Security Policy (CSP) to restrict script execution as an additional defense.
- Adding Spring Security does not automatically encode user input. If HTML input is required, sanitize it with a reviewed allow-list policy.
Examples
These Spring controller excerpts assume that the response is rendered as HTML. HtmlUtils refers to org.springframework.web.util.HtmlUtils; the encoding below applies to an HTML text position.
Before
java
// Before
@RequestMapping("/welcome")
@ResponseBody
public String welcomeMessage(@RequestParam String username) {
// Insert input directly into HTML
return "<h1>Welcome, " + username + "!</h1>";
}
After
java
// After
@RequestMapping("/welcome")
@ResponseBody
public String welcomeMessage(@RequestParam String username) {
// Encode input for HTML text
String safeUsername = HtmlUtils.htmlEscape(username);
return "<h1>Welcome, " + safeUsername + "!</h1>";
}
Explanation:
- Before: Inserts
usernamedirectly into HTML. Input containing malicious script may execute in the browser. - After: Uses
HtmlUtils.htmlEscapeto encode the input as HTML text. In this position, input markup is displayed as text instead of executing.
Related CVEs
- CVE-2021-25926: Python Library Manager did not sufficiently neutralize a user-supplied search term, allowing reflected XSS.
- CVE-2021-25963: Python-based e-commerce platform did not escape returned content on error pages, allowing for reflected Cross-Site Scripting attacks.
- CVE-2021-1879: Universal XSS in mobile operating system, as exploited in the wild per CISA KEV.