forge
Explore
Log in

Don't you dare go Hollow

Sealing and link unlock proofs under derived keys with the purpose bound as associated data

Browse files at this commit

57f59ff1f13b4e1a0eee4ffe3caa847a17a257dcAhmet Kaan GümüşParent: 68aaef6
  • fix
    • sealing and link unlock proofs under derived keys with the purpose bound as associated data
Show full message
🔒 fix: sealing and link unlock proofs under derived keys with the purpose bound as associated data
crates/in-core/src/secret.rsmodified+81 -24
@@ -1,10 +1,14 @@
1 //! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. A sealed value is safe to1 //! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. A sealed value is safe to
2 //! store in the database; the key lives in a file readable only by the service user.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 use std::path::Path;8 use std::path::Path;
5 9
6 use base64::prelude::{BASE64_STANDARD, Engine as _};10 use base64::prelude::{BASE64_STANDARD, Engine as _};
7-use chacha20poly1305::aead::Aead;11+use chacha20poly1305::aead::{Aead, Payload};
8 use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};12 use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
9 use hmac::{Hmac, Mac};13 use hmac::{Hmac, Mac};
10 use sha2::Sha256;14 use sha2::Sha256;
@@ -15,6 +19,21 @@ use crate::error::{Error, Result};
15 const PREFIX: &str = "v1:";19 const PREFIX: &str = "v1:";
16 /// XChaCha20 nonce length. Long enough that a random nonce per seal never repeats in practice.20 /// XChaCha20 nonce length. Long enough that a random nonce per seal never repeats in practice.
17 const NONCE_LEN: usize = 24;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 /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with38 /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with
20 /// mode 0600 and `O_EXCL`, so an existing key is never overwritten. An existing key with group or39 /// 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 fresh105+/// The cipher keyed with the seal subkey of the instance key `key`.
87-/// random nonce each time. The caller must not store the plaintext when this fails.106+fn seal_cipher(key: &[u8; 32]) -> XChaCha20Poly1305 {
88-pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {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 let mut nonce = [0u8; NONCE_LEN];115 let mut nonce = [0u8; NONCE_LEN];
90 rand::fill(&mut nonce);116 rand::fill(&mut nonce);
91- let cipher = XChaCha20Poly1305::new(key.into());117+ let ciphertext = seal_cipher(key)
92- let ciphertext = cipher118+ .encrypt(
93- .encrypt(&XNonce::from(nonce), plaintext)119+ &XNonce::from(nonce),
120+ Payload {
121+ msg: plaintext,
122+ aad: purpose.as_bytes(),
123+ },
124+ )
94 .map_err(|_| Error::Crypto("sealing failed".into()))?;125 .map_err(|_| Error::Crypto("sealing failed".into()))?;
95 let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len());126 let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len());
96 blob.extend_from_slice(&nonce);127 blob.extend_from_slice(&nonce);
@@ -98,12 +129,13 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {
98 Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob)))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 key132+/// The proof a share-link visitor holds after the right password: an HMAC-SHA256 under the unlock subkey of
102-/// over the link id and the stored password hash, in lower-case hex. Changing the password or reminting133+/// the instance key over the link id and the stored password hash, in lower-case hex. Changing the password
103-/// the link changes one of those inputs, so every old proof stops working. It is a cookie value, so the134+/// or reminting the link changes one of those inputs, so every old proof stops working. It is a cookie value,
104-/// key never leaves the server and the password itself is never stored in a cookie.135+/// so the key never leaves the server and the password itself is never stored in a cookie.
105 pub fn unlock_proof(key: &[u8; 32], link_id: &str, password_hash: &str) -> String {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 .expect("HMAC accepts a key of any length");139 .expect("HMAC accepts a key of any length");
108 mac.update(b"link-unlock:");140 mac.update(b"link-unlock:");
109 mac.update(link_id.as_bytes());141 mac.update(link_id.as_bytes());
@@ -123,8 +155,9 @@ pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] {
123 subkey155 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.158+/// Opens a value produced by [`seal`] with the same `purpose`. A wrong key or purpose, a changed byte or a
127-pub fn open(key: &[u8; 32], sealed: &str) -> Result<Vec<u8>> {159+/// malformed value is an error.
160+pub fn open(key: &[u8; 32], purpose: &str, sealed: &str) -> Result<Vec<u8>> {
128 let encoded = sealed161 let encoded = sealed
129 .strip_prefix(PREFIX)162 .strip_prefix(PREFIX)
130 .ok_or_else(|| Error::Crypto("sealed value has no v1 prefix".into()))?;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 let (nonce, ciphertext) = blob.split_at(NONCE_LEN);170 let (nonce, ciphertext) = blob.split_at(NONCE_LEN);
138 let nonce = <[u8; NONCE_LEN]>::try_from(nonce)171 let nonce = <[u8; NONCE_LEN]>::try_from(nonce)
139 .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?;172 .map_err(|_| Error::Crypto("sealed value has a bad nonce".into()))?;
140- let cipher = XChaCha20Poly1305::new(key.into());173+ seal_cipher(key)
141- cipher174+ .decrypt(
142- .decrypt(&XNonce::from(nonce), ciphertext)175+ &XNonce::from(nonce),
176+ Payload {
177+ msg: ciphertext,
178+ aad: purpose.as_bytes(),
179+ },
180+ )
143 .map_err(|_| Error::Crypto("sealed value failed authentication".into()))181 .map_err(|_| Error::Crypto("sealed value failed authentication".into()))
144 }182 }
145 183
@@ -150,18 +188,37 @@ mod tests {
150 #[test]188 #[test]
151 fn seal_and_open_round_trip_and_reject_wrong_key_or_tampering() {189 fn seal_and_open_round_trip_and_reject_wrong_key_or_tampering() {
152 let key = [7u8; 32];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 assert!(sealed.starts_with("v1:"));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 // A fresh nonce means the same plaintext never seals to the same text twice.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());198+ assert_ne!(
158-199+ sealed,
159- assert!(open(&[8u8; 32], &sealed).is_err(), "wrong key must fail");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 let mut tampered = sealed.clone();211 let mut tampered = sealed.clone();
161 let last = tampered.pop().unwrap();212 let last = tampered.pop().unwrap();
162 tampered.push(if last == 'A' { 'B' } else { 'A' });213 tampered.push(if last == 'A' { 'B' } else { 'A' });
163- assert!(open(&key, &tampered).is_err(), "tampered value must fail");214+ assert!(
164- assert!(open(&key, "data").is_err(), "missing prefix must fail");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 pub id: String,29 pub id: String,
30 /// Hex SHA-256 of the token. Lookups go through it.30 /// Hex SHA-256 of the token. Lookups go through it.
31 pub token_hash: String,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 pub token_sealed: String,33 pub token_sealed: String,
34 /// Whether the target is a file or a folder.34 /// Whether the target is a file or a folder.
35 pub kind: ItemKind,35 pub kind: ItemKind,
crates/in-core/src/store/sessions.rsmodified+1 -1
@@ -57,7 +57,7 @@ pub struct NewSession {
57 pub ip: Option<String>,57 pub ip: Option<String>,
58 /// User agent, when sent.58 /// User agent, when sent.
59 pub user_agent: Option<String>,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 pub id_token_sealed: Option<String>,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 /// The URL of a link from its sealed token. Empty when the token cannot be opened.66 /// The URL of a link from its sealed token. Empty when the token cannot be opened.
67 pub fn public_url(state: &AppState, token_sealed: &str) -> String {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 .ok()69 .ok()
70 .and_then(|bytes| String::from_utf8(bytes).ok())70 .and_then(|bytes| String::from_utf8(bytes).ok())
71 {71 {
@@ -205,7 +205,11 @@ pub struct LinkForm {
205 /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`.205 /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`.
206 fn new_token(state: &AppState) -> Result<(String, String, String)> {206 fn new_token(state: &AppState) -> Result<(String, String, String)> {
207 let token = generate_token();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 Ok((hash_token(&token), sealed, token))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 .create_link(NewLink {612 .create_link(NewLink {
613 id: new_id(),613 id: new_id(),
614 token_hash: hash_token(&token),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 kind,621 kind,
617 target_id: target.to_owned(),622 target_id: target.to_owned(),
618 owner: "ann".to_owned(),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 state.oidc.clone()99 state.oidc.clone()
100 }100 }
101 101
102-/// Seals `bytes` with the instance key.102+/// Seals `bytes` for `purpose` with the instance key.
103-fn seal(state: &AppState, bytes: &[u8]) -> CoreResult<String> {103+fn seal(state: &AppState, purpose: &str, bytes: &[u8]) -> CoreResult<String> {
104- secret::seal(&state.key, bytes)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.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, sealed: &str) -> Option<Vec<u8>> {108+fn open(state: &AppState, purpose: &str, sealed: &str) -> Option<Vec<u8>> {
109- secret::open(&state.key, sealed).ok()109+ secret::open(&state.key, purpose, sealed).ok()
110 }110 }
111 111
112 /// Reads the flight cookie. An unreadable, malformed or expired flight is `None`.112 /// Reads the flight cookie. An unreadable, malformed or expired flight is `None`.
113 fn read_flight(state: &AppState, sealed: &str) -> Option<Flight> {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 let flight: Flight = serde_json::from_slice(&bytes).ok()?;115 let flight: Flight = serde_json::from_slice(&bytes).ok()?;
116 (flight.expires_at > now_secs()).then_some(flight)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 let bytes = serde_json::to_vec(&flight).map_err(|e| CoreError::Crypto(e.to_string()))?;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 Ok(see_other(url))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 let token = generate_token();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 let user_agent = headers(cx)229 let user_agent = headers(cx)
225 .get(USER_AGENT)230 .get(USER_AGENT)
226 .and_then(|value| value.to_str().ok())231 .and_then(|value| value.to_str().ok())
@@ -262,7 +267,7 @@ async fn logout(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<SeeOther> {
262 let hint = session267 let hint = session
263 .id_token_sealed268 .id_token_sealed
264 .as_deref()269 .as_deref()
265- .and_then(|sealed| open(state, sealed))270+ .and_then(|sealed| open(state, secret::purpose::OIDC_ID_TOKEN, sealed))
266 .and_then(|bytes| String::from_utf8(bytes).ok());271 .and_then(|bytes| String::from_utf8(bytes).ok());
267 let (Some(oidc), Some(hint)) = (client(state), hint) else {272 let (Some(oidc), Some(hint)) = (client(state), hint) else {
268 return Ok(see_other("/"));273 return Ok(see_other("/"));
crates/in-web/src/state.rsmodified+2 -1
@@ -22,7 +22,8 @@ pub struct AppState {
22 pub store: Store,22 pub store: Store,
23 /// The blob store the configuration names: the local blob tree or an S3-compatible bucket.23 /// The blob store the configuration names: the local blob tree or an S3-compatible bucket.
24 pub blobs: Arc<dyn BlobStore>,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 pub key: Arc<[u8; 32]>,27 pub key: Arc<[u8; 32]>,
27 /// The change counters of the live pages.28 /// The change counters of the live pages.
28 pub live: Arc<LiveHub>,29 pub live: Arc<LiveHub>,
docs/architecture.mdmodified+2 -1
@@ -206,7 +206,8 @@ and has no sessions.
206 - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none).206 - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none).
207 - Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and207 - Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and
208 per link and client address: 10 failures / 15 min) and sets a cookie208 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, so209+ `__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 changing the password or remint invalidates old unlocks.211 changing the password or remint invalidates old unlocks.
211 - Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer212 - Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer
212 works" page. A disabled owner's links and grants stop working at once and are not deleted: enabling the owner213 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 - 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 second96 - 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. Authorization104 ## 7. Authorization