NOTE

1.8 CSRF

CSRF exploits a browser's existing login state to send requests to another site from a malicious page. These notes illustrate the process with a payment-request example.

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. As a result, the payment actually goes through.

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 sends 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 sends a request to 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.

The csrf_token is unique to each user login session, rather than to each 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