Skip to content

fix(security): wipe private keys parsed on the add-key, import and new-wallet screens - #1151

Merged
lklimek merged 3 commits into
v1.0-devfrom
fix/zeroize-remaining-key-inputs
Oct 28, 2026
Merged

lklimek merged 3 commits into
v1.0-devfrom
fix/zeroize-remaining-key-inputs

Conversation

@Claudius-Maginificent

@Claudius-Maginificent Claudius-Maginificent commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

The remaining places that parse a private key or derive a wallet seed now hold them in Zeroizing, so they are wiped when dropped instead of being left in freed memory. This covers:

  • the Add Key screen;
  • private-key import;
  • the SingleKeyWallet WIF and hex parsers;
  • the new-wallet and import-wallet seeds.

Identity load also reserves its user-key list up front, so growing the list leaves no key copies behind. Accepted inputs and messages do not change.

User story

As an Everyday User who pastes a private key or enters a recovery phrase, I want the app to wipe its working copies of that key or seed once it is done with them, so that a later memory dump or swap file does not reveal it.

Scenario

  1. The user does one of the following:
    • adds a key to an identity by pasting its private key as hex;
    • imports a single key as WIF or hex;
    • creates a wallet;
    • imports a wallet from a recovery phrase.
  2. Before:
    • hex was decoded into a plain Vec, then copied into a plain [u8; 32], and the partly decoded bytes were dropped unwiped when a later character was bad;
    • the imported WIF text was a plain String;
    • the BIP39 seed was a plain [u8; 64].
  3. After: each of these is held in Zeroizing and wiped when dropped. The only copies left are the ones the stored and task types take by value.

The messages are unchanged: "Private key not 32 bytes", "Invalid hex string for private key.", "Hex private keys must be exactly 32 bytes; got N bytes.", and the rest.

Detailed discussion

This PR follows #1150, which did the same for verify_key_input, the identity-load lookups and the Key Info screen. It covers SEC-005 from the #1150 review, plus SEC-001 and SEC-002. It is based on v1.0-dev and merges cleanly with #1150.

  • model::key_input::decode_hex_secret (new). It decodes hex straight into a Zeroizing<Vec<u8>> of size len / 2 using hex::decode_to_slice.
    • decode_to_slice checks for an odd length first, and the buffer always has the right length. So it accepts and rejects exactly what hex::decode does, with the same FromHexError: OddLength, then InvalidHexCharacter at the same index.
    • The buffer never grows, and a partly decoded value is wiped with it.
  • Add Key screen (add_key_screen.rs): uses decode_hex_secret, and the key is a Zeroizing<[u8; 32]>. It is hex-encoded from a slice, so no plain temporary is made.
  • Private-key import (import_mnemonic_screen.rs):
    • hex goes through decode_hex_secret, and the parsed key is Zeroizing;
    • the WIF text, whether typed or converted from hex, is a Zeroizing<String>;
    • the recovery-phrase seed is Zeroizing<[u8; 64]>.
  • SingleKeyWallet::from_wif / from_hex (model/wallet/single_key.rs): the WIF path keeps the Zeroizing that EcdsaSecretKey::to_bytes() returns, and the hex path uses decode_hex_secret.
  • Closed single key (model/wallet/single_key.rs): without a password, ClosedSingleKey.encrypted_private_key holds the raw key, but only the open key was wiped on drop. The import preview rebuilds its SingleKeyWallet on every edit, so each replaced preview freed a plain copy of the key. ClosedSingleKey now implements Zeroize, which wipes encrypted_private_key, and runs it on drop. The stored format is unchanged.
  • New wallet (add_new_wallet_screen.rs): the seed is Zeroizing<[u8; 64]>. This is the same one-line change as the import screen, kept consistent.
  • Identity load (SEC-001): Vec<PrivateKey> is built with Vec::with_capacity(keys_input.len()) in a plain loop. collect over filter_map has a lower size hint of 0, so it reallocated and memcpy'd the keys, then freed the old buffer without running Drop. The early return on the first bad key is unchanged.

What remains, deliberately:

  • After fix(security): wipe parsed private-key copies from memory #1150 merges, Key Info still has its own hex pre-scan next to the shared decode_hex_secret. The two behave the same. Routing Key Info through decode_hex_secret is a small follow-up once both PRs are in: Ok with 32 bytes reads the key, any other Ok gives "not 32 bytes", and Err falls back to WIF.

  • Copies into types taken by value stay. This covers Wallet::new_from_seed([u8; 64]), SingleKeyWallet::new([u8; 32]), IdentityTask::AddKeyToIdentity(.., [u8; 32]) and the stored key formats. Changing them is a wider type or storage change.

  • Stack slots left behind when a Zeroizing value moves are the usual residual of Zeroizing. That is SEC-003 in the fix(security): wipe parsed private-key copies from memory #1150 review.

  • The recovery-phrase word fields and the egui text buffers are out of scope.

  • Upstream copies are reported for upstream fixes: dashcore::signer::sign_hash, PrivateKey::from_wif via base58ck::decode_check, and dpp validate_private_key_bytes_for_key_data.

