Skip to content

Commit fe22982

Browse files
committed
fix: always perform timing safe euqal check on PKCE challenge
1 parent e2fcac4 commit fe22982

2 files changed

Lines changed: 11 additions & 4 deletions

File tree

lib/grant-types/authorization-code-grant-type.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,7 @@ class AuthorizationCodeGrantType extends AbstractGrantType {
160160

161161
// xxx: Use timingSafeEqual to prevent against timing attacks when comparing
162162
// the hash of the code_verifier to the stored code_challenge.
163-
const hashesAreEqual = crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(code.codeChallenge));
164-
165-
if (!hashesAreEqual) {
163+
if (!this.hashesAreEqual(hash, code.codeChallenge)) {
166164
throw new InvalidGrantError('Invalid grant: code verifier is invalid');
167165
}
168166
}
@@ -174,6 +172,15 @@ class AuthorizationCodeGrantType extends AbstractGrantType {
174172
}
175173
}
176174

175+
hashesAreEqual(trusted, untrusted) {
176+
const trustedBuf = Buffer.isBuffer(trusted) ? trusted : Buffer.from(trusted);
177+
const untrustedBuf = Buffer.isBuffer(untrusted) ? untrusted : Buffer.from(untrusted);
178+
const equalLength = trustedBuf.byteLength === untrustedBuf.byteLength;
179+
// if the buffers are the same length, compare them,
180+
// otherwise only compare with the trusted buffer but return false anyway
181+
return crypto.timingSafeEqual(trustedBuf, equalLength ? untrustedBuf : trustedBuf) && equalLength;
182+
}
183+
177184
getCodeChallengeMethod(method) {
178185
if (method) {
179186
return method;

test/compliance/pkce_test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ const { base64URLEncode } = require('../../lib/utils/string-util');
4545
const { createHash } = require('../../lib/utils/crypto-util');
4646
const { InvalidRequestError } = require('../../index');
4747
const ServerError = require('../../lib/errors/server-error');
48-
const InvalidGrantError = require('../../lib/errors/invalid-grant-error')
48+
const InvalidGrantError = require('../../lib/errors/invalid-grant-error');
4949
require('chai').should();
5050

5151
/**

0 commit comments

Comments
 (0)