CSRF

Aliases
  • csrf
  • Cross Site Request Forgery
Image of Author
May 31, 2024 (last updated September 16, 2024)

https://en.wikipedia.org/wiki/Cross-site_request_forgery

Stands for Cross Site Request Forgery.

Background: When you log in to a website you will usually get a cookie with session details. This lets you stay logged in across multiple requests, aka a "session", hence the common term for it: "session cookie". When you make a web request to a server your browser will automatically send any cookies associated with that URL along with the request (this is changing with the same-site cookie setting, but for now just assume I'm right.

A bad actor could reason as follows: I can build a malicious website that has a button that when clicked will make an API request to some other web server. If I get lucky and the user is actually signed in to that website (e.g., in another tab) then they will have a session cookie that will get passed to the server. The server will be deceived in thinking it's a valid API request and I can manipulate that user's data maliciously.

This kind of attack still happens to this day. Here are some historical example from Wikipedia The bad actor has forged a request on a malicious site (aka, cross site). Thus, it is a cross-site request forgery. (Rarely called "session riding" as well.)

In fact, you don't even need the user to take an action sometimes, particularly if a bad actor can get the server to do the desired behavior with a GET request. In such a scenario the bad actor could, for example, set the get as an img src as in this MDN example.

The server can prevent this from happening by providing a CSRF token at the start of a session. This token is most commonly set on the cookie with the same-origin attribute. This means that even if the malicious website knows a CSRF token was in the cookie, they couldn't read it. This allows for the Double Submit Cookie solution: all incoming requests include the CSRF token in their payloads. This means the CSRF token is being "double submitted", once on the cookie, and once in the request payload. The malicious site can only submit the token in the cookie, and can't read the cookie, so can't inject the token into the payload.

More modern solutions include the same-site attribute, which when set to strict, informs browsers not to send cookies along with cross site requests. Not all cross site requests are bad. Sometimes you want to provide APIs that other websites can use. A simple example would be a weather website wanting it's "weather widget" to be embedded on other websites. That widget would make cross site requests from the host origin to the weather website origin.