Skip to content

Commit

Permalink
Merge pull request from GHSA-376v-xgjx-7mfr
Browse files Browse the repository at this point in the history
* Correctly use crypto.timingSafeEqual

Signed-off-by: Matteo Collina <hello@matteocollina.com>
Co-Authored-By: Uzlopak <aras.abbasi@googlemail.com>

* apply requested change

Co-authored-by: Uzlopak <aras.abbasi@googlemail.com>
  • Loading branch information
mcollina and Uzlopak committed Jul 13, 2022
1 parent cb61d1f commit 0c468a6
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
19 changes: 14 additions & 5 deletions plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ function verifyBearerAuthFactory (options) {
if (_options.keys instanceof Set) _options.keys = Array.from(_options.keys)
const { keys, errorResponse, contentType, bearerType, auth, addHook = true, verifyErrorLogLevel = 'error' } = _options

for (let i = 0, il = keys.length; i < il; ++i) {
if (typeof keys[i] !== 'string') {
throw new Error('options.keys has to contain only string entries')
}
keys[i] = Buffer.from(keys[i])
}

return function verifyBearerAuth (request, reply, done) {
const header = request.raw.headers.authorization
if (!header) {
Expand Down Expand Up @@ -89,17 +96,19 @@ function verifyBearerAuthFactory (options) {
}

function authenticate (keys, key) {
return keys.findIndex((a) => compare(a, key)) !== -1
const b = Buffer.from(key)
return keys.findIndex((a) => compare(a, b)) !== -1
}

// perform constant-time comparison to prevent timing attacks
function compare (a, b) {
try {
// may throw if they have different length, can't convert to Buffer, etc...
return crypto.timingSafeEqual(Buffer.from(a), Buffer.from(b))
} catch {
if (a.length !== b.length) {
// Delay return with cryptographically secure timing check.
crypto.timingSafeEqual(a, a)
return false
}

return crypto.timingSafeEqual(a, b)
}

function plugin (fastify, options, done) {
Expand Down
8 changes: 8 additions & 0 deletions test/decorate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,11 @@ test('verifyBearerAuthFactory', (t) => {
t.ok(fastify.verifyBearerAuthFactory)
})
})

test('verifyBearerAuthFactory', (t) => {
t.plan(1)
fastify.ready(() => {
const keys = { keys: new Set([123456]) }
t.throws(() => fastify.verifyBearerAuthFactory(keys), /keys has to contain only string entries/)
})
})

0 comments on commit 0c468a6

Please sign in to comment.