Pergunta

First some context.
I've been using nonce tokens to sign my form data in the same way wordpress allows to attach an action to a nonce:

// editing post id:10
$post_id = 10;
$nonce = create_nonce( 'edit-post-'.$post_id );
echo '<input type="hidden" name="post_id" value="'.$post_id.'">';
echo '<input type="hidden" name="nonce" value="'.$nonce.'">';

This allows me later to check if user is editing the post I gave him permissions to, because I reconstruct the nonce and check if the nonce that I recieve is the same I constructed:

$server_nonce = create_nonce( 'edit-post-'.$_POST['post_id'] );
if( $server_nonce != $_POST['nonce'] )
{
    echo 'bad guy...';
}

Up until now I misinterpreted this method as an anti-CSRF token that gave me CSRF protection.
As I deep in the CSRF issue I've found that this solution does not protect me 100% from CSRF because:

  1. The nonce can be reconstructed in server with the data received. CSRF must be not reconstructed.
  2. The nonce token will be the same for a form for a window time. CSRF must be unique at each request.

So, here's my question:

Is it ok to use two tokens in a form to protect from CSRF and data signature? Is there any way to combine these two tokens?

Foi útil?

Solução

Generally, the nonce needs to be saved somewhere server-side. If you're regenerating the nonce when validating it, it means the nonce is a predictable value based on input. That is pretty useless, since that's a static value. It's not a nonce.

The way the nonce is supposed to work is:

  1. Construct the form
  2. Generate a random value, the nonce
  3. Save the nonce in the session and put it in a hidden field in the form
  4. Upon form submission, check that the submitted nonce corresponds to the one in the session

Anything else is just a checksum of the action+post-id, which is pretty useless.

You can easily extend this proper nonce procedure with a checksum of the to-be-submitted fields, by taking the name of all expected fields and other expected static values and adding a hash of them to the session as well. E.g.:

sha1(join(',', array('first_name', 'last_name', $nonce)))

Upon form submission, get all received field names and generate the same hash again and check if it's identical to the one in the session. If not, somebody tampered with the form.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top