Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

crypto: allow zero-length secrets and IKM in HKDF (and in webcrypto PBKDF2) #44201

Closed
wants to merge 2 commits into from
Closed
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: 12 additions & 2 deletions doc/api/crypto.md
Original file line number Diff line number Diff line change
Expand Up @@ -3539,6 +3539,9 @@ and it will be impossible to extract the private key from the returned object.
<!-- YAML
added: v11.6.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/44201
description: The key can now be zero-length.
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/35093
description: The key can also be an ArrayBuffer or string. The encoding
Expand Down Expand Up @@ -4206,6 +4209,9 @@ web-compatible code use [`crypto.webcrypto.getRandomValues()`][] instead.
<!-- YAML
added: v15.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/44201
description: The input keying material can now be zero-length.
- version: v18.0.0
pr-url: https://github.com/nodejs/node/pull/41678
description: Passing an invalid callback to the `callback` argument
Expand All @@ -4215,7 +4221,7 @@ changes:

* `digest` {string} The digest algorithm to use.
* `ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input
keying material. It must be at least one byte in length.
keying material. Must be provided but can be zero-length.
* `salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must
be provided but can be zero-length.
* `info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value.
Expand Down Expand Up @@ -4265,11 +4271,15 @@ hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {

<!-- YAML
added: v15.0.0
changes:
- version: REPLACEME
pr-url: https://github.com/nodejs/node/pull/44201
description: The input keying material can now be zero-length.
-->

* `digest` {string} The digest algorithm to use.
* `ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input
keying material. It must be at least one byte in length.
keying material. Must be provided but can be zero-length.
* `salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must
be provided but can be zero-length.
* `info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value.
Expand Down
4 changes: 1 addition & 3 deletions lib/internal/crypto/hkdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
const {
FunctionPrototypeCall,
Promise,
Uint8Array,
} = primordials;

