Csrf protection drupal hosting
I have some PHP POST scripts that I need to protect from CSRF attacks and have multiple questions:
1) If I submit POST requests to PHP using jquery without an HTML form, just be getting values directly from the HTML elements and submit them using jquery, am I still at risk of CSRF?
2) When a user logs in to website, I store their unique token in a session variable. In the PHP POST script I check if that session variable is set and has the same value I set before. Isn't that enough? why is it needed for the token to be included in the HTML form as well?
asked Nov 15 '14 at 23:43
- Yes. It doesn't matter how you construct the request, the attacker can construct one in the same way. (In theory you could make features of a complex request (which would trigger a CORS preflight request) mandatory, so that another site couldn't get the user's browser to duplicate the whole request, but I wouldn't want to depend on that).
If you just check that it is in the session, then all you are checking is that the user has caused a token to be generated (which usually just means visiting any page on your site… which could be in a hidden frame).
ok. what about if the attacker has a JS that can include the actual HTML FORM from my website into a hidden iframe. I have seen it in another example, Won't the token be included in the form if the user visits the attacker website while logged in? In this case the request would be authentic as the token is there in the form and in the session or am I missing something? - Michael Samuel Nov 15 '14 at 23:58
Yes it's still unsafe
A CSRF token should be a freshly generated token for each time you generate a form. It needs to be unique and unpredictable for each request. A session token set from login is only unique for the entire logged session.
And if you don't post the generated token to check, where do you check it? You match the session token with. The reason why is because you can still give people the possibility to do a request forgery, if the token isn't sent with the request itself, but all checks are done by session/ cookies. If you only check the session it does nothing against csrf. It needs to be sent in the request itself and checked if it matches your session. When you generate a unique token for each request, the bad guys cannot forge someone's request.
answered Nov 15 '14 at 23:55