Sealing under a derived key with the purpose bound as associated data
Browse files at this commit31dcd14b1ef2d7ebfd95c4a28e12a47497b0f103Parent: b79de5e- fix
- sealing under a derived key with the purpose bound as associated data
7 changed files +98 -32
- crates/iz-core/src/secret.rs +82 -22
- crates/iz-web/src/auth.rs +3 -3
- crates/iz-web/src/mail/mod.rs +1 -1
- crates/iz-web/src/pages/settings.rs +5 -1
- crates/iz-web/src/pages/sign_in.rs +2 -2
- crates/iz-web/src/state.rs +1 -1
- docs/conventions.md +4 -2
crates/iz-core/src/secret.rsmodified+82 -22
| @@ -1,16 +1,53 @@ | |||
| 1 | -//! The instance key and sealing of secrets at rest (XChaCha20-Poly1305). Sealed values look like | 1 | +//! The instance key, its derived subkeys, and XChaCha20-Poly1305 sealing of secrets at rest. |
| 2 | -//! `v1:` + base64(nonce || ciphertext). Plaintext secrets are never stored as a fallback. | 2 | +//! |
| 3 | +//! The instance key never encrypts or MACs anything directly. Every use derives its own subkey from it | ||
| 4 | +//! (see [`derive`]), and every sealed value is bound to a purpose (see [`purpose`]) that is checked as | ||
| 5 | +//! associated data, so a value sealed for one purpose does not open as another. | ||
| 6 | +//! | ||
| 7 | +//! A sealed value is `v1:` followed by base64(nonce || ciphertext). The nonce is random for every | ||
| 8 | +//! seal, so sealing the same plaintext twice gives different text. Plaintext secrets are never stored | ||
| 9 | +//! as a fallback. | ||
| 3 | 10 | ||
| 4 | use std::path::Path; | 11 | use std::path::Path; |
| 5 | 12 | ||
| 13 | +use aws_lc_rs::hmac; | ||
| 6 | use base64::prelude::{BASE64_STANDARD, Engine as _}; | 14 | use base64::prelude::{BASE64_STANDARD, Engine as _}; |
| 7 | -use chacha20poly1305::aead::Aead; | 15 | +use chacha20poly1305::aead::{Aead, Payload}; |
| 8 | use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; | 16 | use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; |
| 9 | 17 | ||
| 10 | use crate::error::{Error, Result}; | 18 | use crate::error::{Error, Result}; |
| 11 | 19 | ||
| 12 | const PREFIX: &str = "v1:"; | 20 | const PREFIX: &str = "v1:"; |
| 13 | const NONCE_LEN: usize = 24; | 21 | const NONCE_LEN: usize = 24; |
| 22 | +/// Label of the subkey that seals values. The subkey is [`derive`] of this label. | ||
| 23 | +const SEAL_LABEL: &[u8] = b"iz seal v1"; | ||
| 24 | + | ||
| 25 | +/// What a sealed value is for. Passed as the associated data of [`seal`] and [`open`]: a value sealed | ||
| 26 | +/// under one purpose fails authentication under any other. | ||
| 27 | +pub mod purpose { | ||
| 28 | + /// The sealed cookie that carries a sign-in in progress (state, nonce, PKCE verifier, `next`). | ||
| 29 | + pub const SIGN_IN_FLIGHT: &str = "sign-in-flight"; | ||
| 30 | + /// The sealed ID token kept with a session, as the hint for a later logout. | ||
| 31 | + pub const ID_TOKEN: &str = "id-token"; | ||
| 32 | + /// The SMTP password of the configured sender. | ||
| 33 | + pub const SMTP_PASSWORD: &str = "smtp-password"; | ||
| 34 | +} | ||
| 35 | + | ||
| 36 | +/// Derives a 32-byte subkey of the instance key `key` for `label`: HMAC-SHA256 of the label, keyed with | ||
| 37 | +/// the instance key. Each use names its own label, so no two uses share key material. | ||
| 38 | +pub(crate) fn derive(key: &[u8; 32], label: &[u8]) -> [u8; 32] { | ||
| 39 | + let master = hmac::Key::new(hmac::HMAC_SHA256, key); | ||
| 40 | + let tag = hmac::sign(&master, label); | ||
| 41 | + let mut subkey = [0u8; 32]; | ||
| 42 | + subkey.copy_from_slice(tag.as_ref()); | ||
| 43 | + subkey | ||
| 44 | +} | ||
| 45 | + | ||
| 46 | +/// The cipher keyed with the seal subkey of the instance key `key`. | ||
| 47 | +fn cipher(key: &[u8; 32]) -> XChaCha20Poly1305 { | ||
| 48 | + let subkey = derive(key, SEAL_LABEL); | ||
| 49 | + XChaCha20Poly1305::new((&subkey).into()) | ||
| 50 | +} | ||
| 14 | 51 | ||
| 15 | /// Loads the 32-byte instance key at `path`, creating it with mode 0600 if it is missing. | 52 | /// Loads the 32-byte instance key at `path`, creating it with mode 0600 if it is missing. |
| 16 | /// A key file that is group or world accessible, or has the wrong length, is refused. | 53 | /// 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]> { | |||
| 74 | }) | 111 | }) |
| 75 | } | 112 | } |
| 76 | 113 | ||
| 77 | -/// Seals `plaintext` under `key` with a fresh random nonce. | 114 | +/// Seals `plaintext` under the seal subkey of `key`, bound to `purpose`. Output: `"v1:" + base64(nonce || ciphertext)`. |
| 78 | -pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> { | 115 | +/// |
| 116 | +/// Errors if the cipher rejects the input. The caller must then refuse to store the value, never | ||
| 117 | +/// store it in clear. | ||
| 118 | +pub fn seal(key: &[u8; 32], purpose: &str, plaintext: &[u8]) -> Result<String> { | ||
| 79 | let mut nonce = [0u8; NONCE_LEN]; | 119 | let mut nonce = [0u8; NONCE_LEN]; |
| 80 | rand::fill(&mut nonce); | 120 | rand::fill(&mut nonce); |
| 81 | - let cipher = XChaCha20Poly1305::new(key.into()); | 121 | + let ciphertext = cipher(key) |
| 82 | - let ciphertext = cipher | 122 | + .encrypt( |
| 83 | - .encrypt(&XNonce::from(nonce), plaintext) | 123 | + &XNonce::from(nonce), |
| 124 | + Payload { | ||
| 125 | + msg: plaintext, | ||
| 126 | + aad: purpose.as_bytes(), | ||
| 127 | + }, | ||
| 128 | + ) | ||
| 84 | .map_err(|_| Error::Crypto("sealing failed".into()))?; | 129 | .map_err(|_| Error::Crypto("sealing failed".into()))?; |
| 85 | let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); | 130 | let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); |
| 86 | blob.extend_from_slice(&nonce); | 131 | blob.extend_from_slice(&nonce); |
| @@ -88,8 +133,11 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> { | |||
| 88 | Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) | 133 | Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) |
| 89 | } | 134 | } |
| 90 | 135 | ||
| 91 | -/// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. | 136 | +/// Opens a value produced by [`seal`] under the same key and the same `purpose`. |
| 92 | -pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { | 137 | +/// |
| 138 | +/// Any failure (bad prefix, bad base64, short input, wrong key, wrong purpose, tampering) is an error. | ||
| 139 | +/// The messages are fixed strings, so nothing about the plaintext or the key can leak through them. | ||
| 140 | +pub fn open(key: &[u8; 32], purpose: &str, sealed: &str) -> Result<Vec<u8>> { | ||
| 93 | let encoded = sealed | 141 | let encoded = sealed |
| 94 | .strip_prefix(PREFIX) | 142 | .strip_prefix(PREFIX) |
| 95 | .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?; | 143 | .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<Vec<u8>> { | |||
| 102 | let (nonce, ciphertext) = blob.split_at(NONCE_LEN); | 150 | let (nonce, ciphertext) = blob.split_at(NONCE_LEN); |
| 103 | let nonce = <[u8; NONCE_LEN]>::try_from(nonce) | 151 | let nonce = <[u8; NONCE_LEN]>::try_from(nonce) |
| 104 | .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; | 152 | .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; |
| 105 | - let cipher = XChaCha20Poly1305::new(key.into()); | 153 | + cipher(key) |
| 106 | - cipher | 154 | + .decrypt( |
| 107 | - .decrypt(&XNonce::from(nonce), ciphertext) | 155 | + &XNonce::from(nonce), |
| 156 | + Payload { | ||
| 157 | + msg: ciphertext, | ||
| 158 | + aad: purpose.as_bytes(), | ||
| 159 | + }, | ||
| 160 | + ) | ||
| 108 | .map_err(|_| Error::Crypto("sealed value failed authentication".into())) | 161 | .map_err(|_| Error::Crypto("sealed value failed authentication".into())) |
| 109 | } | 162 | } |
| 110 | 163 | ||
| @@ -115,24 +168,31 @@ mod tests { | |||
| 115 | #[test] | 168 | #[test] |
| 116 | fn seal_open_round_trip_and_fresh_nonce() { | 169 | fn seal_open_round_trip_and_fresh_nonce() { |
| 117 | let key = [7u8; 32]; | 170 | let key = [7u8; 32]; |
| 118 | - let sealed = seal(&key, b"hello secret").unwrap(); | 171 | + let sealed = seal(&key, purpose::SMTP_PASSWORD, b"hello secret").unwrap(); |
| 119 | assert!(sealed.starts_with("v1:")); | 172 | assert!(sealed.starts_with("v1:")); |
| 120 | - assert_eq!(open(&key, &sealed).unwrap(), b"hello secret"); | 173 | + assert_eq!( |
| 121 | - assert_ne!(sealed, seal(&key, b"hello secret").unwrap()); | 174 | + open(&key, purpose::SMTP_PASSWORD, &sealed).unwrap(), |
| 175 | + b"hello secret" | ||
| 176 | + ); | ||
| 177 | + assert!(open(&key, purpose::ID_TOKEN, &sealed).is_err()); | ||
| 178 | + assert_ne!( | ||
| 179 | + sealed, | ||
| 180 | + seal(&key, purpose::SMTP_PASSWORD, b"hello secret").unwrap() | ||
| 181 | + ); | ||
| 122 | } | 182 | } |
| 123 | 183 | ||
| 124 | #[test] | 184 | #[test] |
| 125 | fn open_rejects_wrong_key_tampering_and_garbage() { | 185 | fn open_rejects_wrong_key_tampering_and_garbage() { |
| 126 | let key = [7u8; 32]; | 186 | let key = [7u8; 32]; |
| 127 | - let sealed = seal(&key, b"data").unwrap(); | 187 | + let sealed = seal(&key, purpose::ID_TOKEN, b"data").unwrap(); |
| 128 | - assert!(open(&[8u8; 32], &sealed).is_err()); | 188 | + assert!(open(&[8u8; 32], purpose::ID_TOKEN, &sealed).is_err()); |
| 129 | let mut tampered = sealed.clone(); | 189 | let mut tampered = sealed.clone(); |
| 130 | let last = tampered.pop().unwrap(); | 190 | let last = tampered.pop().unwrap(); |
| 131 | tampered.push(if last == 'A' { 'B' } else { 'A' }); | 191 | tampered.push(if last == 'A' { 'B' } else { 'A' }); |
| 132 | - assert!(open(&key, &tampered).is_err()); | 192 | + assert!(open(&key, purpose::ID_TOKEN, &tampered).is_err()); |
| 133 | - assert!(open(&key, "data").is_err()); | 193 | + assert!(open(&key, purpose::ID_TOKEN, "data").is_err()); |
| 134 | - assert!(open(&key, "v1:!!!").is_err()); | 194 | + assert!(open(&key, purpose::ID_TOKEN, "v1:!!!").is_err()); |
| 135 | - assert!(open(&key, "v1:AAAA").is_err()); | 195 | + assert!(open(&key, purpose::ID_TOKEN, "v1:AAAA").is_err()); |
| 136 | } | 196 | } |
| 137 | 197 | ||
| 138 | #[cfg(unix)] | 198 | #[cfg(unix)] |
crates/iz-web/src/auth.rsmodified+3 -3
| @@ -3,7 +3,7 @@ | |||
| 3 | //! | 3 | //! |
| 4 | //! The browser holds the raw session token in `__Host-iz_session`. The store keeps only its SHA-256 | 4 | //! The browser holds the raw session token in `__Host-iz_session`. The store keeps only its SHA-256 |
| 5 | //! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in | 5 | //! (`iz_core::store::sessions`). The sign-in flight (state, nonce, PKCE verifier, `next`) lives in |
| 6 | -//! `__Host-iz_flight`, sealed with the instance key, so the browser cannot change it. | 6 | +//! `__Host-iz_flight`, sealed with the instance key under the `sign-in-flight` purpose, so the browser cannot change it. |
| 7 | 7 | ||
| 8 | use std::time::Duration; | 8 | use std::time::Duration; |
| 9 | 9 | ||
| @@ -236,12 +236,12 @@ pub fn clear_state_cookie(cx: &Cx) { | |||
| 236 | pub fn seal_sign_in_state(key: &[u8; 32], state: &SignInState) -> iz_core::Result<String> { | 236 | pub fn seal_sign_in_state(key: &[u8; 32], state: &SignInState) -> iz_core::Result<String> { |
| 237 | let json = serde_json::to_vec(state) | 237 | let json = serde_json::to_vec(state) |
| 238 | .map_err(|e| iz_core::Error::Crypto(format!("encoding the sign-in state: {e}")))?; | 238 | .map_err(|e| iz_core::Error::Crypto(format!("encoding the sign-in state: {e}")))?; |
| 239 | - secret::seal(key, &json) | 239 | + secret::seal(key, secret::purpose::SIGN_IN_FLIGHT, &json) |
| 240 | } | 240 | } |
| 241 | 241 | ||
| 242 | /// Opens a sealed sign-in flight. `None` when it is malformed, tampered with, or past its expiry. | 242 | /// Opens a sealed sign-in flight. `None` when it is malformed, tampered with, or past its expiry. |
| 243 | pub fn open_sign_in_state(key: &[u8; 32], sealed: &str) -> Option<SignInState> { | 243 | pub fn open_sign_in_state(key: &[u8; 32], sealed: &str) -> Option<SignInState> { |
| 244 | - let plain = secret::open(key, sealed).ok()?; | 244 | + let plain = secret::open(key, secret::purpose::SIGN_IN_FLIGHT, sealed).ok()?; |
| 245 | let state: SignInState = serde_json::from_slice(&plain).ok()?; | 245 | let state: SignInState = serde_json::from_slice(&plain).ok()?; |
| 246 | (unix_now() < state.expires).then_some(state) | 246 | (unix_now() < state.expires).then_some(state) |
| 247 | } | 247 | } |
crates/iz-web/src/mail/mod.rsmodified+1 -1
| @@ -152,7 +152,7 @@ pub async fn configured(state: &AppState) -> iz_core::Result<Option<Configured>> | |||
| 152 | }; | 152 | }; |
| 153 | let password = match stored.sealed_password { | 153 | let password = match stored.sealed_password { |
| 154 | Some(sealed) => { | 154 | Some(sealed) => { |
| 155 | - let bytes = secret::open(&state.key, &sealed)?; | 155 | + let bytes = secret::open(&state.key, secret::purpose::SMTP_PASSWORD, &sealed)?; |
| 156 | String::from_utf8(bytes) | 156 | String::from_utf8(bytes) |
| 157 | .map_err(|_| iz_core::Error::Crypto("the stored password is not text".into()))? | 157 | .map_err(|_| iz_core::Error::Crypto("the stored password is not text".into()))? |
| 158 | } | 158 | } |
crates/iz-web/src/pages/settings.rsmodified+5 -1
| @@ -273,7 +273,11 @@ async fn save_sender(cx: &Cx, form: Option<Form<SenderSubmit>>) -> Result<Respon | |||
| 273 | None | 273 | None |
| 274 | } else { | 274 | } else { |
| 275 | validate_password(&form.password)?; | 275 | validate_password(&form.password)?; |
| 276 | - Some(secret::seal(&state.key, form.password.as_bytes())?) | 276 | + Some(secret::seal( |
| 277 | + &state.key, | ||
| 278 | + secret::purpose::SMTP_PASSWORD, | ||
| 279 | + form.password.as_bytes(), | ||
| 280 | + )?) | ||
| 277 | }; | 281 | }; |
| 278 | state.store.save_sender(&sender, sealed.as_deref()).await | 282 | state.store.save_sender(&sender, sealed.as_deref()).await |
| 279 | } | 283 | } |
crates/iz-web/src/pages/sign_in.rsmodified+2 -2
| @@ -276,7 +276,7 @@ async fn callback(cx: &Cx) -> Result<impl View> { | |||
| 276 | } | 276 | } |
| 277 | 277 | ||
| 278 | // The ID token is kept, sealed, as the hint of a later logout. | 278 | // The ID token is kept, sealed, as the hint of a later logout. |
| 279 | - let sealed_id_token = secret::seal(&state.key, id_token.as_bytes())?; | 279 | + let sealed_id_token = secret::seal(&state.key, secret::purpose::ID_TOKEN, id_token.as_bytes())?; |
| 280 | let issued = match state | 280 | let issued = match state |
| 281 | .store | 281 | .store |
| 282 | .create_session( | 282 | .create_session( |
| @@ -338,7 +338,7 @@ async fn logout( | |||
| 338 | .session | 338 | .session |
| 339 | .id_token_sealed | 339 | .id_token_sealed |
| 340 | .as_deref() | 340 | .as_deref() |
| 341 | - .and_then(|sealed| secret::open(&state.key, sealed).ok()) | 341 | + .and_then(|sealed| secret::open(&state.key, secret::purpose::ID_TOKEN, sealed).ok()) |
| 342 | .and_then(|plain| String::from_utf8(plain).ok()); | 342 | .and_then(|plain| String::from_utf8(plain).ok()); |
| 343 | let target = match &state.oidc { | 343 | let target = match &state.oidc { |
| 344 | Some(client) => match client | 344 | Some(client) => match client |
crates/iz-web/src/state.rsmodified+1 -1
| @@ -18,7 +18,7 @@ pub struct AppState { | |||
| 18 | pub config: Arc<Config>, | 18 | pub config: Arc<Config>, |
| 19 | /// The database. Reads go to a pooled reader and writes to the single writer. | 19 | /// The database. Reads go to a pooled reader and writes to the single writer. |
| 20 | pub store: Store, | 20 | pub store: Store, |
| 21 | - /// The instance key (`iz.key`). Seals secrets at rest. | 21 | + /// The instance key (`iz.key`). Never used directly: sealing and the manifest MAC each derive a subkey. |
| 22 | pub key: Arc<[u8; 32]>, | 22 | pub key: Arc<[u8; 32]>, |
| 23 | /// The change counters of the live pages. | 23 | /// The change counters of the live pages. |
| 24 | pub live: Arc<LiveHub>, | 24 | pub live: Arc<LiveHub>, |
docs/conventions.mdmodified+4 -2
| @@ -95,8 +95,10 @@ tokens, passwords, cookies, or secrets. | |||
| 95 | - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. | 95 | - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. |
| 96 | - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second | 96 | - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second |
| 97 | factors per user; checked before any lookup; `429` with `Retry-After`. | 97 | factors per user; checked before any lookup; `429` with `Retry-After`. |
| 98 | -- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305 under the instance key, `v1:` + base64(nonce || | 98 | +- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance |
| 99 | - ciphertext). | 99 | + key is never used directly: every use gets its own key, HMAC-SHA256(instance key, "<app> <use> v1"), and |
| 100 | + each seal binds its purpose (a fixed label) as associated data, so a value sealed for one purpose cannot | ||
| 101 | + be opened as another. | ||
| 100 | - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. | 102 | - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. |
| 101 | 103 | ||
| 102 | ## 7. Authorization | 104 | ## 7. Authorization |