Best Way To Prevent CSRF


Xanatos
Member
Registered: 03.12.12 14:12
Timezone: UTC +1
Posts: 19

hi,

I'm practicing making websites and i was wondering what are some ways to prevent CSRF? It seems like kind of a tough one to fix.

thx in advance


ynori7
Administrator
Registered: 24.08.11 12:16
Timezone: UTC +2
Posts: 164

Some people attempt to prevent it by checking the referer, but that's not a very good solution since referers can be spoofed and some browsers don't send referers at all.

The proper way to secure a site against CSRF is to include tokens on each request which modifies data. These tokens should be random and unpredictable, and they should be different for each session.

Here is an example workflow:

  • View form. Form contains some input boxes and also a hidden input field called 'csrf' which has a value of "123348703"
  • Enter data. Submit form.
  • The server receives the request and checks if the token sent matches the token saved in the user's session. If they match continue, else perform some error action.
  • If a hacker attempts to perform a CSRF exploit against the user, he will fail because the token he has in his session does not match the user's token.

For improved security you can also make it so the token changes after each time it's used (like Valhalla does), however this can potentially lead to decreased usability (e.g. a user who opens multiple tabs and then tries to perform an action on each of them. The first will work but the others will be rejected). That issue can be overcome by adding more data to the session so that multiple tokens are saved, but this can make things more complicated and requires the server to keep track of more data.

Here is the CSRF-prevention framework I wrote for Valhalla in PHP: Link

i537.photobucket.com/albums/ff338/ynori77/archenemysig1.jpg


Senzon
Member
Registered: 25.05.12 19:13
Timezone: UTC +3
Posts: 19

Here's something that might be useful:
Owasp CSRF Prevention Cheat Sheet

OWASP does a pretty great job describing web vulnerabilities and how to prevent them. They also have their CSRF Guard framework for Java which works pretty well. It's a pain in the ass to implement though and the documentation isn't that great (but it never is for frameworks it seems).


Xanatos
Member
Registered: 03.12.12 14:12
Timezone: UTC +1
Posts: 19

Wow, thanks for the really helpful answers guys. And thanks for the quick responses. I have a lot to read up on now and practice.

Thx,
Xanatos