NOTE

1.8 CSRF

CSRF, its relationship with the same-origin policy, and defenses.

SecurityCreated Updated 2 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

1. What Is a CSRF Attack

A kind of web attack. Suppose Taobao uses a GET request for payment. The user logs in to Taobao and the cookie is saved locally. The user visits a malicious website, and that website sends a GET request to Taobao’s payment URL. The browser sends Taobao’s cookie when accessing the payment URL. Okay, the payment is actually made in the end.

2. Why Can CSRF Happen Despite Cross-Origin Restrictions

Same-origin policy and cross-origin

  1. The same-origin policy’s restrictions on cookies apply to JavaScript: JavaScript cannot read or write cookies from another origin. But regardless of whether the origins are the same, the browser can still send the corresponding cookie when accessing the server.
  2. The same-origin policy allows cross-origin form submission.

3. How to Prevent CSRF Attacks

Token validation. The steps are as follows:

  1. The frontend requests the backend.
  2. The backend generates a unique token, saves it, and returns it to the frontend. There are two ways:
    • Render the token into the HTML.
    • Write the token into a cookie.
  3. The frontend reads the token and puts it into the request parameters before accessing the backend. There are two ways:
    • Use JavaScript DOM operations to read the token from the HTML (the same-origin policy restricts script API operations).
    • Use JavaScript to read the token from the cookie (the same-origin policy restricts cookie operations).
  4. The backend reads the token from the request parameters and checks whether it matches.

4. Example

4.1. CSRF Filter

  1. The frontend uses JavaScript to read session_cookie (the login state) from the cookie, calculates csrf_token, and puts it into the HTTP URL parameters.
  2. The backend reads csrf_token from the HTTP URL parameters, then reads session_cookie (the login state) from the cookie, calculates csrf_token, and compares the two tokens.

It can be seen that csrf_token is unique within each user login period, but it is not unique for every request. If this token leaks, there is still risk, for example through the referrer, so the following code needs to be added:

<meta name="referrer" content="origin">

5. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub