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)?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jul 13, 2016 at 20:10
\$\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

answered Jul 14, 2016 at 17:15
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.