Skip to content

Commit 1604e8c

Browse files
authored
fix(crypto): reading and writing a private key as PEM zeroizes every buffer (#638)
## What and why Exporting a private key as PEM could leave copies of the key in freed memory. `Pem::encode` built the key's base64 and its 64-character lines in plain `String`s that weren't zeroized when dropped. Only the final `private_key_pem` result was `Zeroizing`, and `format!` built that result by growing a buffer, so each reallocation freed an earlier partial copy without wiping it. Now the base64 is `Zeroizing`, and the PEM is written into one `Zeroizing<String>` allocated at its exact final size, so it never reallocates. `Pem::encode` returns that buffer, `private_key_pem` returns it unchanged, and `PublicKey::pem` copies the public key's PEM out into the `String` it already returned. The public API doesn't change. Decoding had the same gap: `Pem::decode` collected the base64 with `split_whitespace().collect()`, which reallocates as it grows. It now gathers it into a `Zeroizing` buffer allocated at the body's size. Closes #630 ## Testing **Why no test fails on the leak itself:** whether freed memory was wiped can't be observed from safe Rust. Instead, the new `private_key_pem_writes_back_the_pem_it_was_read_from` test checks two things: - **The output is byte-identical:** the SDK vectors' `key-2025.pem` fixture (written by `openssl`), read and exported again, comes back exactly as the file. This already passed on `main`, so the change doesn't alter the bytes. - **The PEM buffer never reallocated:** its capacity equals its length. On `main` this fails (`left: 3356, right: 1704`), because `format!` grew the result, leaving freed copies. With the fix it passes. Also: - `just test -p sourceorigin-crypto --all-features`: 18/18 pass, including the existing PEM round trip in `jwt_persistence_and_trust_boundaries` and the SDK vectors. - Clippy with and without `--all-features` (`-D warnings`), rustdoc with `-D warnings`, `just rust unused`: clean. - `cargo semver-checks -p sourceorigin-crypto --baseline-rev origin/main`: 202 checks pass, no semver update required. ## Checklist - [x] Every surface gets the feature: no surface changes. - [ ] `just validate` passes: I ran the package-scoped checks above, not the whole workspace. - [x] Generated files are regenerated in the same commit: none are affected. > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by Claude Opus 5.5 (via T3 Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
1 parent 0053454 commit 1604e8c

2 files changed

Lines changed: 38 additions & 13 deletions

File tree

‎crates/crypto/src/signing/mod.rs‎

Lines changed: 26 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,8 @@ impl PublicKey {
125125
pub fn pem(&self) -> String {
126126
// `from_jwk` refused a key with a defect, so this one has its DER.
127127
Pem::encode(PUBLIC_KEY_LABEL, self.key.der().unwrap_or_default())
128+
.as_str()
129+
.to_owned()
128130
}
129131

130132
/// Whether this key signs with `alg`. Requiring the header's algorithm to be
@@ -244,10 +246,7 @@ impl Rs256Key {
244246
/// # Errors
245247
/// Preserves encoding failures from the provider.
246248
pub fn private_key_pem(&self) -> Result<Zeroizing<String>, CryptoError> {
247-
Ok(Zeroizing::new(Pem::encode(
248-
PKCS8_LABEL,
249-
&self.private_key_der()?,
250-
)))
249+
Ok(Pem::encode(PKCS8_LABEL, &self.private_key_der()?))
251250
}
252251

253252
/// Signs claims as a compact RS256 token whose `typ` header is `token_type`.
@@ -423,28 +422,42 @@ struct Pem;
423422

424423
impl Pem {
425424
/// The DER of the first block labelled `label` in `text`, if it decodes.
426-
/// A private key's base64 and DER are zeroized when dropped.
425+
/// A private key's base64 and DER are zeroized when dropped; the base64 is
426+
/// gathered into a buffer allocated at the body's size, so it never
427+
/// reallocates and leaves no copy behind.
427428
fn decode(text: &str, label: &str) -> Option<Zeroizing<Vec<u8>>> {
428429
let begin = format!("-----BEGIN {label}-----");
429430
let end = format!("-----END {label}-----");
430431
let body = text.split_once(&begin)?.1.split_once(&end)?.0;
431-
let base64: Zeroizing<String> = Zeroizing::new(body.split_whitespace().collect());
432+
let mut base64 = Zeroizing::new(String::with_capacity(body.len()));
433+
for piece in body.split_whitespace() {
434+
base64.push_str(piece);
435+
}
432436
STANDARD.decode(base64.as_str()).ok().map(Zeroizing::new)
433437
}
434438

435-
/// `der` as a block labelled `label`, in lines of 64 characters.
436-
fn encode(label: &str, der: &[u8]) -> String {
437-
let base64 = STANDARD.encode(der);
438-
let mut lines = String::new();
439+
/// `der` as a block labelled `label`, in lines of 64 characters. For a private
440+
/// key's sake, every buffer holding its base64 is zeroized when dropped, and
441+
/// the PEM is allocated at its final size, so it never reallocates and leaves
442+
/// a copy behind in freed memory.
443+
fn encode(label: &str, der: &[u8]) -> Zeroizing<String> {
444+
let base64 = Zeroizing::new(STANDARD.encode(der));
445+
let begin = format!("-----BEGIN {label}-----\n");
446+
let end = format!("-----END {label}-----\n");
447+
let mut pem = Zeroizing::new(String::with_capacity(
448+
begin.len() + base64.len() + base64.len().div_ceil(64) + end.len(),
449+
));
450+
pem.push_str(&begin);
439451
// Base64 is ASCII, so any split falls between characters.
440452
let mut rest = base64.as_str();
441453
while !rest.is_empty() {
442454
let (line, tail) = rest.split_at(rest.len().min(64));
443-
lines.push_str(line);
444-
lines.push('\n');
455+
pem.push_str(line);
456+
pem.push('\n');
445457
rest = tail;
446458
}
447-
format!("-----BEGIN {label}-----\n{lines}-----END {label}-----\n")
459+
pem.push_str(&end);
460+
pem
448461
}
449462
}
450463

‎crates/crypto/src/signing/tests.rs‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,3 +154,15 @@ fn key_set_verifies_by_kid_and_limits_retired_keys_to_hints() {
154154
Err(CryptoError::KeySet)
155155
));
156156
}
157+
158+
/// A private key exports as the PKCS#8 PEM `openssl` writes, byte for byte, so
159+
/// a key read from a fixture writes back the same file. The export fills the
160+
/// buffer it was allocated, so it never reallocated and left a copy unzeroized.
161+
#[test]
162+
fn private_key_pem_writes_back_the_pem_it_was_read_from() {
163+
let pem = include_str!("../../../../tests/sdk-vectors/keys/key-2025.pem");
164+
let key = Rs256Key::from_pem("2025", pem).expect("fixture key");
165+
let exported = key.private_key_pem().expect("export PEM");
166+
assert_eq!(exported.as_str(), pem);
167+
assert_eq!(exported.capacity(), exported.len());
168+
}

0 commit comments

Comments
 (0)