ikkez / fabulog

the new F3-powered awesome fabulous blog-ware
GNU General Public License v3.0
62 stars 22 forks source link

Should check csrf in forms? #11

Open xmory opened 9 years ago

xmory commented 9 years ago

Someone told me that forms should add token to avoid csrf attack. Then I read the fatfree documentation, the Session class has a csrf method to get the token. But how to get the token? ` $s = new Session();

echo $s->csrf(); //false returned ` Then I look into fabulog to get help, I find that it doesn't check this. Is csrf check needed? Thanks.

ikkez commented 9 years ago

The Session class is a Cache-Based Session handler, which requires to have an activated Cache instance.

$f3->set('CACHE', true);
$s = new Session();
echo $s->csrf(); // z3sysduecint.p63g18fr7nvp

Though the Session handlers have some build in protection already, they only help you for Session-Hijacking attacks. You are right, for better security, this token should be used in forms or URIs that we want to protect.

if ($f3->exists('SESSION.csrf',$csrf))
    var_dump($csrf); // old token from last request, to validate forms
$s = new Session();
$newToken = $s->csrf(); // token for current request, use this in hidden form fields
var_dump($newToken);
$f3->set('SESSION.csrf',$newToken);

I currently have no such check in fabulog, but will consider to add this as feature. thanks ;)

edit: I've added this to the docs. http://fatfreeframework.com/session#csrf

xmory commented 9 years ago

Thanks for your reply.

I know where I got error.

if I test code like this:

$f3=require('lib/base.php');
$f3->set('CACHE',true);
if (true) {
     /*do_login*/
    $session = new Session();
    $f3->set('SESSION.user_id',3);  //
    $f3->set('SESSION.csrf',$session->csrf());
    var_dump($f3->get('SESSION'));
}

every thing is right. But this gets the error:

$f3=require('lib/base.php');
$f3->set('CACHE',true);
if (true) {
    /*do_login*/
    $f3->clear('SESSION');   //this line added
    $session = new Session();
    $f3->set('SESSION.user_id',3);  
    $f3->set('SESSION.csrf',$session->csrf());
    var_dump($f3->get('SESSION'));
    //csrf token is false
}
xmory commented 9 years ago

When a user login, should clear session first? Then can't get csrf token?

xmory commented 9 years ago

It seems that the token is created when the session instance is create. The Session class check if other session data has exists, if not, the token won't be saved. I add a method to the Session class to generate the token, and save it. Call the method when needed.

SaphiLC commented 7 years ago

i keep getting this error "session_start(): Failed to read session data: user" the csrf code gets generated but then the website won't work because that error 500, it's driving me crazy :S