Web Security: CSRF

Web Security: CSRF

Mar 16, 2021 · 1 min read · 376 Words · -Views -Comments

CSRF is less famous than XSS but is a common and high-risk vulnerability. Here’s a quick review.

Concept

CSRF (Cross-Site Request Forgery) is an attack that forges requests to a server by impersonating a trusted, logged-in user.

Examples

Concepts can be abstract—examples help.

Suppose you open a phishing email with enticing text like “You’ve won $5,000,000!”. The HTML includes:

<img src="https://test1.com/index?action=delete&id=123">

When the email loads, the <img> triggers a GET request. If you’re logged in to test1.com, the browser sends cookies and the request succeeds, deleting the resource with id=123.

To avoid this, you switch deletes to POST—but attackers can do this:

  <form method="POST" action="https://test1.com/index">
      <input type="hidden" name="action" value="delete"/>
      <input type="hidden" name="id" value="123"/>
  </form>
<script> document.forms[0].submit(); </script> 

There are also link-based and XHR-based attacks that rely on user interaction:

 <a href="https://test1.com/index?action=delete&id=123">
        点击就中500万
    </a>

These are common CSRF techniques.

Analysis

The pattern is: the victim is logged in at site A. While visiting site B, a request is sent to A without the victim’s awareness, performing an unintended action.

Defenses

Given the above, combine multiple defenses wherever possible:

  1. RESTful API design: destructive actions use the proper verbs (e.g., DELETE). Simple links/GETs or bare POSTs can’t trigger them.
  2. SameSite cookies: set SameSite on cookies. With Strict, third-party requests won’t send cookies. With Lax, only top-level GET navigations send cookies.
  3. CORS: lock down cross-origin requests to prevent illicit XHRs.
  4. Referer/Origin checks: e.g., reject requests not originating from your domain(s).
  5. CSRF tokens: include a per-request or per-session anti-CSRF token that cross-site scripts can’t access.
  6. For sensitive cookies, set SameSite as above; with Strict, no cross-site cookies; with Lax, only GET navigations send them.

Final Thoughts

Security is essential for open web systems—take it seriously and apply layered defenses.

References

Alan H
Authors
Developer, Tech Enthusiast, Open Source Advocate