【发布时间】:2017-10-08 21:30:10
【问题描述】:
有些人建议使用简单的字符串比较来匹配密码是不安全的,因为timing attacks。例如参见this question。 好吧,我试图测量 node.js 中两次密码猜测之间的时间差。 代码如下:
const pass = '................................................................';
const guess1 = '..X.............................................................';
const guess2 = '.............................................................X..';
function ns(hrtime) {
return hrtime[0] * 1e9 + hrtime[1];
}
test(guess1);
test(guess2);
test(guess1);
test(guess2);
test(guess1);
test(guess2);
test(guess1);
test(guess2);
test(guess1);
test(guess2);
test(guess1);
test(guess2);
function test(guess) {
const start = process.hrtime();
for (let i = 0; i < 1e5; ++i) {
if (guess === pass) throw new Error('HIT');
}
const time = ns(process.hrtime(start));
console.log('%d ns %s', time, guess);
}
这是我机器上一次执行的结果:
2073045 ns ..X.............................................................
58420 ns .............................................................X..
57778 ns ..X.............................................................
57468 ns .............................................................X..
57554 ns ..X.............................................................
57436 ns .............................................................X..
57589 ns ..X.............................................................
57798 ns .............................................................X..
57798 ns ..X.............................................................
57506 ns .............................................................X..
57969 ns ..X.............................................................
57974 ns .............................................................X..
时间和不同的密码猜测之间似乎没有相关性。 是我做错了什么还是真的没有可测量的时差?
【问题讨论】:
-
人们没有冒这个险。做一些研究,因为已经写了很多关于这个主题的文章,仅仅因为你没有在第一次尝试时复制它并不意味着它不存在。请参阅 Timing Attacks against String Comparison 和 Using node.js event loop for timing attacks 以及在 Google 搜索中轻松找到的数百个其他参考资料。
-
补充一下我之前的评论,是否存在实际的时序风险取决于使用的精确环境和代码。因此,为了评估时序风险,必须展示一些生产代码的真实示例。为了避免担心您是否遇到具有此类风险的情况,许多人只会选择使用时间中性比较作为最简单的安全方法。
标签: javascript node.js security