Cross-Site Request Forgery

Loading "Intro to CSRF"
CSRF, which stands for Cross-Site Request Forgery, is a type of web security vulnerability where an attacker tricks a victim into performing actions they did not intend to on a web application where they're authenticated. Imagine being logged into your bank's website and another tab manipulates that authenticated session to transfer funds without your knowledge or consent. It could be as simple as:
<form method="POST" action="">
	<input type="hidden" name="amount" value="1000000" />
	<input type="hidden" name="to" value="123456789" />
	<button>Click here to win a free iPad!</button>
Here's what a rendered version may look like:
Whatever you do... DO NOT CLICK THAT BUTTON πŸ‘†
It looks just like a regular button right? But if you click it, you'll be transferring all your money to the attacker (or worse, Rick Astley).
That's a CSRF attack in action. The attack exploits the trust a site has in the user's browser and can have damaging effects.
To fundamentally side-step CSRF vulnerabilities, there are a few foundational principles:
  1. Use Anti-CSRF Tokens: These are unique tokens generated by the server and sent to the client during session establishment. Every subsequent request that modifies any data should carry this token. If a request doesn't have the token, it will be denied. Since the attacker's site won't know this unique and randomly generated token, they won't be able to make it through.
  2. SameSite Cookies: Modern browsers support the SameSite attribute for cookies. Setting it to Strict or Lax will ensure that the cookie isn't sent with cross-site requests, offering protection against CSRF.
  3. Check the Origin Header: Servers can check the Origin and Referer headers of incoming requests. If the request's origin isn't what the server expects, it can reject the request.
  4. Always Logout: Encourage users to log out of sessions when they're done, especially on public or shared computers. This reduces the window of opportunity for an attacker.
We'll get to the Cookies solution in a future workshop. But even with cookies in place, there are some requests that don't require cookies so it's a good general practice to apply CSRF protection to all requests that modify data.
Thanks to our honeypot implementation which requires a "valid from" field, we actually get a similar protection. However, honeypot fields are not intended to protect against CSRF and therefore the implementation could change in a way that no longer provides this protection. So it's best to implement both anti-CSRF tokens and honeypot fields.

Remix Utils

It actually takes a fair bit of work to generate the CSRF token and send it to the client. Luckily, we have a library that can handle this for us called remix-utils! Remix utils includes a number of utilities to facilitate this process.