diff --git a/doc/api/crypto.md b/doc/api/crypto.md index cb8e2186c423..3e63f305c8f8 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -5425,7 +5425,8 @@ OID or one of `commonName`/`CN`, `countryName`/`C`, `localityName`/`L`, `stateOrProvinceName`/`ST`, `organizationName`/`O`, `organizationalUnitName`/`OU`, `serialNumber`, `streetAddress`, `postalCode`, `domainComponent`/`DC`, `userId`/`UID`, -`emailAddress`/`E`, `title`, `surname`/`SN`, or `givenName`/`GN`. +`emailAddress`/`E`, `title`, `surname`/`SN`, or `givenName`/`GN`. `value` must +not contain NUL characters. ```js const subject = [ @@ -5496,13 +5497,14 @@ const extensions = [ ASCII strings without NUL and are not otherwise validated. * Subject Key Identifier: `type: 'subjectKeyIdentifier'` and `value: 'auto'` or `value` {ArrayBuffer|TypedArray|Buffer|DataView}. A binary value contains the - key identifier bytes, not DER. `'auto'` uses [RFC 7093][] method 1: the - leftmost 160 bits of the SHA-256 digest of the `subjectPublicKey` BIT STRING - contents. This typed form is always noncritical. + nonempty key identifier bytes, not DER. `'auto'` uses [RFC 7093][] method 1: + the leftmost 160 bits of the SHA-256 digest of the `subjectPublicKey` BIT + STRING contents. This typed form is always noncritical. * Authority Key Identifier: `type: 'authorityKeyIdentifier'` and `value: 'auto'` or `value` - {ArrayBuffer|TypedArray|Buffer|DataView}. A binary value contains the key - identifier bytes and populates only the extension's `keyIdentifier` field. + {ArrayBuffer|TypedArray|Buffer|DataView}. A binary value contains the + nonempty key identifier bytes and populates only the extension's + `keyIdentifier` field. When `options.issuer` is supplied, `'auto'` asks the configured crypto backend to decode and copy its Subject Key Identifier. If the extension is absent, the identifier is instead derived from the issuer public key using diff --git a/lib/internal/crypto/sig.js b/lib/internal/crypto/sig.js index b94755ac7d88..7090e9792870 100644 --- a/lib/internal/crypto/sig.js +++ b/lib/internal/crypto/sig.js @@ -85,8 +85,8 @@ function getPadding(options, name = 'options') { return getIntOption('padding', options, name); } -function getSaltLength(options, name = 'options') { - let saltLength = getIntOption('saltLength', options, name); +function getSaltLength(options) { + let saltLength = getIntOption('saltLength', options, 'options'); if (options.padding === constants.RSA_PKCS1_PSS_PADDING && saltLength === undefined) { saltLength = constants.RSA_PSS_SALTLEN_MAX_SIGN; } @@ -321,6 +321,6 @@ module.exports = { signOneShot, Verify, verifyOneShot, + getIntOption, getPadding, - getSaltLength, }; diff --git a/lib/internal/crypto/x509_generation.js b/lib/internal/crypto/x509_generation.js index dd890f4870a5..c57958e59e1a 100644 --- a/lib/internal/crypto/x509_generation.js +++ b/lib/internal/crypto/x509_generation.js @@ -36,8 +36,8 @@ const { preparePublicOrPrivateKey, } = require('internal/crypto/keys'); const { + getIntOption, getPadding, - getSaltLength, } = require('internal/crypto/sig'); const { @@ -58,6 +58,7 @@ const { validateInteger, validateObject, validateString, + validateStringWithoutNullBytes, } = require('internal/validators'); const { @@ -170,8 +171,8 @@ function snapshotCertificateRequest(value) { ]); } -function validateUnicode(value, name) { - validateString(value, name); +function validateUnicodeWithoutNul(value, name) { + validateStringWithoutNullBytes(value, name); if (!StringPrototypeIsWellFormed(value)) { throw new ERR_INVALID_ARG_VALUE( name, value, 'contains an unpaired surrogate'); @@ -206,7 +207,7 @@ function normalizeNameAttribute(attribute, name) { if (ObjectPrototypeHasOwnProperty(kNameAttributes, attributeName)) { oid = kNameAttributes[attributeName]; } - validateUnicode(value, `${name}.value`); + validateUnicodeWithoutNul(value, `${name}.value`); return [oid, value]; } @@ -433,12 +434,18 @@ function normalizeExtensions(extensions, arrayPath = 'options.extensions') { case 'subjectKeyIdentifier': case 'authorityKeyIdentifier': { const value = getRequired(extension, 'value', `${path}.value`); + const identifier = + value === 'auto' ? undefined : snapshotBinary(value, `${path}.value`); + if (identifier?.length === 0) { + throw new ERR_INVALID_ARG_VALUE( + `${path}.value`, value, 'must not be empty'); + } normalized = [ type === 'subjectKeyIdentifier' ? kExtensionSubjectKeyIdentifier : kExtensionAuthorityKeyIdentifier, false, - value === 'auto' ? undefined : snapshotBinary(value, `${path}.value`), + identifier, ]; break; } @@ -531,7 +538,8 @@ function normalizeOptions(options, mode) { } = preparePrivateKey(signingKey, 'options.signature.key'); const digest = getRequired(signature, 'digest', 'options.signature.digest'); if (digest !== null) validateString(digest, 'options.signature.digest'); - const saltLength = getSaltLength(signingKey, 'options.signature.key'); + const saltLength = getIntOption( + 'saltLength', signingKey, 'options.signature.key'); const padding = getPadding(signingKey, 'options.signature.key'); let extensions; if (csr !== undefined) { diff --git a/src/crypto/crypto_x509_gen.cc b/src/crypto/crypto_x509_gen.cc index 36edf9df2589..3f2345aae74e 100644 --- a/src/crypto/crypto_x509_gen.cc +++ b/src/crypto/crypto_x509_gen.cc @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -297,7 +298,8 @@ X509NamePointer BuildName(Environment* env, Local spec) { if (!oid) return {}; const std::string text = ReadString(env, content_value); - if (text.size() > static_cast(std::numeric_limits::max())) { + if (text.size() > static_cast(std::numeric_limits::max()) || + text.find('\0') != std::string::npos) { return {}; } const auto* bytes = reinterpret_cast(text.data()); @@ -438,11 +440,11 @@ bool ReadKeyIdentifierSpec(Environment* env, if (!IsAnyBufferSource(identifier_value)) return false; ArrayBufferOrViewContents contents(identifier_value); - if (!contents.CheckSizeInt32()) return false; + if (!contents.CheckSizeInt32() || contents.size() == 0) return false; identifier->reset(ASN1_OCTET_STRING_new()); return *identifier && ASN1_OCTET_STRING_set(identifier->get(), - contents.size() == 0 ? nullptr : contents.data(), + contents.data(), static_cast(contents.size())) == 1; } @@ -765,6 +767,21 @@ bool RequestVerificationFailed(CryptoErrorStore* errors) { return false; } +// Verifiers commonly reject certificate signatures whose salt is not +// digest-sized (RFC 8446 section 4.2.3). +int DefaultPssSaltLength(const EVPKeyPointer& key, + const ncrypto::Digest& digest) { + int salt_length = static_cast(digest.size()); + if (key.isA(ncrypto::KeyAlgorithm::RSA_PSS)) { + const auto pss_params = ncrypto::Rsa::PublicOnly(key).getPssParams(); + if (pss_params.has_value()) { + salt_length = + std::max(salt_length, static_cast(pss_params->salt_length)); + } + } + return salt_length; +} + } // namespace X509GenerateConfig::X509GenerateConfig(X509GenerateConfig&& other) noexcept @@ -895,9 +912,16 @@ Maybe X509GenerateTraits::AdditionalConfig( params->padding = args[padding_offset].As()->Value(); } + const EVPKeyPointer& native_signing_key = signing_key.GetAsymmetricKey(); + if (native_signing_key.isRsaVariant() && !params->salt_length.has_value() && + params->padding.value_or(native_signing_key.getDefaultSignPadding()) == + RSA_PKCS1_PSS_PADDING) { + params->salt_length = + DefaultPssSaltLength(native_signing_key, params->digest); + } + // BoringSSL's X.509 signer supports only restricted RSA-PSS parameters. #if NCRYPTO_USE_BORINGSSL - const EVPKeyPointer& native_signing_key = signing_key.GetAsymmetricKey(); if (native_signing_key.isRsaVariant()) { const int padding = params->padding.value_or(native_signing_key.getDefaultSignPadding()); diff --git a/test/parallel/test-crypto-x509-generate.js b/test/parallel/test-crypto-x509-generate.js index 98e9419db66e..9aa8c9afaf9b 100644 --- a/test/parallel/test-crypto-x509-generate.js +++ b/test/parallel/test-crypto-x509-generate.js @@ -71,6 +71,19 @@ function assertSigned(certificate, publicKey, privateKey) { assert.strictEqual(certificate.checkPrivateKey(privateKey), true); } +function assertPss(keys, signature, expectedSaltLength) { + const certificate = generateX509CertificateSync( + baseOptions(keys, { signature })); + assertSigned(certificate, keys.publicKey, keys.privateKey); + assert.strictEqual(certificate.signatureAlgorithmOid, + '1.2.840.113549.1.1.10'); + // RSASSA-PSS-params saltLength: [2] EXPLICIT INTEGER + const encodedSaltLength = + Buffer.from([0xa2, 0x03, 0x02, 0x01, expectedSaltLength]); + const { parameters } = certificate.signature.algorithm; + assert(parameters.includes(encodedSaltLength), parameters.toString('hex')); +} + function assertSynchronousFailure(options, expected) { assert.throws(() => generateX509CertificateSync(options), expected); assert.throws(() => generateX509Certificate( @@ -459,30 +472,23 @@ assertSigned(generateX509CertificateSync(baseOptions(leafKeys, { })), leafKeys.publicKey, leafKeys.privateKey); { - const certificate = generateX509CertificateSync(baseOptions(leafKeys, { - signature: { - key: { - key: leafKeys.privateKey, - padding: constants.RSA_PKCS1_PSS_PADDING, - saltLength: 32, - }, - digest: 'sha256', + assertPss(leafKeys, { + key: { + key: leafKeys.privateKey, + padding: constants.RSA_PKCS1_PSS_PADDING, }, - })); - assertSigned(certificate, leafKeys.publicKey, leafKeys.privateKey); - assert.strictEqual(certificate.signatureAlgorithmOid, '1.2.840.113549.1.1.10'); -} - -if (!isBoringSSL) { - const keys = generateKeyPairSync('rsa-pss', { - modulusLength: 2048, - hashAlgorithm: 'sha256', - mgf1HashAlgorithm: 'sha256', - saltLength: 64, - }); - const certificate = generateX509CertificateSync(baseOptions(keys)); - assertSigned(certificate, keys.publicKey, keys.privateKey); - assert.strictEqual(certificate.signatureAlgorithmOid, '1.2.840.113549.1.1.10'); + digest: 'sha256', + }, 32); + + if (!isBoringSSL) { + const restricted = generateKeyPairSync('rsa-pss', { + modulusLength: 2048, + hashAlgorithm: 'sha256', + mgf1HashAlgorithm: 'sha256', + saltLength: 64, + }); + assertPss(restricted, { key: restricted.privateKey, digest: 'sha256' }, 64); + } } assert.strictEqual(generateX509Certificate.length, 2); @@ -609,6 +615,21 @@ const invalidOptions = [ names: [{ type: 'dns', value: 'nul\0.example' }], }], })], + ['ERR_INVALID_ARG_VALUE', baseOptions(leafKeys, { + subject: [{ name: 'CN', value: 'example.com\0.example' }], + })], + ['ERR_INVALID_ARG_VALUE', baseOptions(leafKeys, { + extensions: [{ type: 'subjectKeyIdentifier', value: Buffer.alloc(0) }], + })], + ['ERR_INVALID_ARG_VALUE', baseOptions(leafKeys, { + extensions: [{ type: 'authorityKeyIdentifier', value: Buffer.alloc(0) }], + })], + ['ERR_INVALID_ARG_VALUE', baseOptions(leafKeys, { + subject: [ + { name: 'CN', value: 'example.com' }, + [{ name: 'O', value: 'Node.js' }, { name: '2.5.4.11', value: '\0' }], + ], + })], ['ERR_INVALID_ARG_VALUE', baseOptions(leafKeys, { extensions: [{ type: 'subjectAltName',