Sealing and link unlock proofs under derived keys with the purpose bound as associated data
Browse files at this commit57f59ff1f13b4e1a0eee4ffe3caa847a17a257dcParent: 68aaef6- fix
- sealing and link unlock proofs under derived keys with the purpose bound as associated data
9 changed files +118 -43
- crates/in-core/src/secret.rs +81 -24
- crates/in-core/src/store/links.rs +1 -1
- crates/in-core/src/store/sessions.rs +1 -1
- crates/in-web/src/pages/links.rs +6 -2
- crates/in-web/src/pages/public_share.rs +6 -1
- crates/in-web/src/pages/sign_in.rs +15 -10
- crates/in-web/src/state.rs +2 -1
- docs/architecture.md +2 -1
- docs/conventions.md +4 -2
crates/in-core/src/secret.rsmodified+81 -24
| @@ -1,10 +1,14 @@ | ||
| 1 | 1 | //! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. A sealed value is safe to |
| 2 | 2 | //! store in the database; the key lives in a file readable only by the service user. |
| 3 | +//! | |
| 4 | +//! The instance key never encrypts or MACs anything directly. Every use derives its own subkey from it | |
| 5 | +//! (see [`derive_subkey`]), and every seal is bound to a [`purpose`] that is checked as associated data, | |
| 6 | +//! so a value sealed for one purpose does not open as another. | |
| 3 | 7 | |
| 4 | 8 | use std::path::Path; |
| 5 | 9 | |
| 6 | 10 | use base64::prelude::{BASE64_STANDARD, Engine as _}; |
| 7 | -use chacha20poly1305::aead::Aead; | |
| 11 | +use chacha20poly1305::aead::{Aead, Payload}; | |
| 8 | 12 | use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce}; |
| 9 | 13 | use hmac::{Hmac, Mac}; |
| 10 | 14 | use sha2::Sha256; |
| @@ -15,6 +19,21 @@ use crate::error::{Error, Result}; | ||
| 15 | 19 | const PREFIX: &str = "v1:"; |
| 16 | 20 | /// XChaCha20 nonce length. Long enough that a random nonce per seal never repeats in practice. |
| 17 | 21 | const NONCE_LEN: usize = 24; |
| 22 | +/// Label of the subkey that seals values. Its key is `derive_subkey(instance key, SEAL_LABEL)`. | |
| 23 | +const SEAL_LABEL: &[u8] = b"in seal v1"; | |
| 24 | +/// Label of the key of the password-unlock proof of a share link (see [`unlock_proof`]). | |
| 25 | +const UNLOCK_LABEL: &[u8] = b"in link unlock v1"; | |
| 26 | + | |
| 27 | +/// What a sealed value is for. It is the associated data of [`seal`] and [`open`], so a value sealed under | |
| 28 | +/// one purpose fails authentication under any other. | |
| 29 | +pub mod purpose { | |
| 30 | + /// The sealed cookie of a sign-in in progress: its state, nonce, PKCE verifier and `next` target. | |
| 31 | + pub const FLIGHT_COOKIE: &str = "flight-cookie"; | |
| 32 | + /// The ID token of a sign-in, kept on the session as the `id_token_hint` of logout. | |
| 33 | + pub const OIDC_ID_TOKEN: &str = "oidc-id-token"; | |
| 34 | + /// The sealed copy of a public share link's token, so the owner can show the URL again. | |
| 35 | + pub const SHARE_LINK_TOKEN: &str = "share-link-token"; | |
| 36 | +} | |
| 18 | 37 | |
| 19 | 38 | /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with |
| 20 | 39 | /// 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]> { | ||
| 83 | 102 | }) |
| 84 | 103 | } |
| 85 | 104 | |
| 86 | -/// Seals `plaintext` under `key`. The output is `"v1:" + base64(nonce || ciphertext)` with a fresh | |
| 87 | -/// random nonce each time. The caller must not store the plaintext when this fails. | |
| 88 | -pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> { | |
| 105 | +/// The cipher keyed with the seal subkey of the instance key `key`. | |
| 106 | +fn seal_cipher(key: &[u8; 32]) -> XChaCha20Poly1305 { | |
| 107 | + let subkey = derive_subkey(key, SEAL_LABEL); | |
| 108 | + XChaCha20Poly1305::new((&subkey).into()) | |
| 109 | +} | |
| 110 | + | |
| 111 | +/// Seals `plaintext` under the seal subkey of `key`, bound to `purpose` as associated data. The output is | |
| 112 | +/// `"v1:" + base64(nonce || ciphertext)` with a fresh random nonce each time. Opening with any other purpose | |
| 113 | +/// fails. The caller must not store the plaintext when this fails. | |
| 114 | +pub fn seal(key: &[u8; 32], purpose: &str, plaintext: &[u8]) -> Result<String> { | |
| 89 | 115 | let mut nonce = [0u8; NONCE_LEN]; |
| 90 | 116 | rand::fill(&mut nonce); |
| 91 | - let cipher = XChaCha20Poly1305::new(key.into()); | |
| 92 | - let ciphertext = cipher | |
| 93 | - .encrypt(&XNonce::from(nonce), plaintext) | |
| 117 | + let ciphertext = seal_cipher(key) | |
| 118 | + .encrypt( | |
| 119 | + &XNonce::from(nonce), | |
| 120 | + Payload { | |
| 121 | + msg: plaintext, | |
| 122 | + aad: purpose.as_bytes(), | |
| 123 | + }, | |
| 124 | + ) | |
| 94 | 125 | .map_err(|_| Error::Crypto("sealing failed".into()))?; |
| 95 | 126 | let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len()); |
| 96 | 127 | blob.extend_from_slice(&nonce); |
| @@ -98,12 +129,13 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> { | ||
| 98 | 129 | Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob))) |
| 99 | 130 | } |
| 100 | 131 | |
| 101 | -/// The proof a share-link visitor holds after the right password: an HMAC-SHA256 under the instance key | |
| 102 | -/// over the link id and the stored password hash, in lower-case hex. Changing the password or reminting | |
| 103 | -/// the link changes one of those inputs, so every old proof stops working. It is a cookie value, so the | |
| 104 | -/// key never leaves the server and the password itself is never stored in a cookie. | |
| 132 | +/// The proof a share-link visitor holds after the right password: an HMAC-SHA256 under the unlock subkey of | |
| 133 | +/// the instance key over the link id and the stored password hash, in lower-case hex. Changing the password | |
| 134 | +/// or reminting the link changes one of those inputs, so every old proof stops working. It is a cookie value, | |
| 135 | +/// so the key never leaves the server and the password itself is never stored in a cookie. | |
| 105 | 136 | pub fn unlock_proof(key: &[u8; 32], link_id: &str, password_hash: &str) -> String { |
| 106 | - let mut mac = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(key) | |
| 137 | + let subkey = derive_subkey(key, UNLOCK_LABEL); | |
| 138 | + let mut mac = <Hmac<Sha256> as hmac::KeyInit>::new_from_slice(&subkey) | |
| 107 | 139 | .expect("HMAC accepts a key of any length"); |
| 108 | 140 | mac.update(b"link-unlock:"); |
| 109 | 141 | mac.update(link_id.as_bytes()); |
| @@ -123,8 +155,9 @@ pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] { | ||
| 123 | 155 | subkey |
| 124 | 156 | } |
| 125 | 157 | |
| 126 | -/// Opens a value produced by [`seal`]. A wrong key, a changed byte or a malformed value is an error. | |
| 127 | -pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> { | |
| 158 | +/// Opens a value produced by [`seal`] with the same `purpose`. A wrong key or purpose, a changed byte or a | |
| 159 | +/// malformed value is an error. | |
| 160 | +pub fn open(key: &[u8; 32], purpose: &str, sealed: &str) -> Result<Vec<u8>> { | |
| 128 | 161 | let encoded = sealed |
| 129 | 162 | .strip_prefix(PREFIX) |
| 130 | 163 | .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<Vec<u8>> { | ||
| 137 | 170 | let (nonce, ciphertext) = blob.split_at(NONCE_LEN); |
| 138 | 171 | let nonce = <[u8; NONCE_LEN]>::try_from(nonce) |
| 139 | 172 | .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?; |
| 140 | - let cipher = XChaCha20Poly1305::new(key.into()); | |
| 141 | - cipher | |
| 142 | - .decrypt(&XNonce::from(nonce), ciphertext) | |
| 173 | + seal_cipher(key) | |
| 174 | + .decrypt( | |
| 175 | + &XNonce::from(nonce), | |
| 176 | + Payload { | |
| 177 | + msg: ciphertext, | |
| 178 | + aad: purpose.as_bytes(), | |
| 179 | + }, | |
| 180 | + ) | |
| 143 | 181 | .map_err(|_| Error::Crypto("sealed value failed authentication".into())) |
| 144 | 182 | } |
| 145 | 183 | |
| @@ -150,18 +188,37 @@ mod tests { | ||
| 150 | 188 | #[test] |
| 151 | 189 | fn seal_and_open_round_trip_and_reject_wrong_key_or_tampering() { |
| 152 | 190 | let key = [7u8; 32]; |
| 153 | - let sealed = seal(&key, b"hello secret").unwrap(); | |
| 191 | + let sealed = seal(&key, purpose::FLIGHT_COOKIE, b"hello secret").unwrap(); | |
| 154 | 192 | assert!(sealed.starts_with("v1:")); |
| 155 | - assert_eq!(open(&key, &sealed).unwrap(), b"hello secret"); | |
| 193 | + assert_eq!( | |
| 194 | + open(&key, purpose::FLIGHT_COOKIE, &sealed).unwrap(), | |
| 195 | + b"hello secret" | |
| 196 | + ); | |
| 156 | 197 | // A fresh nonce means the same plaintext never seals to the same text twice. |
| 157 | - assert_ne!(sealed, seal(&key, b"hello secret").unwrap()); | |
| 158 | - | |
| 159 | - assert!(open(&[8u8; 32], &sealed).is_err(), "wrong key must fail"); | |
| 198 | + assert_ne!( | |
| 199 | + sealed, | |
| 200 | + seal(&key, purpose::FLIGHT_COOKIE, b"hello secret").unwrap() | |
| 201 | + ); | |
| 202 | + | |
| 203 | + assert!( | |
| 204 | + open(&[8u8; 32], purpose::FLIGHT_COOKIE, &sealed).is_err(), | |
| 205 | + "wrong key must fail" | |
| 206 | + ); | |
| 207 | + assert!( | |
| 208 | + open(&key, purpose::SHARE_LINK_TOKEN, &sealed).is_err(), | |
| 209 | + "a value sealed for one purpose must not open as another" | |
| 210 | + ); | |
| 160 | 211 | let mut tampered = sealed.clone(); |
| 161 | 212 | let last = tampered.pop().unwrap(); |
| 162 | 213 | tampered.push(if last == 'A' { 'B' } else { 'A' }); |
| 163 | - assert!(open(&key, &tampered).is_err(), "tampered value must fail"); | |
| 164 | - assert!(open(&key, "data").is_err(), "missing prefix must fail"); | |
| 214 | + assert!( | |
| 215 | + open(&key, purpose::FLIGHT_COOKIE, &tampered).is_err(), | |
| 216 | + "tampered value must fail" | |
| 217 | + ); | |
| 218 | + assert!( | |
| 219 | + open(&key, purpose::FLIGHT_COOKIE, "data").is_err(), | |
| 220 | + "missing prefix must fail" | |
| 221 | + ); | |
| 165 | 222 | } |
| 166 | 223 | } |
| 167 | 224 |
crates/in-core/src/store/links.rsmodified+1 -1
| @@ -29,7 +29,7 @@ pub struct Link { | ||
| 29 | 29 | pub id: String, |
| 30 | 30 | /// Hex SHA-256 of the token. Lookups go through it. |
| 31 | 31 | pub token_hash: String, |
| 32 | - /// The token, sealed under the instance key, so the owner can show the URL again. | |
| 32 | + /// The token, sealed for the share-link token purpose, so the owner can show the URL again. | |
| 33 | 33 | pub token_sealed: String, |
| 34 | 34 | /// Whether the target is a file or a folder. |
| 35 | 35 | pub kind: ItemKind, |
crates/in-core/src/store/sessions.rsmodified+1 -1
| @@ -57,7 +57,7 @@ pub struct NewSession { | ||
| 57 | 57 | pub ip: Option<String>, |
| 58 | 58 | /// User agent, when sent. |
| 59 | 59 | pub user_agent: Option<String>, |
| 60 | - /// The sealed ID token of the sign-in. Sealed by the caller with the instance key. | |
| 60 | + /// The sealed ID token of the sign-in, sealed by the caller for the OIDC ID token purpose. | |
| 61 | 61 | pub id_token_sealed: Option<String>, |
| 62 | 62 | } |
| 63 | 63 |
crates/in-web/src/pages/links.rsmodified+6 -2
| @@ -65,7 +65,7 @@ pub struct LinkView { | ||
| 65 | 65 | |
| 66 | 66 | /// The URL of a link from its sealed token. Empty when the token cannot be opened. |
| 67 | 67 | pub fn public_url(state: &AppState, token_sealed: &str) -> String { |
| 68 | - match secret::open(&state.key, token_sealed) | |
| 68 | + match secret::open(&state.key, secret::purpose::SHARE_LINK_TOKEN, token_sealed) | |
| 69 | 69 | .ok() |
| 70 | 70 | .and_then(|bytes| String::from_utf8(bytes).ok()) |
| 71 | 71 | { |
| @@ -205,7 +205,11 @@ pub struct LinkForm { | ||
| 205 | 205 | /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`. |
| 206 | 206 | fn new_token(state: &AppState) -> Result<(String, String, String)> { |
| 207 | 207 | let token = generate_token(); |
| 208 | - let sealed = secret::seal(&state.key, token.as_bytes())?; | |
| 208 | + let sealed = secret::seal( | |
| 209 | + &state.key, | |
| 210 | + secret::purpose::SHARE_LINK_TOKEN, | |
| 211 | + token.as_bytes(), | |
| 212 | + )?; | |
| 209 | 213 | Ok((hash_token(&token), sealed, token)) |
| 210 | 214 | } |
| 211 | 215 |
crates/in-web/src/pages/public_share.rsmodified+6 -1
| @@ -612,7 +612,12 @@ mod tests { | ||
| 612 | 612 | .create_link(NewLink { |
| 613 | 613 | id: new_id(), |
| 614 | 614 | token_hash: hash_token(&token), |
| 615 | - token_sealed: secret::seal(&state.key, token.as_bytes()).expect("seal"), | |
| 615 | + token_sealed: secret::seal( | |
| 616 | + &state.key, | |
| 617 | + secret::purpose::SHARE_LINK_TOKEN, | |
| 618 | + token.as_bytes(), | |
| 619 | + ) | |
| 620 | + .expect("seal"), | |
| 616 | 621 | kind, |
| 617 | 622 | target_id: target.to_owned(), |
| 618 | 623 | owner: "ann".to_owned(), |
crates/in-web/src/pages/sign_in.rsmodified+15 -10
| @@ -99,19 +99,19 @@ fn client(state: &AppState) -> Option<Arc<OidcClient>> { | ||
| 99 | 99 | state.oidc.clone() |
| 100 | 100 | } |
| 101 | 101 | |
| 102 | -/// Seals `bytes` with the instance key. | |
| 103 | -fn seal(state: &AppState, bytes: &[u8]) -> CoreResult<String> { | |
| 104 | - secret::seal(&state.key, bytes) | |
| 102 | +/// Seals `bytes` for `purpose` with the instance key. | |
| 103 | +fn seal(state: &AppState, purpose: &str, bytes: &[u8]) -> CoreResult<String> { | |
| 104 | + secret::seal(&state.key, purpose, bytes) | |
| 105 | 105 | } |
| 106 | 106 | |
| 107 | -/// Opens a sealed value. Any failure reads as "not there", which the callers treat as a refusal. | |
| 108 | -fn open(state: &AppState, sealed: &str) -> Option<Vec<u8>> { | |
| 109 | - secret::open(&state.key, sealed).ok() | |
| 107 | +/// Opens a value sealed for `purpose`. Any failure reads as "not there", which the callers treat as a refusal. | |
| 108 | +fn open(state: &AppState, purpose: &str, sealed: &str) -> Option<Vec<u8>> { | |
| 109 | + secret::open(&state.key, purpose, sealed).ok() | |
| 110 | 110 | } |
| 111 | 111 | |
| 112 | 112 | /// Reads the flight cookie. An unreadable, malformed or expired flight is `None`. |
| 113 | 113 | fn read_flight(state: &AppState, sealed: &str) -> Option<Flight> { |
| 114 | - let bytes = open(state, sealed)?; | |
| 114 | + let bytes = open(state, secret::purpose::FLIGHT_COOKIE, sealed)?; | |
| 115 | 115 | let flight: Flight = serde_json::from_slice(&bytes).ok()?; |
| 116 | 116 | (flight.expires_at > now_secs()).then_some(flight) |
| 117 | 117 | } |
| @@ -146,7 +146,12 @@ async fn login(cx: &Cx, query: Option<Form<LoginQuery>>) -> Result<SeeOther> { | ||
| 146 | 146 | } |
| 147 | 147 | }; |
| 148 | 148 | let bytes = serde_json::to_vec(&flight).map_err(|e| CoreError::Crypto(e.to_string()))?; |
| 149 | - set_cookie(cx, FLIGHT_COOKIE, seal(state, &bytes)?, FLIGHT_TTL); | |
| 149 | + set_cookie( | |
| 150 | + cx, | |
| 151 | + FLIGHT_COOKIE, | |
| 152 | + seal(state, secret::purpose::FLIGHT_COOKIE, &bytes)?, | |
| 153 | + FLIGHT_TTL, | |
| 154 | + ); | |
| 150 | 155 | Ok(see_other(url)) |
| 151 | 156 | } |
| 152 | 157 | |
| @@ -220,7 +225,7 @@ async fn callback(cx: &Cx, query: Option<Form<CallbackQuery>>) -> Result<SeeOthe | ||
| 220 | 225 | } |
| 221 | 226 | |
| 222 | 227 | let token = generate_token(); |
| 223 | - let id_token_sealed = seal(state, id_token.as_bytes())?; | |
| 228 | + let id_token_sealed = seal(state, secret::purpose::OIDC_ID_TOKEN, id_token.as_bytes())?; | |
| 224 | 229 | let user_agent = headers(cx) |
| 225 | 230 | .get(USER_AGENT) |
| 226 | 231 | .and_then(|value| value.to_str().ok()) |
| @@ -262,7 +267,7 @@ async fn logout(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<SeeOther> { | ||
| 262 | 267 | let hint = session |
| 263 | 268 | .id_token_sealed |
| 264 | 269 | .as_deref() |
| 265 | - .and_then(|sealed| open(state, sealed)) | |
| 270 | + .and_then(|sealed| open(state, secret::purpose::OIDC_ID_TOKEN, sealed)) | |
| 266 | 271 | .and_then(|bytes| String::from_utf8(bytes).ok()); |
| 267 | 272 | let (Some(oidc), Some(hint)) = (client(state), hint) else { |
| 268 | 273 | return Ok(see_other("/")); |
crates/in-web/src/state.rsmodified+2 -1
| @@ -22,7 +22,8 @@ pub struct AppState { | ||
| 22 | 22 | pub store: Store, |
| 23 | 23 | /// The blob store the configuration names: the local blob tree or an S3-compatible bucket. |
| 24 | 24 | pub blobs: Arc<dyn BlobStore>, |
| 25 | - /// The instance key (`in.key`). Seals secrets at rest. | |
| 25 | + /// The instance key (`in.key`). Never used directly: every seal and MAC uses a subkey derived from it (see | |
| 26 | + /// `in_core::secret`). | |
| 26 | 27 | pub key: Arc<[u8; 32]>, |
| 27 | 28 | /// The change counters of the live pages. |
| 28 | 29 | pub live: Arc<LiveHub>, |
docs/architecture.mdmodified+2 -1
| @@ -206,7 +206,8 @@ and has no sessions. | ||
| 206 | 206 | - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none). |
| 207 | 207 | - Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and |
| 208 | 208 | per link and client address: 10 failures / 15 min) and sets a cookie |
| 209 | - `__Host-in_link_<id>` = HMAC-SHA256(instance key, "link-unlock:" || link id || password_hash), 12 h, so | |
| 209 | + `__Host-in_link_<id>` = HMAC-SHA256(unlock subkey, link id || "|" || password_hash), where the unlock subkey is | |
| 210 | + HMAC-SHA256(instance key, "in link unlock v1"), 12 h, so | |
| 210 | 211 | changing the password or remint invalidates old unlocks. |
| 211 | 212 | - Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer |
| 212 | 213 | works" page. A disabled owner's links and grants stop working at once and are not deleted: enabling the owner |
docs/conventions.mdmodified+4 -2
| @@ -95,8 +95,10 @@ tokens, passwords, cookies, or secrets. | ||
| 95 | 95 | - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once. |
| 96 | 96 | - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second |
| 97 | 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 || | |
| 99 | - ciphertext). | |
| 98 | +- Secrets at rest: `seal`/`open` with XChaCha20-Poly1305, `v1:` + base64(nonce || ciphertext). The instance | |
| 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 | 102 | - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left. |
| 101 | 103 | |
| 102 | 104 | ## 7. Authorization |