Testing

New tests pin the unchanged behaviour:

  • model::key_input::tests::decode_hex_secret_matches_hex_decode compares bytes and errors against hex::decode. The inputs cover empty, valid, wrong length, odd length, non-hex, a bad character late in the string, and free text.
  • ui::wallets::import_mnemonic_screen::tests::hex_private_key_rejections_are_unchanged checks that 31-byte hex gives PrivateKeyWrongLength { byte_count: 31 }, that odd-length and non-hex input give PrivateKeyUnrecognized, and that nothing is imported.
  • ui::wallets::import_mnemonic_screen::tests::a_32_byte_hex_private_key_is_imported covers the success path: 32-byte hex is converted to WIF and imported, and the imported key's address is the one the hex names.
  • model::wallet::single_key::tests::closed_key_wipes_its_stored_key_bytes checks that zeroize empties encrypted_private_key and keeps the hash, salt and nonce. It also checks at compile time that ClosedSingleKey is ZeroizeOnDrop.
  • model::wallet::single_key::tests::from_hex_rejections_keep_their_messages checks the hex::decode error text and the wrong-length message.
  • ui::identity::keys::key_info_screen::tests::a_paste_is_read_as_hex_when_it_is_hex_and_as_wif_otherwise pins the hex-or-WIF split by its banners (SEC-002):
    • 31-byte hex, and valid hex of a WIF key's length (52 characters), both give "Private key not 32 bytes". The 52-character case is not a valid WIF either, so it pins the message, not which format is tried first;
    • odd-length and non-hex input give "Invalid hex string or WIF for private key.".
    • A 64-character hex paste is still saved, as covered by a_write_behind_the_screen_survives_a_paste.

These are behaviour pins, so they pass before and after the change; there is no RED step for a refactor that keeps behaviour. Zeroization itself is not tested with memory-scraping tests, because those would be unreliable.

Run with cargo test --all-features --lib -- model::key_input model::wallet::single_key ui::wallets::import_mnemonic_screen ui::identity::keys::key_info_screen backend_task::identity::load_identity wallet_backend::single_key backend_task::migration::single_key_restore: 127 passed. cargo clippy --all-features --lib --profile test -- -D warnings is clean.

🤖 Generated with Claude Code

https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q

PR Hygiene · f87a006

  • Bots — coderabbitai skipped by lklimek · thepastaclaw skipped by lklimek
  • Self-review — not asked of a bot author
  • Build green
  • Approvals
    • files with no dedicated owner (src/backend_task/identity/load_identity.rs, src/model/key_input.rs, src/model/wallet/single_key.rs and 4 more) — approved by lklimek

When every merge requirement is met, the PR Hygiene check passes. Reviewer limits do not block merging; other required GitHub checks and protections still apply.

The Add Key screen, the private-key import, the single-key wallet
parsers and the new-wallet and import-wallet seeds kept private keys
and seeds in plain arrays, Vecs and Strings that were freed without
being erased.

A shared model::key_input::decode_hex_secret decodes hex straight into
a Zeroizing buffer of the final size. It accepts and rejects exactly
what hex::decode does, with the same error, so every caller keeps its
messages. Parsed keys, the imported WIF text and the BIP39 seeds are
held in Zeroizing. The user-key list on identity load reserves its
capacity up front, so growth does not leave key copies in freed heap.

New tests pin the unchanged behaviour: decode_hex_secret against
hex::decode, the import screen's hex rejections, SingleKeyWallet::from_hex
messages, and the Key Info hex-or-WIF split by its banners.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q
@coderabbitai

coderabbitai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 59 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

Learn how review limits work.

Review configuration:

Run configuration
Commits

Reviewing files that changed from the base of the PR and between cba068d and f87a006.

Files selected for processing: 7
  • src/backend_task/identity/load_identity.rs
  • src/model/key_input.rs
  • src/model/wallet/single_key.rs
  • src/ui/identity/keys/add_key_screen.rs
  • src/ui/identity/keys/key_info_screen.rs
  • src/ui/wallets/add_new_wallet_screen.rs
  • src/ui/wallets/import_mnemonic_screen.rs
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

⛔ Final review complete — 1 blocking finding(s) (commit f87a006)

lklimek and others added 2 commits October 27, 2026 15:16
With no password, ClosedSingleKey.encrypted_private_key holds the raw
private key, but only the open key was wiped on drop. The import preview
rebuilds its SingleKeyWallet on every edit, so each replaced preview
freed a plain copy of the key.

