diff --git a/Cargo.lock b/Cargo.lock index 1f99c80..dc0a370 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2295,6 +2295,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91632f3b4fb6bd1d72aa3d78f41ffecfcf2b1a6648d8c241dbe7dbfaf4875e15" dependencies = [ "cc", + "openssl-sys", "pkg-config", "vcpkg", ] @@ -2653,6 +2654,7 @@ dependencies = [ "tor-rtcompat", "tracing-subscriber", "x25519-dalek", + "zeroize", ] [[package]] @@ -2692,6 +2694,15 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "openssl-src" +version = "300.6.1+3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846" +dependencies = [ + "cc", +] + [[package]] name = "openssl-sys" version = "0.9.117" @@ -2700,6 +2711,7 @@ checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" dependencies = [ "cc", "libc", + "openssl-src", "pkg-config", "vcpkg", ] diff --git a/Cargo.toml b/Cargo.toml index 7285691..68a965f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,7 +32,7 @@ futures = "0.3" safelog = "0.9" ed25519-dalek = { version = "2", features = ["rand_core"] } rand = "0.8" -rusqlite = { version = "0.36", features = ["bundled"] } +rusqlite = { version = "0.36", features = ["bundled-sqlcipher-vendored-openssl"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-util", "time", "net"] } tor-cell = "0.46" tor-hsservice = "0.46" @@ -47,6 +47,7 @@ sha3 = "0.10" sha2 = "0.10" md-5 = "0.10" rpassword = "7" +zeroize = { version = "1", features = ["derive"] } [dev-dependencies] tempfile = "3" diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 9773e46..d0baa0a 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -16,11 +16,41 @@ A signed `loc` frame (`onion`, `ts`, `sig`) rewrites a friend’s locator **only `F4` changes the locator only. The identity key is unchanged. Anyone who already has your pubkey can still prove they are talking to you, and a later invite paste with the same `k` updates their row. To become a new person, `/wipe-all` (new identity key). There is no in-band unfriend/revoke in v1. -## Message bodies are encrypted at rest; keys are not +## Your store is encrypted -Chat bodies in sqlite are ChaCha20-Poly1305 (`nonce || ciphertext` in the `messages.plaintext` column) with AAD `owmsg1 || friend_id_le64 || dir || 0x00 || row_id_le64`. Swapping ciphertext between rows fails closed. A random 32-byte data key is wrapped with Argon2id (same params as identity backup) from a non-empty passphrase. Salt + wrapped key live in `store_meta`. Unlock is fail-closed: wrong or empty passphrase does not open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` never falls back to empty AAD. +The sqlite store is SQLCipher (`rusqlite` feature `bundled-sqlcipher-vendored-openssl`). +A 32-byte key is derived from the store passphrase with Argon2id (same params as +identity backup) over a per-install 16-byte salt in `store_salt`, and handed to +SQLCipher as a **raw** key (`PRAGMA key = "x'…'"`) — no second KDF pass over it. +The key is the first statement after open, so the file header, schema, identity +secret key, friend public keys, locators, profiles and payment rows are all +ciphertext on disk. There is no `identity_sk`-on-disk problem to work around +because `identity_sk` is inside the encrypted file. A wrong or empty passphrase +fails closed before any write; an encrypted store whose `store_salt` is missing +refuses to open instead of guessing. -Identity secret key, friend public keys, and locators remain plaintext in the same db. The message key is not wrapped with `identity_sk` (that key is already on disk). A seized laptop still yields who you talk to and your identity unless you add OS/FDE. sqlcipher is out of v1. `/wipe` deletes chat and payments history (overwrite message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data dir (new identity); same disk caveat. +v0.2.1 installs have a plaintext db. The first open with the right passphrase +upgrades it in place (`ATTACH … KEY` + `sqlcipher_export` after a WAL +checkpoint), and swaps the file in only after the new file opens, passes +`integrity_check` and unwraps `store_meta`. A wrong passphrase leaves the +plaintext file untouched. The `store_salt` file is not secret (a salt never is). + +Chat bodies carry a second, row-bound layer: ChaCha20-Poly1305 (`nonce || +ciphertext` in `messages.plaintext`) with AAD `owmsg1 || friend_id_le64 || dir || +0x00 || row_id_le64`, plus a random 32-byte data key wrapped with Argon2id from +the same passphrase (`store_meta`). Whole-db encryption does not stop someone who +can write the file from moving one row's ciphertext into another row; the AAD +does, and it stays. Unlock is fail-closed: wrong or empty passphrase does not +open chat. Empty-AAD v0.2 blobs are rewrapped once on unlock; `list_messages` +never falls back to empty AAD. + +At-rest encryption is not a defense against a live compromise: while OnionWire +runs, the passphrase, the db key and decrypted bodies are in process memory, and +SQLCipher's page cache holds decrypted pages. It also does not stop an attacker +who has your passphrase. `/wipe` deletes chat and payments history (overwrite +message bodies, `VACUUM`, WAL checkpoint); roster and identity stay. It is not a +forensic erase — SSD wear-leveling can keep copies. `/wipe-all` deletes the data +dir (new identity); same disk caveat. ## Fail closed @@ -66,4 +96,4 @@ the peer already knows the plaintext they sent. ## Out of v1 Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server, -sqlcipher, A/V. +A/V. diff --git a/docs/TUI.md b/docs/TUI.md index 925d351..40e82e5 100644 --- a/docs/TUI.md +++ b/docs/TUI.md @@ -510,3 +510,63 @@ add it on this card. Preferred: depend on `unicode-width` explicitly and assert `tests/tui_frames.rs` `chars_count_is_not_terminal_cells` documents the three examples without adding a crate. + +## After frames (spacing / ASCII / wrap / copy) + +Base: `origin/main` after PR #24 (`33beede`). Hierarchy, fail-closed footer, +1-line header, roster width, help overlay, and `NO_COLOR` palette are unchanged +here. Optional 3-line wordmark at height ≥ 40 was skipped (it fights the 1-line +header without buying hierarchy). + +### 80x24 — `draw_share` after (field-boundary wrap) + +Invite lines break on `:`. `sig=` hex that does not fit continues as an +all-hex line. Joining those lines (no extra spaces) is the original payload. + +``` +┌(o) invite────────────────────────────────────────────────────────────────────┐ +│give this string to a friend; they F3 paste it │ +│ │ +│fp ea4a6c63… │ +│onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion │ +│ │ +│onionwire:v1: │ +│k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: │ +│o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: │ +│spk=0101010101010101010101010101010101010101010101010101010101010101: │ +│sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0│ +│5401b0af934cefea617f71466f406af4bef956847200a8e915190b │ +└──────────────────────────────────────────────────────────────────────────────┘ +``` + +### 80x24 — ASCII switch (`ONIONWIRE_ASCII=1`) + +No non-ASCII byte. Truncation marker is `...`. Borders are `+` `-` `|`. + +``` ++(o) invite--------------------------------------------------------------------+ +|give this string to a friend; they F3 paste it | +| | +|fp ea4a6c63... | +|onion abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion | +| | +|onionwire:v1: | +|k=ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c: | +|o=abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion: | +|spk=0101010101010101010101010101010101010101010101010101010101010101: | +|sig=46caf16b6da95e86bf93a6ee80605ec74d9e24a419c4ef802632af74f46406fae9953690e0| +|5401b0af934cefea617f71466f406af4bef956847200a8e915190b | ++------------------------------------------------------------------------------+ +``` + +### 80x24 / 120x40 — main chrome after + +Same 1-line header, unboxed composer, fail-closed footer as PR #24. Dump: + +``` +cargo test --locked --test tui_spec -- --nocapture dump_spec_frames +``` + +Copy wired in `src/tui.rs` (not in the reconstructed standin): empty thread is +`no messages` / `type below, Enter sends`; paste error is `{err}` then +`Enter resubmits Esc back`; alerts truncate to the frame width. diff --git a/src/backup.rs b/src/backup.rs index b946476..5e6a775 100644 --- a/src/backup.rs +++ b/src/backup.rs @@ -4,6 +4,7 @@ use argon2::{Algorithm, Argon2, Params, Version}; use chacha20poly1305::aead::{Aead, AeadCore, KeyInit, OsRng, Payload}; use chacha20poly1305::{ChaCha20Poly1305, Key, Nonce}; use rand::RngCore; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; pub const MAGIC: &[u8] = b"owbak1"; const SALT_LEN: usize = 16; @@ -11,17 +12,31 @@ const NONCE_LEN: usize = 12; const KEY_LEN: usize = 32; 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 identity_sk: [u8; 32], + #[zeroize(skip)] pub identity_pk: [u8; 32], pub prekey_sk: [u8; 32], + #[zeroize(skip)] 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", &"") + .field("identity_pk", &self.identity_pk) + .field("prekey_sk", &"") + .field("prekey_pk", &self.prekey_pk) + .finish() + } +} + impl BackupKeys { - pub fn to_bytes(&self) -> [u8; PLAIN_LEN] { - let mut out = [0u8; PLAIN_LEN]; + pub fn to_bytes(&self) -> Zeroizing<[u8; PLAIN_LEN]> { + let mut out = Zeroizing::new([0u8; PLAIN_LEN]); out[0..32].copy_from_slice(&self.identity_sk); out[32..64].copy_from_slice(&self.identity_pk); 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, String> { if passphrase.is_empty() { 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 argon = Argon2::new(Algorithm::Argon2id, Version::V0x13, params); - let mut key = [0u8; 32]; + let mut key = Zeroizing::new([0u8; 32]); 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())?; Ok(key) } @@ -62,13 +77,13 @@ pub fn seal(passphrase: &str, keys: &BackupKeys) -> Result, String> { let mut salt = [0u8; SALT_LEN]; rand::rngs::OsRng.fill_bytes(&mut 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); if nonce.len() != NONCE_LEN { return Err("nonce length".into()); } let ct = cipher - .encrypt(&nonce, keys.to_bytes().as_ref()) + .encrypt(&nonce, &keys.to_bytes()[..]) .map_err(|_| "encrypt failed".to_string())?; let mut out = Vec::with_capacity(MAGIC.len() + SALT_LEN + NONCE_LEN + ct.len()); out.extend_from_slice(MAGIC); @@ -88,11 +103,13 @@ pub fn open(passphrase: &str, blob: &[u8]) -> Result { let nonce = Nonce::from_slice(&blob[nonce_off..nonce_off + NONCE_LEN]); let ct = &blob[nonce_off + NONCE_LEN..]; let key = kdf(passphrase, salt)?; - let cipher = ChaCha20Poly1305::new(Key::from_slice(&key)); - let pt = cipher - .decrypt(nonce, ct) - .map_err(|_| "wrong passphrase or corrupt backup".to_string())?; - BackupKeys::from_bytes(&pt) + let cipher = ChaCha20Poly1305::new(Key::from_slice(&key[..])); + let pt = Zeroizing::new( + cipher + .decrypt(nonce, ct) + .map_err(|_| "wrong passphrase or corrupt backup".to_string())?, + ); + BackupKeys::from_bytes(&pt[..]) } pub(crate) fn aead_encrypt( @@ -133,3 +150,45 @@ pub(crate) fn aead_decrypt(key: &[u8; 32], blob: &[u8], aad: &[u8]) -> Result 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(""), "{dbg}"); + assert!(dbg.contains("174"), "public half should stay: {dbg}"); + } +} diff --git a/src/node.rs b/src/node.rs index 97745a2..06298b8 100644 --- a/src/node.rs +++ b/src/node.rs @@ -8,6 +8,7 @@ use futures::StreamExt; use futures::io::{AsyncRead, AsyncWrite}; use tor_cell::relaycell::msg::Connected; use tor_hsservice::{RunningOnionService, handle_rend_requests}; +use zeroize::Zeroizing; use crate::dispatch::{self, Kind}; use crate::file; @@ -53,12 +54,14 @@ pub struct Node { impl Node { pub async fn start(home: PathBuf) -> Result, String> { - let pass = std::env::var("ONIONWIRE_STORE_PASSPHRASE") - .map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?; + let pass = Zeroizing::new( + std::env::var("ONIONWIRE_STORE_PASSPHRASE") + .map_err(|_| "ONIONWIRE_STORE_PASSPHRASE required".to_string())?, + ); if pass.is_empty() { 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( diff --git a/src/pay.rs b/src/pay.rs index ae17390..21485fb 100644 --- a/src/pay.rs +++ b/src/pay.rs @@ -1,5 +1,6 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use sha3::{Digest, Keccak256}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -386,9 +387,12 @@ fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec { } fn sign_bytes(identity_sk: &[u8], msg: &[u8]) -> Result> { - let sk_bytes: [u8; 32] = identity_sk - .try_into() - .map_err(|_| Error("identity secret key must be 32 bytes".into()))?; + // ed25519-dalek's `SigningKey` wipes itself on drop (its default `zeroize` + // feature); the raw copy we make to build it is ours to wipe. + 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); Ok(sk.sign(msg).to_bytes().to_vec()) } diff --git a/src/qr.rs b/src/qr.rs index 4a5e365..3746775 100644 --- a/src/qr.rs +++ b/src/qr.rs @@ -1,4 +1,5 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -34,9 +35,10 @@ pub fn encode(identity_sk: &[u8], onion: &str, signed_prekey: &[u8]) -> Result::try_from(identity_sk) + .map_err(|_| Error("identity secret key must be 32 bytes".into()))?, + ); let sk = SigningKey::from_bytes(&sk_bytes); let k = to_hex(&sk.verifying_key().to_bytes()); let spk = to_hex(signed_prekey); diff --git a/src/session.rs b/src/session.rs index e5e21b6..fc2c47a 100644 --- a/src/session.rs +++ b/src/session.rs @@ -2,6 +2,7 @@ use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey}; use rand::rngs::OsRng; use snow::Builder; use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; +use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; use crate::store::SelfIdentity; @@ -51,11 +52,15 @@ impl From 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 identity_sk: [u8; 32], + #[zeroize(skip)] pub identity_pk: [u8; 32], pub prekey_sk: [u8; 32], + #[zeroize(skip)] pub prekey_pk: [u8; 32], } @@ -121,7 +126,7 @@ pub fn handshake_pinned(init: &Keys, resp: &Keys, pinned: &[u8; 32]) -> Result<( .prologue(PROLOGUE)? .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 msg1 = buf[..n].to_vec(); let n = responder.read_message(&msg1, &mut buf)?; @@ -190,7 +195,7 @@ where .prologue(PROLOGUE)? .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)?; crate::frame::write_frame(stream, &buf[..n]) .await @@ -244,7 +249,7 @@ where .prologue(PROLOGUE)? .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) .await .map_err(|e| Error::new(e.to_string()))?; diff --git a/src/store.rs b/src/store.rs index 1be94f3..0650b29 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,4 +1,5 @@ use std::fs; +use std::io::Read; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; @@ -8,6 +9,7 @@ use rand::RngCore; use rand::rngs::OsRng; use rusqlite::{Connection, OptionalExtension, params}; use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -42,14 +44,15 @@ impl From for Error { pub struct Store { 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 identity_sk: Vec, + pub identity_sk: Zeroizing>, pub identity_pk: Vec, pub onion: String, - pub prekey_sk: Vec, + pub prekey_sk: Zeroizing>, pub prekey_pk: Vec, } @@ -108,7 +111,8 @@ impl Store { } pub fn open_at(home: &Path) -> Result { - 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 { @@ -119,7 +123,7 @@ impl Store { mkdir_700(&home.join("arti"))?; mkdir_700(&home.join("cache"))?; let db_path = home.join("onionwire.db"); - let conn = Connection::open(&db_path)?; + let conn = open_store_db(home, &db_path, passphrase)?; let journal: String = conn.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0))?; if !journal.eq_ignore_ascii_case("wal") { return Err(Error(format!("journal_mode WAL failed: {journal}"))); @@ -198,7 +202,7 @@ impl Store { } let mut store = Self { conn, - msg_key: [0u8; 32], + msg_key: Zeroizing::new([0u8; 32]), }; store.migrate()?; store.ensure_self()?; @@ -274,8 +278,11 @@ impl Store { match row { Some((salt, wrapped)) => { let wrap_key = crate::backup::kdf(passphrase, &salt)?; - let raw = crate::backup::aead_decrypt(&wrap_key, &wrapped, b"") - .map_err(|_| Error("wrong passphrase".into()))?; + // The unwrapped data key lands in a Zeroizing buffer immediately. + let raw = Zeroizing::new( + crate::backup::aead_decrypt(&wrap_key, &wrapped, b"") + .map_err(|_| Error("wrong passphrase".into()))?, + ); if raw.len() != 32 { return Err(Error("wrapped message key length".into())); } @@ -284,12 +291,12 @@ impl Store { Ok(()) } None => { - let mut data_key = [0u8; 32]; - OsRng.fill_bytes(&mut data_key); + let mut data_key = Zeroizing::new([0u8; 32]); + OsRng.fill_bytes(&mut data_key[..]); let mut salt = [0u8; 16]; OsRng.fill_bytes(&mut 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( "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", params![salt.as_slice(), wrapped], @@ -383,13 +390,13 @@ impl Store { })?; if exists == 0 { 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 (psk, ppk) = gen_prekey(); self.conn.execute( "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')", - params![sk, pk, psk, ppk], + params![&sk[..], pk, &psk[..], ppk], )?; } else { let empty: i64 = self.conn.query_row( @@ -401,7 +408,7 @@ impl Store { let (psk, ppk) = gen_prekey(); self.conn.execute( "UPDATE self SET prekey_sk = ?1, prekey_pk = ?2 WHERE id = 1", - params![psk, ppk], + params![&psk[..], ppk], )?; } } @@ -415,10 +422,10 @@ impl Store { [], |row| { Ok(SelfIdentity { - identity_sk: row.get(0)?, + identity_sk: Zeroizing::new(row.get(0)?), identity_pk: row.get(1)?, onion: row.get(2)?, - prekey_sk: row.get(3)?, + prekey_sk: Zeroizing::new(row.get(3)?), prekey_pk: row.get(4)?, }) }, @@ -809,10 +816,194 @@ fn friend_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result { }) } -fn gen_prekey() -> (Vec, Vec) { +fn gen_prekey() -> (Zeroizing>, Vec) { let sk = StaticSecret::random_from_rng(OsRng); 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 +/// is); kept in the data dir so the db key never has to live inside the db it +/// opens. +const SALT_FILE: &str = "store_salt"; +const SQLITE_HEADER: &[u8] = b"SQLite format 3\0"; + +enum DbState { + Missing, + Empty, + Plaintext, + Encrypted, +} + +fn db_state(path: &Path) -> Result { + let meta = match fs::metadata(path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(DbState::Missing), + Err(e) => return Err(e.into()), + }; + if meta.len() == 0 { + return Ok(DbState::Empty); + } + let mut head = [0u8; 16]; + let mut f = fs::File::open(path)?; + match f.read_exact(&mut head) { + Ok(()) if head.as_slice() == SQLITE_HEADER => Ok(DbState::Plaintext), + Ok(()) => Ok(DbState::Encrypted), + Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Ok(DbState::Encrypted), + Err(e) => Err(e.into()), + } +} + +fn read_salt(path: &Path) -> Result> { + match fs::read(path) { + Ok(b) if b.len() == 16 => Ok(Some(b.try_into().expect("len checked"))), + Ok(b) => Err(Error(format!("{SALT_FILE} has {} bytes, want 16", b.len()))), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(e.into()), + } +} + +fn write_salt(path: &Path, salt: &[u8; 16]) -> Result<()> { + fs::write(path, salt)?; + let mut perms = fs::metadata(path)?.permissions(); + perms.set_mode(0o600); + fs::set_permissions(path, perms)?; + Ok(()) +} + +fn random_salt() -> [u8; 16] { + let mut salt = [0u8; 16]; + OsRng.fill_bytes(&mut salt); + salt +} + +/// Opens the store, creating it encrypted and upgrading a v0.2.1 plaintext +/// file in place. Any failure before the swap leaves the old file untouched. +fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result { + let salt_path = home.join(SALT_FILE); + let mut salt = read_salt(&salt_path)?; + match db_state(db_path)? { + DbState::Plaintext => { + let conn = Connection::open(db_path)?; + let ok = wrapped_key_opens(&conn, passphrase)?; + drop(conn); + if !ok { + return Err(Error("wrong passphrase".into())); + } + let s = salt.unwrap_or_else(random_salt); + let key = crate::backup::kdf(passphrase, &s)?; + write_salt(&salt_path, &s)?; + migrate_plaintext_to_encrypted(db_path, &key, passphrase)?; + salt = Some(s); + } + DbState::Missing | DbState::Empty => { + if salt.is_none() { + let s = random_salt(); + write_salt(&salt_path, &s)?; + salt = Some(s); + } + } + DbState::Encrypted => {} + } + let Some(salt) = salt else { + return Err(Error(format!( + "{SALT_FILE} is missing next to an encrypted onionwire.db; restore it from \ + your backup, or restore the db from backup and re-import" + ))); + }; + let key = crate::backup::kdf(passphrase, &salt)?; + open_keyed(db_path, &key) +} + +/// SQLCipher `PRAGMA key` with the raw-key form: the 32-byte Argon2id output is +/// the key, with no second KDF pass over it. +fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result { + let conn = Connection::open(db_path)?; + conn.execute_batch(pragma_key(key).as_str())?; + // A rejected key otherwise logs SQLCipher's internal "hmac check failed" + // at ERROR to stderr. A wrong passphrase is a normal user error here. + let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE"); + // Force a read so a wrong key fails here, not on the first later query. + conn.query_row("SELECT count(*) FROM sqlite_master", [], |r| { + r.get::<_, i64>(0) + }) + .map_err(|_| Error("wrong passphrase or corrupt store".into()))?; + Ok(conn) +} + +/// SQLCipher's key material as hex inside the pragma text. The `String` holds +/// the database key, so it wipes on drop. +fn pragma_key(key: &[u8; 32]) -> Zeroizing { + Zeroizing::new(format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key))) +} + +/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh +/// store) accepts any passphrase, matching the v0.2.1 behaviour. +fn wrapped_key_opens(conn: &Connection, passphrase: &str) -> Result { + let row: Option<(Vec, Vec)> = conn + .query_row( + "SELECT kdf_salt, wrapped_key FROM store_meta WHERE id = 1", + [], + |r| Ok((r.get(0)?, r.get(1)?)), + ) + .optional()?; + let Some((salt, wrapped)) = row else { + return Ok(true); + }; + let wrap_key = crate::backup::kdf(passphrase, &salt)?; + Ok(crate::backup::aead_decrypt(&wrap_key, &wrapped, b"").is_ok()) +} + +/// Rewrites a plaintext sqlite store as an encrypted one and swaps it in. +/// The source file is only replaced after the new file opens, passes +/// `integrity_check` and unlocks with this passphrase. +fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &str) -> Result<()> { + let mut tmp_name = db_path.as_os_str().to_owned(); + tmp_name.push(".migrating"); + let tmp = PathBuf::from(tmp_name); + let _ = fs::remove_file(&tmp); + let mode = fs::metadata(db_path)?.permissions().mode() & 0o777; + + { + // Fold the WAL in so the export sees every committed row. + let conn = Connection::open(db_path)?; + let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)"); + let target = tmp.to_string_lossy().replace('\'', "''"); + let attach = Zeroizing::new(format!( + "ATTACH DATABASE '{target}' AS enc KEY \"x'{hex}'\";", + hex = fingerprint(key) + )); + conn.execute_batch(attach.as_str())?; + conn.execute_batch("SELECT sqlcipher_export('enc');")?; + conn.execute_batch("DETACH DATABASE enc;")?; + } + + let verified = (|| -> Result<()> { + let conn = open_keyed(&tmp, key)?; + let check: String = conn.query_row("PRAGMA integrity_check", [], |r| r.get(0))?; + if check != "ok" { + return Err(Error(format!("migration integrity_check: {check}"))); + } + if !wrapped_key_opens(&conn, passphrase)? { + return Err(Error("migrated store failed to unlock".into())); + } + Ok(()) + })(); + if let Err(e) = verified { + let _ = fs::remove_file(&tmp); + return Err(e); + } + + fs::rename(&tmp, db_path)?; + let mut perms = fs::metadata(db_path)?.permissions(); + perms.set_mode(mode); + fs::set_permissions(db_path, perms)?; + for suffix in ["-wal", "-shm"] { + let mut stale = db_path.as_os_str().to_owned(); + stale.push(suffix); + let _ = fs::remove_file(PathBuf::from(stale)); + } + Ok(()) } fn home_dir() -> Result { @@ -823,29 +1014,29 @@ fn home_dir() -> Result { Ok(PathBuf::from(home).join(".local/share/onionwire")) } -fn passphrase_from_env() -> Result { +fn passphrase_from_env() -> Result> { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { 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())), } } /// 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( read_secret: impl FnOnce(&str) -> std::io::Result, -) -> Result { +) -> Result> { match std::env::var("ONIONWIRE_STORE_PASSPHRASE") { Ok(p) if p.is_empty() => Err(Error("empty passphrase".into())), - Ok(p) => Ok(p), + Ok(p) => Ok(Zeroizing::new(p)), Err(_) => { let s = read_secret("onionwire: store passphrase: ")?; let s = s.trim_end_matches(['\n', '\r']).to_string(); if s.is_empty() { Err(Error("empty passphrase".into())) } else { - Ok(s) + Ok(Zeroizing::new(s)) } } } @@ -884,6 +1075,21 @@ fn fingerprint(pubkey: &[u8]) -> String { #[cfg(test)] mod at_rest { 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] fn swapped_ciphertext_does_not_show_other_friends_body() { @@ -1027,6 +1233,214 @@ mod at_rest { } } + /// The exact v0.2.1 on-disk layout, hand-built: a plaintext sqlite file with + /// the identity row in the clear, a `store_meta` row holding the + /// Argon2id-wrapped message key and ChaCha20-Poly1305 message rows bound to + /// their row AAD. Pin it here so the migration test cannot drift with the + /// production schema. + const LEGACY_SCHEMA: &str = " + CREATE TABLE friends ( + id INTEGER PRIMARY KEY, + pubkey BLOB NOT NULL UNIQUE, + fingerprint TEXT NOT NULL, + petname TEXT, + onion TEXT NOT NULL, + onion_updated_at INTEGER NOT NULL, + added_at INTEGER NOT NULL, + last_connect_ok INTEGER NOT NULL DEFAULT 1, + prekey BLOB NOT NULL DEFAULT x'' + ); + CREATE TABLE messages ( + id INTEGER PRIMARY KEY, + friend_id INTEGER NOT NULL REFERENCES friends(id), + dir TEXT NOT NULL CHECK(dir IN ('in','out')), + plaintext BLOB NOT NULL, + created_at INTEGER NOT NULL + ); + CREATE TABLE self ( + id INTEGER PRIMARY KEY CHECK (id = 1), + identity_sk BLOB NOT NULL, + identity_pk BLOB NOT NULL, + onion TEXT NOT NULL, + onion_rotated_at INTEGER NOT NULL, + prekey_sk BLOB NOT NULL, + prekey_pk BLOB NOT NULL, + hs_nickname TEXT NOT NULL DEFAULT 'ow0' + ); + CREATE TABLE self_profile ( + id INTEGER PRIMARY KEY CHECK (id = 1), + display_name TEXT NOT NULL DEFAULT '', + bio TEXT NOT NULL DEFAULT '', + xmr_addr TEXT NOT NULL DEFAULT '', + updated_at INTEGER NOT NULL DEFAULT 0 + ); + CREATE TABLE friend_profiles ( + pubkey BLOB PRIMARY KEY, + display_name TEXT NOT NULL, + bio TEXT NOT NULL, + xmr_addr TEXT NOT NULL DEFAULT '', + updated_at INTEGER NOT NULL + ); + CREATE TABLE store_meta ( + id INTEGER PRIMARY KEY CHECK (id = 1), + kdf_salt BLOB NOT NULL, + wrapped_key BLOB NOT NULL + ); + CREATE TABLE payments ( + id INTEGER PRIMARY KEY, + friend_id INTEGER NOT NULL REFERENCES friends(id), + dir TEXT NOT NULL CHECK(dir IN ('in','out')), + kind TEXT NOT NULL CHECK(kind IN ('invoice','receipt')), + amount_atomic TEXT NOT NULL, + address TEXT NOT NULL, + memo TEXT NOT NULL DEFAULT '', + txid TEXT, + verified INTEGER NOT NULL DEFAULT 0, + created_at INTEGER NOT NULL + ); + INSERT OR IGNORE INTO self_profile (id) VALUES (1); + "; + + const LEGACY_IDENTITY_SK: [u8; 32] = [0x11; 32]; + const LEGACY_FRIEND_PK: [u8; 32] = [0x55; 32]; + + /// Writes a v0.2.1 store at `db_path` with no encryption at all. + fn write_legacy_plaintext_store(db_path: &Path, passphrase: &str) { + let conn = Connection::open(db_path).unwrap(); + conn.execute_batch(LEGACY_SCHEMA).unwrap(); + conn.execute( + "INSERT INTO self (id, identity_sk, identity_pk, onion, onion_rotated_at, prekey_sk, prekey_pk, hs_nickname) + VALUES (1, ?1, ?2, 'legacy.onion', 7, ?3, ?4, 'ow0')", + params![ + LEGACY_IDENTITY_SK.to_vec(), + vec![0x22u8; 32], + vec![0x33u8; 32], + vec![0x44u8; 32] + ], + ) + .unwrap(); + conn.execute( + "INSERT INTO friends (pubkey, fingerprint, petname, onion, onion_updated_at, added_at, last_connect_ok, prekey) + VALUES (?1, ?2, 'legacy-friend', 'legacy-friend.onion', 7, 7, 1, x'')", + params![LEGACY_FRIEND_PK.as_slice(), fingerprint(&LEGACY_FRIEND_PK)], + ) + .unwrap(); + let mut salt = [0u8; 16]; + OsRng.fill_bytes(&mut salt); + let mut data_key = Zeroizing::new([0u8; 32]); + OsRng.fill_bytes(&mut data_key[..]); + let wrap = crate::backup::kdf(passphrase, &salt).unwrap(); + let wrapped = crate::backup::aead_encrypt(&wrap, &data_key[..], b"").unwrap(); + conn.execute( + "INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)", + params![salt.as_slice(), wrapped], + ) + .unwrap(); + for (dir, body) in [ + ("in", "legacy-body-xyz"), + ("out", "legacy-reply-xyz"), + ] { + conn.execute( + "INSERT INTO messages (friend_id, dir, plaintext, created_at) VALUES (1, ?1, x'', 7)", + params![dir], + ) + .unwrap(); + let id = conn.last_insert_rowid(); + let blob = crate::backup::aead_encrypt( + &data_key, + body.as_bytes(), + &message_aad(1, dir, id), + ) + .unwrap(); + conn.execute( + "UPDATE messages SET plaintext = ?1 WHERE id = ?2", + params![blob, id], + ) + .unwrap(); + } + conn.close().unwrap(); + } + + fn file_has(path: &Path, needle: &[u8]) -> bool { + let Ok(bytes) = std::fs::read(path) else { + return false; + }; + bytes.windows(needle.len()).any(|w| w == needle) + } + + #[test] + fn plaintext_v0_2_1_store_is_encrypted_in_place_and_keeps_history() { + let dir = tempfile::tempdir().unwrap(); + let db_path = dir.path().join("onionwire.db"); + write_legacy_plaintext_store(&db_path, "legacy-pass"); + let raw = std::fs::read(&db_path).unwrap(); + assert!( + raw.starts_with(b"SQLite format 3\0"), + "fixture must be a plaintext sqlite file" + ); + + 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[..] + ); + let msgs = store.list_messages(&LEGACY_FRIEND_PK).unwrap(); + assert_eq!(msgs.len(), 2, "history must survive the upgrade"); + assert_eq!(msgs[0].plaintext, b"legacy-body-xyz"); + assert_eq!(msgs[1].plaintext, b"legacy-reply-xyz"); + assert_eq!( + store.get_friend(&LEGACY_FRIEND_PK).unwrap().unwrap().onion, + "legacy-friend.onion" + ); + drop(store); + + let enc = std::fs::read(&db_path).unwrap(); + assert!( + !enc.starts_with(b"SQLite format 3\0"), + "db header must be encrypted after the in-place upgrade" + ); + for (needle, what) in [ + (b"legacy-body-xyz".to_vec(), "message body"), + (fingerprint(&LEGACY_FRIEND_PK).into_bytes(), "friend pubkey hex"), + (LEGACY_IDENTITY_SK.to_vec(), "identity secret"), + (b"legacy-friend.onion".to_vec(), "locator"), + ] { + assert!( + !file_has(&db_path, &needle), + "upgraded db still contains the {what}" + ); + } + + let store = Store::open_at_with_passphrase(dir.path(), "legacy-pass").expect("reopen"); + assert_eq!(store.list_messages(&LEGACY_FRIEND_PK).unwrap().len(), 2); + } + + #[test] + fn legacy_plaintext_store_with_wrong_passphrase_is_left_untouched() { + let dir = tempfile::tempdir().unwrap(); + let db_path = dir.path().join("onionwire.db"); + write_legacy_plaintext_store(&db_path, "legacy-pass"); + let before = std::fs::read(&db_path).unwrap(); + + let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") { + Ok(_) => panic!("wrong passphrase must not open a legacy store"), + Err(e) => e, + }; + assert!( + err.to_string().to_ascii_lowercase().contains("passphrase"), + "got {err}" + ); + assert_eq!( + std::fs::read(&db_path).unwrap(), + before, + "a failed legacy upgrade must not modify the plaintext db" + ); + assert!( + !dir.path().join("store_salt").exists(), + "a failed legacy upgrade must not leave a salt file behind" + ); + } + #[test] fn first_unlock_reencrypts_legacy_plaintext_rows() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/tui.rs b/src/tui.rs index 2ce2eab..20eb4b6 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -5,6 +5,7 @@ use std::time::Duration; use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::style::{Color, Modifier, Style}; +use ratatui::symbols::border; use ratatui::widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph, Wrap}; use ratatui::{DefaultTerminal, Frame}; @@ -38,8 +39,90 @@ fn color_mode() -> ColorMode { } } +/// ASCII chrome when `ONIONWIRE_ASCII` or `NO_COLOR` is set. No extra crate. +pub fn ascii_chrome() -> bool { + std::env::var_os("ONIONWIRE_ASCII").is_some() || std::env::var_os("NO_COLOR").is_some() +} + +const ASCII_BORDERS: border::Set = border::Set { + top_left: "+", + top_right: "+", + bottom_left: "+", + bottom_right: "+", + vertical_left: "|", + vertical_right: "|", + horizontal_top: "-", + horizontal_bottom: "-", +}; + fn ellipsis() -> &'static str { - "…" + if ascii_chrome() { "..." } else { "…" } +} + +/// Truncate or keep an alert so it cannot spill into the roster row. +pub fn alert_line(msg: &str, width: u16) -> String { + let mut text = msg.to_string(); + if color_mode() == ColorMode::None && !text.starts_with("! ") { + text = format!("! {text}"); + } + truncate_chars(&text, width as usize) +} + +/// Wrap an invite at `:` so a mouse-copy cannot lose a mid-hex continuation. +/// Joining the lines (no extra spaces) reconstructs `payload`. +pub fn wrap_invite(payload: &str, width: usize) -> String { + if width == 0 { + return String::new(); + } + let mut lines: Vec = Vec::new(); + let mut cur = String::new(); + let parts: Vec<&str> = payload.split(':').collect(); + for (i, part) in parts.iter().enumerate() { + let piece = if i + 1 < parts.len() { + format!("{part}:") + } else { + (*part).to_string() + }; + for chunk in char_chunks(&piece, width) { + if cur.is_empty() { + cur = chunk; + } else if char_len(&cur) + char_len(&chunk) <= width { + cur.push_str(&chunk); + } else { + lines.push(std::mem::take(&mut cur)); + cur = chunk; + } + } + } + if !cur.is_empty() { + lines.push(cur); + } + lines.join("\n") +} + +fn char_chunks(s: &str, width: usize) -> Vec { + if width == 0 { + return Vec::new(); + } + if char_len(s) <= width { + return vec![s.to_string()]; + } + let chars: Vec = s.chars().collect(); + chars.chunks(width).map(|c| c.iter().collect()).collect() +} + +/// Friend selected, no messages yet. +pub fn empty_friend_chat_text() -> &'static str { + "no messages\ntype below, Enter sends" +} + +/// Paste overlay copy. Error keeps the resubmit hint. +pub fn paste_screen_text(buf: &str, err: Option<&str>) -> String { + let hint = match err { + Some(e) => format!("{e}\nEnter resubmits Esc back"), + None => "paste onionwire:v1 payload, Enter to submit".to_string(), + }; + format!("{hint}\n\n{buf}") } fn char_len(s: &str) -> usize { @@ -1429,11 +1512,7 @@ impl App { f.render_widget(Paragraph::new(header).style(style_accent()), cols[0]); if let Some(msg) = &self.alert { - let text = if color_mode() == ColorMode::None && !msg.starts_with("! ") { - format!("! {msg}") - } else { - msg.clone() - }; + let text = alert_line(msg, area.width); f.render_widget(Paragraph::new(text).style(style_alert()), cols[1]); } @@ -1559,7 +1638,10 @@ impl App { ]; }; match self.node.list_messages(&friend.pubkey) { - Ok(msgs) if msgs.is_empty() => vec!["no messages".into()], + Ok(msgs) if msgs.is_empty() => empty_friend_chat_text() + .lines() + .map(str::to_string) + .collect(), Ok(msgs) => msgs .iter() .map(|m| { @@ -1583,8 +1665,7 @@ impl App { } else { style_dim() }; - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(border) .title(title) .title_style(title_style) @@ -1699,9 +1780,17 @@ fn footer_hints(screen: &Screen) -> &'static str { } } +fn apply_chrome_borders(block: Block<'_>) -> Block<'_> { + let block = block.borders(Borders::ALL); + if ascii_chrome() { + block.border_set(ASCII_BORDERS) + } else { + block + } +} + fn themed_block(title: &str) -> Block<'_> { - Block::default() - .borders(Borders::ALL) + apply_chrome_borders(Block::default()) .border_style(style_accent()) .title(title) .title_style(style_accent().add_modifier(Modifier::BOLD)) @@ -1712,8 +1801,10 @@ pub fn draw_share(f: &mut Frame, payload: &str) { Ok(p) => (truncate_fp(&to_hex(&p.pubkey)), p.onion), Err(_) => ("?".into(), "?".into()), }; + let inner = f.area().width.saturating_sub(2) as usize; + let invite = wrap_invite(payload, inner.max(1)); let body = format!( - "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{payload}" + "give this string to a friend; they F3 paste it\n\nfp {fp}\nonion {onion}\n\n{invite}" ); f.render_widget( Paragraph::new(body) @@ -1725,10 +1816,9 @@ pub fn draw_share(f: &mut Frame, payload: &str) { } fn draw_paste(f: &mut Frame, buf: &str, err: Option<&str>) { - let hint = err - .unwrap_or("paste onionwire:v1 payload, Enter to submit") - .to_string(); - let body = format!("{hint}\n\n{buf}"); + let inner = f.area().width.saturating_sub(2) as usize; + let shown = wrap_invite(buf, inner.max(1)); + let body = paste_screen_text(&shown, err); let style = if err.is_some() { style_alert() } else { diff --git a/src/wallet.rs b/src/wallet.rs index 9dd574f..1917cd7 100644 --- a/src/wallet.rs +++ b/src/wallet.rs @@ -3,6 +3,7 @@ use std::time::Duration; use rand::RngCore; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; +use zeroize::Zeroizing; pub type Result = std::result::Result; @@ -23,7 +24,7 @@ struct Endpoint { port: u16, path: String, user: String, - pass: String, + pass: Zeroizing, } impl std::fmt::Debug for Endpoint { @@ -59,12 +60,15 @@ impl Wallet { pub fn from_env() -> Self { 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() => { + let url = Zeroizing::new(s); let login = std::env::var("ONIONWIRE_WALLET_RPC_LOGIN") .ok() - .map(|v| v.trim().to_string()) + .map(|v| Zeroizing::new(v.trim().to_string())) .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 { 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()) } -fn parse_login(login: &str) -> Result<(String, String)> { +fn parse_login(login: &str) -> Result<(String, Zeroizing)> { let (user, pass) = login.split_once(':').ok_or_else(credentials_required)?; if user.is_empty() || pass.is_empty() { 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 { @@ -405,7 +409,9 @@ fn digest_authorization(ep: &Endpoint, challenge: &str) -> Result { let nonce = digest_param(challenge, "nonce") .ok_or_else(|| Error("wallet RPC digest required (--rpc-login / HTTP Digest)".into()))?; 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 (qop_part, resp) = if qop .as_deref() diff --git a/tests/backup.rs b/tests/backup.rs index 37590b6..51ee582 100644 --- a/tests/backup.rs +++ b/tests/backup.rs @@ -72,9 +72,9 @@ fn restore_overwrites_self_keys_friends_stay() { ) .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.prekey_sk, incoming.prekey_sk); + assert_eq!(me.prekey_sk[..], incoming.prekey_sk[..]); assert_eq!(me.prekey_pk, incoming.prekey_pk); assert_eq!(me.onion, old.onion, "onion is locator, not restored"); assert_eq!(store.friend_count().unwrap(), 1); diff --git a/tests/store.rs b/tests/store.rs index 7bc688a..2390261 100644 --- a/tests/store.rs +++ b/tests/store.rs @@ -67,7 +67,7 @@ fn first_run_creates_0700_dirs_and_self_row() { let me = store.self_identity().expect("self"); assert_eq!(me.identity_pk.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!(store.friend_count().unwrap(), 0); @@ -152,7 +152,7 @@ fn self_has_x25519_prekey_and_set_onion() { let me = store.self_identity().unwrap(); assert_eq!(me.prekey_pk.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(); assert_eq!(store.self_identity().unwrap().onion, "abc.onion"); } @@ -233,6 +233,121 @@ fn append_message_db_file_does_not_contain_plaintext() { ); } +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn db_files(home: &Path) -> Vec<(String, Vec)> { + let mut out = Vec::new(); + for ent in fs::read_dir(home).expect("read_dir").flatten() { + let name = ent.file_name().to_string_lossy().to_string(); + if !name.starts_with("onionwire.db") { + continue; + } + out.push((name, fs::read(ent.path()).expect("read db file"))); + } + out.sort(); + out +} + +fn store_contains(home: &Path, needle: &[u8]) -> bool { + db_files(home) + .iter() + .any(|(_, bytes)| bytes.windows(needle.len()).any(|w| w == needle)) +} + +#[test] +fn whole_store_file_is_encrypted_at_rest() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "at-rest-pass").expect("open"); + let me = store.self_identity().unwrap(); + store + .upsert_friend(&pk(7), "friend.onion", Some("alice")) + .unwrap(); + store + .append_message(&pk(7), "out", b"body-at-rest-xyz") + .unwrap(); + store + .append_message(&pk(7), "in", b"reply-at-rest-xyz") + .unwrap(); + drop(store); + + for (needle, what) in [ + (b"body-at-rest-xyz".to_vec(), "chat body"), + (b"reply-at-rest-xyz".to_vec(), "inbound chat body"), + (hex(&pk(7)).into_bytes(), "friend pubkey hex"), + (b"friend.onion".to_vec(), "friend locator"), + (me.identity_sk.to_vec(), "identity secret key"), + ] { + assert!( + !store_contains(dir.path(), &needle), + "onionwire.db* still contains the {what}" + ); + } +} + +#[test] +fn wrong_passphrase_touches_nothing_and_leaves_store_readable() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "right-pass").expect("open"); + store.upsert_friend(&pk(1), "b.onion", None).unwrap(); + store + .append_message(&pk(1), "in", b"secret-chat-body") + .unwrap(); + drop(store); + let before = db_files(dir.path()); + assert!(!before.is_empty(), "expected store files on disk"); + + let err = match Store::open_at_with_passphrase(dir.path(), "wrong-pass") { + Ok(_) => panic!("wrong passphrase should fail"), + Err(e) => e, + }; + let msg = err.to_string().to_ascii_lowercase(); + assert!( + msg.contains("passphrase") || msg.contains("decrypt") || msg.contains("wrong"), + "got {err}" + ); + assert_eq!( + db_files(dir.path()), + before, + "a failed unlock must not modify the store files" + ); + + let store = Store::open_at_with_passphrase(dir.path(), "right-pass").expect("reopen"); + assert_eq!( + store.list_messages(&pk(1)).unwrap()[0].plaintext, + b"secret-chat-body" + ); +} + +#[test] +fn encrypted_store_without_salt_file_refuses_to_guess() { + let dir = tempfile::tempdir().expect("tempdir"); + let store = Store::open_at_with_passphrase(dir.path(), "at-rest-pass").expect("open"); + store.upsert_friend(&pk(1), "b.onion", None).unwrap(); + let me = store.self_identity().unwrap(); + drop(store); + + fs::remove_file(dir.path().join("store_salt")).expect("remove salt"); + let err = match Store::open_at_with_passphrase(dir.path(), "at-rest-pass") { + Ok(_) => panic!("an encrypted store without its salt must not open"), + Err(e) => e, + }; + assert!(err.to_string().contains("store_salt"), "got {err}"); + + // The salt is only a salt: putting it back restores access, no data lost. + fs::write(dir.path().join("store_salt"), [0u8; 16]).unwrap(); + let err = match Store::open_at_with_passphrase(dir.path(), "at-rest-pass") { + Ok(_) => panic!("a wrong salt must not silently open the store"), + Err(e) => e, + }; + assert!( + err.to_string().to_ascii_lowercase().contains("passphrase"), + "a wrong salt must not silently open the store: {err}" + ); + assert_eq!(me.identity_sk.len(), 32); +} + #[test] fn wrong_passphrase_cannot_open_or_list() { let dir = tempfile::tempdir().expect("tempdir"); @@ -279,7 +394,7 @@ fn env_passphrase_skips_prompt() { unsafe { std::env::remove_var("ONIONWIRE_STORE_PASSPHRASE"); } - assert_eq!(got.unwrap(), "from-env"); + assert_eq!(got.unwrap().as_str(), "from-env"); assert!(!prompted); } @@ -313,7 +428,7 @@ fn missing_env_reads_secret_and_strips_newline() { Ok("secret-from-tty\n".into()) }) .unwrap(); - assert_eq!(got, "secret-from-tty"); + assert_eq!(got.as_str(), "secret-from-tty"); } #[test] diff --git a/tests/tui_spec.rs b/tests/tui_spec.rs index b29270f..2310487 100644 --- a/tests/tui_spec.rs +++ b/tests/tui_spec.rs @@ -1,17 +1,21 @@ //! Spec implementation tests for docs/TUI.md (this card). //! Does not own `tests/tui_frames.rs` (PR #23). +use onionwire::qr; use onionwire::tui::{ - draw_text_overlay, help_overlay_text, main_footer_hints, main_header_line, roster_col_width, - status_footer, + alert_line, ascii_chrome, draw_share, draw_text_overlay, empty_friend_chat_text, + help_overlay_text, main_footer_hints, main_header_line, paste_screen_text, roster_col_width, + status_footer, wrap_invite, }; use ratatui::Frame; use ratatui::Terminal; use ratatui::backend::TestBackend; use ratatui::layout::{Constraint, Layout}; use ratatui::widgets::{Block, Borders, List, ListItem, Paragraph, Wrap}; +use std::sync::Mutex; const FP: &str = "abcdef0123456789deadbeefcafebabe"; +static ASCII_ENV: Mutex<()> = Mutex::new(()); const ONION: &str = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvwx.onion"; fn screen_from(buf: &ratatui::buffer::Buffer, w: u16, h: u16) -> String { @@ -179,6 +183,8 @@ fn reconstructed_main_keeps_send_failed_on_footer() { #[test] fn dump_spec_frames() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; for (w, h) in [(80u16, 24u16), (120, 40)] { let backend = TestBackend::new(w, h); let mut terminal = Terminal::new(backend).expect("terminal"); @@ -205,5 +211,168 @@ fn dump_spec_frames() { .expect("draw"); println!("===== AFTER help {w}x{h} ====="); print!("{}", screen_from(terminal.backend().buffer(), w, h)); + + let invite = sample_invite(); + let backend = TestBackend::new(w, h); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + println!("===== AFTER share {w}x{h} ====="); + print!("{}", screen_from(terminal.backend().buffer(), w, h)); } } + +fn sample_invite() -> String { + let sk = [7u8; 32]; + qr::encode(&sk, ONION, &[1u8; 32]).expect("encode") +} + +fn invite_line_ok(line: &str) -> bool { + let t = line.trim(); + t.is_empty() + || t.starts_with("onionwire:") + || t.starts_with("k=") + || t.starts_with("o=") + || t.starts_with("spk=") + || t.starts_with("sig=") + || t.chars().all(|c| c.is_ascii_hexdigit()) +} + +#[test] +fn alert_line_truncates_to_frame_width() { + let long = "passphrases do not match and then a lot more context that would collide with the roster on the next row if left unwrapped"; + let line = alert_line(long, 80); + assert!( + line.chars().count() <= 80, + "alert wider than 80: {} {line:?}", + line.chars().count() + ); + assert!( + line.contains('…') || line.contains("..."), + "long alert was not truncated: {line:?}" + ); + assert!( + !line.contains("roster on the next row"), + "alert still has overflow tail: {line:?}" + ); +} + +#[test] +fn wrap_invite_breaks_on_field_boundaries() { + let invite = sample_invite(); + assert!(invite.len() > 78, "fixture too short to wrap: {invite}"); + let wrapped = wrap_invite(&invite, 78); + for line in wrapped.lines() { + assert!( + line.chars().count() <= 78, + "invite line wider than 78: {} {line:?}", + line.chars().count() + ); + assert!( + invite_line_ok(line), + "invite wrapped mid-token: {line:?}\n{wrapped}" + ); + } + assert!( + wrapped.contains("onionwire:v1:"), + "lost invite prefix:\n{wrapped}" + ); + assert!(wrapped.contains("k="), "lost k= field:\n{wrapped}"); + assert!(wrapped.contains("spk="), "lost spk= field:\n{wrapped}"); + let joined: String = wrapped.lines().map(str::trim).collect(); + assert_eq!( + joined, invite, + "wrap must be newline-joinable back to payload" + ); +} + +#[test] +fn draw_share_invite_does_not_wrap_mid_token() { + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + assert!( + screen.contains("onionwire:v1:"), + "missing prefix:\n{screen}" + ); + for raw in screen.lines() { + let inner = raw.trim_start_matches(['│', '|', ' ']); + let inner = inner.trim_end_matches(['│', '|', ' ']); + if inner.starts_with("onionwire:") + || inner.starts_with("k=") + || inner.starts_with("o=") + || inner.starts_with("spk=") + || inner.starts_with("sig=") + || inner.chars().all(|c| c.is_ascii_hexdigit()) + { + assert!( + invite_line_ok(inner), + "share pane mid-token wrap: {inner:?}\n{screen}" + ); + } + if inner.starts_with('c') && inner.contains(":o=") { + panic!("share still wraps mid-hex into :o=: {inner:?}\n{screen}"); + } + } +} + +#[test] +fn empty_friend_chat_has_send_hint() { + let text = empty_friend_chat_text(); + assert!(text.contains("no messages"), "{text:?}"); + assert!(text.contains("type below, Enter sends"), "{text:?}"); +} + +#[test] +fn paste_error_keeps_resubmit_hint() { + let body = paste_screen_text("", Some("bad invite")); + assert!(body.contains("bad invite"), "{body:?}"); + assert!(body.contains("Enter resubmits"), "{body:?}"); + assert!(body.contains("Esc back"), "{body:?}"); + let ok = paste_screen_text("onionwire:v1:k=x", None); + assert!( + ok.contains("paste onionwire:v1 payload"), + "happy-path hint lost: {ok:?}" + ); +} + +#[test] +fn ascii_switch_80x24_frame_is_pure_ascii() { + let _guard = ASCII_ENV.lock().expect("ascii env lock"); + unsafe { std::env::set_var("ONIONWIRE_ASCII", "1") }; + assert!( + ascii_chrome(), + "ONIONWIRE_ASCII set but ascii_chrome() is false" + ); + let footer = status_footer(80, FP, ONION, None, main_footer_hints()); + assert!( + footer.contains("..."), + "ASCII truncation marker missing: {footer:?}" + ); + assert!( + !footer.contains('…'), + "unicode ellipsis still in footer: {footer:?}" + ); + + let invite = sample_invite(); + let backend = TestBackend::new(80, 24); + let mut terminal = Terminal::new(backend).expect("terminal"); + terminal.draw(|f| draw_share(f, &invite)).expect("draw"); + let screen = screen_from(terminal.backend().buffer(), 80, 24); + let non_ascii: Vec = screen.chars().filter(|c| !c.is_ascii()).collect(); + assert!( + non_ascii.is_empty(), + "ASCII switch ignored, non-ASCII in 80x24 frame: {non_ascii:?}\n{screen}" + ); + assert!( + screen.contains("..."), + "truncation marker missing from ASCII frame:\n{screen}" + ); + assert!( + screen.contains('+') && screen.contains('|') && screen.contains('-'), + "ASCII borders missing:\n{screen}" + ); + println!("===== AFTER ascii share 80x24 =====\n{screen}"); + unsafe { std::env::remove_var("ONIONWIRE_ASCII") }; +} diff --git a/tests/zeroize.rs b/tests/zeroize.rs new file mode 100644 index 0000000..985a77c --- /dev/null +++ b/tests/zeroize.rs @@ -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() {} + +#[test] +fn session_and_backup_key_types_are_zeroize_on_drop() { + assert_zeroize_on_drop::(); + assert_zeroize_on_drop::(); +} + +/// 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` 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` 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` 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> = &me.identity_sk; + let _: &Zeroizing> = &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:hunter2@127.0.0.1:18083/json_rpc").expect("url"); + let dbg = format!("{w:?}"); + assert!( + !dbg.contains("hunter2"), + "wallet RPC password leaked into Debug: {dbg}" + ); + assert!(dbg.contains(""), "{dbg}"); +}