// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Share links: stateless tokens minted by control and checked by edge. //! //! A link token is `ish1.` + base64url(payload ‖ mac): //! //! ```text //! payload = version (1) ‖ id (16) ‖ epoch (u32 BE) ‖ expires_at (u64 BE, Unix s) ‖ flags (1) ‖ path prefix //! mac = HMAC-SHA256(key, "ianitor share link v1" 0 host 0 payload [0 HMAC-SHA256(key, "ianitor share password v1" 0 id password)]) //! ``` //! //! - The host is not in the token but in the MAC, so a token for one host fails on another. //! - With a password (flag bit 0), the MAC can only be checked by someone who has both the key //! and the password: the token carries no password hash, so holding a link does not allow //! guessing its password offline. Edge rate-limits guesses. //! - The session cookie edge sets after a successful check is `iss1.` + base64url(payload ‖ //! HMAC(key, "ianitor share session v1" 0 host 0 payload)): a different domain, so a link //! token is never accepted as a cookie and a cookie never as a link (and a cookie for a //! password link proves the password was given). //! - Revocation: every token carries the epoch it was minted in; edge refuses tokens from an //! older epoch ("stop all") and ids on the deny list ("stop this link"). //! //! [`path_within`] decides whether a raw request path lies under a link's prefix. It refuses //! anything an upstream might read differently from a plain byte comparison. use std::collections::BTreeSet; use std::fmt; use base64::Engine as _; use base64::engine::general_purpose::URL_SAFE_NO_PAD; use ring::hmac; /// Name of the credential (`$CREDENTIALS_DIRECTORY/`) holding the share-link key, read by /// both edge and control. pub const KEY_CREDENTIAL: &str = "share-link-key"; /// Shortest key accepted, in bytes. pub const MIN_KEY_LEN: usize = 32; /// Query parameter carrying a link token. Edge only takes values that start with /// [`LINK_PREFIX`]; anything else is left to the upstream. pub const QUERY_PARAM: &str = "share"; /// Start of every link token. pub const LINK_PREFIX: &str = "ish1."; /// Start of every session cookie value. pub const SESSION_PREFIX: &str = "iss1."; /// Session cookie name (`__Secure-`: browsers only accept it with `Secure`). pub const COOKIE_NAME: &str = "__Secure-ianitor-share"; /// Path the password form posts to, on hosts with share links. pub const PASSWORD_PATH: &str = "/.well-known/ianitor/share"; /// Longest path prefix. pub const MAX_PREFIX_LEN: usize = 256; /// Password length limits, in characters. pub const MIN_PASSWORD_CHARS: usize = 8; pub const MAX_PASSWORD_CHARS: usize = 128; const VERSION: u8 = 1; const FLAG_PASSWORD: u8 = 1; const FIXED_LEN: usize = 1 + 16 + 4 + 8 + 1; const MAC_LEN: usize = 32; /// Longest token or cookie accepted before decoding. const MAX_ENCODED_LEN: usize = 1024; /// A link id: 16 random bytes, written as 32 lowercase hex digits. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ShareId(pub [u8; 16]); impl ShareId { pub fn to_hex(&self) -> String { self.0.iter().map(|b| format!("{b:02x}")).collect() } pub fn from_hex(s: &str) -> Option { if s.len() != 32 || !s .bytes() .all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) { return None; } let mut out = [0u8; 16]; for (i, o) in out.iter_mut().enumerate() { *o = u8::from_str_radix(s.get(2 * i..2 * i + 2)?, 16).ok()?; } Some(ShareId(out)) } } impl fmt::Display for ShareId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(&self.to_hex()) } } /// The HMAC key. Never printed. pub struct ShareKey(hmac::Key); impl fmt::Debug for ShareKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("ShareKey()") } } #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ShareError { #[error("the share-link key must be at least {MIN_KEY_LEN} bytes")] KeyTooShort, #[error("the path prefix is not usable: {0}")] Prefix(&'static str), #[error("the password must be {MIN_PASSWORD_CHARS} to {MAX_PASSWORD_CHARS} characters")] Password, } impl ShareKey { pub fn new(bytes: &[u8]) -> Result { if bytes.len() < MIN_KEY_LEN { return Err(ShareError::KeyTooShort); } Ok(ShareKey(hmac::Key::new(hmac::HMAC_SHA256, bytes))) } } /// What a token says. For a token checked with [`verify_link`] or [`verify_session`], all of /// it is proven by the MAC; from [`peek`], none of it is. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Claims { pub id: ShareId, pub epoch: u32, pub expires_at: u64, pub password: bool, pub prefix: String, } /// What to mint. #[derive(Debug, Clone)] pub struct LinkSpec<'a> { pub id: ShareId, pub epoch: u32, pub expires_at: u64, /// Already checked with [`check_prefix`]. pub prefix: &'a str, pub password: Option<&'a str>, } /// Why a token was refused. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Rejection { /// Not a token at all (bad encoding, wrong version, too long). Malformed, /// The MAC does not match: altered, minted for another host, made with another key, or /// (for a password link) the wrong password. Invalid, /// The link needs a password and none was given. PasswordRequired, /// Proven genuine, but past its expiry. Expired { expires_at: u64 }, /// Proven genuine, but stopped (deny list or an older epoch). Revoked, } /// The revocation state edge checks against (from the deny-list file control writes). #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct Revocations { /// Tokens minted in an older epoch are refused ("stop all"). pub epoch: u32, /// Stopped links. pub deny: BTreeSet, } impl Revocations { pub fn is_revoked(&self, c: &Claims) -> bool { c.epoch < self.epoch || self.deny.contains(&c.id) } } fn payload(spec: &LinkSpec<'_>) -> Vec { let mut p = Vec::with_capacity(FIXED_LEN + spec.prefix.len()); p.push(VERSION); p.extend_from_slice(&spec.id.0); p.extend_from_slice(&spec.epoch.to_be_bytes()); p.extend_from_slice(&spec.expires_at.to_be_bytes()); p.push(if spec.password.is_some() { FLAG_PASSWORD } else { 0 }); p.extend_from_slice(spec.prefix.as_bytes()); p } fn password_tag(key: &ShareKey, id: &ShareId, password: &str) -> hmac::Tag { let mut ctx = hmac::Context::with_key(&key.0); ctx.update(b"ianitor share password v1\0"); ctx.update(&id.0); ctx.update(password.as_bytes()); ctx.sign() } fn link_message( key: &ShareKey, host: &str, payload: &[u8], id: &ShareId, password: Option<&str>, ) -> Vec { let mut m = Vec::with_capacity(64 + host.len() + payload.len()); m.extend_from_slice(b"ianitor share link v1\0"); m.extend_from_slice(host.as_bytes()); m.push(0); m.extend_from_slice(payload); if let Some(pw) = password { m.push(0); m.extend_from_slice(password_tag(key, id, pw).as_ref()); } m } fn session_message(host: &str, payload: &[u8]) -> Vec { let mut m = Vec::with_capacity(64 + host.len() + payload.len()); m.extend_from_slice(b"ianitor share session v1\0"); m.extend_from_slice(host.as_bytes()); m.push(0); m.extend_from_slice(payload); m } fn check_password(pw: &str) -> Result<(), ShareError> { let n = pw.chars().count(); if (MIN_PASSWORD_CHARS..=MAX_PASSWORD_CHARS).contains(&n) { Ok(()) } else { Err(ShareError::Password) } } /// Mint a link token for `host` (a validated hostname). pub fn mint(key: &ShareKey, host: &str, spec: &LinkSpec<'_>) -> Result { let prefix = check_prefix(spec.prefix).map_err(ShareError::Prefix)?; if prefix != spec.prefix { return Err(ShareError::Prefix("it is not in its normal form")); } if let Some(pw) = spec.password { check_password(pw)?; } let p = payload(spec); let tag = hmac::sign( &key.0, &link_message(key, host, &p, &spec.id, spec.password), ); let mut raw = p; raw.extend_from_slice(tag.as_ref()); Ok(format!("{LINK_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw))) } /// Split and decode without checking the MAC. Only for showing a password page. fn decode(token: &str, prefix: &str) -> Result<(Claims, Vec, Vec), Rejection> { if token.len() > MAX_ENCODED_LEN { return Err(Rejection::Malformed); } let body = token.strip_prefix(prefix).ok_or(Rejection::Malformed)?; let raw = URL_SAFE_NO_PAD .decode(body) .map_err(|_| Rejection::Malformed)?; if raw.len() < FIXED_LEN + MAC_LEN + 1 { return Err(Rejection::Malformed); } let (p, mac) = raw.split_at(raw.len() - MAC_LEN); if p[0] != VERSION || p[FIXED_LEN - 1] & !FLAG_PASSWORD != 0 { return Err(Rejection::Malformed); } let mut id = [0u8; 16]; id.copy_from_slice(&p[1..17]); let mut e = [0u8; 4]; e.copy_from_slice(&p[17..21]); let mut x = [0u8; 8]; x.copy_from_slice(&p[21..29]); let prefix = std::str::from_utf8(&p[FIXED_LEN..]).map_err(|_| Rejection::Malformed)?; // A token whose prefix is not in normal form was never minted. if check_prefix(prefix).ok().as_deref() != Some(prefix) { return Err(Rejection::Malformed); } Ok(( Claims { id: ShareId(id), epoch: u32::from_be_bytes(e), expires_at: u64::from_be_bytes(x), password: p[FIXED_LEN - 1] & FLAG_PASSWORD != 0, prefix: prefix.to_owned(), }, p.to_vec(), mac.to_vec(), )) } /// What a link token claims, unchecked (for the password page: is a password needed, and /// until when does it claim to work). Never grant anything on this alone. pub fn peek(token: &str) -> Result { decode(token, LINK_PREFIX).map(|(c, _, _)| c) } /// Check a link token for `host`. The order of checks fixes what a visitor learns: a password /// is asked for before anything else is proven; expiry and revocation are reported only for /// tokens proven genuine. pub fn verify_link( key: &ShareKey, host: &str, token: &str, password: Option<&str>, now: u64, revocations: &Revocations, ) -> Result { let (claims, p, mac) = decode(token, LINK_PREFIX)?; let password = match (claims.password, password) { (true, None) => return Err(Rejection::PasswordRequired), (true, Some(pw)) => Some(pw), (false, _) => None, }; let msg = link_message(key, host, &p, &claims.id, password); hmac::verify(&key.0, &msg, &mac).map_err(|_| Rejection::Invalid)?; finish(claims, now, revocations) } fn finish(claims: Claims, now: u64, revocations: &Revocations) -> Result { if now >= claims.expires_at { return Err(Rejection::Expired { expires_at: claims.expires_at, }); } if revocations.is_revoked(&claims) { return Err(Rejection::Revoked); } Ok(claims) } /// The session cookie value for claims proven by [`verify_link`]. pub fn session_value(key: &ShareKey, host: &str, claims: &Claims) -> String { let spec = LinkSpec { id: claims.id, epoch: claims.epoch, expires_at: claims.expires_at, prefix: &claims.prefix, password: claims.password.then_some(""), }; let p = payload(&spec); let tag = hmac::sign(&key.0, &session_message(host, &p)); let mut raw = p; raw.extend_from_slice(tag.as_ref()); format!("{SESSION_PREFIX}{}", URL_SAFE_NO_PAD.encode(raw)) } /// Check a session cookie value for `host`. pub fn verify_session( key: &ShareKey, host: &str, value: &str, now: u64, revocations: &Revocations, ) -> Result { let (claims, p, mac) = decode(value, SESSION_PREFIX)?; hmac::verify(&key.0, &session_message(host, &p), &mac).map_err(|_| Rejection::Invalid)?; finish(claims, now, revocations) } /// Normalise and check a path prefix: starts with `/`, at most [`MAX_PREFIX_LEN`] bytes, only /// unreserved characters and `!$&'()*+,=:@-._~`, no `%`, `;`, backslash, empty segment or dot /// segment. A trailing `/` is dropped (except for `/` itself). pub fn check_prefix(prefix: &str) -> Result { if !prefix.starts_with('/') { return Err("it must start with /"); } if prefix.len() > MAX_PREFIX_LEN { return Err("it is longer than 256 characters"); } let ok = |c: u8| c.is_ascii_alphanumeric() || b"/!$&'()*+,=:@-._~".contains(&c); if !prefix.bytes().all(ok) { return Err("only letters, digits, / and -._~!$&'()*+,=:@ are allowed"); } if prefix.contains("//") { return Err("it has an empty segment (//)"); } let trimmed = if prefix.len() > 1 { prefix.strip_suffix('/').unwrap_or(prefix) } else { prefix }; if trimmed == "/" { return Ok("/".into()); } for seg in trimmed[1..].split('/') { if seg.is_empty() { return Err("it has an empty segment (//)"); } if seg.bytes().all(|c| c == b'.') { return Err("it has a . or .. segment"); } } Ok(trimmed.to_owned()) } /// Is `raw_path` (the request path exactly as sent, still percent-encoded) under `prefix`? /// /// Refused outright, whatever the prefix: anything but visible ASCII, a backslash, an empty /// segment (`//`), a dot segment (`.`, `..`, also with `;params`), and the percent-encoded /// forms of `.`, `/`, `\`, `%` and NUL. Other paths match on whole segments, case-sensitively: /// prefix `/a` covers `/a` and `/a/x`, not `/ab` or `/A`. pub fn path_within(prefix: &str, raw_path: &str) -> bool { if !raw_path.starts_with('/') || !raw_path.bytes().all(|c| c.is_ascii_graphic()) || raw_path.contains('\\') { return false; } let lower = raw_path.to_ascii_lowercase(); if ["%2e", "%2f", "%5c", "%25", "%00"] .iter() .any(|bad| lower.contains(bad)) { return false; } // An empty segment anywhere but at the end (a trailing slash) is `//`. if raw_path.contains("//") { return false; } for seg in raw_path[1..].split('/') { // `..;x` is `..` to Tomcat and friends. let name = seg.split(';').next().unwrap_or(seg); if !name.is_empty() && name.bytes().all(|c| c == b'.') { return false; } } if prefix == "/" { return true; } match raw_path.strip_prefix(prefix) { Some(rest) => rest.is_empty() || rest.starts_with('/'), None => false, } }