为什么生成的 CSRF 保护令牌没有像建议的那样通过 SESSION 保存和使用here http://codeutopia.net/blog/2008/10/16/how-to-csrf-protect-all-your-forms/?目前在CI2中,CSRF保护机制(Security类)是这样的:
1.在_csrf_set_hash()函数中为CSRF令牌生成唯一值:
$this->csrf_hash = md5(uniqid(rand(), TRUE));
2.将该标记插入表单隐藏字段(使用 form_open 助手)
3.用户提交表单,服务器通过POST获取令牌。 CI 在 Input 类中的“_sanitize_globals()”函数中执行令牌验证:
$this->security->csrf_verify();
4.Security类的函数“csrf_verify”只是检查是否设置了POST['token']并且POST['token']等于COOKIE['token'];
public function csrf_verify(){
// If no POST data exists we will set the CSRF cookie
if (count($_POST) == 0)
{
return $this->csrf_set_cookie();
}
// Do the tokens exist in both the _POST and _COOKIE arrays?
if ( ! isset($_POST[$this->_csrf_token_name]) OR
! isset($_COOKIE[$this->_csrf_cookie_name]))
{
$this->csrf_show_error();
}
// Do the tokens match?
if ($_POST[$this->_csrf_token_name] != $_COOKIE[$this->_csrf_cookie_name])
{
$this->csrf_show_error();
}
// We kill this since we're done and we don't want to
// polute the _POST array
unset($_POST[$this->_csrf_token_name]);
// Nothing should last forever
unset($_COOKIE[$this->_csrf_cookie_name]);
$this->_csrf_set_hash();
$this->csrf_set_cookie();
log_message('debug', "CSRF token verified ");
return $this;
}
为什么不在会话中存储令牌?恕我直言,仅检查 POST['token'] 非空且等于 COOKIE['token'] 是不够的,因为两者都可能是由邪恶站点发送的。