Repository navigation
crypto: accept EC SPKI public keys with explicit curve parameters #34888
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
Changes from all commits
2c313b9
100d092
c7638af
cdcbc4d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,7 @@ | |
| #include "headers-handwritten.h" | ||
| #include <openssl/asn1.h> | ||
| #include <openssl/bn.h> | ||
| #include <openssl/bytestring.h> | ||
| #include <openssl/dh.h> | ||
| #include <openssl/evp.h> | ||
| #include <openssl/hmac.h> | ||
|
|
@@ -1933,6 +1934,52 @@ EVPKeyPointer::ParseKeyResult TryParsePublicKeyInner(const BIOPointer& bp, | |
| return EVPKeyPointer::ParseKeyResult(WTF::move(pkey)); | ||
| } | ||
|
|
||
| // BoringSSL's d2i_PUBKEY rejects EC SPKI with specifiedCurve (explicit) parameters | ||
| // while OpenSSL/Node.js accept them. Reuse EC_KEY_parse_parameters (which BoringSSL | ||
| // already uses for PKCS#8/SEC1 private keys) to map them to a named curve. | ||
| EVP_PKEY* TryParseECSubjectPublicKeyInfo(const unsigned char* der, size_t der_len) | ||
| { | ||
| MarkPopErrorOnReturn mark_pop_error_on_return; | ||
|
|
||
| CBS cbs, spki, algorithm, oid, key; | ||
| CBS_init(&cbs, der, der_len); | ||
| if (!CBS_get_asn1(&cbs, &spki, CBS_ASN1_SEQUENCE) || CBS_len(&cbs) != 0 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 (optional) Callers passing a DER SPKI buffer with explicit curve parameters and trailing bytes still get "Failed to read asymmetric key" while Node.js accepts it, so the fix is incomplete for that input class. At ncrypto.cpp:1946 the fallback requires CBS_len(&cbs) == 0 after the outer SEQUENCE, but d2i_PUBKEY (the path it is emulating, ncrypto.cpp:2105) tolerates trailing data and advances the pointer. Fix: match d2i_PUBKEY semantics on the DER path by dropping the trailing-data check for the outer SEQUENCE (or only enforcing it on the PEM path), and add a DER-with-trailing-bytes variant to the tests. Why this was flaggedTrigger: createPublicKey({key: der, format:'der', type:'spki'}) where der is an explicit-parameter SPKI followed by extra bytes, e.g. a slice of a larger buffer or a zero-padded allocation; arrives via TryParsePublicKey at ncrypto.cpp:2104. d2i_PUBKEY fails on the explicit params, and the fallback at ncrypto.cpp:1946 rejects because CBS_len(&cbs) != 0. OpenSSL's d2i_PUBKEY in Node ignores trailing bytes, so Node returns the key. The dismissal called the buffer malformed, but d2i_PUBKEY at ncrypto.cpp:2105 accepts the same trailing bytes for a namedCurve key in Bun today, so the fallback is stricter than the sibling path it supplements. Remedy: drop the outer trailing-length check on the DER path to mirror d2i_PUBKEY. Verification: Pre-existing on the base. Trigger: createPublicKey({key, format:'der', type:'spki'}) with an explicit-parameter EC SPKI with trailing bytes after the outer SEQUENCE. src/jsc/bindings/ncrypto.cpp:1946 rejects trailing data, whereas d2i_PUBKEY at ncrypto.cpp:2105 tolerates it. So it is still rejected with PKParseError::FAILED at ncrypto.cpp:2114, while Node.js accepts it. |
||
| || !CBS_get_asn1(&spki, &algorithm, CBS_ASN1_SEQUENCE) | ||
| || !CBS_get_asn1(&algorithm, &oid, CBS_ASN1_OBJECT)) { | ||
| return nullptr; | ||
| } | ||
|
|
||
| // id-ecPublicKey OBJECT IDENTIFIER ::= { 1.2.840.10045.2.1 } | ||
| static constexpr uint8_t kIdEcPublicKey[] = { 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01 }; | ||
| if (!CBS_mem_equal(&oid, kIdEcPublicKey, sizeof(kIdEcPublicKey))) { | ||
| return nullptr; | ||
| } | ||
|
|
||
| const EC_GROUP* group = EC_KEY_parse_parameters(&algorithm); | ||
| if (group == nullptr || CBS_len(&algorithm) != 0) { | ||
| return nullptr; | ||
| } | ||
|
|
||
| uint8_t padding; | ||
| if (!CBS_get_asn1(&spki, &key, CBS_ASN1_BITSTRING) || CBS_len(&spki) != 0 | ||
| || !CBS_get_u8(&key, &padding) || padding != 0) { | ||
| return nullptr; | ||
| } | ||
|
|
||
| ECKeyPointer eckey(EC_KEY_new()); | ||
| if (!eckey || !EC_KEY_set_group(eckey.get(), group) | ||
| || !EC_KEY_oct2key(eckey.get(), CBS_data(&key), CBS_len(&key), nullptr)) { | ||
| return nullptr; | ||
| } | ||
|
|
||
| auto pkey = EVPKeyPointer::New(); | ||
| if (!pkey || !EVP_PKEY_assign_EC_KEY(pkey.get(), eckey.get())) { | ||
| return nullptr; | ||
| } | ||
| eckey.release(); | ||
| return pkey.release(); | ||
| } | ||
|
|
||
| constexpr bool IsASN1Sequence(const unsigned char* data, | ||
| size_t size, | ||
| size_t* data_offset, | ||
|
|
@@ -1997,8 +2044,15 @@ EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePublicKeyPEM( | |
| if (auto ret = TryParsePublicKeyInner( | ||
| bp, | ||
| "PUBLIC KEY", | ||
| [](const unsigned char** p, long l) { // NOLINT(runtime/int) | ||
| return d2i_PUBKEY(nullptr, p, l); | ||
| [](const unsigned char** p, long l) -> EVP_PKEY* { // NOLINT(runtime/int) | ||
| const unsigned char* der = *p; | ||
| if (EVP_PKEY* key = d2i_PUBKEY(nullptr, p, l)) return key; | ||
| if (EVP_PKEY* key = TryParseECSubjectPublicKeyInfo(der, l)) { | ||
| // Discard d2i_PUBKEY's decode error since the fallback succeeded. | ||
| ERR_clear_error(); | ||
| return key; | ||
| } | ||
| return nullptr; | ||
| })) { | ||
| return ret; | ||
| } | ||
|
|
@@ -2047,8 +2101,14 @@ EVPKeyPointer::ParseKeyResult EVPKeyPointer::TryParsePublicKey( | |
| return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); | ||
| } | ||
|
|
||
| if (config.type == PKEncodingType::SPKI && (key = d2i_PUBKEY(nullptr, &start, buffer.len))) { | ||
| return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); | ||
| if (config.type == PKEncodingType::SPKI) { | ||
| if ((key = d2i_PUBKEY(nullptr, &start, buffer.len))) { | ||
| return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); | ||
| } | ||
| if ((key = TryParseECSubjectPublicKeyInfo(buffer.data, buffer.len))) { | ||
| ERR_clear_error(); | ||
| return EVPKeyPointer::ParseKeyResult(EVPKeyPointer(key)); | ||
| } | ||
| } | ||
|
|
||
| return ParseKeyResult(PKParseError::FAILED); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -620,6 +620,72 @@ describe("crypto.KeyObjects", () => { | |
| }); | ||
| }); | ||
|
|
||
| describe("ec with explicit curve parameters", () => { | ||
| // P-256 key pair whose PEM encodings use the specifiedCurve (explicit) form of | ||
| // ECParameters instead of a namedCurve OID. OpenSSL emits this form for | ||
| // `openssl ec -param_enc explicit`; jsonwebtoken's committed ES256 fixtures | ||
| // use it. BoringSSL's d2i_PUBKEY rejects the public key but OpenSSL accepts it. | ||
| const publicPem = | ||
| "-----BEGIN PUBLIC KEY-----\n" + | ||
| "MIIBSzCCAQMGByqGSM49AgEwgfcCAQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAA\n" + | ||
| "AAAAAAAAAAAA////////////////MFsEIP////8AAAABAAAAAAAAAAAAAAAA////\n" + | ||
| "///////////8BCBaxjXYqjqT57PrvVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSd\n" + | ||
| "NgiG5wSTamZ44ROdJreBn36QBEEEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5\n" + | ||
| "RdiYwpZP40Li/hp/m47n60p8D54WK84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA\n" + | ||
| "//////////+85vqtpxeehPO5ysL8YyVRAgEBA0IABGrCjldfJzjPCHeMi8LX++ZD\n" + | ||
| "9NLZxsyXF3HNMrOm9JWKYcV32b4R/4z2MnDKMxLXaQLFHgjYKdLxbBjpeIBkqc0=\n" + | ||
| "-----END PUBLIC KEY-----\n"; | ||
| const privatePem = | ||
| "-----BEGIN EC PRIVATE KEY-----\n" + | ||
| "MIIBaAIBAQQgImAk/YsR1fRVtjTAB4W4JB/71TOst16Bv8muhUb0BZWggfowgfcC\n" + | ||
| "AQEwLAYHKoZIzj0BAQIhAP////8AAAABAAAAAAAAAAAAAAAA////////////////\n" + | ||
| "MFsEIP////8AAAABAAAAAAAAAAAAAAAA///////////////8BCBaxjXYqjqT57Pr\n" + | ||
| "vVV2mIa8ZR0GsMxTsPY7zjw+J9JgSwMVAMSdNgiG5wSTamZ44ROdJreBn36QBEEE\n" + | ||
| "axfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li/hp/m47n60p8D54W\n" + | ||
| "K84zV2sxXs7LtkBoN79R9QIhAP////8AAAAA//////////+85vqtpxeehPO5ysL8\n" + | ||
| "YyVRAgEBoUQDQgAEasKOV18nOM8Id4yLwtf75kP00tnGzJcXcc0ys6b0lYphxXfZ\n" + | ||
| "vhH/jPYycMozEtdpAsUeCNgp0vFsGOl4gGSpzQ==\n" + | ||
| "-----END EC PRIVATE KEY-----\n"; | ||
|
|
||
| test("createPublicKey accepts PEM SPKI with explicit parameters", () => { | ||
| const key = createPublicKey(publicPem); | ||
| expect({ | ||
| type: key.type, | ||
| asymmetricKeyType: key.asymmetricKeyType, | ||
| asymmetricKeyDetails: key.asymmetricKeyDetails, | ||
| }).toEqual({ | ||
| type: "public", | ||
| asymmetricKeyType: "ec", | ||
| asymmetricKeyDetails: { namedCurve: "prime256v1" }, | ||
| }); | ||
| // Re-export should produce a well-formed SPKI that we can parse again. | ||
| const exported = key.export({ type: "spki", format: "pem" }); | ||
| expect(createPublicKey(exported).asymmetricKeyDetails).toEqual({ namedCurve: "prime256v1" }); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 (optional) Users who import an explicit-parameter EC public key and re-export it get different PEM/DER bytes than Node.js produces for the same input, so code comparing exported keys to the original (key dedup, fixture equality, kid derivation from the DER) diverges after merging. The fallback at ncrypto.cpp:1958 maps the explicit parameters to the built-in named group, and BoringSSL marshals only the namedCurve OID, whereas OpenSSL keeps the specifiedCurve form on export. The test at crypto.key-objects.test.ts:663 only checks re-import succeeds, not the bytes. Fix: either document the divergence in the test with an exact-bytes assertion against Node's output, or preserve the encoding form on export. Why this was flaggedTrigger: createPublicKey(explicitPem).export({type:'spki',format:'pem'|'der'}) for any key accepted via TryParseECSubjectPublicKeyInfo (ncrypto.cpp:1941). Bun builds an EC_KEY on the named group (ncrypto.cpp:1970-1973), so export emits the namedCurve OID form; Node/OpenSSL retains OPENSSL_EC_EXPLICIT_CURVE and emits the explicit form, so the exported bytes differ from both the input and Node. Base branch throws on import, so no export happened at all; now callers get a silently different representation. The population is every consumer that hashes or compares exported key material (JWK thumbprints are unaffected, but SPKI-hash pinning and PEM string equality are). The test at crypto.key-objects.test.ts:663 asserts only that re-import yields prime256v1, which cannot catch this. Remedy: assert exact exported bytes and decide explicitly whether to match Node. Verification: Triggers when a key accepted only via the new fallback is re-exported; the base throws on import, so nothing working there breaks, but the new path diverges from Node on export. ncrypto.cpp:1958 returns BoringSSL's built-in group, so export emits only the namedCurve OID while Node returns the explicit SPKI. The test at crypto.key-objects.test.ts:662-663 only checks the re-export re-parses. |
||
| }); | ||
|
|
||
| test("createPublicKey accepts DER SPKI with explicit parameters", () => { | ||
| const der = Buffer.from(publicPem.replace(/-----(BEGIN|END) PUBLIC KEY-----/g, "").replace(/\s/g, ""), "base64"); | ||
| const key = createPublicKey({ key: der, format: "der", type: "spki" }); | ||
| expect({ | ||
| asymmetricKeyType: key.asymmetricKeyType, | ||
| asymmetricKeyDetails: key.asymmetricKeyDetails, | ||
| }).toEqual({ | ||
| asymmetricKeyType: "ec", | ||
| asymmetricKeyDetails: { namedCurve: "prime256v1" }, | ||
| }); | ||
| }); | ||
|
|
||
| test("sign/verify round-trips with explicit-parameter key pair", () => { | ||
| const priv = createPrivateKey(privatePem); | ||
| expect(priv.asymmetricKeyDetails).toEqual({ namedCurve: "prime256v1" }); | ||
| const data = Buffer.from("explicit-params"); | ||
| const sig = sign("sha256", data, priv); | ||
| expect(verify("sha256", data, publicPem, sig)).toBe(true); | ||
| expect(verify("sha256", data, createPublicKey(publicPem), sig)).toBe(true); | ||
| expect(createVerify("sha256").update(data).verify(publicPem, sig)).toBe(true); | ||
| }); | ||
| }); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 (optional) Maintainers get no regression guard that the new hand-written SPKI parser still rejects malformed explicit-parameter keys. The three tests at crypto.key-objects.test.ts:650-686 only exercise the happy path; none asserts that a specifiedCurve SPKI with an off-curve point, a non-zero BIT STRING padding byte, trailing bytes, or parameters matching no built-in curve still throws from createPublicKey. Fix: add negative cases that mutate the fixture (flip a byte of the public point, set the padding byte to 1, append a trailing byte, change the prime) and assert createPublicKey throws, for both the PEM and the DER spki entry points, so each guard in TryParseECSubjectPublicKeyInfo at ncrypto.cpp:1946-1972 is covered. Why this was flaggedTryParseECSubjectPublicKeyInfo at src/jsc/bindings/ncrypto.cpp:1940 is a new parser over user-controlled DER that runs whenever d2i_PUBKEY fails, i.e. on every rejected SPKI input reaching createPublicKey, verify and createVerify through KeyObject.cpp:1730 and KeyObject.cpp:1769. Its rejection clauses (CBS_len(&cbs) != 0, CBS_len(&algorithm) != 0, padding != 0, EC_KEY_oct2key point validation) are each load-bearing, but the added tests at crypto.key-objects.test.ts:650-686 only import one valid fixture and round-trip a signature. Deleting any of those guards, or a future edit that loosens them, leaves the suite green; the repository review rules call for adversarial inputs for anything parsing user data and for confirming that removing each clause of the fix breaks a test. On the base branch there was no hand-written parser here, so this is coverage the change newly needs rather than a behavioural regression. Verification: Any future edit to the new SPKI parser that drops one of its rejection clauses would go unnoticed by the suite. The three added tests at test/js/node/crypto/crypto.key-objects.test.ts:650-686 feed only the one valid fixture and assert success. The parser at src/jsc/bindings/ncrypto.cpp:1940 has several rejection clauses, and deleting any one leaves all three tests passing. |
||
|
|
||
| test("private encrypted should work", async () => { | ||
| // Reading an encrypted key without a passphrase should fail. | ||
| expect(() => createPrivateKey(privateEncryptedPem)).toThrow(); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment explains a fallback for a gap in BoringSSL:
eckey_pub_decodeaccepts only a namedCurve OID, andeckey_priv_decodealso accepts explicit parameters. I am checking if the fix belongs in that function instead of a fallback inncrypto.cpp. I will update this thread when that is decided.