diff --git a/crates/in-core/src/secret.rs b/crates/in-core/src/secret.rs index b2633ec..89fb518 100644 --- a/crates/in-core/src/secret.rs +++ b/crates/in-core/src/secret.rs @@ -1,10 +1,14 @@ //! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. A sealed value is safe to //! store in the database; the key lives in a file readable only by the service user. +//! +//! The instance key never encrypts or MACs anything directly. Every use derives its own subkey from it +//! (see [`derive_subkey`]), and every seal is bound to a [`purpose`] that is checked as associated data, +//! so a value sealed for one purpose does not open as another. use std::path::Path; use base64::prelude::{BASE64_STANDARD, Engine as _}; -use chacha20poly1305::aead::Aead; +use chacha20poly1305::aead::{Aead, Payload}; use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; use hmac::{Hmac, Mac}; use sha2::Sha256; @@ -15,6 +19,21 @@ use crate::error::{Error, Result}; const PREFIX: &str = "v1:"; /// XChaCha20 nonce length. Long enough that a random nonce per seal never repeats in practice. const NONCE_LEN: usize = 24; +/// Label of the subkey that seals values. Its key is `derive_subkey(instance key, SEAL_LABEL)`. +const SEAL_LABEL: &[u8] = b"in seal v1"; +/// Label of the key of the password-unlock proof of a share link (see [`unlock_proof`]). +const UNLOCK_LABEL: &[u8] = b"in link unlock v1"; + +/// What a sealed value is for. It is the associated data of [`seal`] and [`open`], so a value sealed under +/// one purpose fails authentication under any other. +pub mod purpose { + /// The sealed cookie of a sign-in in progress: its state, nonce, PKCE verifier and `next` target. + pub const FLIGHT_COOKIE: &str = "flight-cookie"; + /// The ID token of a sign-in, kept on the session as the `id_token_hint` of logout. + pub const OIDC_ID_TOKEN: &str = "oidc-id-token"; + /// The sealed copy of a public share link's token, so the owner can show the URL again. + pub const SHARE_LINK_TOKEN: &str = "share-link-token"; +} /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with /// mode 0600 and `O_EXCL`, so an existing key is never overwritten. An existing key with group or @@ -83,14 +102,26 @@ pub fn read_key(path: &Path) -> Result<[u8; 32]> { }) } -/// Seals `plaintext` under `key`. The output is `"v1:" + base64(nonce || ciphertext)` with a fresh -/// random nonce each time. The caller must not store the plaintext when this fails. -pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { +/// The cipher keyed with the seal subkey of the instance key `key`. +fn seal_cipher(key: &[u8; 32]) -> XChaCha20Poly1305 { + let subkey = derive_subkey(key, SEAL_LABEL); + XChaCha20Poly1305::new((&subkey).into()) +} + +/// Seals `plaintext` under the seal subkey of `key`, bound to `purpose` as associated data. The output is +/// `"v1:" + base64(nonce || ciphertext)` with a fresh random nonce each time. Opening with any other purpose +/// fails. The caller must not store the plaintext when this fails. +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 = seal_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); @@ -98,12 +129,13 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result { Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) } -/// The proof a share-link visitor holds after the right password: an HMAC-SHA256 under the instance key -/// over the link id and the stored password hash, in lower-case hex. Changing the password or reminting -/// the link changes one of those inputs, so every old proof stops working. It is a cookie value, so the -/// key never leaves the server and the password itself is never stored in a cookie. +/// The proof a share-link visitor holds after the right password: an HMAC-SHA256 under the unlock subkey of +/// the instance key over the link id and the stored password hash, in lower-case hex. Changing the password +/// or reminting the link changes one of those inputs, so every old proof stops working. It is a cookie value, +/// so the key never leaves the server and the password itself is never stored in a cookie. pub fn unlock_proof(key: &[u8; 32], link_id: &str, password_hash: &str) -> String { - let mut mac = as hmac::KeyInit>::new_from_slice(key) + let subkey = derive_subkey(key, UNLOCK_LABEL); + let mut mac = as hmac::KeyInit>::new_from_slice(&subkey) .expect("HMAC accepts a key of any length"); mac.update(b"link-unlock:"); mac.update(link_id.as_bytes()); @@ -123,8 +155,9 @@ pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] { subkey } -/// 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`] with the same `purpose`. A wrong key or purpose, a changed byte or a +/// malformed value is an error. +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()))?; @@ -137,9 +170,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) + seal_cipher(key) + .decrypt( + &XNonce::from(nonce), + Payload { + msg: ciphertext, + aad: purpose.as_bytes(), + }, + ) .map_err(|_| Error::Crypto("sealed value failed authentication".into())) } @@ -150,18 +188,37 @@ mod tests { #[test] fn seal_and_open_round_trip_and_reject_wrong_key_or_tampering() { let key = [7u8; 32]; - let sealed = seal(&key, b"hello secret").unwrap(); + let sealed = seal(&key, purpose::FLIGHT_COOKIE, b"hello secret").unwrap(); assert!(sealed.starts_with("v1:")); - assert_eq!(open(&key, &sealed).unwrap(), b"hello secret"); + assert_eq!( + open(&key, purpose::FLIGHT_COOKIE, &sealed).unwrap(), + b"hello secret" + ); // A fresh nonce means the same plaintext never seals to the same text twice. - assert_ne!(sealed, seal(&key, b"hello secret").unwrap()); - - assert!(open(&[8u8; 32], &sealed).is_err(), "wrong key must fail"); + assert_ne!( + sealed, + seal(&key, purpose::FLIGHT_COOKIE, b"hello secret").unwrap() + ); + + assert!( + open(&[8u8; 32], purpose::FLIGHT_COOKIE, &sealed).is_err(), + "wrong key must fail" + ); + assert!( + open(&key, purpose::SHARE_LINK_TOKEN, &sealed).is_err(), + "a value sealed for one purpose must not open as another" + ); let mut tampered = sealed.clone(); let last = tampered.pop().unwrap(); tampered.push(if last == 'A' { 'B' } else { 'A' }); - assert!(open(&key, &tampered).is_err(), "tampered value must fail"); - assert!(open(&key, "data").is_err(), "missing prefix must fail"); + assert!( + open(&key, purpose::FLIGHT_COOKIE, &tampered).is_err(), + "tampered value must fail" + ); + assert!( + open(&key, purpose::FLIGHT_COOKIE, "data").is_err(), + "missing prefix must fail" + ); } } diff --git a/crates/in-core/src/store/links.rs b/crates/in-core/src/store/links.rs index 5db77a5..4fdcff9 100644 --- a/crates/in-core/src/store/links.rs +++ b/crates/in-core/src/store/links.rs @@ -29,7 +29,7 @@ pub struct Link { pub id: String, /// Hex SHA-256 of the token. Lookups go through it. pub token_hash: String, - /// The token, sealed under the instance key, so the owner can show the URL again. + /// The token, sealed for the share-link token purpose, so the owner can show the URL again. pub token_sealed: String, /// Whether the target is a file or a folder. pub kind: ItemKind, diff --git a/crates/in-core/src/store/sessions.rs b/crates/in-core/src/store/sessions.rs index 364f757..4e5ffb3 100644 --- a/crates/in-core/src/store/sessions.rs +++ b/crates/in-core/src/store/sessions.rs @@ -57,7 +57,7 @@ pub struct NewSession { pub ip: Option, /// User agent, when sent. pub user_agent: Option, - /// The sealed ID token of the sign-in. Sealed by the caller with the instance key. + /// The sealed ID token of the sign-in, sealed by the caller for the OIDC ID token purpose. pub id_token_sealed: Option, } diff --git a/crates/in-web/src/pages/links.rs b/crates/in-web/src/pages/links.rs index a348feb..4c18d63 100644 --- a/crates/in-web/src/pages/links.rs +++ b/crates/in-web/src/pages/links.rs @@ -65,7 +65,7 @@ pub struct LinkView { /// The URL of a link from its sealed token. Empty when the token cannot be opened. pub fn public_url(state: &AppState, token_sealed: &str) -> String { - match secret::open(&state.key, token_sealed) + match secret::open(&state.key, secret::purpose::SHARE_LINK_TOKEN, token_sealed) .ok() .and_then(|bytes| String::from_utf8(bytes).ok()) { @@ -205,7 +205,11 @@ pub struct LinkForm { /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`. fn new_token(state: &AppState) -> Result<(String, String, String)> { let token = generate_token(); - let sealed = secret::seal(&state.key, token.as_bytes())?; + let sealed = secret::seal( + &state.key, + secret::purpose::SHARE_LINK_TOKEN, + token.as_bytes(), + )?; Ok((hash_token(&token), sealed, token)) } diff --git a/crates/in-web/src/pages/public_share.rs b/crates/in-web/src/pages/public_share.rs index 55612ad..06ca4a6 100644 --- a/crates/in-web/src/pages/public_share.rs +++ b/crates/in-web/src/pages/public_share.rs @@ -612,7 +612,12 @@ mod tests { .create_link(NewLink { id: new_id(), token_hash: hash_token(&token), - token_sealed: secret::seal(&state.key, token.as_bytes()).expect("seal"), + token_sealed: secret::seal( + &state.key, + secret::purpose::SHARE_LINK_TOKEN, + token.as_bytes(), + ) + .expect("seal"), kind, target_id: target.to_owned(), owner: "ann".to_owned(), diff --git a/crates/in-web/src/pages/sign_in.rs b/crates/in-web/src/pages/sign_in.rs index a1bddef..d18840b 100644 --- a/crates/in-web/src/pages/sign_in.rs +++ b/crates/in-web/src/pages/sign_in.rs @@ -99,19 +99,19 @@ fn client(state: &AppState) -> Option> { state.oidc.clone() } -/// Seals `bytes` with the instance key. -fn seal(state: &AppState, bytes: &[u8]) -> CoreResult { - secret::seal(&state.key, bytes) +/// Seals `bytes` for `purpose` with the instance key. +fn seal(state: &AppState, purpose: &str, bytes: &[u8]) -> CoreResult { + secret::seal(&state.key, purpose, bytes) } -/// Opens a sealed value. Any failure reads as "not there", which the callers treat as a refusal. -fn open(state: &AppState, sealed: &str) -> Option> { - secret::open(&state.key, sealed).ok() +/// Opens a value sealed for `purpose`. Any failure reads as "not there", which the callers treat as a refusal. +fn open(state: &AppState, purpose: &str, sealed: &str) -> Option> { + secret::open(&state.key, purpose, sealed).ok() } /// Reads the flight cookie. An unreadable, malformed or expired flight is `None`. fn read_flight(state: &AppState, sealed: &str) -> Option { - let bytes = open(state, sealed)?; + let bytes = open(state, secret::purpose::FLIGHT_COOKIE, sealed)?; let flight: Flight = serde_json::from_slice(&bytes).ok()?; (flight.expires_at > now_secs()).then_some(flight) } @@ -146,7 +146,12 @@ async fn login(cx: &Cx, query: Option>) -> Result { } }; let bytes = serde_json::to_vec(&flight).map_err(|e| CoreError::Crypto(e.to_string()))?; - set_cookie(cx, FLIGHT_COOKIE, seal(state, &bytes)?, FLIGHT_TTL); + set_cookie( + cx, + FLIGHT_COOKIE, + seal(state, secret::purpose::FLIGHT_COOKIE, &bytes)?, + FLIGHT_TTL, + ); Ok(see_other(url)) } @@ -220,7 +225,7 @@ async fn callback(cx: &Cx, query: Option>) -> Result) -> Result { let hint = session .id_token_sealed .as_deref() - .and_then(|sealed| open(state, sealed)) + .and_then(|sealed| open(state, secret::purpose::OIDC_ID_TOKEN, sealed)) .and_then(|bytes| String::from_utf8(bytes).ok()); let (Some(oidc), Some(hint)) = (client(state), hint) else { return Ok(see_other("/")); diff --git a/crates/in-web/src/state.rs b/crates/in-web/src/state.rs index 802a8cd..d267242 100644 --- a/crates/in-web/src/state.rs +++ b/crates/in-web/src/state.rs @@ -22,7 +22,8 @@ pub struct AppState { pub store: Store, /// The blob store the configuration names: the local blob tree or an S3-compatible bucket. pub blobs: Arc, - /// The instance key (`in.key`). Seals secrets at rest. + /// The instance key (`in.key`). Never used directly: every seal and MAC uses a subkey derived from it (see + /// `in_core::secret`). pub key: Arc<[u8; 32]>, /// The change counters of the live pages. pub live: Arc, diff --git a/docs/architecture.md b/docs/architecture.md index 79a24f4..f19a262 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -206,7 +206,8 @@ and has no sessions. - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none). - Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and per link and client address: 10 failures / 15 min) and sets a cookie - `__Host-in_link_` = HMAC-SHA256(instance key, "link-unlock:" || link id || password_hash), 12 h, so + `__Host-in_link_` = HMAC-SHA256(unlock subkey, link id || "|" || password_hash), where the unlock subkey is + HMAC-SHA256(instance key, "in link unlock v1"), 12 h, so changing the password or remint invalidates old unlocks. - Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer works" page. A disabled owner's links and grants stop working at once and are not deleted: enabling the owner 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