Home > Backend Development > PHP Tutorial > php安全开发 添加随机字符串验证,防止伪造跨站请求_php技巧

php安全开发 添加随机字符串验证,防止伪造跨站请求_php技巧

WBOY
Release: 2016-05-17 09:06:44
Original
1048 people have browsed it

yahoo对付伪造跨站请求的办法是在表单里加入一个叫.crumb的随机串;而facebook也有类似的解决办法,它的表单里常常会有post_form_id和fb_dtsg。

比较常见而且也很廉价的防范手段是在所有可能涉及用户写操作的表单中加入一个随机且变换频繁的字符串,然后在处理表单的时候对这个字符串进行检查。这个随机字符串如果和当前用户身份相关联的话,那么攻击者伪造请求会比较麻烦。现在防范方法基本上都是基于这种方法的了

随机串代码实现
咱们按照这个思路,山寨一个crumb的实现,代码如下:

复制代码 代码如下:

class Crumb { 
    CONST SALT = "your-secret-salt";                                                            
    static $ttl = 7200;                                                                                           
    static public function challenge($data) {   
        return hash_hmac('md5', $data, self::SALT);   
    }                                                                                                                
    static public function issueCrumb($uid, $action = -1) {   
        $i = ceil(time() / self::$ttl);   
        return substr(self::challenge($i . $action . $uid), -12, 10);   
    }                                                                                                                
    static public function verifyCrumb($uid, $crumb, $action = -1) {   
        $i = ceil(time() / self::$ttl);                                                                              
        if(substr(self::challenge($i . $action . $uid), -12, 10) == $crumb ||   
            substr(self::challenge(($i - 1) . $action . $uid), -12, 10) == $crumb)   
            return true;                                                                                       
        return false;   
    }                                                                                                              

代码中的$uid表示用户唯一标识,而$ttl表示这个随机串的有效时间。
应用示例
构造表单
在表单中插入一个隐藏的随机串crumb

复制代码 代码如下:

   
    
    
    
 
 

处理表单 demo.php
对crumb进行检查
复制代码 代码如下:

if(Crumb::verifyCrumb($uid, $_POST['crumb'])) {   
    //按照正常流程处理表单   
} else {   
    //crumb校验失败,错误提示流程   


本文出自包子博客
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template