php跨站攻击的原理与防范技巧及token实例分析

分类:PHP_Python| 发布:llmaomi| 查看:281 | 发表时间:2015/5/31

跨站攻击就是利用程序上的一些细节或bug问题进行的,那么我们要如何耿防止跨站攻击呢?下面就以一个防止跨站攻击例子来说明,希望对各位有帮助。

代码如下:
01<?php
02 #demo for prevent csrf
03 /**
04 * enc
05 */
06 function encrypt($token_time) {
07 return md5('!@##$@$$#%43' . $token_time);
08 }
09 $token_time = time();
10 $token = encrypt($token_time);
11 $expire_time = 10;
12 if ($_POST) {
13 $_token_time = $_POST['token_time'];
14 $_token = $_POST['token'];
15 if ((time() – $_token_time) > $expire_time) {
16 echo "expired token";
17 echo
18”;
19 }
20 echo $_token;
21 echo "
22";
23 $_token_real = encrypt($_token_time);
24 echo $_token_real;
25 //compare $_token and $_token_real
26 }
27 ?>
28 <!DOCTYPE html>
29 <html>
30 <head>
31 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
32 <title>test for csrf - camnpr</title>
33 <meta http-equiv="" content="" />
34 </head>
35 <body>
36 <form method="post" action="">
37 <input type="text" name="text" id="" value="hello" />
38 <input type="hidden" name="token" id="" value="<?php echo $token ?>" />
39 <input type="hidden" name="token_time" id="" value="<?php echo $token_time ?>" />
40 <input type="submit" name="submit" id="" value="submit" />
41 </form>
42 </body>
43 </html>


 
通过在你的表单中包括验证码,你事实上已经消除了跨站请求伪造攻击的风险。可以在任何需要执行操作的任何表单中使用这个流程
当然,将token 存储到session更好,这里只是简单示例下

简单分析:

token防攻击也叫作令牌,我们在用户访问页面时就生成了一个随机的token保存session与表单了,用户提交时如果我们获取到的token与session不一样就可以提交重新输入提交数据了

365据说看到好文章不转的人,服务器容易宕机
原创文章如转载,请注明:转载自郑州网建-前端开发 http://camnpr.com/
本文链接:http://camnpr.com/php-python/2020.html