From 5b7e016d6e52a0d0b007f1bd493e5a05973979f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Thu, 10 Oct 2019 02:41:30 +0200 Subject: [PATCH] crypto: reject public keys properly Fixes: https://github.com/nodejs/node/issues/29904 PR-URL: https://github.com/nodejs/node/pull/29913 Reviewed-By: Sam Roberts Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Ben Noordhuis --- lib/internal/crypto/keys.js | 5 ++++- test/parallel/test-crypto-key-objects.js | 21 +++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/internal/crypto/keys.js b/lib/internal/crypto/keys.js index fb17ba36ced0e3..250147d7529439 100644 --- a/lib/internal/crypto/keys.js +++ b/lib/internal/crypto/keys.js @@ -270,7 +270,10 @@ function prepareAsymmetricKey(key, ctx) { ...(ctx !== kCreatePrivate ? ['KeyObject'] : [])], key); } - return { data, ...parseKeyEncoding(key, undefined) }; + + const isPublic = + (ctx === kConsumePrivate || ctx === kCreatePrivate) ? false : undefined; + return { data, ...parseKeyEncoding(key, undefined, isPublic) }; } else { throw new ERR_INVALID_ARG_TYPE( 'key', diff --git a/test/parallel/test-crypto-key-objects.js b/test/parallel/test-crypto-key-objects.js index 558f7dc1f4b673..15de241b358fb1 100644 --- a/test/parallel/test-crypto-key-objects.js +++ b/test/parallel/test-crypto-key-objects.js @@ -200,6 +200,27 @@ const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem', library: 'BIO routines', function: 'BIO_new_mem_buf', }); + + // This should not abort either: https://github.com/nodejs/node/issues/29904 + assert.throws(() => { + createPrivateKey({ key: Buffer.alloc(0), format: 'der', type: 'spki' }); + }, { + code: 'ERR_INVALID_OPT_VALUE', + message: 'The value "spki" is invalid for option "type"' + }); + + // Unlike SPKI, PKCS#1 is a valid encoding for private keys (and public keys), + // so it should be accepted by createPrivateKey, but OpenSSL won't parse it. + assert.throws(() => { + const key = createPublicKey(publicPem).export({ + format: 'der', + type: 'pkcs1' + }); + createPrivateKey({ key, format: 'der', type: 'pkcs1' }); + }, { + message: /asn1 encoding/, + library: 'asn1 encoding routines' + }); } [