Skip to content

Commit

Permalink
Prevent subtler timing attack in token comparison function
Browse files Browse the repository at this point in the history
  • Loading branch information
ycombinator committed May 23, 2018
1 parent a95f1e0 commit ce0c080
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions x-pack/plugins/beats/server/lib/crypto/are_tokens_equal.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@

import { timingSafeEqual } from 'crypto';

const RANDOM_TOKEN_1 = 'b48c4bda384a40cb91c6eb9b8849e77f';
const RANDOM_TOKEN_2 = '80a3819e3cd64f4399f1d4886be7a08b';

export function areTokensEqual(token1, token2) {
return token1.length === token2.length
&& timingSafeEqual(Buffer.from(token1, 'utf8'), Buffer.from(token2, 'utf8'));
if ((typeof token1 !== 'string') || (typeof token2 !== 'string') || (token1.length !== token2.length)) {
// This prevents a more subtle timing attack where we know already the tokens aren't going to
// match but still we don't return fast. Instead we compare two pre-generated random tokens using
// the same comparison algorithm that we would use to compare two equal-length tokens.
return timingSafeEqual(Buffer.from(RANDOM_TOKEN_1, 'utf8'), Buffer.from(RANDOM_TOKEN_2, 'utf8'));
}

return timingSafeEqual(Buffer.from(token1, 'utf8'), Buffer.from(token2, 'utf8'));
}

0 comments on commit ce0c080

Please sign in to comment.