Linux / PHP / Java / Designer

As melhores dicas estão aqui.

Preventing CSRF

| 0 comentários

Preventing CSRF requires three things:

  1. Make sure your forms use POST
  2. Make sure your site is not vulnerable to XSS
  3. Make your forms use a CSRF key

Step 1 isn’t really a requirement – you could CSRF protect forms which use GET too, but it’s generally a bad idea to have forms use GET for any possibly dangerous things. In fact, the only good use for GET forms I can think of is a search query, so that you can easily use it in the future by just changing the query in the URL.

Step 2 is quite critical. It’s difficult to protect forms against CSRF if there’s a script in the page which sends the CSRF key to the attacker.

Step 3 is the actual anti-CSRF measure. It’s quite simple, actually – create a key, store it in the session, and require it as a value in form submissions. If the form doesn’t contain the key generated on the previous request, it’s probably not a proper form submission.

A simple protection script

It’s relatively simple to protect a form against CSRF. We first need to generate a key, store it, and put it in the form. In the next request, the script needs to check whether the value was actually in the request or not..

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    //Here we parse the form
    if(!isset($_SESSION['csrf']) || $_SESSION['csrf'] !== $_POST['csrf'])
        throw new RuntimeException('CSRF attack');

    //Do the rest of the processing here
}

//Generate a key, print a form:
$key = sha1(microtime());
$_SESSION['csrf'] = $key;
?>

<form action="this.php" method="post">
<input type="hidden" name="csrf" value="<?php echo $key; ?>" />
<!-- Some other form fields you want here, and of course a submit button -->
</form>

Deixe uma resposta

Campos requeridos estão marcados *.