PHP的CSRF攻击 [英] PHP CSRF Attack

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

问题描述

我想知道这段代码是否足够强大,以防止对PHP Form的CSRF攻击?

 <?php 
session_start();
session_regenerate_id(true);

if(isset($ _ SESSION ['token'])&&($ _POST ['token'])如果(isset($ _ POST ['submit'])){
if == $ _SESSION ['token'])){
}
}
$ token = hash('sha256',uniqid(mt_rand(),true));
$ _SESSION ['token'] = $ token;
?>

// FORM

< form method =POSTaction =page.php>
< input type =hiddenname =tokenvalue =<?php echo $ token;?>>
< input type =submitname =submit>
< / form>

谢谢。

解决方案如果受害者没有在您的网站上查看任何表格,他将不会在他的会话中存储令牌。



如果攻击者提供因为 $ _ POST ['token'] $ _ SESSION ['token'] 都将为空。 (或者两个空字符串都取决于PHP如何初始化未知变量)。

在检查之前,您还必须检查会话中的令牌是否存在如果其中任何一项测试失败,则平等和放弃。



根据您的网站,未见过表单的用户可能很可能或者可能是极端情况。首先检查令牌是否存在,无论您在网站上有多少表格,都不可能发生CSRF攻击。



除了那个小问题,我看不到任何CSRF漏洞。这段代码看起来好像会完成这项工作。


I want to know if this code is strong enough to prevent CSRF attack on PHP Form?

<?php
session_start();
session_regenerate_id(true);

if (isset($_POST['submit'])) {
if (isset($_SESSION['token']) && ($_POST['token'] == $_SESSION['token'])) {
}
}
$token = hash('sha256', uniqid(mt_rand(), true));
$_SESSION['token'] = $token;
?>

//FORM

<form method="POST" action="page.php">
<input type="hidden" name="token" value="<?php echo $token; ?>">
<input type="submit" name="submit">
</form>

Thanks.

解决方案

If the victim has not viewed any forms on your site, he will not yet have a token stored in his session.

If the attacker presents the victim with a form with no token field at all, the POST request made by the victim will pass the CSRF check because $_POST['token'] and $_SESSION['token'] will both be null. (Or both empty strings depending on how PHP initialises unknown variables.)

You must also check that the token exists in the session before checking for equality and abort if either of those tests fail.

Depending on your site, a user not having seen a form may be very likely or it may be an extreme edge case. With checking for the existence of the token first, it doesn't matter how many forms you have on your website, there is no possibility of a CSRF attack.

Apart from that small problem, I can't see any CSRF vulnerability in it. That code looks like it will do the job.

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

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