feat(core): zeroize in-memory secret material (Noise/Ed25519/X25519/store key)
All checks were successful
ci / test (pull_request) Successful in 4m7s
All checks were successful
ci / test (pull_request) Successful in 4m7s
Wrap every secret this crate holds in zeroize: the local identity and prekey secrets (Keys), the backup bundle and its derived Argon2id wrap key, the store data key and the SQLCipher key material, the identity secret handed out by Store::self_identity, the raw identity-secret copies in pay/qr signing, and the wallet RPC password plus the user:realm:password digest input.
This commit is contained in:
parent
3adfc24391
commit
f3fca69fbe
12 changed files with 297 additions and 71 deletions
91
src/store.rs
91
src/store.rs
|
|
@ -9,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<T> = std::result::Result<T, Error>;
|
||||
|
||||
|
|
@ -43,14 +44,15 @@ impl From<String> 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<u8>,
|
||||
pub identity_sk: Zeroizing<Vec<u8>>,
|
||||
pub identity_pk: Vec<u8>,
|
||||
pub onion: String,
|
||||
pub prekey_sk: Vec<u8>,
|
||||
pub prekey_sk: Zeroizing<Vec<u8>>,
|
||||
pub prekey_pk: Vec<u8>,
|
||||
}
|
||||
|
||||
|
|
@ -109,7 +111,8 @@ impl Store {
|
|||
}
|
||||
|
||||
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> {
|
||||
|
|
@ -199,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()?;
|
||||
|
|
@ -275,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()));
|
||||
}
|
||||
|
|
@ -285,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],
|
||||
|
|
@ -384,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(
|
||||
|
|
@ -402,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],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
|
@ -416,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)?,
|
||||
})
|
||||
},
|
||||
|
|
@ -810,10 +816,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 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
|
||||
|
|
@ -913,7 +919,7 @@ fn open_store_db(home: &Path, db_path: &Path, passphrase: &str) -> Result<Connec
|
|||
/// the key, with no second KDF pass over it.
|
||||
fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
|
||||
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"
|
||||
// at ERROR to stderr. A wrong passphrase is a normal user error here.
|
||||
let _ = conn.execute_batch("PRAGMA cipher_log_level = NONE");
|
||||
|
|
@ -925,8 +931,10 @@ fn open_keyed(db_path: &Path, key: &[u8; 32]) -> Result<Connection> {
|
|||
Ok(conn)
|
||||
}
|
||||
|
||||
fn pragma_key(key: &[u8; 32]) -> String {
|
||||
format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key))
|
||||
/// 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<String> {
|
||||
Zeroizing::new(format!("PRAGMA key = \"x'{hex}'\"", hex = fingerprint(key)))
|
||||
}
|
||||
|
||||
/// True when `passphrase` unwraps `store_meta`. An empty `store_meta` (fresh
|
||||
|
|
@ -961,10 +969,11 @@ fn migrate_plaintext_to_encrypted(db_path: &Path, key: &[u8; 32], passphrase: &s
|
|||
let conn = Connection::open(db_path)?;
|
||||
let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE)");
|
||||
let target = tmp.to_string_lossy().replace('\'', "''");
|
||||
conn.execute_batch(&format!(
|
||||
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;")?;
|
||||
}
|
||||
|
|
@ -1005,29 +1014,29 @@ fn home_dir() -> Result<PathBuf> {
|
|||
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") {
|
||||
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<String>,
|
||||
) -> Result<String> {
|
||||
) -> Result<Zeroizing<String>> {
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1066,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() {
|
||||
|
|
@ -1303,10 +1327,10 @@ mod at_rest {
|
|||
.unwrap();
|
||||
let mut salt = [0u8; 16];
|
||||
OsRng.fill_bytes(&mut salt);
|
||||
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 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(
|
||||
"INSERT INTO store_meta (id, kdf_salt, wrapped_key) VALUES (1, ?1, ?2)",
|
||||
params![salt.as_slice(), wrapped],
|
||||
|
|
@ -1356,7 +1380,10 @@ mod at_rest {
|
|||
);
|
||||
|
||||
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();
|
||||
assert_eq!(msgs.len(), 2, "history must survive the upgrade");
|
||||
assert_eq!(msgs[0].plaintext, b"legacy-body-xyz");
|
||||
|
|
|
|||
Loading…
Reference in a new issue