Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

forms - PHP CSRF Attack

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...