PSA: Protect your apps against CSRF
What is CSRF?
CSRF is when attackers "forge" requests, that is, making fake requests that the user didn't actually make. This only works if the user is authenticated.
Let's say you have something like this:
<form method="POST" action="https://repl.it/change-password"> <input name="password" type="hidden" value="abc123"/> </form> <script>document.querySelector('form').submit();</script>
The form is automatically submitted, and now the attacker can access the user's account.
Another common way that this happens is with images.
You can logout people with this:
Since the browser tries to request
https://repl.it/logout, and the server responds by logging the user out.
What should I do to prevent this?
Most of my apps have CSRF vulnerabilities and I only recently realized that
Well, first check if your framework/library has CSRF protection, I know for a fact that flask-wtf, Django, and express (with
csurf) have protection.
If they donn't, you'll have to write your own.
Keep these things in mind:
1. Use CSRF tokens
The idea behind CSRF tokens is that you you generate a random string and pass it as a form parameter and stores in somewhere such as cookies, and the server checks if the csrf token is valid, and errors if it doesn't.
2. Turn off CORS (except for in the API)
DO NOT use CORS, which allows cross origin requests with JS.
3. DO NOT use GET for destructive actions (looking at you repl.it)
You should NOT use GET for destructive actions such as login or logout. Instead use POST, PUT, or DELETE.
Now that you know what CSRF is and how to prevent it, make sure to start protecting your apps. The below repl is a demonstration of CSRF (carried out against this wiki).