ClosedSingleKey now implements Zeroize, wiping encrypted_private_key,
and runs it on drop. The stored format is unchanged; the hash, salt and
nonce are not secret and are kept.

Also from review: a test for the 32-byte hex import success path, and a
corrected comment on the 52-character Key Info case, which does not
prove that hex is tried before WIF.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q
@Claudius-Maginificent
Claudius-Maginificent marked this pull request as ready for review October 28, 2026 10:25
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai not yet · thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Oct 28, 2026

@thepastaclaw thepastaclaw left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Final validation — Phase 2 only (no Phase 1 for this repository)

The implementation changes are otherwise consistent with the stated zeroization goal, and the available CI checks passed. However, the PR adds deterministic 32-byte private-key material to repository tests, violating the repository's explicit prohibition on committing private keys outside the approved historical fixture; this must be removed before merge.

🔴 1 blocking

Review provenance

Source: reviewer 1: gpt-6.1-sol (agent: phase2-reviewer, role: general); reviewer 2: gpt-6.1-sol (agent: phase2-reviewer, role: rust-quality); final verifier: gpt-6.1-sol (agent: sol-verifier, role: final-verifier)

  • Triage: critical by gpt-6.1-sol (effort low) — The diff is intricate and directly changes private-key and wallet-seed handling in functions such as decode_hex_secret, SingleKeyWallet::from_wif/from_hex, and identity loading, which are critical key-handling surfaces.
  • Phase 1 reviewers: not run (disabled for this repository)
  • Fresh verifier: gpt-6.1-sol — final-verifier; agent sol-verifier
  • Phase 2 reviewers: gpt-6.1-sol — general (completed, effort xhigh); agent phase2-reviewer, gpt-6.1-sol — rust-quality (completed, effort xhigh); agent phase2-reviewer
🤖 Prompt for all review comments with AI agents
These findings are from an automated code review. Verify each finding against the current code and only fix it if needed.

In `src/ui/wallets/import_mnemonic_screen.rs`:
- [BLOCKING] src/ui/wallets/import_mnemonic_screen.rs:785-789: Do not commit hard-coded private-key material in tests
  This test embeds `[0x2B; 32]` and verifies that it is accepted by `PrivateKey::from_byte_array`, making the bytes an explicitly valid private key committed to the repository. The same pattern appears in `src/model/wallet/single_key.rs:510` as `[0x2A; 32]` in the zeroization test. The repository policy prohibits plaintext private keys in tests and documentation except for the specifically approved historical migration fixture. Generate valid key bytes at runtime using the existing randomness facilities, or use a non-secret test helper, so no deterministic private-key material is stored in git.
Out-of-scope follow-up suggestions (1)

These are valid observations, but they are outside this PR's scope and should be handled in separate issues or author/maintainer-requested PRs rather than blocking this review.

  • Upstream WIF decoding still retains additional transient copies — The pinned rust-dashcore implementation decodes WIF data into a plain buffer in PrivateKey::from_wif, so this local PR cannot guarantee complete wiping of every upstream transient on the WIF path. The issue is tracked upstream as dashpay/rust-dashcore#1225 and should be addressed there before updating the dependency.

@github-actions github-actions Bot added waiting-self-review Waiting for the author to post /self-reviewed bot-review-skipped A required review bot did not report; it was skipped by the window or by a person. and removed waiting-bots Waiting for the review bots to report on this head labels Oct 28, 2026
@lklimek
lklimek dismissed thepastaclaw’s stale review October 28, 2026 15:54

False positive - this is a placeholder, not a key.

@lklimek
lklimek enabled auto-merge (squash) October 28, 2026 15:58
@github-actions

Copy link
Copy Markdown
Contributor

Waiting for bot review — coderabbitai skipped after its own rate limit · thepastaclaw not yet. Wait for the missing reviews, or a writer can post /skip-bots to proceed without them; blocking findings still need addressing.
Full checklist in the description.

@github-actions github-actions Bot added waiting-bots Waiting for the review bots to report on this head and removed waiting-self-review Waiting for the author to post /self-reviewed labels Oct 28, 2026
@lklimek

lklimek commented Oct 28, 2026

Copy link
Copy Markdown
Contributor

/skip-bots

@github-actions

Copy link
Copy Markdown
Contributor

Policy satisfied — this can merge.
Full checklist in the description.

@github-actions github-actions Bot removed the waiting-bots Waiting for the review bots to report on this head label Oct 28, 2026
@lklimek
lklimek merged commit 19747b8 into v1.0-dev Oct 28, 2026
20 checks passed
@lklimek
lklimek deleted the fix/zeroize-remaining-key-inputs branch October 28, 2026 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot-review-skipped A required review bot did not report; it was skipped by the window or by a person.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants