1
\$\begingroup\$

I am using codeigniter framework in PHP. In signup form I have:

Controller:

$info['csrf_token'] = array('signup'=>$this->csrf_token('signup'));
echo $this->load->view('/signup',$info,TRUE);

// generate token:
public function csrf_token($form_name){
    if (function_exists('mcrypt_create_iv')) {
        $t = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
    } else {
        $t = bin2hex(openssl_random_pseudo_bytes(32));
    }

    $sess_array = array();
    $sess_array[$form_name] = $t;
    $this->session->set_userdata('csrf', $sess_array);

    return $t;
}

View:

<form>
<input type="hidden" name="csrf_token" value="<?=hash_hmac('sha256', 'signup', $csrf_token['signup'])?>" />
</form>

Validation check on form submit:

$csrf_sess = $this->session->userdata('csrf');
if(hash_hmac('sha256', 'signup', $csrf_sess['signup'])==$_POST['csrf_token']){
    return true; // Valid request.
}else{
    return false;
}

Will it prevent website from CSRF (Cross-Site Request Forgery)?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

From what it looks like, you are correctly checking the submission form for a valid CSRF token before processing, therefore a separate, malicious website [EDIT: without access to the hidden CSRF token on the submission form] would be unable to execute CSRF.

From here: Cross-Site Request Forgery (CSRF) is a type of attack that occurs when a malicious web site, email, blog, instant message, or program causes a user's web browser to perform an unwanted action on a trusted site for which the user is currently authenticated

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.