我试图在表单上实现简单的CSRF保护,但我无法做到正确。如果有人可以指出我做错了什么,我将不胜感激。
错误:每次提交表单时,我都会收到" Invalid Submission2"因为令牌更改(在提交表单之后),因为是在同一页面上生成的吗?
编辑 - 我忘了提及,另一个文件(config.php)已经有session_start()。
<?php
class Module_Post extends Base_Module {
public function start()
{
requireLogin();
if (isset($_GET['act'])) {
switch($_GET['act']) {
case 'text':
$this->text();
break;
case 'image':
$this->image();
break;
default:
$this->text();
break;
}
} else {
$this->text();
}
}
private function text()
{
// Generate random unique token to prevent cross-site request forgery (CSRF).
if(empty($_SESSION['form_token']))
{
$form_token = md5(uniqid(rand(), TRUE));
$_SESSION['form_token'] = $form_token;
}
if(isset($_POST['submit']))
{
// Clean the content from cross-site scripting (xss)
$content = trim($_POST['content']);
$content = Xss::clean($content);
// Validate that the form token
if(!isset($_POST['form_token'], $_SESSION['form_token'])) {
$err = 'Invalid Submission';
} elseif ($_POST['form_token'] != $_SESSION['form_token']) {
$err = 'Invalid Submission2';
} elseif (strlen($content) < 10) {
$err = 'Your content contains too few characters.';
}
if(isset($err)) {
unset( $_SESSION['form_token']);
$this->setMessage($err, 'FAIL');
header('Location: index.php?mod=post');
exit;
}
// Insert database data here, then redirect
$this->setMessage('Your post was published successfully.', 'GOOD');
header('Location: index.php');
exit;
}
$this->tpl->assign('form_token', $form_token);
$this->tpl->display('new/text.tpl');
}
}
?>
HTML(text.tpl文件)
<form method='post' enctype='multipart/form-data' action='#'>
<fieldset>
<textarea rows="8" id="new_post" name="content" class="input-block-level"></textarea>
<input type="hidden" name="form_token" value="{$form_token}" />
<button type="submit" name="submit" class="btn btn-info pull-left">Create Post</button>
</fieldset>
</form>
答案 0 :(得分:1)
您需要更改此行
$this->tpl->assign('form_token', $form_token);
成:
$this->tpl->assign('form_token', $_SESSION['form_token']);
那是因为你只使用这个条件生成你的令牌:
if(empty($_SESSION['form_token']))
{
$form_token = md5(uniqid(rand(), TRUE));
$_SESSION['form_token'] = $form_token;
}
并使用此条件取消设置:
if(isset($err)) {
unset( $_SESSION['form_token']);
}
因此,如果您发送一次表单然后重新加载页面(不提交表单只是url),$form_token
变量未知,因为$_SESSION['form_token']
不为空,然后在您的表单中您有空令牌
如果您在PHP中显示错误,则在本例中将在PHP中看到:
Undefined variable: form_token in