防止PHP中的CSRF [英] preventing csrf in php

查看:437
本文介绍了防止PHP中的CSRF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 需要GET和 POST参数,不仅是cookie;

  1. Requiring authentication in GET and POST parameters, not only cookies;

检查HTTP Referer标头;

Checking the HTTP Referer header;

在Wikipedia上看到了这篇文章,想知道如何应用它们

saw this post on wikipedia and was wondering how I can apply them

好...我正在使用Kohana PHP框架,并且具有确定引荐来源标头的功能,但是究竟要检查引荐来源标头什么呢?框架函数仅返回引用者的URL

ok...I am using the Kohana PHP framework and I have the facility to determine the referrer header, but what exactly do I check in the referrer header? the framework function only returns the URL of the referrer

以及如何验证GET和POST参数?反对什么?存储的信息?预期的类型?

and how do I validate GET and POST params? against what? stored information? expected type?

推荐答案

为防止CSRF,您需要验证一次令牌,该令牌已过POST,并与当前会话相关联.类似以下内容. .

To prevent CSRF you'll want to validate a one-time token, POST'ed and associated with the current session. Something like the following . . .

在用户请求删除记录的页面上:

On the page where the user requests to delete a record:

confirm.php

<?php
 session_start();
 $token = isset($_SESSION['delete_customer_token']) ? $_SESSION['delete_customer_token'] : "";
 if (!$token) {
     // generate token and persist for later verification
     // - in practice use openssl_random_pseudo_bytes() or similar instead of uniqid() 
     $token = md5(uniqid());
     $_SESSION['delete_customer_token']= $token;
 }
 session_write_close();
?>
<html>
<body>
<form method="post" action="confirm_save.php">
 <input type="hidden" name="token" value="<?php echo $token; ?>" />
Do you really want to delete?
<input type="submit" value=" Yes " />
<input type="button" value=" No " onclick="history.go(-1);" />
</form>
</body>
</html>

然后要实际删除记录:

confirm_save.php

<?php
 session_start();
 // validate token
 $token = isset($_SESSION['delete_customer_token']) ? $_SESSION['delete_customer_token'] : "";
 if ($token && $_POST['token'] === $token) {
   // delete the record
   ...
   // remove token after successful delete
   unset($_SESSION['delete_customer_token']);
 } else {
   // log potential CSRF attack.
 }
 session_write_close();
?>

令牌应该很难猜测,对于每个删除请求都是唯一的,只能通过$ _POST接受并且在几分钟后过期(此示例中未显示过期).

The token should be hard to guess, unique for each delete request, accepted via $_POST only and expire after a few minutes (expiration not shown in this example).

这篇关于防止PHP中的CSRF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