Skip to content

fix(libSceLibreSsl3): decode the algorithm and key bits in X509_get0_pubkey - #25654

Merged
oneandonlydean merged 1 commit into
boykopovar:mainfrom
kessler-drift:fix/libscelibressl3-x509-get0-pubkey-bits
Nov 22, 2026
Merged

oneandonlydean merged 1 commit into
boykopovar:mainfrom
kessler-drift:fix/libscelibressl3-x509-get0-pubkey-bits

Conversation

@kessler-drift

Copy link
Copy Markdown
Contributor

What

X509_get0_pubkey passed the BIT STRING contents of the certificate's X509_PUBKEY to d2i_PUBKEY as if they were a whole SubjectPublicKeyInfo and ignored the algorithm. The BIT STRING of a SubjectPublicKeyInfo holds only the key itself (an RSAPublicKey or an EC point), so every certificate whose key was not cached yet returned null. This library's own X509_STORE_load_locations fills algor and public_key that way and leaves pkey null, so no certificate it loads had a public key.

LibreSSL X509_PUBKEY_get0 picks the key method from the algorithm OID and calls its pub_decode on public_key->data, without looking at the unused-bits count, then caches the key (3.4.1, x_pubkey.c l.178-222, the pinned submodule; 4.0.0 l.185-228 is the same). The function now re-encodes the algorithm identifier (OID and parameter) and the key bits, with no unused bits, as a SubjectPublicKeyInfo and decodes it with this library's d2i_PUBKEY, so both entry points share one decoder. Caching, the other-thread check and errno handling are unchanged. Because the key is now cached on certificates that this library decodes (X509_STORE_load_locations, d2i_PKCS7), FreePubkey in X509StoreLoadLocations.cpp frees it with the X509_PUBKEY, as LibreSSL's ASN1_OP_FREE_POST callback does; without that, every certificate read by X509_get0_pubkey leaked its key when freed.

BOOLEAN, NULL, OBJECT, SEQUENCE, SET and "other" parameters and the ASN.1 string types up to 30 are encoded; any other parameter type, a null algorithm, null parameter data and unreadable guest memory throw. A null algorithm object is encoded as an empty OID, which gives the unsupported-algorithm errors that OBJ_obj2nid(NULL) gives in LibreSSL. The pending debt fragment of X509_get0_pubkey said the field was assumed to be a complete SubjectPublicKeyInfo; it is rewritten in place, because debt_fold.py refuses a second fragment for the same entry and asks to merge them, and now lists the d2i_PUBKEY refusals that this path inherits.

Tested

Ubuntu 26.04 x86-64 container under Rosetta on macOS 27.2, GCC 15.2, main 0eb40875597. A harness gives the same SubjectPublicKeyInfo to LibreSSL 3.4.1 built from the 3rdparty/libressl-openbsd submodule (d2i_X509_PUBKEY, then X509_PUBKEY_get0) and to the module (the same X509_PUBKEY built by hand, with the last byte masked as c2i_ASN1_BIT_STRING does, in a certificate, then X509_get0_pubkey), and compares null or key, base type, EVP_PKEY_bits, the cached pointer and the error queue. Both sides also run d2i_PUBKEY on the original DER. Inputs: 20 keys from OpenSSL 3.5 (RSA 512 to 3072 with e = 3 and 65537; P-256, P-384, P-521, P-224 and secp256k1, named and explicit; X25519; Ed25519), each with absent, NULL and P-256 parameters and with 3 unused bits, then random mutations of the key bits, OID and parameter (seed 1101: 3 000 inputs; seed 1102: 4 000; seed 1103: 4 000, which also draws BOOLEAN, INTEGER, OCTET STRING, UTF8String and PrintableString parameters).

Seed 1101 / 1102 / 1103 main this PR
Inputs whose result (null or key, type, bits) differs from 3.4.1 691 / 934 / 950 329 / 470 / 481
Of those, inputs where this library's d2i_PUBKEY already differs from 3.4.1 423 / 582 / 605 329 / 470 / 481
Inputs that matched on main and no longer match 0 / 0 / 0

