Membership
Main Menu
Forum Boards
Stats
- 20 tutorials
- 74,813 members
- 734,857 forum posts
- 13 blog posts
Tutorials
PHP Security
Views: 79535
8. Cross-site request forgery
Cross-site request forgery (CSRF) is when you trick the user into making a request they have never made. Imagine that in your application it is possible to delete users like this: /user/delete/Joe. That would delete the user with the username "Joe". A malicious user might place this bit of HTML on his website:
This will basically trick the user into making a request to that page without them knowing it. Obviously only people who are logged in as administrators should be able to call this URL and therefore it will fail for most users. However, if a logged in administrator goes to the page where the above piece of HTML is located then the request will be successfully completed and "Joe" will be gone.
How can we prevent this? Well, in this case we could simply ask the admin to verify the action with his password before performing it. Yes, I know, this is kind of like Windows Vista's UAC (User Account Control) that people claim is incredibly annoying and prompts them to verify their action every fifth millisecond, but sometimes you will, unfortunately, have to add just a little amount of nuisance in order to keep your application safe.
Had the account come from a form then we could simply require that the information (in the previous case the username) be submitted using post and read it like $_POST['username']. However, this adds only a minimum of extra security. More sophisticated attacks than the above could just as easily trick the user into performing a POST request instead GET. We could use the "enter your password" method like before, but we could also use another kind of token. Imagine this form:
Here we have added a hidden field called token and stored its content in a session. On the next page we can do something like this:
We simply check that it is a valid token and we have then successfully ensured that the request did in fact come from the form.
