Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions doc/api/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions lib/internal/crypto/sig.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -321,6 +321,6 @@ module.exports = {
signOneShot,
Verify,
verifyOneShot,
getIntOption,
getPadding,
getSaltLength,
};
20 changes: 14 additions & 6 deletions lib/internal/crypto/x509_generation.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ const {
preparePublicOrPrivateKey,
} = require('internal/crypto/keys');
const {
getIntOption,
getPadding,
getSaltLength,
} = require('internal/crypto/sig');

const {
Expand All @@ -58,6 +58,7 @@ const {
validateInteger,
validateObject,
validateString,
validateStringWithoutNullBytes,
} = require('internal/validators');

const {
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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];
}
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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) {
Expand Down
32 changes: 28 additions & 4 deletions src/crypto/crypto_x509_gen.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#include <openssl/x509.h>
#include <openssl/x509v3.h>

#include <algorithm>
#include <array>
#include <limits>
#include <string>
Expand Down Expand Up @@ -297,7 +298,8 @@ X509NamePointer BuildName(Environment* env, Local<Array> spec) {
if (!oid) return {};

const std::string text = ReadString(env, content_value);
if (text.size() > static_cast<size_t>(std::numeric_limits<int>::max())) {
if (text.size() > static_cast<size_t>(std::numeric_limits<int>::max()) ||
text.find('\0') != std::string::npos) {
return {};
}
const auto* bytes = reinterpret_cast<const unsigned char*>(text.data());
Expand Down Expand Up @@ -438,11 +440,11 @@ bool ReadKeyIdentifierSpec(Environment* env,
if (!IsAnyBufferSource(identifier_value)) return false;

ArrayBufferOrViewContents<unsigned char> 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<int>(contents.size())) == 1;
}

Expand Down Expand Up @@ -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<int>(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<int>(pss_params->salt_length));
}
}
return salt_length;
}

} // namespace

X509GenerateConfig::X509GenerateConfig(X509GenerateConfig&& other) noexcept
Expand Down Expand Up @@ -895,9 +912,16 @@ Maybe<void> X509GenerateTraits::AdditionalConfig(
params->padding = args[padding_offset].As<v8::Int32>()->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());
Expand Down
67 changes: 44 additions & 23 deletions test/parallel/test-crypto-x509-generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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',
Expand Down
Loading