Repository navigation
Conversation
BoringSSL's d2i_PUBKEY only accepts the namedCurve form of ECParameters in SubjectPublicKeyInfo, while OpenSSL (and therefore Node.js) also accepts the specifiedCurve (explicit) form. BoringSSL already matches explicit parameters to a known named curve for PKCS#8/SEC1 private keys via EC_KEY_parse_parameters, so the matching SEC1 private key imported fine while the public half of the same pair was rejected with a misleading ERR_OSSL_NO_START_LINE. Add a fallback in TryParsePublicKey/TryParsePublicKeyPEM that parses the SPKI by hand, matches the id-ecPublicKey OID, and uses EC_KEY_parse_parameters on the AlgorithmIdentifier parameters so the explicit form is mapped to its named curve the same way the private-key path already does. Fixes jsonwebtoken's ES256 jwt.verify tests, whose committed P-256 public key fixture uses explicit parameters.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info
WalkthroughPEM and DER SPKI parsing now fall back to an EC-specific parser when the standard parser fails. Tests cover explicit-parameter P-256 public-key imports and signature verification. ChangesEC SPKI parsing
Suggested reviewers: Priority: ⬇️ Low Merge Risk: ⚪ Minimal · up to
|
|
Updated 12:05 PM PT - Oct 15th, 2026
❌ @robobun, your commit cdcbc4d has 2 failures in
🧪 To try this PR locally: bunx bun-pr 34888That installs a local version of the PR into your bun-34888 --bun |
There was a problem hiding this comment.
I didn't find any bugs, but this adds hand-rolled SPKI DER parsing to the node:crypto public-key import path — worth a human look given it's a security-sensitive surface.
What was reviewed:
- Ownership in
TryParseECSubjectPublicKeyInfo:ECKeyPointer/EVPKeyPointerRAII on all failure paths;eckey.release()only afterEVP_PKEY_assign_EC_KEYtransfers ownership — no leak/double-free. - Both call sites pass the original DER pointer (not the one
d2i_PUBKEYmay advance) and clear the error stack only when the fallback succeeds. - CBS parsing checks trailing data at each level (
CBS_len(...) != 0) and the BIT STRING padding byte, so malformed input falls through to the existing error path. EC_KEY_parse_parametersreturns a static built-in group in BoringSSL, so not freeing it is correct.
Extended reasoning...
Overview
Adds a fallback in src/jsc/bindings/ncrypto.cpp so crypto.createPublicKey() accepts EC SubjectPublicKeyInfo encodings that use explicit (specifiedCurve) ECParameters instead of a namedCurve OID. BoringSSL's d2i_PUBKEY rejects these while its private-key decoder accepts them; OpenSSL/Node accepts both. The new TryParseECSubjectPublicKeyInfo manually walks the SPKI SEQUENCE with BoringSSL's CBS API, matches the id-ecPublicKey OID, hands the parameters to EC_KEY_parse_parameters (the same routine BoringSSL already uses for the private-key path), and builds the EC_KEY from the BIT STRING via EC_KEY_oct2key. It is wired into both the PEM and DER SPKI paths as a fallback after d2i_PUBKEY fails. Three new tests cover PEM import, DER import, and sign/verify round-trip.
Security risks
This is public-key import — untrusted DER on a security-sensitive path. The parsing itself defers to BoringSSL primitives (CBS_get_asn1, EC_KEY_parse_parameters, EC_KEY_oct2key) rather than hand-decoding lengths, and every level checks for trailing bytes, so bounds handling is delegated to a hardened library. EC_KEY_parse_parameters only maps to a known built-in curve (it doesn't accept arbitrary explicit curves), so the accepted key space is the same as before, just via an alternate encoding. The fallback only runs after d2i_PUBKEY has already rejected the input, so previously-accepted keys are unaffected. Still, any widening of what a crypto import accepts merits a human check.
Level of scrutiny
High. The repo review guidance calls out never hand-rolling security-sensitive parsing and having a human weigh in on crypto/TLS paths. This implementation is careful and reuses BoringSSL's own parameter parser, but ~45 lines of new DER-walking C++ in the key-import path is not something I'm comfortable approving without a maintainer's eyes.
Other factors
Memory handling looks correct: RAII wrappers cover every early return; eckey.release() is placed after EVP_PKEY_assign_EC_KEY succeeds (which transfers ownership), and pkey.release() hands ownership to the caller which immediately wraps it in EVPKeyPointer. The MarkPopErrorOnReturn inside the helper plus ERR_clear_error() at the call sites keeps the OpenSSL error stack clean on both success and failure. The id-ecPublicKey OID bytes (2a 86 48 ce 3d 02 01) are the correct DER encoding of 1.2.840.10045.2.1. Tests are placed in the existing key-objects suite and assert exact asymmetricKeyDetails plus a real sign/verify round-trip.
|
Status Reproduced on main ( This PR is a draft again. The diff as written is not the planned fix:
Planned fix: each of these paths reaches That plan changes what Bun-native TLS loads: a server can then load a leaf certificate whose key has explicit parameters. This needs a maintainer decision first. The alternative is an opt-in decoder that only |
…plicit-params-spki
ECKeyPointer::New(const EC_GROUP*) no longer exists on main. It was removed as dead code in #40413. TryParseECSubjectPublicKeyInfo was its only caller, so create the EC_KEY and set its group directly.
| // 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. |
There was a problem hiding this comment.
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.
The comment explains a fallback for a gap in BoringSSL: eckey_pub_decode accepts only a namedCurve OID, and eckey_priv_decode also accepts explicit parameters. I am checking if the fix belongs in that function instead of a fallback in ncrypto.cpp. I will update this thread when that is decided.
There was a problem hiding this comment.
Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.
Additional findings (outside the current diff — GitHub can't attach inline comments there):
-
🟣
src/jsc/bindings/ncrypto.cpp— Pre-existing: users importing an EC public key from an X.509 certificate with explicit curve parameters still get a failure that Node.js does not. The new fallback only runs behind d2i_PUBKEY in the "PUBLIC KEY" lambda and the DER SPKI branch; the "CERTIFICATE" lambda at ncrypto.cpp:2076 and X509View::getPublicKey at ncrypto.cpp:1019 still rely on X509_get_pubkey, which BoringSSL leaves NULL for the same SPKI. Fix: route every SPKI-to-EVP_PKEY site through one helper that falls back to TryParseECSubjectPublicKeyInfo on the re-encoded X509_PUBKEY, which covers the 2 sites listed. Same pattern at 2 sites (ncrypto.cpp:2076, ncrypto.cpp:1019).Why this was flagged
A certificate PEM whose SubjectPublicKeyInfo uses the specifiedCurve form is passed to crypto.createPublicKey, crypto.verify, or read via X509Certificate.publicKey. In TryParsePublicKeyPEM the "PUBLIC KEY" section does not match, so the "CERTIFICATE" lambda at ncrypto.cpp:2075-2076 runs d2i_X509 then X509_get_pubkey. BoringSSL's X509_PUBKEY decode tries EVP_parse_public_key, which rejects explicit parameters, and leaves pubkey->pkey NULL, so X509_get_pubkey returns NULL and the lambda returns nullptr; the same happens in X509View::getPublicKey at ncrypto.cpp:1019 used by JSX509Certificate.cpp:1176. The user still gets "Failed to read asymmetric key" / ERR_OSSL_NO_START_LINE, exactly as on the base branch, while Node.js (OpenSSL) returns a prime256v1 key. The PR says the fix is applied to "both the PEM and DER SPKI paths" and excludes WebCrypto, but does not mention the certificate paths, so this is the unaddressed remainder of the same class.
Verification: In src/jsc/bindings/ncrypto.cpp the new fallback TryParseECSubjectPublicKeyInfo is invoked only from the "PUBLIC KEY" lambda (lines 2047-2056) and the DER SPKI branch (lines 2104-2111). The "CERTIFICATE" lambda is unchanged at lines 2074-2076, and X509View::getPublicKey() at line 1019 still calls X509_get_pubkey, which BoringSSL leaves NULL for such certs.
|
|
||
| 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 |
There was a problem hiding this comment.
🟡 (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 flagged
Trigger: 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.
| }); | ||
| // 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" }); |
There was a problem hiding this comment.
🟡 (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 flagged
Trigger: 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.
| expect(verify("sha256", data, createPublicKey(publicPem), sig)).toBe(true); | ||
| expect(createVerify("sha256").update(data).verify(publicPem, sig)).toBe(true); | ||
| }); | ||
| }); |
There was a problem hiding this comment.
🟡 (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 flagged
TryParseECSubjectPublicKeyInfo 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.
|
I checked each review finding against a build of this branch and against Node v26.3.0.
The first two findings have one cause: the fallback is a second SPKI parser beside the real one. In a local experiment I removed the fallback and changed one line in BoringSSL's That change has one measured cost. A I am deciding between the two layers now. I will push the result to this PR. |
|
Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-15. The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR. |
What does this PR do?
crypto.createPublicKey()rejected an EC (prime256v1) SPKI public key whose PEM uses the specifiedCurve (explicit) form ofECParameters, throwing a misleadingERR_OSSL_NO_START_LINEeven though the PEM is well-formed. The matching SEC1 private key with the same explicit parameters imported fine, so Bun accepted one half of the key pair but not the other.crypto.verify()with that public PEM failed the same way.Node.js (OpenSSL) imports both and sign/verify round-trips.
Repro
Real-world hit: jsonwebtoken 9.0.3's committed ES256 fixture (output of
openssl ec -pubout) uses this encoding, so itsjwt.verifytests fail under Bun withinvalid algorithm.Cause
BoringSSL's
eckey_pub_decode(reached viad2i_PUBKEY/EVP_parse_public_key) callsec_key_parse_curve_name, which only accepts a namedCurve OID. Itseckey_priv_decodeinstead callsec_key_parse_parameters, which accepts both namedCurve and the explicit specifiedCurve form (matching it to a known named curve). That asymmetry is why the SEC1 private key worked but the SPKI public key did not. OpenSSL accepts both forms in both places.Fix
In
ncrypto.cpp, whend2i_PUBKEYfails on SPKI input, fall back to parsing theSubjectPublicKeyInfodirectly: match theid-ecPublicKeyOID, feed theAlgorithmIdentifierparameters to BoringSSL'sEC_KEY_parse_parameters(so explicit parameters are mapped to a named curve the same way the private-key path already does), and build theEC_KEYfrom the BIT STRING viaEC_KEY_oct2key. Applied to both the PEM and DER SPKI paths.This is scoped to
node:crypto; WebCrypto behaviour is unchanged.How did you verify your code works?
New tests in
test/js/node/crypto/crypto.key-objects.test.tscovering PEM SPKI import, DER SPKI import, and sign/verify round-trip with an explicit-parameter key pair. All three fail on main withERR_OSSL_NO_START_LINE/ "Failed to read asymmetric key" and pass with the fix. The fullcrypto.key-objects.test.tssuite and upstreamtest-crypto-key-objects.jscontinue to pass.no test proof · iteration 2 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/crypto/crypto.key-objects.test.ts