在PHP中没有Cookie的CSRF令牌 [英] CSRF token without cookies in PHP

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

问题描述

我正在寻找一种方法来添加CSRF令牌到我正在做的应用程序。注意,应用程序目前不使用Cookie或会话。

I am looking for a way to add a CSRF token to an application I'm making. The caveat is, the application does not currently use cookies or sessions.

我想找到一种方法来引入CSRF令牌,而不必:

I would love to find a way to introduce a CSRF token without having to:


  1. 在我的申请中介绍状态。

  2. 使用工作阶段或Cookie( $ _ SESSION / $ _ COOKIE )存储

  1. Introduce state in my application.
  2. Use session or cookie ($_SESSION / $_COOKIE) storage

可能性,或者我在我的应用程序中卡住了创建新状态。

Is this at all a possibility, or am I stuck creating new state in my application.

推荐答案

你可以,但不会很安全。

You can, but it's not going to be very secure.

这里有一个例子但是不要使用它,这是一个很糟糕的想法

// Do this somewhere
define('CSRF_SALT', '4dedMj4CWgBMNhRsoTpJlokwB5wTz7UsmF8Mq4uzFIbv');

$token = base64_encode(
    hash_hmac(
        'sha256', 
        date('Ymd') . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'],
        CSRF_SALT,
        true
    )
);

if (\hash_equals($_POST['security_token'], $token)) {
    // Form passes validation
}

缺点是这些令牌本质上是可重用的,所以如果一个泄漏的攻击者可以简单地重用(或重新计算)。您也可以尝试在哈希计算中添加表单action =。

The downside is that these tokens are inherently reusable, so if one leaks an attacker can simply reuse (or recalculate) it. You can also try adding the form action="" value in the hash calculation.

function getToken($action)
{
    return base64_encode(
        hash_hmac(
            'sha256', 
            hash_hmac(
                'sha256',
                date('Ymd') . $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'],
                hash('sha256', $action, true),
                true
            ),
            CSRF_SALT,
            true
        )
    );
}

echo "<form action='register.php' method='post'>\n";
echo "<input type='hidden' name='security_token' value='".getToken('register.php')."' />\n";
// ...

你们对会话的厌恶是什么?

What's your anathema for sessions anyway?

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

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