Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a secure way to set the token CSRF?

Tags:

security

php

I am wondering if this is a secure way to set a token, unless there actually is a token generated, I generate one, and use it throughout the applications and those forms. One token per session?

if (!isset($_SESSION['token'])) {
    $data['token'] = uniqid(rand(), true);
    session_regenerate_id();
    $_SESSION['token'] = $data['token'];
}

Would it be necessary to clear out the token on a submitted form? or just stay with it, even though I submitted a form?

like image 999
user1831020 Avatar asked Dec 09 '12 17:12

user1831020


2 Answers

If you don't know these links, this should help you understand some scenarios and specifically this will tell you the DOs and DONT's. Hope it helps.

like image 193
palako Avatar answered Sep 21 '22 07:09

palako


Personally I would generate a new token for every form I want to display. If you do it this way, someone just needs a session cookie to read your token and use it as long as the session stays active.

In my applications I generate a token for each form display like this:

<?php
$token = uniqid(rand(), true);
$_SESSION['csrf_tokens'][$token] = true;

HTML

<form>
    <input type="hidden" name="token" value="<?php echo $token ?>" />
</form>

On form validation I check for that token like this:

if (isset($_SESSION['csrf_tokens'][$token]) && $_SESSION['csrf_tokens'][$token] === true) {
    unset($_SESSION['csrf_tokens'][$token]);
    // additional code here
}
like image 28
Benjamin Paap Avatar answered Sep 21 '22 07:09

Benjamin Paap