crypto: coerce -0 to +0 before native calls

Signed-off-by: Filip Skokan <panva.ip@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/63556
Backport-PR-URL: https://github.com/nodejs/node/pull/64629
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Filip Skokan authored and Antoine du Hamel committed 2026-07-30 13:51:52 +02:00
1 parent c83b79874e
commit 73aba92689
7 files changed
+213 -14

No files matched your search

+10 -3
View File
@@ -108,7 +108,8 @@ function getUIntOption(options, key) {
if (options && (value = options[key]) != null) {
if (value >>> 0 !== value)
throw new ERR_INVALID_ARG_VALUE(`options.${key}`, value);
return value;
// Coerce -0 to +0.
return value + 0;
}
return -1;
}
@@ -265,10 +266,16 @@ function getCipherInfo(nameOrNid, options) {
if (options !== undefined) {
validateObject(options, 'options');
({ keyLength, ivLength } = options);
if (keyLength !== undefined)
if (keyLength !== undefined) {
validateInt32(keyLength, 'options.keyLength');
if (ivLength !== undefined)
// Coerce -0 to +0.
keyLength += 0;
}
if (ivLength !== undefined) {
validateInt32(ivLength, 'options.ivLength');
// Coerce -0 to +0.
ivLength += 0;
}
}
const ret = _getCipherInfo({}, nameOrNid, keyLength, ivLength);
+4 -1
View File
@@ -98,8 +98,11 @@ function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) {
// rejected with ERR_OSSL_BN_BITS_TOO_SMALL) by OpenSSL. The glue code
// in node_crypto.cc accepts values that are IsInt32() for that reason
// and that's why we do that here too.
if (typeof sizeOrKey === 'number')
if (typeof sizeOrKey === 'number') {
validateInt32(sizeOrKey, 'sizeOrKey');
// Coerce -0 to +0.
sizeOrKey += 0;
}
if (keyEncoding && !Buffer.isEncoding(keyEncoding) &&
keyEncoding !== 'buffer') {
+7 -2
View File
@@ -95,10 +95,13 @@ function Hash(algorithm, options) {
const isCopy = algorithm instanceof _Hash;
if (!isCopy)
validateString(algorithm, 'algorithm');
const xofLen = typeof options === 'object' && options !== null ?
let xofLen = typeof options === 'object' && options !== null ?
options.outputLength : undefined;
if (xofLen !== undefined)
if (xofLen !== undefined) {
validateUint32(xofLen, 'options.outputLength');
// Coerce -0 to +0.
xofLen += 0;
}
// Lookup the cached ID from JS land because it's faster than decoding
// the string in C++ land.
const algorithmId = isCopy ? -1 : getCachedHashId(algorithm);
@@ -288,6 +291,8 @@ function hash(algorithm, input, options) {
if (outputLength !== undefined) {
validateUint32(outputLength, 'outputLength');
// Coerce -0 to +0.
outputLength += 0;
}
if (outputLength === undefined) {
+2
View File
@@ -58,6 +58,8 @@ const validateParameters = hideStackFrames((hash, key, salt, info, length) => {
info = validateByteSource.withoutStackTrace(info, 'info');
validateInteger.withoutStackTrace(length, 'length', 0, kMaxLength);
// Coerce -0 to +0.
length += 0;
if (info.byteLength > 1024) {
throw new ERR_OUT_OF_RANGE.HideStackFramesError(
+24 -6
View File
@@ -219,14 +219,18 @@ function createJob(mode, type, options) {
case 'rsa-pss':
{
validateObject(options, 'options');
const { modulusLength } = options;
let { modulusLength } = options;
validateUint32(modulusLength, 'options.modulusLength');
// Coerce -0 to +0.
modulusLength += 0;
let { publicExponent } = options;
if (publicExponent == null) {
publicExponent = 0x10001;
} else {
validateUint32(publicExponent, 'options.publicExponent');
// Coerce -0 to +0.
publicExponent += 0;
}
if (type === 'rsa') {
@@ -239,11 +243,15 @@ function createJob(mode, type, options) {
}
const {
hash, mgf1Hash, hashAlgorithm, mgf1HashAlgorithm, saltLength,
hash, mgf1Hash, hashAlgorithm, mgf1HashAlgorithm,
} = options;
let { saltLength } = options;
if (saltLength !== undefined)
if (saltLength !== undefined) {
validateInt32(saltLength, 'options.saltLength', 0);
// Coerce -0 to +0.
saltLength += 0;
}
if (hashAlgorithm !== undefined)
validateString(hashAlgorithm, 'options.hashAlgorithm');
if (mgf1HashAlgorithm !== undefined)
@@ -284,14 +292,19 @@ function createJob(mode, type, options) {
case 'dsa':
{
validateObject(options, 'options');
const { modulusLength } = options;
let { modulusLength } = options;
validateUint32(modulusLength, 'options.modulusLength');
// Coerce -0 to +0.
modulusLength += 0;
let { divisorLength } = options;
if (divisorLength == null) {
divisorLength = -1;
} else
} else {
validateInt32(divisorLength, 'options.divisorLength', 0);
// Coerce -0 to +0.
divisorLength += 0;
}
return new DsaKeyPairGenJob(
mode,
@@ -321,7 +334,8 @@ function createJob(mode, type, options) {
case 'dh':
{
validateObject(options, 'options');
const { group, primeLength, prime, generator } = options;
const { group, prime } = options;
let { primeLength, generator } = options;
if (group != null) {
if (prime != null)
throw new ERR_INCOMPATIBLE_OPTION_PAIR('group', 'prime');
@@ -342,6 +356,8 @@ function createJob(mode, type, options) {
validateBuffer(prime, 'options.prime');
} else if (primeLength != null) {
validateInt32(primeLength, 'options.primeLength', 0);
// Coerce -0 to +0.
primeLength += 0;
} else {
throw new ERR_MISSING_OPTION(
'At least one of the group, prime, or primeLength options');
@@ -349,6 +365,8 @@ function createJob(mode, type, options) {
if (generator != null) {
validateInt32(generator, 'options.generator', 0);
// Coerce -0 to +0.
generator += 0;
}
return new DhKeyPairGenJob(
mode,
+6 -2
View File
@@ -603,12 +603,14 @@ function checkPrime(candidate, options = kEmptyObject, callback) {
}
validateFunction(callback, 'callback');
validateObject(options, 'options');
const {
let {
checks = 0,
} = options;
// The checks option is unsigned but must fit into a signed C int for OpenSSL.
validateInt32(checks, 'options.checks', 0);
// Coerce -0 to +0.
checks += 0;
const job = new CheckPrimeJob(kCryptoJobAsync, candidate, checks);
job.ondone = callback;
@@ -632,12 +634,14 @@ function checkPrimeSync(candidate, options = kEmptyObject) {
);
}
validateObject(options, 'options');
const {
let {
checks = 0,
} = options;
// The checks option is unsigned but must fit into a signed C int for OpenSSL.
validateInt32(checks, 'options.checks', 0);
// Coerce -0 to +0.
checks += 0;
const job = new CheckPrimeJob(kCryptoJobSync, candidate, checks);
const { 0: err, 1: result } = job.run();
+160
View File
@@ -0,0 +1,160 @@
'use strict';
const common = require('../common');
if (!common.hasCrypto)
common.skip('missing crypto');
const assert = require('assert');
const crypto = require('crypto');
const { hasOpenSSL } = require('../common/crypto');
function getOutcome(fn) {
try {
return { result: fn() };
} catch (err) {
return { err };
}
}
function assertSameOutcome(actual, expected) {
if (expected.err !== undefined) {
assert(actual.err instanceof Error);
assert.strictEqual(actual.err.name, expected.err.name);
assert.strictEqual(actual.err.code, expected.err.code);
assert.strictEqual(actual.err.message, expected.err.message);
} else {
assert.deepStrictEqual(actual.result, expected.result);
}
}
function assertSameErrorOrSuccess(actual, expected) {
if (expected.err !== undefined) {
assert(actual.err instanceof Error);
assert.strictEqual(actual.err.name, expected.err.name);
assert.strictEqual(actual.err.code, expected.err.code);
assert.strictEqual(actual.err.message, expected.err.message);
} else {
assert.strictEqual(actual.err, undefined);
}
}
{
const expected = getOutcome(() =>
crypto.hkdfSync('sha256', 'key', 'salt', 'info', 0),
);
assertSameOutcome(
getOutcome(() => crypto.hkdfSync('sha256', 'key', 'salt', 'info', -0)),
expected,
);
crypto.hkdf('sha256', 'key', 'salt', 'info', -0,
common.mustCall((err, result) => {
assertSameOutcome({ err, result }, expected);
}));
}
{
assert.strictEqual(
crypto.checkPrimeSync(Buffer.from([3]), { checks: -0 }),
true,
);
crypto.checkPrime(Buffer.from([3]), { checks: -0 },
common.mustSucceed((result) => {
assert.strictEqual(result, true);
}));
}
{
assert.throws(() => crypto.createDiffieHellman(-0, 2), {
name: 'Error',
});
}
{
for (const [type, getOptions] of [
['rsa', (zero) => ({ modulusLength: zero })],
['rsa', (zero) => ({ modulusLength: 512, publicExponent: zero })],
['rsa-pss', (zero) => ({
modulusLength: 512,
publicExponent: 65537,
saltLength: zero,
})],
['dsa', (zero) => ({ modulusLength: zero })],
['dh', (zero) => ({ primeLength: zero })],
['dh', (zero) => ({ primeLength: 2, generator: zero })],
]) {
assertSameErrorOrSuccess(
getOutcome(() => crypto.generateKeyPairSync(type, getOptions(-0))),
getOutcome(() => crypto.generateKeyPairSync(type, getOptions(0))),
);
}
if (!hasOpenSSL(3)) {
common.printSkipMessage(
'Skipping DSA divisorLength 0 key generation on OpenSSL 1.1.1');
} else {
assertSameErrorOrSuccess(
getOutcome(() => crypto.generateKeyPairSync('dsa', {
modulusLength: 512,
divisorLength: -0,
})),
getOutcome(() => crypto.generateKeyPairSync('dsa', {
modulusLength: 512,
divisorLength: 0,
})),
);
}
crypto.generateKeyPair('rsa', { modulusLength: -0 },
common.mustCall((err) => {
assert(err instanceof Error);
}));
}
if (!process.features.openssl_is_boringssl) {
assert.strictEqual(
crypto.createHash('shake128', { outputLength: -0 }).digest('hex'),
'',
);
assert.strictEqual(
crypto.createHash('shake128', { outputLength: 5 })
.copy({ outputLength: -0 })
.digest('hex'),
'',
);
assert.strictEqual(
crypto.hash('shake128', 'data', { outputLength: -0 }),
'',
);
}
{
const key = Buffer.alloc(16);
const iv = Buffer.alloc(12);
assertSameErrorOrSuccess(
getOutcome(() => crypto.createCipheriv(
'aes-128-gcm', key, iv, { authTagLength: -0 })),
getOutcome(() => crypto.createCipheriv(
'aes-128-gcm', key, iv, { authTagLength: 0 })),
);
assertSameErrorOrSuccess(
getOutcome(() => crypto.createCipheriv(
'aes-128-gcm', key, iv).setAAD(
Buffer.alloc(0),
{ plaintextLength: -0 },
)),
getOutcome(() => crypto.createCipheriv(
'aes-128-gcm', key, iv).setAAD(
Buffer.alloc(0),
{ plaintextLength: 0 },
)),
);
assert.strictEqual(
crypto.getCipherInfo('aes-128-cbc', { keyLength: -0 }),
undefined,
);
assert.strictEqual(
crypto.getCipherInfo('aes-128-cbc', { ivLength: -0 }),
undefined,
);
}