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:
<img src="http://example.com/user/delete/Joe" height="1"
width="1" />
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 _fth millisec-
ond, 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:
<?php
session_start();
$_SESSION['token'] = uniqid(md5(microtime()), true);
?>
<form action="/delete-user.php" method="post">
<input type="hidden" name="token" value="<?php echo $_SESSION['token'] ?>" />
Username: <input type="text" name="username" />
<button type="submit">Delete user</button>
</form>
Here we have added a hidden _eld called token and stored its content in a
session. On the next page we can do something like this:
<?php
session_start();
if ($_POST['token'] !== $_SESSION['token']) {
die('Invalid token');
}
// form processing here
?>
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
Web Development using PHP and MYSQL and AJAX and JAVASCRIPT,php source code,php5,php web links,php tutorial
Saturday, August 1, 2009
Cross-site request forgery
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment