gpt4 book ai didi

PHP 安全 : 'Nonce' or 'unique form key' problem

转载 作者:可可西里 更新时间:2023-11-01 00:38:03 27 4
gpt4 key购买 nike

我使用此类(取自博客教程)生成唯一键来验证表单:

class formKey {
//Here we store the generated form key
private $formKey;

//Here we store the old form key
private $old_formKey;

//The constructor stores the form key (if one excists) in our class variable
function __construct() {
//We need the previous key so we store it
if(isset($_SESSION['form_key'])) {
$this->old_formKey = $_SESSION['form_key'];
}
}

//Function to generate the form key
private function generateKey() {
//Get the IP-address of the user
$ip = $_SERVER['REMOTE_ADDR'];

//We use mt_rand() instead of rand() because it is better for generating random numbers.
//We use 'true' to get a longer string.
$uniqid = uniqid(mt_rand(), true);

//Return the hash
return md5($ip . $uniqid);
}

//Function to output the form key
public function outputKey() {
//Generate the key and store it inside the class
$this->formKey = $this->generateKey();
//Store the form key in the session
$_SESSION['form_key'] = $this->formKey;

//Output the form key
// echo "<input type='hidden' name='form_key' id='form_key' value='".$this->formKey."' />";
return $this->formKey;
}

//Function that validated the form key POST data
public function validate() {
//We use the old formKey and not the new generated version
if($_POST['form_key'] == $this->old_formKey) {
//The key is valid, return true.
return true;
}
else {
//The key is invalid, return false.
return false;
}
}
}

我网站上的所有内容都首先通过 index.php,所以我将它放在 index.php 中:$formKey = new formKey();

然后,在每一种形式中我都输入:<?php $formKey->outputKey(); ?>

生成这个:<input type="hidden" name="form_key" id="form_key" value="7bd8496ea1518e1850c24cf2de8ded23" />

然后我可以简单地检查 if(!isset($_POST['form_key']) || !$formKey->validate())

我有两个问题。第一:我不能在每个页面使用多个表单,因为只有最后生成的 key 才会生效。

其次:因为一切都首先通过 index.php,如果我使用 ajax 验证表单,第一次会验证但第二次不会,因为 index.php 生成一个新 key ,但包含表单的页面会' t 刷新,因此表单 key 未更新..

我已经尝试了几件事,但我无法让它工作。也许你可以更新/修改代码/类来让它工作??谢谢!!!

最佳答案

您可以将它放入一个类中,但这是不必要的复杂性。简单的安全系统是最好的,因为它们更容易审计。

//Put this in a header file
session_start();
if(!$_SESSION['xsrf_token']){
//Not the best but this should be enough entropy
$_SESSION['xsrf_token']=uniqid(mt_rand(),true);
}
//$_REQUEST is used because you might need it for a GET or POST request.
function validate_xsrf(){
return $_SESSION['xsrf_token']==$_REQUEST['xsrf_token'] && $_SESSION['xsrf_token'];
}
//End of header file.

额外的 && $_SESSION['xsrf_token'] 确保填充此变量。它在那里确保实现安全失败。 (就像你忘记了头文件一样!;)

下面的 html/php 放在任何你想防止 XSRF 的文件中,确保你的头文件中有上面的代码。

if(validate_xsrf()){
//do somthing with $_POST
}

这就是打印表单所需的全部内容,再次确保在执行任何操作之前调用 session_start();,多次调用也没关系。

<input type="hidden" name="xsrf_token" id="form_key" value="<?=$_SESSION['xsrf_token']?>" />

关于PHP 安全 : 'Nonce' or 'unique form key' problem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3183049/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com