From 5ef9ee4254465230cc1f001b7224f85cf583d33a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Fri, 4 Sep 2020 12:15:14 +0200 Subject: [PATCH] crypto: fix randomInt range check Refs: https://github.com/nodejs/node/pull/34600 PR-URL: https://github.com/nodejs/node/pull/35052 Reviewed-By: Richard Lau Reviewed-By: Denys Otrishko Reviewed-By: Colin Ihrig --- lib/internal/crypto/random.js | 4 ++-- test/parallel/test-crypto-random.js | 17 ++++++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index 13a8030e671f8f..5f7f7efbf5b7c3 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -149,8 +149,8 @@ function randomInt(min, max, callback) { if (!NumberIsSafeInteger(max)) { throw new ERR_INVALID_ARG_TYPE('max', 'safe integer', max); } - if (!(max >= min)) { - throw new ERR_OUT_OF_RANGE('max', `>= ${min}`, max); + if (max <= min) { + throw new ERR_OUT_OF_RANGE('max', `> ${min}`, max); } // First we generate a random int between [0..range) diff --git a/test/parallel/test-crypto-random.js b/test/parallel/test-crypto-random.js index 67b63c42b52814..b3f14013e59a33 100644 --- a/test/parallel/test-crypto-random.js +++ b/test/parallel/test-crypto-random.js @@ -456,13 +456,16 @@ assert.throws( } ); - crypto.randomInt(0, common.mustCall()); - crypto.randomInt(0, 0, common.mustCall()); - assert.throws(() => crypto.randomInt(-1, common.mustNotCall()), { - code: 'ERR_OUT_OF_RANGE', - name: 'RangeError', - message: 'The value of "max" is out of range. It must be >= 0. Received -1' - }); + crypto.randomInt(1, common.mustCall()); + crypto.randomInt(0, 1, common.mustCall()); + for (const arg of [[0], [1, 1], [3, 2], [-5, -5], [11, -10]]) { + assert.throws(() => crypto.randomInt(...arg, common.mustNotCall()), { + code: 'ERR_OUT_OF_RANGE', + name: 'RangeError', + message: 'The value of "max" is out of range. It must be > ' + + `${arg[arg.length - 2] || 0}. Received ${arg[arg.length - 1]}` + }); + } const MAX_RANGE = 0xFFFF_FFFF_FFFF; crypto.randomInt(MAX_RANGE, common.mustCall());