php - 随机 sleep 可以防止定时攻击吗?

标签 php security cryptography timing timing-attack

来自 Wikipedia

In cryptography, a timing attack is a side channel attack in which the attacker attempts to compromise a cryptosystem by analyzing the time taken to execute cryptographic algorithms.

实际上,为了防止定时攻击,我使用了以下来自 this answer 的函数:

function timingSafeCompare($safe, $user) {
    // Prevent issues if string length is 0
    $safe .= chr(0);
    $user .= chr(0);

    $safeLen = strlen($safe);
    $userLen = strlen($user);

    // Set the result to the difference between the lengths
    $result = $safeLen - $userLen;

    // Note that we ALWAYS iterate over the user-supplied length
    // This is to prevent leaking length information
    for ($i = 0; $i < $userLen; $i++) {
        // Using % here is a trick to prevent notices
        // It's safe, since if the lengths are different
        // $result is already non-0
        $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i]));
    }

    // They are only identical strings if $result is exactly 0...
    return $result === 0;
}

但我在想是否有可能使用随机 sleep 来防止这种攻击

function timingSafeCompare($a,$b) {
    sleep(rand(0,100));
    if ($a === $b) {
        return true;
    } else {
        return false;
    }
}

或者可能增加 sleep 的随机性

sleep(rand(1,10)+rand(1,10)+rand(1,10)+rand(1,10));

这种做法完全可以防止定时攻击?或者只是让工作更难?

最佳答案

This kind of approach can totally prevent timing attacks? Or just make the work harder?

都没有。它不会阻止计时攻击,也不会增加它们的难度。

要了解原因,请查看 docs for sleep .具体第一个参数的含义:

Halt time in seconds.

因此您的应用需要 0.3 秒才能在不休眠的情况下做出响应。 sleep 需要 0.3、1.3、2.3 等...

所以真的,为了得到我们关心的部分(时间差异),我们只需要砍掉整数部分:

$real_time = $time - floor($time);

但让我们更进一步。假设您使用 usleep 随机休眠.这要细化得多。那就是在几微秒内休眠。

好吧,测量是在 15-50 秒的范围内进行的。因此, sleep 的粒度仍然比正在进行的测量大约 100 倍。所以我们可以平均到单个微秒:

$microseconds = $time * 1000000;
$real_microseconds = $microseconds - floor($microseconds);

并且仍然有有意义的数据。

你可以走得更远,使用 time_nanosleep它可以休眠到纳秒级精度。

然后你就可以开始玩弄数字了。

但是数据还在。随机性的美妙之处在于您可以将其平均化:

$x = 15 + rand(1, 10000);

运行足够多次,你会得到一个漂亮的图表。您会发现大约有 10000 个不同的数字,因此您可以平均掉随机性并推断出“私有(private)”15。

由于良好的随机性是无偏的,因此很容易通过足够大的样本进行统计检测。

所以我要问的问题是:

当您可以正确解决问题时,为什么还要费心进行类似 sleep 的黑客攻击?

关于php - 随机 sleep 可以防止定时攻击吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28395665/

相关文章:

php - 将 MySQL 查询结果合并为一条记录

PHP 在不使用列名的情况下动态回显查询结果列

php - 从经纬度获取国家名称

java - Spring-Security:Spring-Security 中/** 和/* url 模式的区别

C# RSA 使用给定的 PKCS#1 公钥加密文本

php - 我想删除 Framesets 和 Iframes 并且仍然有独立的页面刷新 PHP 数据而不刷新整个页面

ruby-on-rails - 生产服务器上的 Rails 安全性

java - 如何在 glassfish 3 中使用 ssl 传输登录凭据

c++ - 使用MSVC在Windows上编译报错Botan库

cryptography - C# HMACSHA1 哈希不正确