Files
ianitor/crates/core/src/share.rs
T

555 lines
19 KiB
Rust

// 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/<name>`) 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<ShareId> {
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(<redacted>)")
}
}
#[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<ShareKey, ShareError> {
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<ShareId>,
}
impl Revocations {
pub fn is_revoked(&self, c: &Claims) -> bool {
c.epoch < self.epoch || self.deny.contains(&c.id)
}
}
fn payload(spec: &LinkSpec<'_>) -> Vec<u8> {
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<u8> {
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<u8> {
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<String, ShareError> {
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<u8>, Vec<u8>), 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<Claims, Rejection> {
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<Claims, Rejection> {
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<Claims, Rejection> {
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<Claims, Rejection> {
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<String, &'static str> {
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())
}
/// Percent-encodings no plain path needs (lowercased before matching): `.`, `/`, `\`, `%`
/// itself (double encoding), NUL, and IIS `%u` escapes.
pub const REFUSED_ENCODINGS: &[&str] = &["%2e", "%2f", "%5c", "%25", "%00", "%u"];
/// ASCII characters a look-alike must not stand for after NFKC normalisation.
/// ASCII characters a non-ASCII character must not turn into under NFKC.
const STRUCTURAL: &[char] = &['/', '\\', ';', '?', '#', '%'];
/// Slash and backslash look-alikes NFKC leaves alone (some upstreams still treat them as
/// separators): division slash, fraction slash, big solidus, big reverse solidus, set minus,
/// reverse solidus operator, box-drawing diagonals.
const SLASH_LOOKALIKES: &[char] = &[
'\u{2215}', '\u{2044}', '\u{29F8}', '\u{29F9}', '\u{2216}', '\u{29F5}', '\u{2571}', '\u{2572}',
];
/// Unicode's Default_Ignorable_Code_Point (DerivedCoreProperties.txt, Unicode 15).
fn default_ignorable(c: char) -> bool {
matches!(
c as u32,
0x00AD
| 0x034F
| 0x061C
| 0x115F..=0x1160
| 0x17B4..=0x17B5
| 0x180B..=0x180F
| 0x200B..=0x200F
| 0x202A..=0x202E
| 0x2060..=0x206F
| 0x3164
| 0xFE00..=0xFE0F
| 0xFEFF
| 0xFFA0
| 0xFFF0..=0xFFF8
| 0x1BCA0..=0x1BCA3
| 0x1D173..=0x1D17A
| 0xE0000..=0xE0FFF
)
}
/// Decode `%xx` escapes once. `None` for a broken escape.
fn percent_decode(raw: &str) -> Option<Vec<u8>> {
let b = raw.as_bytes();
let mut out = Vec::with_capacity(b.len());
let mut i = 0;
while i < b.len() {
if b[i] == b'%' {
let hex = raw.get(i + 1..i + 3)?;
// from_str_radix would also take "+f".
if !hex.bytes().all(|c| c.is_ascii_hexdigit()) {
return None;
}
out.push(u8::from_str_radix(hex, 16).ok()?);
i += 3;
} else {
out.push(b[i]);
i += 1;
}
}
Some(out)
}
/// 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 (`//`);
/// - the encodings in [`REFUSED_ENCODINGS`] and broken `%` escapes;
/// - escapes that do not decode to valid UTF-8 (this refuses every overlong form, such as
/// `%c0%ae`);
/// - any encoded character that NFKC normalisation turns into something containing `/`, `\`,
/// `;`, `?`, `#`, `%` or a control character (fullwidth and small forms), and the slash
/// look-alikes NFKC leaves alone ([`SLASH_LOOKALIKES`]);
/// - a segment that NFKC turns into only dots or nothing, after dropping default-ignorable
/// characters and combining marks and trimming whitespace (two-dot
/// leaders, ellipses, fullwidth dots, look-alike spaces); look-alike dots and spaces inside a
/// name with other characters (`Wait….pdf`, an ideographic space) are fine;
/// - a segment of only dots, also with `;params` (`..;x`, `..%3b`), and any segment that is
/// one or more dots followed by a percent-encoded byte (`..%20`, `..%3f`, `..%23`), since
/// some servers trim or decode that into a dot segment.
///
/// 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 {
use unicode_normalization::UnicodeNormalization;
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 REFUSED_ENCODINGS.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;
}
let Some(decoded) = percent_decode(raw_path) else {
return false;
};
let Ok(decoded) = String::from_utf8(decoded) else {
return false;
};
let looks_structural = decoded.chars().filter(|c| !c.is_ascii()).any(|c| {
SLASH_LOOKALIKES.contains(&c)
|| std::iter::once(c)
.nfkc()
.any(|n| STRUCTURAL.contains(&n) || n.is_control())
});
if looks_structural {
return false;
}
// Dot segments as an upstream that normalises (NFKC) and trims whitespace would see them.
let segments: Vec<&str> = decoded[1..].split('/').collect();
for (i, seg) in segments.iter().enumerate() {
if seg.is_empty() && i + 1 == segments.len() {
continue; // trailing slash
}
if seg.is_ascii() {
continue; // the raw checks below cover ASCII segments
}
// Invisible characters (default-ignorable code points, combining marks) do not count:
// `\u{200B}..` is `..` to a server that drops them.
let n: String = seg.nfkc().collect();
let visible: String = n
.split(';')
.next()
.unwrap_or("")
.chars()
.filter(|c| {
!default_ignorable(*c) && !unicode_normalization::char::is_combining_mark(*c)
})
.collect();
if visible.trim().chars().all(|c| c == '.') {
return false;
}
}
for seg in lower[1..].split('/') {
// `..;x` is `..` to Tomcat and friends; `..%3b` is `..;` to servers that decode
// before splitting.
let seg = seg.replace("%3b", ";");
let name = seg.split(';').next().unwrap_or("");
let after_dots = name.trim_start_matches('.');
if name.starts_with('.') && (after_dots.is_empty() || after_dots.starts_with('%')) {
return false;
}
}
if prefix == "/" {
return true;
}
match raw_path.strip_prefix(prefix) {
Some(rest) => rest.is_empty() || rest.starts_with('/'),
None => false,
}
}