diff --git a/crates/iz-core/src/secret.rs b/crates/iz-core/src/secret.rs index 405f15a..8ecad33 100644 --- a/crates/iz-core/src/secret.rs +++ b/crates/iz-core/src/secret.rs @@ -1,16 +1,53 @@ -//! The instance key and sealing of secrets at rest (XChaCha20-Poly1305). Sealed values look like -//! `v1:` + base64(nonce || ciphertext). Plaintext secrets are never stored as a fallback. +//! The instance key, its derived subkeys, and XChaCha20-Poly1305 sealing of secrets at rest. +//! +//! The instance key never encrypts or MACs anything directly. Every use derives its own subkey from it +//! (see [`derive`]), and every sealed value is bound to a purpose (see [`purpose`]) that is checked as +//! associated data, so a value sealed for one purpose does not open as another. +//! +//! A sealed value is `v1:` followed by base64(nonce || ciphertext). The nonce is random for every +//! seal, so sealing the same plaintext twice gives different text. Plaintext secrets are never stored +//! as a fallback. use std::path::Path; +use aws_lc_rs::hmac; use base64::prelude::{BASE64_STANDARD, Engine as _}; -use chacha20poly1305::aead::Aead; +use chacha20poly1305::aead::{Aead, Payload}; use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; use crate::error::{Error, Result}; const PREFIX: &str = "v1:"; const NONCE_LEN: usize = 24; +/// Label of the subkey that seals values. The subkey is [`derive`] of this label. +const SEAL_LABEL: &[u8] = b"iz seal v1"; + +/// What a sealed value is for. Passed as the associated data of [`seal`] and [`open`]: a value sealed +/// under one purpose fails authentication under any other. +pub mod purpose { + /// The sealed cookie that carries a sign-in in progress (state, nonce, PKCE verifier, `next`). + pub const SIGN_IN_FLIGHT: &str = "sign-in-flight"; + /// The sealed ID token kept with a session, as the hint for a later logout. + pub const ID_TOKEN: &str = "id-token"; + /// The SMTP password of the configured sender. + pub const SMTP_PASSWORD: &str = "smtp-password"; +} + +/// Derives a 32-byte subkey of the instance key `key` for `label`: HMAC-SHA256 of the label, keyed with +/// the instance key. Each use names its own label, so no two uses share key material. +pub(crate) fn derive(key: &[u8; 32], label: &[u8]) -> [u8; 32] { + let master = hmac::Key::new(hmac::HMAC_SHA256, key); + let tag = hmac::sign(&master, label); + let mut subkey = [0u8; 32]; + subkey.copy_from_slice(tag.as_ref()); + subkey +} + +/// The cipher keyed with the seal subkey of the instance key `key`. +fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 { + let subkey = derive(key, SEAL_LABEL); + XChaCha20Poly1305::new((&subkey).into()) +} /// Loads the 32-byte instance key at `path`, creating it with mode 0600 if it is missing. /// A key file that is group or world accessible, or has the wrong length, is refused. @@ -74,13 +111,21 @@ pub fn read_key(path: &Path) -> Result<[u8; 32]> { }) } -/// Seals `plaintext` under `key` with a fresh random nonce. -pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { +/// Seals `plaintext` under the seal subkey of `key`, bound to `purpose`. Output: `"v1:" + base64(nonce || ciphertext)`. +/// +/// Errors if the cipher rejects the input. The caller must then refuse to store the value, never +/// store it in clear. +pub fn seal(key: &[u8; 32], purpose: &str, plaintext: &[u8]) -> Result { let mut nonce = [0u8; NONCE_LEN]; rand::fill(&mut nonce); - let cipher = XChaCha20Poly1305::new(key.into()); - let ciphertext = cipher - .encrypt(&XNonce::from(nonce), plaintext) + let ciphertext = cipher(key) + .encrypt( + &XNonce::from(nonce), + Payload { + msg: plaintext, + aad: purpose.as_bytes(), + }, + ) .map_err(|_| Error::Crypto("sealing failed".into()))?; let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); blob.extend_from_slice(&nonce); @@ -88,8 +133,11 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) } -/// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. -pub fn open(key: &[u8; 32], sealed: &str) -> Result> { +/// Opens a value produced by [`seal`] under the same key and the same `purpose`. +/// +/// Any failure (bad prefix, bad base64, short input, wrong key, wrong purpose, tampering) is an error. +/// The messages are fixed strings, so nothing about the plaintext or the key can leak through them. +pub fn open(key: &[u8; 32], purpose: &str, sealed: &str) -> Result> { let encoded = sealed .strip_prefix(PREFIX) .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?; @@ -102,9 +150,14 @@ pub fn open(key: &[u8; 32], sealed: &str) -> Result> { let (nonce, ciphertext) = blob.split_at(NONCE_LEN); let nonce = <[u8; NONCE_LEN]>::try_from(nonce) .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; - let cipher = XChaCha20Poly1305::new(key.into()); - cipher - .decrypt(&XNonce::from(nonce), ciphertext) + cipher(key) + .decrypt( + &XNonce::from(nonce), + Payload { + msg: ciphertext, + aad: purpose.as_bytes(), + }, + ) .map_err(|_| Error::Crypto("sealed value failed authentication".into())) } @@ -115,24 +168,31 @@ mod tests { #[test] fn seal_open_round_trip_and_fresh_nonce() { let key = [7u8; 32]; - let sealed = seal(&key, b"hello secret").unwrap(); + let sealed = seal(&key, purpose::SMTP_PASSWORD, b"hello secret").unwrap(); assert!(sealed.starts_with("v1:")); - assert_eq!(open(&key, &sealed).unwrap(), b"hello secret"); - assert_ne!(sealed, seal(&key, b"hello secret").unwrap()); + assert_eq!( + open(&key, purpose::SMTP_PASSWORD, &sealed).unwrap(), + b"hello secret" + ); + assert!(open(&key, purpose::ID_TOKEN, &sealed).is_err()); + assert_ne!( + sealed, + seal(&key, purpose::SMTP_PASSWORD, b"hello secret").unwrap() + ); } #[test] fn open_rejects_wrong_key_tampering_and_garbage() { let key = [7u8; 32]; - let sealed = seal(&key, b"data").unwrap(); - assert!(open(&[8u8; 32], &sealed).is_err()); + let sealed = seal(&key, purpose::ID_TOKEN, b"data").unwrap(); + assert!(open(&[8u8; 32], purpose::ID_TOKEN, &sealed).is_err()); let mut tampered = sealed.clone(); let last = tampered.pop().unwrap(); tampered.push(if last == 'A' { 'B' } else { 'A' }); - assert!(open(&key, &tampered).is_err()); - assert!(open(&key, "data").is_err()); - assert!(open(&key, "v1:!!!").is_err()); - assert!(open(&key, "v1:AAAA").is_err()); + assert!(open(&key, purpose::ID_TOKEN, &tampered).is_err()); + assert!(open(&key, purpose::ID_TOKEN, "data").is_err()); + assert!(open(&key, purpose::ID_TOKEN, "v1:!!!").is_err()); + assert!(open(&key, purpose::ID_TOKEN, "v1:AAAA").is_err()); } #[cfg(unix)] diff --git a/crates/iz-web/src/auth.rs b/crates/iz-web/src/auth.rs index 01252be..ed4dcd9 100644 --- a/crates/iz-web/src/auth.rs +++ b/crates/iz-web/src/auth.rs @@ -3,7 +3,7 @@ //! //! The browser holds the raw session token in `__Host-iz_session`. The store keeps only its SHA-256 //! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in -//! `__Host-iz_flight`, sealed with the instance key, so the browser cannot change it. +//! `__Host-iz_flight`, sealed with the instance key under the `sign-in-flight` purpose, so the browser cannot change it. use std::time::Duration; @@ -236,12 +236,12 @@ pub fn clear_state_cookie(cx: &Cx) { pub fn seal_sign_in_state(key: &[u8; 32], state: &SignInState) -> iz_core::Result { let json = serde_json::to_vec(state) .map_err(|e| iz_core::Error::Crypto(format!("encoding the sign-in state: {e}")))?; - secret::seal(key, &json) + secret::seal(key, secret::purpose::SIGN_IN_FLIGHT, &json) } /// Opens a sealed sign-in flight. `None` when it is malformed, tampered with, or past its expiry. pub fn open_sign_in_state(key: &[u8; 32], sealed: &str) -> Option { - let plain = secret::open(key, sealed).ok()?; + let plain = secret::open(key, secret::purpose::SIGN_IN_FLIGHT, sealed).ok()?; let state: SignInState = serde_json::from_slice(&plain).ok()?; (unix_now() < state.expires).then_some(state) } diff --git a/crates/iz-web/src/mail/mod.rs b/crates/iz-web/src/mail/mod.rs index fa45742..c18e5f0 100644 --- a/crates/iz-web/src/mail/mod.rs +++ b/crates/iz-web/src/mail/mod.rs @@ -152,7 +152,7 @@ pub async fn configured(state: &AppState) -> iz_core::Result> }; let password = match stored.sealed_password { Some(sealed) => { - let bytes = secret::open(&state.key, &sealed)?; + let bytes = secret::open(&state.key, secret::purpose::SMTP_PASSWORD, &sealed)?; String::from_utf8(bytes) .map_err(|_| iz_core::Error::Crypto("the stored password is not text".into()))? } diff --git a/crates/iz-web/src/pages/settings.rs b/crates/iz-web/src/pages/settings.rs index 0e25b2a..b89f007 100644 --- a/crates/iz-web/src/pages/settings.rs +++ b/crates/iz-web/src/pages/settings.rs @@ -273,7 +273,11 @@ async fn save_sender(cx: &Cx, form: Option>) -> Result Result { } // The ID token is kept, sealed, as the hint of a later logout. - let sealed_id_token = secret::seal(&state.key, id_token.as_bytes())?; + let sealed_id_token = secret::seal(&state.key, secret::purpose::ID_TOKEN, id_token.as_bytes())?; let issued = match state .store .create_session( @@ -338,7 +338,7 @@ async fn logout( .session .id_token_sealed .as_deref() - .and_then(|sealed| secret::open(&state.key, sealed).ok()) + .and_then(|sealed| secret::open(&state.key, secret::purpose::ID_TOKEN, sealed).ok()) .and_then(|plain| String::from_utf8(plain).ok()); let target = match &state.oidc { Some(client) => match client diff --git a/crates/iz-web/src/state.rs b/crates/iz-web/src/state.rs index 2354bd0..68f8ae8 100644 --- a/crates/iz-web/src/state.rs +++ b/crates/iz-web/src/state.rs @@ -18,7 +18,7 @@ pub struct AppState { pub config: Arc, /// The database. Reads go to a pooled reader and writes to the single writer. pub store: Store, - /// The instance key (`iz.key`). Seals secrets at rest. + /// The instance key (`iz.key`). Never used directly: sealing and the manifest MAC each derive a subkey. pub key: Arc<[u8; 32]>, /// The change counters of the live pages. pub live: Arc, diff --git a/docs/conventions.md b/docs/conventions.md index f5869f3..935efc1 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -95,8 +95,10 @@ tokens, passwords, cookies, or secrets. - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second factors per user; checked before any lookup; `429` with `Retry-After`. -- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305 under the instance key, `v1:` + base64(nonce || - ciphertext). +- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance + key is never used directly: every use gets its own key, HMAC-SHA256(instance key, " v1"), and + each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot + be opened as another. - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. ## 7. Authorization