XSS Attacks: Introduction, Classification, Prevention, and Detection
This article explains the fundamentals of Cross‑Site Scripting (XSS) attacks, presents real‑world examples, classifies stored, reflected, and DOM‑based XSS, and provides comprehensive prevention, detection, and mitigation techniques for frontend developers, including proper escaping, whitelist schemes, CSP, and secure coding practices.
With the rapid growth of the internet, information security has become a top concern for enterprises, and the front‑end is a high‑risk point for security issues. This article, sourced from Meituan’s technical team, introduces Cross‑Site Scripting (XSS), its classifications, real‑world cases, and detailed mitigation strategies.
Background
Front‑end developers face traditional XSS and CSRF problems as well as newer threats such as network hijacking and illegal Hybrid API calls. Browsers have introduced defenses like CSP and Same‑Site Cookies, but many vulnerabilities remain.
XSS Attack Introduction
The article starts with a quiz to challenge readers about XSS responsibilities and proper data handling.
Vulnerability Demonstration
A simple search page that directly injects the keyword URL parameter into an <input> value and a <div> leads to script execution when the URL contains malicious payloads.
<input type="text" value="<%= getParameter("keyword") %>">
<button>搜索</button>
<div>您搜索的关键词是:<%= getParameter("keyword") %></div>When the request http://xxx/search?keyword="><script>alert('XSS');</script> is processed, the malicious script is reflected in the HTML and executed.
Fixing the Issue
Applying escapeHTML() to the parameter sanitizes the output, converting special characters to HTML entities.
<input type="text" value="<%= escapeHTML(getParameter("keyword")) %>">
<button>搜索</button>
<div>您搜索的关键词是:<%= escapeHTML(getParameter("keyword")) %></div>The resulting HTML safely displays the input without executing scripts.
Special Cases: URL Redirection
Even after HTML escaping, URLs like javascript:alert('XSS') in href attributes can trigger XSS. The article shows a whitelist approach that only allows http and https schemes.
// 禁止 URL 以 "javascript:" 开头
xss = getParameter("redirect_to").startsWith('javascript:');
if (!xss) {
<a href="<%= escapeHTML(getParameter("redirect_to")) %>">跳转...</a>
} else {
<a href="/404">跳转...</a>
}Embedding JSON Safely
Directly inserting JSON into a <script> tag cannot use escapeHTML() because it would corrupt the JSON syntax. The article proposes an escapeEmbedJSON() function that handles characters like U+2028, U+2029, and embedded <script> tags.
<script>
var initData = <%= escapeEmbedJSON(data.toJSON()) %>
</script>XSS Classification
Stored XSS – malicious code is saved in a database and served to users.
Reflected XSS – payload is reflected from the request URL or parameters.
DOM‑based XSS – the browser’s JavaScript processes untrusted data and injects it into the DOM.
Each type has distinct attack steps and typical targets such as search pages, comment sections, and URL parameters.
Prevention Strategies
Input Filtering
Filtering on the client side is insufficient; validation must also occur on the server, but the core defense is proper output encoding.
Output Encoding
Use context‑aware escaping: HTML content, attribute values, CSS, JavaScript strings, URLs, etc., each require specific encoding. Mature libraries like org.owasp.encoder provide functions such as Encode.forHtml , Encode.forHtmlAttribute , Encode.forJavaScript , and Encode.forUriComponent .
<div><%= Encode.forHtml(UNTRUSTED) %></div>
<input value="<%= Encode.forHtmlAttribute(UNTRUSTED) %>" />
<script>var msg = "<%= Encode.forJavaScript(UNTRUSTED) %>";</script>Pure Front‑End Rendering
Load a static HTML skeleton and let JavaScript fetch data via Ajax, inserting it with safe APIs like .innerText , .setAttribute , or framework bindings that automatically escape.
Content Security Policy (CSP)
Deploy strict CSP headers to block inline scripts, external code loading, and data exfiltration, reducing the impact of any residual XSS.
Additional Measures
HTTP‑only cookies to prevent JavaScript access.
CAPTCHA to deter automated attacks.
Input length limits to raise attack difficulty.
XSS Detection
Manual testing with polyglot payloads (e.g., the "Ultimate XSS Polyglot") and automated scanners such as Arachni, Mozilla HTTP Observatory, or w3af can uncover existing vulnerabilities.
jaVasCript:/*-/*`/*\`/*'/*"/**/(/* */oncliCk=alert())//%0D%0A...Case Studies
QQ Mail m.exmail.qq.com reflected XSS via unescaped uin and domain parameters.
Weibo “明星堂” reflected XSS allowing script injection through crafted URLs.
Further Reading
Automatic Context‑Aware Escaping in template systems (Google) automatically selects the correct escaping based on insertion context, reducing developer burden. Supported engines include Go’s html/template and Google Closure Templates.
References
Wikipedia – Cross‑Site Scripting
OWASP XSS Prevention Cheat Sheet
OWASP Java Encoder
Ahmed Elsobky – Ultimate XSS Polyglot
Jad S. Boutros – Automatic Context‑Aware Escaping
Vue.js – v‑html
React – dangerouslySetInnerHTML
Qunar Tech Salon
Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.