const {
Expand Down Expand Up @@ -80,9 +79,8 @@ function prepareKey(key) {
if (isKeyObject(key))
return key;

// TODO(@jasnell): createSecretKey should allow using an ArrayBuffer
if (isAnyArrayBuffer(key))
return createSecretKey(new Uint8Array(key));
return createSecretKey(key);

key = toBuf(key);

Expand Down
3 changes: 0 additions & 3 deletions lib/internal/crypto/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ const {
ERR_ILLEGAL_CONSTRUCTOR,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ARG_VALUE,
ERR_OUT_OF_RANGE,
}
} = require('internal/errors');

Expand Down Expand Up @@ -588,8 +587,6 @@ function prepareSecretKey(key, encoding, bufferOnly = false) {

function createSecretKey(key, encoding) {
key = prepareSecretKey(key, encoding, true);
if (key.byteLength === 0)
throw new ERR_OUT_OF_RANGE('key.byteLength', '> 0', key.byteLength);
const handle = new KeyObjectHandle();
handle.init(kKeyTypeSecret, key);
return new SecretKeyObject(handle);
Expand Down
3 changes: 0 additions & 3 deletions lib/internal/crypto/webcrypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -494,9 +494,6 @@ async function importGenericSecretKey(

const checkLength = keyData.byteLength * 8;

if (checkLength === 0 || length === 0)
throw lazyDOMException('Zero-length key is not supported', 'DataError');

// The Web Crypto spec allows for key lengths that are not multiples of
// 8. We don't. Our check here is stricter than that defined by the spec
// in that we require that algorithm.length match keyData.length * 8 if
Expand Down
54 changes: 46 additions & 8 deletions src/crypto/crypto_hkdf.cc
Original file line number Diff line number Diff line change
Expand Up @@ -103,20 +103,58 @@ bool HKDFTraits::DeriveBits(
EVPKeyCtxPointer ctx =
EVPKeyCtxPointer(EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr));
if (!ctx || !EVP_PKEY_derive_init(ctx.get()) ||
!EVP_PKEY_CTX_hkdf_mode(ctx.get(),
EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) ||
!EVP_PKEY_CTX_set_hkdf_md(ctx.get(), params.digest) ||
!EVP_PKEY_CTX_set1_hkdf_salt(
ctx.get(), params.salt.data<unsigned char>(), params.salt.size()) ||
!EVP_PKEY_CTX_set1_hkdf_key(
ctx.get(),
reinterpret_cast<const unsigned char*>(params.key->GetSymmetricKey()),
params.key->GetSymmetricKeySize()) ||
!EVP_PKEY_CTX_add1_hkdf_info(
ctx.get(), params.info.data<unsigned char>(), params.info.size())) {
return false;
}

// TODO(panva): Once support for OpenSSL 1.1.1 is dropped the whole
// of HKDFTraits::DeriveBits can be refactored to use
// EVP_KDF which does handle zero length key.
if (params.key->GetSymmetricKeySize() != 0) {
if (!EVP_PKEY_CTX_hkdf_mode(ctx.get(),
EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND) ||
!EVP_PKEY_CTX_set1_hkdf_salt(
ctx.get(), params.salt.data<unsigned char>(), params.salt.size()) ||
!EVP_PKEY_CTX_set1_hkdf_key(ctx.get(),
reinterpret_cast<const unsigned char*>(
params.key->GetSymmetricKey()),
params.key->GetSymmetricKeySize())) {
return false;
}
} else {
// Workaround for EVP_PKEY_derive HKDF not handling zero length keys.
unsigned char temp_key[EVP_MAX_MD_SIZE];
unsigned int len = sizeof(temp_key);
if (params.salt.size() != 0) {
if (HMAC(params.digest,
params.salt.data(),
params.salt.size(),
nullptr,
0,
temp_key,
&len) == nullptr) {
return false;
}
} else {
char salt[EVP_MAX_MD_SIZE] = {0};
if (HMAC(params.digest,
salt,
EVP_MD_size(params.digest),
nullptr,
0,
temp_key,
&len) == nullptr) {
return false;
}
}
if (!EVP_PKEY_CTX_hkdf_mode(ctx.get(), EVP_PKEY_HKDEF_MODE_EXPAND_ONLY) ||
!EVP_PKEY_CTX_set1_hkdf_key(ctx.get(), temp_key, len)) {
return false;
}
}

size_t length = params.length;
ByteSource::Builder buf(length);
if (EVP_PKEY_derive(ctx.get(), buf.data<unsigned char>(), &length) <= 0)
Expand Down
1 change: 0 additions & 1 deletion src/crypto/crypto_keys.cc
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,6 @@ void KeyObjectData::MemoryInfo(MemoryTracker* tracker) const {
}

std::shared_ptr<KeyObjectData> KeyObjectData::CreateSecret(ByteSource key) {
CHECK(key);
return std::shared_ptr<KeyObjectData>(new KeyObjectData(std::move(key)));
}

Expand Down
2 changes: 2 additions & 0 deletions test/parallel/test-crypto-hkdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ const {

const algorithms = [
['sha256', 'secret', 'salt', 'info', 10],
['sha256', '', '', '', 10],
['sha256', '', 'salt', '', 10],
['sha512', 'secret', 'salt', '', 15],
];
if (!common.hasOpenSSL3)
Expand Down
9 changes: 9 additions & 0 deletions test/parallel/test-crypto-hmac.js
Original file line number Diff line number Diff line change
Expand Up @@ -450,3 +450,12 @@ assert.strictEqual(
() => crypto.createHmac('sha7', 'key'),
/Invalid digest/);
}

{
const buf = Buffer.alloc(0);
const keyObject = crypto.createSecretKey(Buffer.alloc(0));
assert.deepStrictEqual(
crypto.createHmac('sha256', buf).update('foo').digest(),
crypto.createHmac('sha256', keyObject).update('foo').digest(),
);
}
22 changes: 10 additions & 12 deletions test/parallel/test-crypto-key-objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,18 +33,6 @@ const publicDsa = fixtures.readKey('dsa_public_1025.pem', 'ascii');
const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
'ascii');

{
// Attempting to create an empty key should throw.
assert.throws(() => {
createSecretKey(Buffer.alloc(0));
}, {
name: 'RangeError',
code: 'ERR_OUT_OF_RANGE',
message: 'The value of "key.byteLength" is out of range. ' +
'It must be > 0. Received 0'
});
}

{
// Attempting to create a key of a wrong type should throw
const TYPE = 'wrong_type';
Expand Down Expand Up @@ -870,3 +858,13 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
assert(!first.privateKey.equals(second.privateKey));
assert(!first.privateKey.equals(second.publicKey));
}

{
const first = createSecretKey(Buffer.alloc(0));
const second = createSecretKey(new ArrayBuffer(0));
const third = createSecretKey(Buffer.alloc(1));
assert(first.equals(first));
assert(first.equals(second));
assert(!first.equals(third));
assert(!third.equals(first));
}
2 changes: 1 addition & 1 deletion test/parallel/test-webcrypto-derivebits-hkdf.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const kDerivedKeys = {
short: '5040737377307264',
long: '55736572732073686f756c64207069636b206c6f6e6720706173737068726' +
'173657320286e6f74207573652073686f72742070617373776f7264732921',
// empty: ''
empty: ''
};

const kSalts = {
Expand Down
Loading