Merge pull request 'feat(core): zeroize in-memory secret material (Noise/Ed25519/X25519/store key)' (#46) from feat/zeroize-secrets into main
All checks were successful
ci / test (push) Successful in 3m54s
release / version (push) Successful in 2s
release / x86_64 (push) Successful in 1m53s
release / aarch64 (push) Successful in 2m27s
release / publish (push) Successful in 11s

Reviewed-on: #46
This commit is contained in:
sirius 2026-09-12 19:06:58 +00:00
commit c39259b919
12 changed files with 297 additions and 71 deletions

1
Cargo.lock generated
View file

@ -2654,6 +2654,7 @@ dependencies = [
"tor-rtcompat", "tor-rtcompat",
"tracing-subscriber", "tracing-subscriber",
"x25519-dalek", "x25519-dalek",
"zeroize",
] ]
[[package]] [[package]]

View file

@ -47,6 +47,7 @@ sha3 = "0.10"
sha2 = "0.10" sha2 = "0.10"
md-5 = "0.10" md-5 = "0.10"
rpassword = "7" rpassword = "7"
zeroize = { version = "1", features = ["derive"] }
[dev-dependencies] [dev-dependencies]
tempfile = "3" tempfile = "3"

View file

@ -4,6 +4,7 @@ use argon2::{Algorithm, Argon2, Params, Version};
use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload}; use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload};
use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use rand::RngCore; use rand::RngCore;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
pub const MAGIC: &[u8] = b"owbak1"; pub const MAGIC: &[u8] = b"owbak1";
const SALT_LEN: usize = 16; const SALT_LEN: usize = 16;
@ -11,17 +12,31 @@ const NONCE_LEN: usize = 12;
const KEY_LEN: usize = 32; const KEY_LEN: usize = 32;
const PLAIN_LEN: usize = KEY_LEN * 4; const PLAIN_LEN: usize = KEY_LEN * 4;
#[derive(Debug, Clone, PartialEq, Eq)] /// The identity bundle. Secret halves wipe on drop; `Debug` never prints them.
#[derive(Clone, PartialEq, Eq, Zeroize, ZeroizeOnDrop)]
pub struct BackupKeys { pub struct BackupKeys {
pub identity_sk: [u8; 32], pub identity_sk: [u8; 32],
#[zeroize(skip)]
pub identity_pk: [u8; 32], pub identity_pk: [u8; 32],
pub prekey_sk: [u8; 32], pub prekey_sk: [u8; 32],
#[zeroize(skip)]
pub prekey_pk: [u8; 32], pub prekey_pk: [u8; 32],
} }
impl std::fmt::Debug for BackupKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BackupKeys")
.field("identity_sk", &"<redacted>")
.field("identity_pk", &self.identity_pk)
.field("prekey_sk", &"<redacted>")
.field("prekey_pk", &self.prekey_pk)
.finish()
}
}
impl BackupKeys { impl BackupKeys {
pub fn to_bytes(&self) -> [u8; PLAIN_LEN] { pub fn to_bytes(&self) -> Zeroizing<[u8; PLAIN_LEN]> {
let mut out = [0u8; PLAIN_LEN]; let mut out = Zeroizing::new([0u8; PLAIN_LEN]);
out[0..32].copy_from_slice(&self.identity_sk); out[0..32].copy_from_slice(&self.identity_sk);
out[32..64].copy_from_slice(&self.identity_pk); out[32..64].copy_from_slice(&self.identity_pk);
out[64..96].copy_from_slice(&self.prekey_sk); out[64..96].copy_from_slice(&self.prekey_sk);
@ -42,7 +57,7 @@ impl BackupKeys {
} }
} }
pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<[u8; 32], String> { pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>, String> {
if passphrase.is_empty() { if passphrase.is_empty() {
return Err("empty passphrase".into()); return Err("empty passphrase".into());
} }
@ -51,9 +66,9 @@ pub(crate) fn kdf(passphrase: &str, salt: &[u8]) -> Result<[u8; 32], String> {
} }
let params = Params::new(19_456, 2, 1, Some(32)).map_err(|e| e.to_string())?; let params = Params::new(19_456, 2, 1, Some(32)).map_err(|e| e.to_string())?;
let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); let argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
let mut key = [0u8; 32]; let mut key = Zeroizing::new([0u8; 32]);
argon argon
.hash_password_into(passphrase.as_bytes(), salt, &mut key) .hash_password_into(passphrase.as_bytes(), salt, &mut key[..])
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
Ok(key) Ok(key)
} }
@ -62,13 +77,13 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result<Vec<u8>, String> {
let mut salt = [0u8; SALT_LEN]; let mut salt = [0u8; SALT_LEN];
rand::rngs::OsRng.fill_bytes(&mut salt); rand::rngs::OsRng.fill_bytes(&mut salt);
let key = kdf(passphrase, &salt)?; let key = kdf(passphrase, &salt)?;
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key)); let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng);
if nonce.len() != NONCE_LEN { if nonce.len() != NONCE_LEN {
return Err("nonce length".into()); return Err("nonce length".into());
} }
let ct = cipher let ct = cipher
.encrypt(&nonce, keys.to_bytes().as_ref()) .encrypt(&nonce, &keys.to_bytes()[..])
.map_err(|_| "encrypt failed".to_string())?; .map_err(|_| "encrypt failed".to_string())?;
let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len()); let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len());
out.extend_from_slice(MAGIC); out.extend_from_slice(MAGIC);
@ -88,11 +103,13 @@ pub fn open(passphrase: &str, blob: &[u8]) -> Result<BackupKeys, String> {
let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]); let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]);
let ct = &blob[nonce_off + NONCE_LEN..]; let ct = &blob[nonce_off + NONCE_LEN..];
let key = kdf(passphrase, salt)?; let key = kdf(passphrase, salt)?;
let cipher = ChaCha20Poly1305::new(Key::from_slice(&key)); let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..]));
let pt = cipher let pt = Zeroizing::new(
.decrypt(nonce, ct) cipher
.map_err(|_| "wrong passphrase or corrupt backup".to_string())?; .decrypt(nonce, ct)
BackupKeys::from_bytes(&pt) .map_err(|_| "wrong passphrase or corrupt backup".to_string())?,
);
BackupKeys::from_bytes(&pt[..])
} }
pub(crate) fn aead_encrypt( pub(crate) fn aead_encrypt(
@ -133,3 +150,45 @@ pub(crate) fn aead_decrypt(key: &[u8; 32], blob: &[u8], aad: &[u8]) -> Result<Ve
) )
.map_err(|_| "wrong passphrase or corrupt".to_string()) .map_err(|_| "wrong passphrase or corrupt".to_string())
} }
#[cfg(test)]
mod tests {
use super::*;
fn keys(tag: u8) -> BackupKeys {
BackupKeys {
identity_sk: [tag; 32],
identity_pk: [tag.wrapping_add(1); 32],
prekey_sk: [tag.wrapping_add(2); 32],
prekey_pk: [tag.wrapping_add(3); 32],
}
}
#[test]
fn derived_wrap_key_is_a_zeroizing_buffer() {
let mut key = kdf("correct horse", &[7u8; 16]).expect("kdf");
let _: &Zeroizing<[u8; 32]> = &key;
let before = *key;
assert_ne!(before, [0u8; 32]);
key.zeroize();
assert_eq!(*key, [0u8; 32], "derived key not wiped");
}
#[test]
fn backup_plaintext_buffer_is_a_zeroizing_buffer() {
let mut bytes = keys(5).to_bytes();
let _: &Zeroizing<[u8; PLAIN_LEN]> = &bytes;
assert_eq!(&bytes[..32], &[5u8; 32][..]);
bytes.zeroize();
assert_eq!(&bytes[..], &[0u8; PLAIN_LEN][..], "backup plaintext kept");
}
#[test]
fn backup_keys_debug_redacts_the_secret_halves() {
let dbg = format!("{:?}", keys(0xAB));
assert!(!dbg.contains("171"), "identity secret in Debug: {dbg}");
assert!(!dbg.contains("173"), "prekey secret in Debug: {dbg}");
assert!(dbg.contains("<redacted>"), "{dbg}");
assert!(dbg.contains("174"), "public half should stay: {dbg}");
}
}