The inputs left are d2i_PUBKEY decisions, counted in this order for seeds 1101 / 1102 / 1103: an RSA key with a parameter other than NULL (105 / 125 / 165), bytes after the RSAPublicKey, which rsa_pub_decode ignores (111 / 197 / 162), explicit EC parameters (52 / 73 / 64), P-224, P-521 and secp256k1 (29 / 34 / 44), EC keys for which this library's EVP_PKEY_bits returns 0 (30 / 36 / 43), RSA-PSS (1 / 4 / 1) and other RSA (1 / 1 / 2). Every error queue that still differs from 3.4.1 (2 130 / 2 875 / 2 951 inputs) also differs for d2i_PUBKEY, mostly by the nested ASN.1 entries this library does not queue.

End to end, four self-signed certificates (RSA 2048, RSA 1024 with e = 3, P-256, P-384) and a bundle of two, loaded with X509_STORE_load_locations and read back from the store: main returns null for all six, this PR returns the key with the same type as 3.4.1 and the same RSA bit counts.

guest_libressl3_x509_public_key_accessors now builds the X509_PUBKEY as LibreSSL lays it out: P-256 with its curve OID, RSA 512 with a NULL parameter and 3 unused bits, RSA 1024 and 2048 (long-form lengths), EC with a BOOLEAN parameter, RSA 512 with an undefined (-1) BOOLEAN parameter, a whole SubjectPublicKeyInfo in the key bits, Ed25519 and a null algorithm object (null), a null algorithm (throws), and the earlier invalid, negative-length, null-data and read-only cases. It fails with the main source, when the unused-bits count is copied into the re-encoded BIT STRING, when long-form lengths are written as 0x81 or as short form below 256, when a BOOLEAN parameter throws, and when an undefined BOOLEAN is encoded. guest_libressl3_pkcs7 now reads the key of the decoded signed message's certificate twice (same pointer) before PKCS7_free and still requires every allocation to be freed; it fails when the new EVP_PKEY_free line in FreePubkey is removed. The 98 libSceLibreSsl3 tests and the 92 public_headers, registration and progress tests pass, apart from the failures main already has under Rosetta.

Not tested on a console, on Windows or on macOS.

#25081, open, changes how d2i_PUBKEY decodes RSA keys (ParseAlgorithm and DecodeSpki in KeyDer.cpp); this path goes through the same decoder and touches a different file.

python3 tools/check_conventions.py --base upstream/main passes. python3 tools/pr_overlap.py --names X509_get0_pubkey finds no open pull request on the function. python3 tools/pr_overlap.py --branch cannot compare #25082, which conflicts with the base branch and shares X509StoreLoadLocations.cpp; its diff changes the certificate file loader and its error queue and does not touch FreePubkey or the public key accessors.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes

🤖 Generated with Claude Code

…pubkey

X509_get0_pubkey passed the BIT STRING contents of the X509_PUBKEY to
d2i_PUBKEY as if they were a whole SubjectPublicKeyInfo, so a certificate
whose key was not cached yet, such as one loaded by
X509_STORE_load_locations, gave a null key. LibreSSL X509_PUBKEY_get0
decodes the key from the algorithm identifier and the key bits, ignoring
the unused-bits count. Re-encode both as a SubjectPublicKeyInfo and decode
it with d2i_PUBKEY.

The key is now cached on certificates decoded by the project, so free it
with the X509_PUBKEY, as LibreSSL does, instead of leaking it when the
certificate is freed.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>

@PrivacyOnion PrivacyOnion left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against 4d5bc3a521:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_libressl3_pkcs7_tests, guest_libressl3_x509_public_key_accessors_tests built cleanly.
  • CTest (guest_libressl3_x509_public_key_accessors, guest_libressl3_pkcs7):
    1/2 Test #4771: guest_libressl3_x509_public_key_accessors ...   Passed    0.02 sec
    2/2 Test #4772: guest_libressl3_pkcs7 .......................   Passed    0.02 sec
    100% tests passed, 0 tests failed out of 2
    
  • Negative control: with core/libs/prx/libSceLibreSsl3/src/X509PublicKeyAccessors.cpp, core/libs/prx/libSceLibreSsl3/src/X509StoreLoadLocations.cpp reverted to main and the new tests kept, the suite fails:
    1/2 Test #4771: guest_libressl3_x509_public_key_accessors ...Subprocess aborted***Exception:   0.99 sec
    2/2 Test #4772: guest_libressl3_pkcs7 .......................Subprocess aborted***Exception:   1.30 sec
    0% tests passed, 2 tests failed out of 2
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified SubjectPublicKeyInfo DER encoding in EncodeSubjectPublicKeyInfo (tag 0x30 SEQUENCE wrapper, AlgorithmIdentifier SEQUENCE with OID and parameters, and tag 0x03 BIT STRING with zero unused-bits prefix) matches RFC 5280 and d2i_PUBKEY requirements.
    • Verified error handling and memory management in DecodeEncodedKey: cursor parsing errors, race conditions where another thread cached the key first, and read-only guest memory pages properly release decoded EVP_PKEY and preserve errno.
    • Verified parameter parsing in AppendParameter across ASN.1 BOOLEAN (tag 0x01), NULL (tag 0x05), OBJECT IDENTIFIER (tag 0x06), constructed types (SEQUENCE/SET), and unsupported tags throwing NotImplemented_nid_no_patch.
    • Verified resource cleanup in FreePubkey in X509StoreLoadLocations.cpp correctly calls EVP_PKEY_free_nid_disambig1_nid_postfix on pubkey->pkey without leaking memory or crashing on null pointers.
    • Verified LP64/LLP64 portability, null checks, and bounds safety across AppendGuestBytes, AppendElement, and CopyInPreservingErrno.
    • Verified strict AGENTS.md compliance: no comments introduced in source code, technical debt fragment present in docs/dev/debt/changes/, and conventions pass mechanically.

Looks Good To Me

@MarcZX10 MarcZX10 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — looks good

The change fixes public key decoding by rebuilding SubjectPublicKeyInfo from the algorithm and key bits; no blocking defect was verified in the code read.

What I ran

Read the prepared description, commits, manifest, diff, and changed source files at head 4d5bc3a52155eaa19d12d8c46d30223874c41a8d. No tests or other commands were run.

Results

Check Result Note
Changed source review passed Core encoding and cleanup paths read
Tests not run Results in the description are author-reported
Remaining changed files not run Test and debt files not read in full

Findings

Blocking

None.

Non-blocking

None.

Not verified

The changed test files and debt fragment were not read. Console, Windows, and macOS behavior was not verified. The author-reported test results were not independently run.

To get this to a good state

Nothing is required.

@throny throny left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: ✅ correct

Basis: code read; compared with LibreSSL ce488b78 (the revision the debt file links), x509/x509_cmp.c and asn1/x_pubkey.c

Checked

  • On main, DecodeEncodedKey fed the BIT STRING contents to d2i_PUBKEY as if they were a whole SubjectPublicKeyInfo, while DecodePubkey stores only the key bits in publicKey and the algorithm in algor, so X509_get0_pubkey returned null for certificates loaded through X509_STORE_load_locations or PKCS7.
  • Now it re-encodes algorithm + key bits as an SPKI and caches the result in the X509_PUBKEY, returning an already-cached key, as X509_PUBKEY_get0 does (x_pubkey.c:185-229). The key is borrowed and freed in FreePubkey; the PKCS7 test's empty-allocation check covers leaks.
  • Tests (EC P-256, RSA 512/1024/2048, unused-bits flags, null algorithm, read-only memory) fail on main.

Findings

  1. For a malformed key, the error queue holds what d2i_PUBKEY queues (ASN1/EVP codes); LibreSSL pushes X509_R_UNSUPPORTED_ALGORITHM / X509_R_PUBLIC_KEY_DECODE_ERROR. Covered by the debt entry's "compared with the console" condition; not blocking.

Suggested action: merge.

AI-assisted review (Claude Code) · head 4d5bc3a521 · base main 337a948bf1

@oneandonlydean
oneandonlydean merged commit 393814d into boykopovar:main Nov 22, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants