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 @@
11 //! The instance key and XChaCha20-Poly1305 sealing of secrets at rest. A sealed value is safe to
22 //! 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.
37
48 use std::path::Path;
59
610 use base64::prelude::{BASE64_STANDARD, Engine as _};
7-use chacha20poly1305::aead::Aead;
11+use chacha20poly1305::aead::{Aead, Payload};
812 use chacha20poly1305::{KeyInit, XChaCha20Poly1305, XNonce};
913 use hmac::{Hmac, Mac};
1014 use sha2::Sha256;
@@ -15,6 +19,21 @@ use crate::error::{Error, Result};
1519 const PREFIX: &str = "v1:";
1620 /// XChaCha20 nonce length. Long enough that a random nonce per seal never repeats in practice.
1721 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+}
1837
1938 /// Loads the 32-byte instance key at `path`, creating it when missing. A new key is created with
2039 /// 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]> {
83102 })
84103 }
85104
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> {
89115 let mut nonce = [0u8; NONCE_LEN];
90116 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+ )
94125 .map_err(|_| Error::Crypto("sealing failed".into()))?;
95126 let mut blob = Vec::with_capacity(NONCE_LEN + ciphertext.len());
96127 blob.extend_from_slice(&nonce);
@@ -98,12 +129,13 @@ pub fn seal(key: &[u8; 32], plaintext: &[u8]) -> Result<String> {
98129 Ok(format!("{PREFIX}{}", BASE64_STANDARD.encode(blob)))
99130 }
100131
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.
105136 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)
107139 .expect("HMAC accepts a key of any length");
108140 mac.update(b"link-unlock:");
109141 mac.update(link_id.as_bytes());
@@ -123,8 +155,9 @@ pub fn derive_subkey(master: &[u8; 32], label: &[u8]) -> [u8; 32] {
123155 subkey
124156 }
125157
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>> {
128161 let encoded = sealed
129162 .strip_prefix(PREFIX)
130163 .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>> {
137170 let (nonce, ciphertext) = blob.split_at(NONCE_LEN);
138171 let nonce = <[u8; NONCE_LEN]>::try_from(nonce)
139172 .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+ )
143181 .map_err(|_| Error::Crypto("sealed value failed authentication".into()))
144182 }
145183
@@ -150,18 +188,37 @@ mod tests {
150188 #[test]
151189 fn seal_and_open_round_trip_and_reject_wrong_key_or_tampering() {
152190 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();
154192 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+ );
156197 // 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+ );
160211 let mut tampered = sealed.clone();
161212 let last = tampered.pop().unwrap();
162213 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+ );
165222 }
166223 }
167224
crates/in-core/src/store/links.rsmodified+1 -1
@@ -29,7 +29,7 @@ pub struct Link {
2929 pub id: String,
3030 /// Hex SHA-256 of the token. Lookups go through it.
3131 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.
3333 pub token_sealed: String,
3434 /// Whether the target is a file or a folder.
3535 pub kind: ItemKind,
crates/in-core/src/store/sessions.rsmodified+1 -1
@@ -57,7 +57,7 @@ pub struct NewSession {
5757 pub ip: Option<String>,
5858 /// User agent, when sent.
5959 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.
6161 pub id_token_sealed: Option<String>,
6262 }
6363
crates/in-web/src/pages/links.rsmodified+6 -2
@@ -65,7 +65,7 @@ pub struct LinkView {
6565
6666 /// The URL of a link from its sealed token. Empty when the token cannot be opened.
6767 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)
6969 .ok()
7070 .and_then(|bytes| String::from_utf8(bytes).ok())
7171 {
@@ -205,7 +205,11 @@ pub struct LinkForm {
205205 /// Makes a fresh token and its sealed copy: `(token hash, sealed token, token)`.
206206 fn new_token(state: &AppState) -> Result<(String, String, String)> {
207207 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+ )?;
209213 Ok((hash_token(&token), sealed, token))
210214 }
211215
crates/in-web/src/pages/public_share.rsmodified+6 -1
@@ -612,7 +612,12 @@ mod tests {
612612 .create_link(NewLink {
613613 id: new_id(),
614614 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"),
616621 kind,
617622 target_id: target.to_owned(),
618623 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>> {
9999 state.oidc.clone()
100100 }
101101
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)
105105 }
106106
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()
110110 }
111111
112112 /// Reads the flight cookie. An unreadable, malformed or expired flight is `None`.
113113 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)?;
115115 let flight: Flight = serde_json::from_slice(&bytes).ok()?;
116116 (flight.expires_at > now_secs()).then_some(flight)
117117 }
@@ -146,7 +146,12 @@ async fn login(cx: &Cx, query: Option<Form<LoginQuery>>) -> Result<SeeOther> {
146146 }
147147 };
148148 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+ );
150155 Ok(see_other(url))
151156 }
152157
@@ -220,7 +225,7 @@ async fn callback(cx: &Cx, query: Option<Form<CallbackQuery>>) -> Result<SeeOthe
220225 }
221226
222227 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())?;
224229 let user_agent = headers(cx)
225230 .get(USER_AGENT)
226231 .and_then(|value| value.to_str().ok())
@@ -262,7 +267,7 @@ async fn logout(cx: &Cx, Form(form): Form<LogoutForm>) -> Result<SeeOther> {
262267 let hint = session
263268 .id_token_sealed
264269 .as_deref()
265- .and_then(|sealed| open(state, sealed))
270+ .and_then(|sealed| open(state, secret::purpose::OIDC_ID_TOKEN, sealed))
266271 .and_then(|bytes| String::from_utf8(bytes).ok());
267272 let (Some(oidc), Some(hint)) = (client(state), hint) else {
268273 return Ok(see_other("/"));
crates/in-web/src/state.rsmodified+2 -1
@@ -22,7 +22,8 @@ pub struct AppState {
2222 pub store: Store,
2323 /// The blob store the configuration names: the local blob tree or an S3-compatible bucket.
2424 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`).
2627 pub key: Arc<[u8; 32]>,
2728 /// The change counters of the live pages.
2829 pub live: Arc<LiveHub>,
docs/architecture.mdmodified+2 -1
@@ -206,7 +206,8 @@ and has no sessions.
206206 - Options: can download, password (argon2id), expiry (1 hour to 1 year, or none).
207207 - Password gate: POST checks the password (throttled per link: 100 failures / 15 min from all visitors together; and
208208 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
210211 changing the password or remint invalidates old unlocks.
211212 - Dead links (revoked, expired, target trashed or purged, owner disabled) answer one identical "link no longer
212213 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.
9595 - Tokens: 32 random bytes, base64url; stored as hex SHA-256; compared with `subtle`; shown once.
9696 - Throttle (in memory, sliding window, bounded key count): failed logins per account and per IP, failed second
9797 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.
100102 - Client IP: the TCP peer unless it is in `trusted_proxies`; then `X-Forwarded-For` right to left.
101103
102104 ## 7. Authorization