View file

@ -8,6 +8,7 @@ use futures::StreamExt;
use futures::io::{AsyncRead, AsyncWrite}; use futures::io::{AsyncRead, AsyncWrite};
use tor_cell::relaycell::msg::Connected; use tor_cell::relaycell::msg::Connected;
use tor_hsservice::{RunningOnionService, handle_rend_requests}; use tor_hsservice::{RunningOnionService, handle_rend_requests};
use zeroize::Zeroizing;
use crate::dispatch::{self, Kind}; use crate::dispatch::{self, Kind};
use crate::file; use crate::file;
@ -65,12 +66,14 @@ pub struct Node {
impl Node { impl Node {
pub async fn start(home: PathBuf) -> Result<Arc<Self>, String> { pub async fn start(home: PathBuf) -> Result<Arc<Self>, String> {
let pass = std::env::var("ONIONWIRE_STORE_PASSPHRASE") let pass = Zeroizing::new(
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?; std::env::var("ONIONWIRE_STORE_PASSPHRASE")
.map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?,
);
if pass.is_empty() { if pass.is_empty() {
return Err("empty passphrase".into()); return Err("empty passphrase".into());
} }
Self::start_with_passphrase(home, &pass).await Self::start_with_passphrase(home, pass.as_str()).await
} }
pub async fn start_with_passphrase( pub async fn start_with_passphrase(

View file

@ -1,5 +1,6 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use sha3::{Digest, Keccak256}; use sha3::{Digest, Keccak256};
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
@ -386,9 +387,12 @@ fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec<u8> {
} }
fn sign_bytes(identity_sk: &[u8], msg: &[u8]) -> Result<Vec<u8>> { fn sign_bytes(identity_sk: &[u8], msg: &[u8]) -> Result<Vec<u8>> {
let sk_bytes: [u8; 32] = identity_sk // ed25519-dalek's `SigningKey` wipes itself on drop (its default `zeroize`
.try_into() // feature); the raw copy we make to build it is ours to wipe.
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?; let sk_bytes = Zeroizing::new(
<[u8; 32]>::try_from(identity_sk)
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?,
);
let sk = SigningKey::from_bytes(&sk_bytes); let sk = SigningKey::from_bytes(&sk_bytes);
Ok(sk.sign(msg).to_bytes().to_vec()) Ok(sk.sign(msg).to_bytes().to_vec())
} }

View file

@ -1,4 +1,5 @@
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
@ -34,9 +35,10 @@ pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result<S
if !is_v3_onion(onion) { if !is_v3_onion(onion) {
return Err(Error("o must be a v3 onion".into())); return Err(Error("o must be a v3 onion".into()));
} }
let sk_bytes: [u8; 32] = identity_sk let sk_bytes = Zeroizing::new(
.try_into() <[u8; 32]>::try_from(identity_sk)
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?; .map_err(|_| Error("identity secret key must be 32 bytes".into()))?,
);
let sk = SigningKey::from_bytes(&sk_bytes); let sk = SigningKey::from_bytes(&sk_bytes);
let k = to_hex(&sk.verifying_key().to_bytes()); let k = to_hex(&sk.verifying_key().to_bytes());
let spk = to_hex(signed_prekey); let spk = to_hex(signed_prekey);

View file

@ -2,6 +2,7 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use rand::rngs::OsRng; use rand::rngs::OsRng;
use snow::Builder; use snow::Builder;
use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use crate::store::SelfIdentity; use crate::store::SelfIdentity;
@ -61,11 +62,15 @@ impl From<snow::Error> for Error {
} }
} }
#[derive(Clone)] /// Local secret keys. `Clone` copies the secrets, but the copy is itself
/// `ZeroizeOnDrop`, so no clone outlives its owner un-wiped.
#[derive(Clone, Zeroize, ZeroizeOnDrop)]
pub struct Keys { pub struct Keys {
pub identity_sk: [u8; 32], pub identity_sk: [u8; 32],
#[zeroize(skip)]
pub identity_pk: [u8; 32], pub identity_pk: [u8; 32],
pub prekey_sk: [u8; 32], pub prekey_sk: [u8; 32],
#[zeroize(skip)]
pub prekey_pk: [u8; 32], pub prekey_pk: [u8; 32],
} }
@ -131,7 +136,7 @@ pub fn handshake_pinned(init: &Keys, resp: &Keys, pinned: &[u8; 32]) -> Result<(
.prologue(PROLOGUE)? .prologue(PROLOGUE)?
.build_responder()?; .build_responder()?;
let mut buf = vec![0u8; MSG_BUF]; let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let n = initiator.write_message(&[], &mut buf)?; let n = initiator.write_message(&[], &mut buf)?;
let msg1 = buf[..n].to_vec(); let msg1 = buf[..n].to_vec();
let n = responder.read_message(&msg1, &mut buf)?; let n = responder.read_message(&msg1, &mut buf)?;
@ -200,7 +205,7 @@ where
.prologue(PROLOGUE)? .prologue(PROLOGUE)?
.build_initiator()?; .build_initiator()?;
let mut buf = vec![0u8; MSG_BUF]; let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let n = hs.write_message(&[], &mut buf)?; let n = hs.write_message(&[], &mut buf)?;
crate::frame::write_frame(stream, &buf[..n]) crate::frame::write_frame(stream, &buf[..n])
.await .await
@ -254,7 +259,7 @@ where
.prologue(PROLOGUE)? .prologue(PROLOGUE)?
.build_responder()?; .build_responder()?;
let mut buf = vec![0u8; MSG_BUF]; let mut buf = Zeroizing::new(vec![0u8; MSG_BUF]);
let msg1 = crate::frame::read_frame(stream) let msg1 = crate::frame::read_frame(stream)
.await .await
.map_err(|e| Error::new(e.to_string()))?; .map_err(|e| Error::new(e.to_string()))?;

View file

@ -9,6 +9,7 @@ use rand::RngCore;
use rand::rngs::OsRng; use rand::rngs::OsRng;
use rusqlite::{Connection, OptionalExtension, params}; use rusqlite::{Connection, OptionalExtension, params};
use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; use x25519_dalek::{PublicKey as X25519Public, StaticSecret};
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
@ -52,14 +53,15 @@ impl From<Error> for String {
pub struct Store { pub struct Store {
conn: Connection, conn: Connection,
msg_key: [u8; 32], msg_key: Zeroizing<[u8; 32]>,
} }
/// The identity row. Secret halves wipe when this is dropped.
pub struct SelfIdentity { pub struct SelfIdentity {
pub identity_sk: Vec<u8>, pub identity_sk: Zeroizing<Vec<u8>>,
pub identity_pk: Vec<u8>, pub identity_pk: Vec<u8>,
pub onion: String, pub onion: String,
pub prekey_sk: Vec<u8>, pub prekey_sk: Zeroizing<Vec<u8>>,
pub prekey_pk: Vec<u8>, pub prekey_pk: Vec<u8>,
} }
@ -176,7 +178,8 @@ impl Store {
} }
pub fn open_at(home: &Path) -> Result<Self> { pub fn open_at(home: &Path) -> Result<Self> {
Self::open_at_with_passphrase(home, &passphrase_from_env()?) let passphrase = passphrase_from_env()?;
Self::open_at_with_passphrase(home, passphrase.as_str())
} }
pub fn open_at_with_passphrase(home: &Path, passphrase: &str) -> Result<Self> { pub fn open_at_with_passphrase(home: &Path, passphrase: &str) -> Result<Self> {
@ -278,7 +281,7 @@ impl Store {
} }
let mut store = Self { let mut store = Self {
conn, conn,
msg_key: [0u8; 32], msg_key: Zeroizing::new([0u8; 32]),
}; };
store.migrate()?; store.migrate()?;
store.ensure_self()?; store.ensure_self()?;
@ -354,8 +357,11 @@ impl Store {
match row { match row {
Some((salt, wrapped)) => { Some((salt, wrapped)) => {
let wrap_key = crate::backup::kdf(passphrase, &salt)?; let wrap_key = crate::backup::kdf(passphrase, &salt)?;
let raw = crate::backup::aead_decrypt(&wrap_key, &wrapped, b"") // The unwrapped data key lands in a Zeroizing buffer immediately.
.map_err(|_| Error("wrong passphrase".into()))?; let raw = Zeroizing::new(
crate::backup::aead_decrypt(&wrap_key, &wrapped, b"")
.map_err(|_| Error("wrong passphrase".into()))?,
);
if raw.len() != 32 { if raw.len() != 32 {
return Err(Error("wrapped message key length".into())); return Err(Error("wrapped message key length".into()));
} }
@ -364,12 +370,12 @@ impl Store {
Ok(()) Ok(())
} }
None => { None => {
let mut data_key = [0u8; 32]; let mut data_key = Zeroizing::new([0u8; 32]);
OsRng.fill_bytes(&mut data_key); OsRng.fill_bytes(&mut data_key[..]);
let mut salt = [0u8; 16]; let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt); OsRng.fill_bytes(&mut salt);
let wrap_key = crate::backup::kdf(passphrase, &salt)?; let wrap_key = crate::backup::kdf(passphrase, &salt)?;
let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key, b"")?; let wrapped = crate::backup::aead_encrypt(&wrap_key, &data_key[..], b"")?;
self.conn.execute( self.conn.execute(
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
params![salt.as_slice(), wrapped], params![salt.as_slice(), wrapped],
@ -463,13 +469,13 @@ impl Store {
})?; })?;
if exists == 0 { if exists == 0 {
let signing = SigningKey::generate(&mut OsRng); let signing = SigningKey::generate(&mut OsRng);
let sk = signing.to_bytes().to_vec(); let sk = Zeroizing::new(signing.to_bytes().to_vec());
let pk = signing.verifying_key().to_bytes().to_vec(); let pk = signing.verifying_key().to_bytes().to_vec();
let (psk, ppk) = gen_prekey(); let (psk, ppk) = gen_prekey();
self.conn.execute( self.conn.execute(
"INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname) "INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname)
VALUES (1, ?1, ?2, '', 0, ?3, ?4, 'ow0')", VALUES (1, ?1, ?2, '', 0, ?3, ?4, 'ow0')",
params![sk, pk, psk, ppk], params![&sk[..], pk, &psk[..], ppk],
)?; )?;
} else { } else {
let empty: i64 = self.conn.query_row( let empty: i64 = self.conn.query_row(
@ -481,7 +487,7 @@ impl Store {
let (psk, ppk) = gen_prekey(); let (psk, ppk) = gen_prekey();
self.conn.execute( self.conn.execute(
"UPDATE self SET prekey_sk = ?1, prekey_pk = ?2 WHERE id = 1", "UPDATE self SET prekey_sk = ?1, prekey_pk = ?2 WHERE id = 1",
params![psk, ppk], params![&psk[..], ppk],
)?; )?;
} }
} }
@ -495,10 +501,10 @@ impl Store {
[], [],
|row| { |row| {
Ok(SelfIdentity { Ok(SelfIdentity {
identity_sk: row.get(0)?, identity_sk: Zeroizing::new(row.get(0)?),
identity_pk: row.get(1)?, identity_pk: row.get(1)?,
onion: row.get(2)?, onion: row.get(2)?,
prekey_sk: row.get(3)?, prekey_sk: Zeroizing::new(row.get(3)?),
prekey_pk: row.get(4)?, prekey_pk: row.get(4)?,
}) })
}, },
@ -1099,10 +1105,10 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Friend> {
}) })
} }
fn gen_prekey() -> (Vec<u8>, Vec<u8>) { fn gen_prekey() -> (Zeroizing<Vec<u8>>, Vec<u8>) {
let sk = StaticSecret::random_from_rng(OsRng); let sk = StaticSecret::random_from_rng(OsRng);
let pk = X25519Public::from(&sk); let pk = X25519Public::from(&sk);
(sk.to_bytes().to_vec(), pk.to_bytes().to_vec()) (Zeroizing::new(sk.to_bytes().to_vec()), pk.to_bytes().to_vec())
} }
/// Per-install KDF salt for the whole-database key. Not secret (a salt never /// Per-install KDF salt for the whole-database key. Not secret (a salt never
@ -1202,7 +1208,7 @@ fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connec
/// the key, with no second KDF pass over it. /// the key, with no second KDF pass over it.
fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> { fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
let conn = Connection::open(db_path)?; let conn = Connection::open(db_path)?;
conn.execute_batch(&pragma_key(key))?; conn.execute_batch(pragma_key(key).as_str())?;
// A rejected key otherwise logs SQLCipher's internal "hmac check failed" // A rejected key otherwise logs SQLCipher's internal "hmac check failed"
// at ERROR to stderr. A wrong passphrase is a normal user error here. // at ERROR to stderr. A wrong passphrase is a normal user error here.
let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE"); let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE");
@ -1214,8 +1220,10 @@ fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
Ok(conn) Ok(conn)
} }
fn pragma_key(key: &[u8; 32]) -> String { /// SQLCipher's key material as hex inside the pragma text. The `String` holds
format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key)) /// the database key, so it wipes on drop.
fn pragma_key(key: &[u8; 32]) -> Zeroizing<String> {
Zeroizing::new(format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key)))
} }
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh /// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
@ -1250,10 +1258,11 @@ fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &s
let conn = Connection::open(db_path)?; let conn = Connection::open(db_path)?;
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
let target = tmp.to_string_lossy().replace('\'', "''"); let target = tmp.to_string_lossy().replace('\'', "''");
conn.execute_batch(&format!( let attach = Zeroizing::new(format!(
"ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";", "ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";",
hex = fingerprint(key) hex = fingerprint(key)
))?; ));
conn.execute_batch(attach.as_str())?;
conn.execute_batch("SELECT sqlcipher_export('enc');")?; conn.execute_batch("SELECT sqlcipher_export('enc');")?;
conn.execute_batch("DETACH DATABASE enc;")?; conn.execute_batch("DETACH DATABASE enc;")?;
} }
@ -1294,29 +1303,29 @@ fn home_dir() -> Result<PathBuf> {
Ok(PathBuf::from(home).join(".local/share/onionwire")) Ok(PathBuf::from(home).join(".local/share/onionwire"))
} }
fn passphrase_from_env() -> Result<String> { fn passphrase_from_env() -> Result<Zeroizing<String>> {
match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") {
Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())), Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())),
Ok(p) => Ok(p), Ok(p) => Ok(Zeroizing::new(p)),
Err(_) => Err(Error("ONIONWIRE_STORE_PASSPHRASE required".into())), Err(_) => Err(Error("ONIONWIRE_STORE_PASSPHRASE required".into())),
} }
} }
/// Env `ONIONWIRE_STORE_PASSPHRASE` if set (non-empty). Otherwise `read_secret` /// Env `ONIONWIRE_STORE_PASSPHRASE` if set (non-empty). Otherwise `read_secret`
/// (TTY, no echo). Empty values fail closed. /// (TTY, no echo). Empty values fail closed. The passphrase is wiped on drop.
pub fn resolve_store_passphrase( pub fn resolve_store_passphrase(
read_secret: impl FnOnce(&str) -> std::io::Result<String>, read_secret: impl FnOnce(&str) -> std::io::Result<String>,
) -> Result<String> { ) -> Result<Zeroizing<String>> {
match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") {
Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())), Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())),
Ok(p) => Ok(p), Ok(p) => Ok(Zeroizing::new(p)),
Err(_) => { Err(_) => {
let s = read_secret("onionwire: store passphrase: ")?; let s = read_secret("onionwire: store passphrase: ")?;
let s = s.trim_end_matches(['\n', '\r']).to_string(); let s = s.trim_end_matches(['\n', '\r']).to_string();
if s.is_empty() { if s.is_empty() {
Err(Error("empty passphrase".into())) Err(Error("empty passphrase".into()))
} else { } else {
Ok(s) Ok(Zeroizing::new(s))
} }
} }
} }
@ -1361,6 +1370,21 @@ fn fingerprint(pubkey: &[u8]) -> String {
#[cfg(test)] #[cfg(test)]
mod at_rest { mod at_rest {
use super::*; use super::*;
use zeroize::Zeroize;
#[test]
fn store_data_key_is_a_zeroizing_wrapper_that_wipes() {
let dir = tempfile::tempdir().unwrap();
let mut store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").unwrap();
// Type-level: the field is `Zeroizing<[u8; 32]>`, so its Drop wipes it.
let _: &Zeroizing<[u8; 32]> = &store.msg_key;
let before = *store.msg_key;
assert_ne!(before, [0u8; 32], "store has no data key");
store.msg_key.zeroize();
assert_eq!(*store.msg_key, [0u8; 32], "store data key not wiped");
}
#[test] #[test]
fn swapped_ciphertext_does_not_show_other_friends_body() { fn swapped_ciphertext_does_not_show_other_friends_body() {
@ -1598,10 +1622,10 @@ mod at_rest {
.unwrap(); .unwrap();
let mut salt = [0u8; 16]; let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt); OsRng.fill_bytes(&mut salt);
let mut data_key = [0u8; 32]; let mut data_key = Zeroizing::new([0u8; 32]);
OsRng.fill_bytes(&mut data_key); OsRng.fill_bytes(&mut data_key[..]);
let wrap = crate::backup::kdf(passphrase, &salt).unwrap(); let wrap = crate::backup::kdf(passphrase, &salt).unwrap();
let wrapped = crate::backup::aead_encrypt(&wrap, &data_key, b"").unwrap(); let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap();
conn.execute( conn.execute(
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
params![salt.as_slice(), wrapped], params![salt.as_slice(), wrapped],
@ -1651,7 +1675,10 @@ mod at_rest {
); );
let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade"); let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("open+upgrade");
assert_eq!(store.self_identity().unwrap().identity_sk, LEGACY_IDENTITY_SK); assert_eq!(
store.self_identity().unwrap().identity_sk[..],
LEGACY_IDENTITY_SK[..]
);
let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap(); let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap();
assert_eq!(msgs.len(), 2, "history must survive the upgrade"); assert_eq!(msgs.len(), 2, "history must survive the upgrade");
assert_eq!(msgs[0].plaintext, b"legacy-body-xyz"); assert_eq!(msgs[0].plaintext, b"legacy-body-xyz");

View file

@ -3,6 +3,7 @@ use std::time::Duration;
use rand::RngCore; use rand::RngCore;
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream; use tokio::net::TcpStream;
use zeroize::Zeroizing;
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
@ -23,7 +24,7 @@ struct Endpoint {
port: u16, port: u16,
path: String, path: String,
user: String, user: String,
pass: String, pass: Zeroizing<String>,
} }
impl std::fmt::Debug for Endpoint { impl std::fmt::Debug for Endpoint {
@ -59,12 +60,15 @@ impl Wallet {
pub fn from_env() -> Self { pub fn from_env() -> Self {
match std::env::var("ONIONWIRE_WALLET_RPC") { match std::env::var("ONIONWIRE_WALLET_RPC") {
// The URL can carry `user:pass@` in its userinfo: keep it in a
// wiping buffer, not a bare `String`.
Ok(s) if !s.trim().is_empty() => { Ok(s) if !s.trim().is_empty() => {
let url = Zeroizing::new(s);
let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN") let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN")
.ok() .ok()
.map(|v| v.trim().to_string()) .map(|v| Zeroizing::new(v.trim().to_string()))
.filter(|v| !v.is_empty()); .filter(|v| !v.is_empty());
match parse_http_url(s.trim(), login.as_deref()) { match parse_http_url(url.trim(), login.as_ref().map(|v| v.as_str())) {
Ok(endpoint) => Self { Ok(endpoint) => Self {
endpoint: Some(endpoint), endpoint: Some(endpoint),
}, },
@ -185,12 +189,12 @@ fn credentials_required() -> Error {
Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into()) Error("wallet RPC requires credentials (user:pass in URL or ONIONWIRE_WALLET_RPC_LOGIN)".into())
} }
fn parse_login(login: &str) -> Result<(String, String)> { fn parse_login(login: &str) -> Result<(String, Zeroizing<String>)> {
let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?; let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?;
if user.is_empty() || pass.is_empty() { if user.is_empty() || pass.is_empty() {
return Err(credentials_required()); return Err(credentials_required());
} }
Ok((user.to_string(), pass.to_string())) Ok((user.to_string(), Zeroizing::new(pass.to_string())))
} }
fn parse_http_url(url: &str, extra_login: Option<&str>) -> Result<Endpoint> { fn parse_http_url(url: &str, extra_login: Option<&str>) -> Result<Endpoint> {
@ -405,7 +409,9 @@ fn digest_authorization(ep: &Endpoint, challenge: &str) -> Result<String> {
let nonce = digest_param(challenge, "nonce") let nonce = digest_param(challenge, "nonce")
.ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?; .ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?;
let qop = digest_param(challenge, "qop"); let qop = digest_param(challenge, "qop");
let ha1 = md5_hex(&format!("{}:{realm}:{}", ep.user, ep.pass)); // `user:realm:password` never leaves a bare `String` behind.
let pw_input = Zeroizing::new(format!("{}:{realm}:{}", ep.user, ep.pass.as_str()));
let ha1 = md5_hex(pw_input.as_str());
let ha2 = md5_hex(&format!("POST:{}", ep.path)); let ha2 = md5_hex(&format!("POST:{}", ep.path));
let (qop_part, resp) = if qop let (qop_part, resp) = if qop
.as_deref() .as_deref()

View file

@ -72,9 +72,9 @@ fn restore_overwrites_self_keys_friends_stay() {
) )
.unwrap(); .unwrap();
let me = store.self_identity().unwrap(); let me = store.self_identity().unwrap();
assert_eq!(me.identity_sk, incoming.identity_sk); assert_eq!(me.identity_sk[..], incoming.identity_sk[..]);
assert_eq!(me.identity_pk, incoming.identity_pk); assert_eq!(me.identity_pk, incoming.identity_pk);
assert_eq!(me.prekey_sk, incoming.prekey_sk); assert_eq!(me.prekey_sk[..], incoming.prekey_sk[..]);
assert_eq!(me.prekey_pk, incoming.prekey_pk); assert_eq!(me.prekey_pk, incoming.prekey_pk);
assert_eq!(me.onion, old.onion, "onion is locator, not restored"); assert_eq!(me.onion, old.onion, "onion is locator, not restored");
assert_eq!(store.friend_count().unwrap(), 1); assert_eq!(store.friend_count().unwrap(), 1);

View file

@ -67,7 +67,7 @@ fn first_run_creates_0700_dirs_and_self_row() {
let me = store.self_identity().expect("self"); let me = store.self_identity().expect("self");
assert_eq!(me.identity_pk.len(), 32); assert_eq!(me.identity_pk.len(), 32);
assert_eq!(me.identity_sk.len(), 32); assert_eq!(me.identity_sk.len(), 32);
assert_ne!(me.identity_pk, me.identity_sk); assert_ne!(me.identity_pk, me.identity_sk.to_vec());
assert_eq!(me.onion, ""); assert_eq!(me.onion, "");
assert_eq!(store.friend_count().unwrap(), 0); assert_eq!(store.friend_count().unwrap(), 0);
@ -152,7 +152,7 @@ fn self_has_x25519_prekey_and_set_onion() {
let me = store.self_identity().unwrap(); let me = store.self_identity().unwrap();
assert_eq!(me.prekey_pk.len(), 32); assert_eq!(me.prekey_pk.len(), 32);
assert_eq!(me.prekey_sk.len(), 32); assert_eq!(me.prekey_sk.len(), 32);
assert_ne!(me.prekey_pk, me.prekey_sk); assert_ne!(me.prekey_pk, me.prekey_sk.to_vec());
store.set_onion("abc.onion").unwrap(); store.set_onion("abc.onion").unwrap();
assert_eq!(store.self_identity().unwrap().onion, "abc.onion"); assert_eq!(store.self_identity().unwrap().onion, "abc.onion");
} }
@ -277,7 +277,7 @@ fn whole_store_file_is_encrypted_at_rest() {
(b"reply-at-rest-xyz".to_vec(), "inbound chat body"), (b"reply-at-rest-xyz".to_vec(), "inbound chat body"),
(hex(&pk(7)).into_bytes(), "friend pubkey hex"), (hex(&pk(7)).into_bytes(), "friend pubkey hex"),
(b"friend.onion".to_vec(), "friend locator"), (b"friend.onion".to_vec(), "friend locator"),
(me.identity_sk.clone(), "identity secret key"), (me.identity_sk.to_vec(), "identity secret key"),
] { ] {
assert!( assert!(
!store_contains(dir.path(), &needle), !store_contains(dir.path(), &needle),
@ -394,7 +394,7 @@ fn env_passphrase_skips_prompt() {
unsafe { unsafe {
std::env::remove_var("ONIONWIRE_STORE_PASSPHRASE"); std::env::remove_var("ONIONWIRE_STORE_PASSPHRASE");
} }
assert_eq!(got.unwrap(), "from-env"); assert_eq!(got.unwrap().as_str(), "from-env");
assert!(!prompted); assert!(!prompted);
} }
@ -428,7 +428,7 @@ fn missing_env_reads_secret_and_strips_newline() {
Ok("secret-from-tty\n".into()) Ok("secret-from-tty\n".into())
}) })
.unwrap(); .unwrap();
assert_eq!(got, "secret-from-tty"); assert_eq!(got.as_str(), "secret-from-tty");
} }
#[test] #[test]

118
tests/zeroize.rs Normal file
View file

@ -0,0 +1,118 @@
//! Wipe in-memory secrets on drop — keys, not just the file at rest.
//!
//! Not covered here (see the PR body): allocator copies, swap/hibernation,
//! core dumps, OS `String` interning, `src/file.rs` + TUI buffers, and the
//! Noise handshake/transport state that lives inside `snow`.
use onionwire::backup::BackupKeys;
use onionwire::session::Keys;
use onionwire::wallet::Wallet;
use onionwire::Store;
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
/// Type-level: the wrapper is applied to the type, not just mentioned in a
/// comment. Removing the derive breaks the build here.
fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
#[test]
fn session_and_backup_key_types_are_zeroize_on_drop() {
assert_zeroize_on_drop::<Keys>();
assert_zeroize_on_drop::<BackupKeys>();
}
/// Behavioural: the derived impl must wipe the secret halves and leave the
/// public halves alone. A `Zeroize` that only touched the publics would still
/// satisfy a bare drop assertion and leak anyway.
#[test]
fn session_keys_zeroize_wipes_secrets_and_keeps_publics() {
let mut k = Keys::generate();
let (id_pk, prekey_pk) = (k.identity_pk, k.prekey_pk);
assert_ne!(k.identity_sk, [0u8; 32]);
assert_ne!(k.prekey_sk, [0u8; 32]);
k.zeroize();
assert_eq!(k.identity_sk, [0u8; 32], "identity secret not wiped");
assert_eq!(k.prekey_sk, [0u8; 32], "prekey secret not wiped");
assert_eq!(k.identity_pk, id_pk, "identity public key was wiped");
assert_eq!(k.prekey_pk, prekey_pk, "prekey public key was wiped");
}
/// Drops `v` in place and reads its secret field back, so a drop test cannot
/// pass on a copy that the caller still holds.
///
/// SAFETY: only for `ManuallyDrop<Keys>` locals — the value is dropped exactly
/// once, at its own address, and its storage is still alive when it is read.
unsafe fn drop_in_place_and_peek_identity_sk(v: &mut Keys) -> [u8; 32] {
let p = std::ptr::addr_of!(v.identity_sk);
// SAFETY: the caller guarantees `v` is a `ManuallyDrop<Keys>` dropped once.
unsafe {
std::ptr::drop_in_place(v as *mut Keys);
std::ptr::read_volatile(p)
}
}
/// Drop behaviour, not a comment: after the value drops, the local secret key
/// material that feeds the Noise IK handshake is gone from its memory.
#[test]
fn dropped_session_keys_leave_no_secret_behind() {
let mut k = std::mem::ManuallyDrop::new(Keys::generate());
// SAFETY: `k` is a live local; the pointer targets its own field.
assert_ne!(unsafe { *std::ptr::addr_of!(k.identity_sk) }, [0u8; 32]);
let after = unsafe { drop_in_place_and_peek_identity_sk(&mut k) };
assert_eq!(after, [0u8; 32], "identity secret survived drop");
}
/// `Keys` is `Clone`, so a cloned copy is itself live secret material. It must
/// wipe on *its* drop, and dropping it must not wipe the original it came from.
#[test]
fn cloned_session_keys_wipe_their_own_copy_only() {
let original = std::mem::ManuallyDrop::new(Keys::generate());
let mut copy = std::mem::ManuallyDrop::new((*original).clone());
let after = unsafe { drop_in_place_and_peek_identity_sk(&mut copy) };
assert_eq!(after, [0u8; 32], "cloned secret survived its drop");
// SAFETY: `original` is a live local; the pointer targets its own field.
assert_ne!(
unsafe { *std::ptr::addr_of!(original.identity_sk) },
[0u8; 32],
"dropping the clone wiped the original's key"
);
}
/// The identity secret handed out by the store is a `Zeroizing`, not a bare
/// `Vec<u8>` that outlives every caller.
#[test]
fn self_identity_secrets_are_zeroizing_and_wipe() {
let dir = tempfile::tempdir().expect("tempdir");
let store = Store::open_at_with_passphrase(dir.path(), "zeroize-pass").expect("open");
let mut me = store.self_identity().expect("self");
let _: &Zeroizing<Vec<u8>> = &me.identity_sk;
let _: &Zeroizing<Vec<u8>> = &me.prekey_sk;
assert_eq!(me.identity_sk.len(), 32);
assert!(me.identity_sk.iter().any(|b| *b != 0));
me.identity_sk.zeroize();
me.prekey_sk.zeroize();
assert!(me.identity_sk.iter().all(|b| *b == 0));
assert!(me.prekey_sk.iter().all(|b| *b == 0));
}
/// The wallet RPC password is a secret, so it is `Zeroizing` and its `Debug`
/// redacts it instead of printing it.
#[test]
fn wallet_endpoint_debug_redacts_the_rpc_password() {
let w = Wallet::from_url("http://monero:[email protected]:18083/json_rpc").expect("url");
let dbg = format!("{w:?}");
assert!(
!dbg.contains("hunter2"),
"wallet RPC password leaked into Debug: {dbg}"
);
assert!(dbg.contains("<redacted>"), "{dbg}");
}