[share] Share links and the browser build: custos-share (blob v1, key in the fragment, optional password), custos-wasm (JSON ABI, no wasm-bindgen), docs/SHARE.md, threat model (v0.3.0)

This commit is contained in:
2026-10-31 18:20:51 +01:00
parent 4aac99fb47
commit 5ee1c0da6b
16 changed files with 1153 additions and 5 deletions
+20
View File
@@ -0,0 +1,20 @@
[package]
name = "custos-share"
description = "Custos private share links: the secret encrypted in the sender's app, the key in the link fragment"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
custos-vault = { path = "../custos-vault" }
argon2.workspace = true
chacha20poly1305.workspace = true
hkdf.workspace = true
sha2.workspace = true
rand.workspace = true
zeroize.workspace = true
serde.workspace = true
serde_json.workspace = true
data-encoding.workspace = true
thiserror.workspace = true
+296
View File
@@ -0,0 +1,296 @@
//! Private share links (docs/SHARE.md): a secret encrypted in the sender's app with a random key that
//! travels only in the link's fragment, optionally combined with a password told separately. The share
//! server stores the blob and never sees a key.
use argon2::{Algorithm, Argon2, Params, Version};
use chacha20poly1305::aead::{Aead, KeyInit, Payload as AeadPayload};
use chacha20poly1305::{XChaCha20Poly1305, XNonce};
use custos_vault::{Item, SecretString};
use data_encoding::BASE64URL_NOPAD;
use hkdf::Hkdf;
use rand::Rng;
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::fmt;
use zeroize::{Zeroize, Zeroizing};
pub use custos_vault::Field;
const MAGIC: &[u8; 4] = b"CSH1";
const FLAG_PASSWORD: u8 = 0x01;
const KEY_LEN: usize = 32;
const SALT_LEN: usize = 16;
const NONCE_LEN: usize = 24;
const TAG_LEN: usize = 16;
const KDF_LEN: usize = 12;
const INFO: &[u8] = b"custos-share v1";
/// The largest blob a share may be (the server enforces the same limit).
pub const MAX_BLOB: usize = 64 * 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum ShareError {
#[error("this is not a Custos share")]
Malformed,
#[error("the link is incomplete: the part after # is missing or damaged")]
BadLink,
#[error("this share needs a password")]
PasswordRequired,
#[error("the share's password settings are not supported")]
UnsupportedKdf,
#[error("wrong password, or the link or the share is damaged; nothing was decrypted")]
DecryptFailed,
#[error("the secret is too large to share (at most 64 KB)")]
TooLarge,
}
/// Argon2id parameters for a password share.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ShareKdf {
pub m_cost_kib: u32,
pub t_cost: u32,
pub p_cost: u32,
}
impl ShareKdf {
/// 19 MiB, 2 passes, 1 lane: OWASP's Argon2id minimum, about a second in a phone browser.
pub const DEFAULT: ShareKdf = ShareKdf { m_cost_kib: 19_456, t_cost: 2, p_cost: 1 };
fn check(&self) -> Result<(), ShareError> {
let ok = (8 * 1024..=256 * 1024).contains(&self.m_cost_kib)
&& (1..=16).contains(&self.t_cost)
&& (1..=4).contains(&self.p_cost);
if ok { Ok(()) } else { Err(ShareError::UnsupportedKdf) }
}
}
/// What a share carries: a title and the fields to show, with secret ones hidden until revealed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Payload {
pub title: String,
/// The item type (`web-login`, `wifi`, …), only for the recipient page's label.
pub kind: Option<String>,
pub fields: Vec<Field>,
pub notes: Option<SecretString>,
}
/// Fields never put into a share.
const NEVER_SHARED: [&str; 4] = ["totp", "autotype-match", "autotype-sequence", "domi-ref"];
impl Payload {
/// The item's non-empty fields and notes, without its TOTP seed (that would hand over the second
/// factor too) and its auto-type settings.
pub fn from_item(item: &Item) -> Payload {
let kind = serde_json::to_value(item.kind).ok().and_then(|v| v.as_str().map(str::to_owned));
Payload {
title: item.title.clone(),
kind,
fields: item
.fields
.iter()
.filter(|f| !f.value.is_empty() && !NEVER_SHARED.contains(&f.name.as_str()))
.cloned()
.collect(),
notes: (!item.notes.is_empty()).then(|| item.notes.clone()),
}
}
}
#[derive(Serialize)]
struct WireOut<'a> {
v: u32,
title: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
kind: Option<&'a str>,
fields: &'a [Field],
#[serde(skip_serializing_if = "Option::is_none")]
notes: Option<&'a SecretString>,
}
#[derive(Deserialize)]
struct WireIn {
v: u32,
title: String,
#[serde(default)]
kind: Option<String>,
#[serde(default)]
fields: Vec<Field>,
#[serde(default)]
notes: Option<SecretString>,
}
/// A sealed share: the blob to upload and the link fragment (`k=…` or `k=…&p=1`) to put after `#`.
pub struct Sealed {
pub blob: Vec<u8>,
pub fragment: String,
}
impl Sealed {
pub fn needs_password(&self) -> bool {
fragment_needs_password(&self.fragment)
}
/// `https://host/s/<id>#<fragment>`.
pub fn link(&self, base_url: &str, id: &str) -> String {
format!("{}/s/{id}#{}", base_url.trim_end_matches('/'), self.fragment)
}
}
impl fmt::Debug for Sealed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Sealed").field("blob_len", &self.blob.len()).field("fragment", &"[redacted]").finish()
}
}
impl Drop for Sealed {
fn drop(&mut self) {
self.fragment.zeroize();
}
}
/// Whether a link fragment says the recipient needs a password (only a hint for the page; the blob decides).
pub fn fragment_needs_password(fragment: &str) -> bool {
fragment.trim_start_matches('#').split('&').any(|p| p == "p=1")
}
fn rng() -> UnwrapErr<SysRng> {
UnwrapErr(SysRng)
}
fn link_key(fragment: &str) -> Result<Zeroizing<[u8; KEY_LEN]>, ShareError> {
let k =
fragment.trim_start_matches('#').split('&').find_map(|p| p.strip_prefix("k=")).ok_or(ShareError::BadLink)?;
let bytes = Zeroizing::new(BASE64URL_NOPAD.decode(k.as_bytes()).map_err(|_| ShareError::BadLink)?);
let mut key = Zeroizing::new([0u8; KEY_LEN]);
if bytes.len() != KEY_LEN {
return Err(ShareError::BadLink);
}
key.copy_from_slice(&bytes);
Ok(key)
}
fn message_key(
link: &[u8; KEY_LEN],
password: Option<(&SecretString, ShareKdf, &[u8])>,
) -> Result<Zeroizing<[u8; KEY_LEN]>, ShareError> {
let Some((pw, kdf, salt)) = password else {
return Ok(Zeroizing::new(*link));
};
kdf.check()?;
let params =
Params::new(kdf.m_cost_kib, kdf.t_cost, kdf.p_cost, Some(KEY_LEN)).map_err(|_| ShareError::UnsupportedKdf)?;
let mut ikm = Zeroizing::new([0u8; 2 * KEY_LEN]);
ikm[..KEY_LEN].copy_from_slice(link);
Argon2::new(Algorithm::Argon2id, Version::V0x13, params)
.hash_password_into(pw.expose().as_bytes(), salt, &mut ikm[KEY_LEN..])
.map_err(|_| ShareError::UnsupportedKdf)?;
let mut key = Zeroizing::new([0u8; KEY_LEN]);
Hkdf::<Sha256>::new(Some(salt), ikm.as_ref()).expand(INFO, key.as_mut()).map_err(|_| ShareError::UnsupportedKdf)?;
Ok(key)
}
fn cipher(key: &[u8; KEY_LEN]) -> XChaCha20Poly1305 {
XChaCha20Poly1305::new_from_slice(key).expect("32-byte key")
}
/// Seals `payload` with a fresh link key and, if given, a password (default KDF).
pub fn seal(payload: &Payload, password: Option<&SecretString>) -> Result<Sealed, ShareError> {
seal_with_kdf(payload, password, ShareKdf::DEFAULT)
}
pub fn seal_with_kdf(payload: &Payload, password: Option<&SecretString>, kdf: ShareKdf) -> Result<Sealed, ShareError> {
let wire = WireOut {
v: 1,
title: &payload.title,
kind: payload.kind.as_deref(),
fields: &payload.fields,
notes: payload.notes.as_ref(),
};
let plaintext = Zeroizing::new(serde_json::to_vec(&wire).map_err(|_| ShareError::Malformed)?);
let overhead = 5 + KDF_LEN + SALT_LEN + NONCE_LEN + TAG_LEN;
if plaintext.len() + overhead > MAX_BLOB {
return Err(ShareError::TooLarge);
}
let mut link = Zeroizing::new([0u8; KEY_LEN]);
rng().fill_bytes(link.as_mut());
let mut blob = Vec::with_capacity(plaintext.len() + overhead);
blob.extend_from_slice(MAGIC);
let mut salt = [0u8; SALT_LEN];
if password.is_some() {
kdf.check()?;
rng().fill_bytes(&mut salt);
blob.push(FLAG_PASSWORD);
for v in [kdf.m_cost_kib, kdf.t_cost, kdf.p_cost] {
blob.extend_from_slice(&v.to_le_bytes());
}
blob.extend_from_slice(&salt);
} else {
blob.push(0);
}
let mut nonce = [0u8; NONCE_LEN];
rng().fill_bytes(&mut nonce);
blob.extend_from_slice(&nonce);
let key = message_key(&link, password.map(|p| (p, kdf, &salt[..])))?;
let ct = cipher(&key)
.encrypt(
&XNonce::try_from(&nonce[..]).map_err(|_| ShareError::Malformed)?,
AeadPayload { msg: &plaintext, aad: &blob },
)
.map_err(|_| ShareError::Malformed)?;
blob.extend_from_slice(&ct);
let mut fragment = format!("k={}", BASE64URL_NOPAD.encode(link.as_ref()));
if password.is_some() {
fragment.push_str("&p=1");
}
Ok(Sealed { blob, fragment })
}
/// Opens a blob with the link fragment (with or without its leading `#`) and the password, if the
/// share has one. Any change to the blob, a wrong key or a wrong password gives `DecryptFailed`.
pub fn open(blob: &[u8], fragment: &str, password: Option<&SecretString>) -> Result<Payload, ShareError> {
if blob.len() > MAX_BLOB || blob.len() < 5 || &blob[..4] != MAGIC || blob[4] & !FLAG_PASSWORD != 0 {
return Err(ShareError::Malformed);
}
let has_password = blob[4] & FLAG_PASSWORD != 0;
let mut at = 5;
let mut kdf = ShareKdf::DEFAULT;
let mut salt: &[u8] = &[];
if has_password {
if blob.len() < at + KDF_LEN + SALT_LEN {
return Err(ShareError::Malformed);
}
let u = |i: usize| u32::from_le_bytes(blob[at + i..at + i + 4].try_into().unwrap());
kdf = ShareKdf { m_cost_kib: u(0), t_cost: u(4), p_cost: u(8) };
at += KDF_LEN;
salt = &blob[at..at + SALT_LEN];
at += SALT_LEN;
}
if blob.len() < at + NONCE_LEN + TAG_LEN {
return Err(ShareError::Malformed);
}
let (header, ct) = blob.split_at(at + NONCE_LEN);
let nonce = &header[at..];
let link = link_key(fragment)?;
let pw = match (has_password, password) {
(true, None) => return Err(ShareError::PasswordRequired),
(true, Some(p)) => Some((p, kdf, salt)),
(false, _) => None,
};
let key = message_key(&link, pw)?;
let plaintext = Zeroizing::new(
cipher(&key)
.decrypt(&XNonce::try_from(nonce).map_err(|_| ShareError::Malformed)?, AeadPayload { msg: ct, aad: header })
.map_err(|_| ShareError::DecryptFailed)?,
);
let w: WireIn = serde_json::from_slice(&plaintext).map_err(|_| ShareError::Malformed)?;
if w.v != 1 {
return Err(ShareError::Malformed);
}
Ok(Payload { title: w.title, kind: w.kind, fields: w.fields, notes: w.notes })
}
+163
View File
@@ -0,0 +1,163 @@
//! The mandatory share tests (Day 2, tests 5 and 6) and the format checks from docs/SHARE.md.
use custos_share::{Field, Payload, ShareError, ShareKdf, open, seal, seal_with_kdf};
use custos_vault::{Item, ItemType, SecretString};
/// Fast parameters for tests; the format and the code path are the same as the default's.
const TEST_KDF: ShareKdf = ShareKdf { m_cost_kib: 8 * 1024, t_cost: 1, p_cost: 1 };
fn payload() -> Payload {
Payload {
title: "Router".into(),
kind: Some("wifi".into()),
fields: vec![Field::text("ssid", "Home"), Field::secret("password", "correct-horse-ž!")],
notes: None,
}
}
fn pw(s: &str) -> SecretString {
SecretString::from(s)
}
#[test]
fn round_trip_without_password() {
let s = seal(&payload(), None).unwrap();
assert!(s.fragment.starts_with("k=") && s.fragment.len() == 45, "{}", s.fragment);
assert!(!s.needs_password());
let got = open(&s.blob, &s.fragment, None).unwrap();
assert_eq!(got, payload());
}
#[test]
fn tamper_any_byte_or_wrong_key_fails_with_a_clear_error() {
let s = seal(&payload(), None).unwrap();
for i in 0..s.blob.len() {
let mut bad = s.blob.clone();
bad[i] ^= 0x01;
let e = open(&bad, &s.fragment, None).unwrap_err();
// Flipping the password flag on asks for a password; everything else fails to decrypt or parse.
assert!(
matches!(e, ShareError::DecryptFailed | ShareError::Malformed | ShareError::PasswordRequired),
"byte {i}: {e:?}"
);
}
// A different, well-formed key.
let other = seal(&payload(), None).unwrap();
assert_eq!(open(&s.blob, &other.fragment, None).unwrap_err(), ShareError::DecryptFailed);
// Truncated or extended.
assert!(open(&s.blob[..s.blob.len() - 1], &s.fragment, None).is_err());
let mut longer = s.blob.clone();
longer.push(0);
assert_eq!(open(&longer, &s.fragment, None).unwrap_err(), ShareError::DecryptFailed);
// The message is plain and never contains the secret.
let msg = ShareError::DecryptFailed.to_string();
assert!(msg.contains("damaged") && !msg.contains("correct-horse"), "{msg}");
}
#[test]
fn password_share_wrong_password_fails_right_one_works() {
let s = seal_with_kdf(&payload(), Some(&pw("tell-them-by-phone")), TEST_KDF).unwrap();
assert!(s.fragment.ends_with("&p=1") && s.needs_password());
assert_eq!(open(&s.blob, &s.fragment, None).unwrap_err(), ShareError::PasswordRequired);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("tell-them-by-phone!"))).unwrap_err(), ShareError::DecryptFailed);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw(""))).unwrap_err(), ShareError::DecryptFailed);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("tell-them-by-phone"))).unwrap(), payload());
// The link alone is not enough even with the hint removed: the blob decides.
let bare = s.fragment.trim_end_matches("&p=1");
assert_eq!(open(&s.blob, bare, None).unwrap_err(), ShareError::PasswordRequired);
// The password alone is not enough: a different link key with the right password fails.
let other = seal(&payload(), None).unwrap();
let wrong_key = format!("{}&p=1", other.fragment);
assert_eq!(open(&s.blob, &wrong_key, Some(&pw("tell-them-by-phone"))).unwrap_err(), ShareError::DecryptFailed);
}
#[test]
fn default_kdf_is_the_documented_one_and_works() {
assert_eq!(ShareKdf::DEFAULT, ShareKdf { m_cost_kib: 19_456, t_cost: 2, p_cost: 1 });
let s = seal(&payload(), Some(&pw("pw"))).unwrap();
assert_eq!(&s.blob[5..17], [0x00, 0x4c, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0]);
assert_eq!(open(&s.blob, &s.fragment, Some(&pw("pw"))).unwrap(), payload());
}
#[test]
fn layout_matches_docs() {
let s = seal(&payload(), None).unwrap();
assert_eq!(&s.blob[..4], b"CSH1");
assert_eq!(s.blob[4], 0);
let p = seal_with_kdf(&payload(), Some(&pw("x")), TEST_KDF).unwrap();
assert_eq!(p.blob[4], 1);
// magic + flags + kdf (12) + salt (16) + nonce (24) + tag (16) + plaintext
assert_eq!(p.blob.len(), s.blob.len() + 28);
// Unknown flags are rejected before any crypto.
let mut bad = s.blob.clone();
bad[4] = 0x02;
assert_eq!(open(&bad, &s.fragment, None).unwrap_err(), ShareError::Malformed);
}
#[test]
fn kdf_limits_are_checked_before_argon2() {
let s = seal_with_kdf(&payload(), Some(&pw("x")), TEST_KDF).unwrap();
for (offset, value) in [(5usize, 300 * 1024u32), (5, 1024), (9, 17), (9, 0), (13, 5), (13, 0)] {
let mut bad = s.blob.clone();
bad[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
assert_eq!(
open(&bad, &s.fragment, Some(&pw("x"))).unwrap_err(),
ShareError::UnsupportedKdf,
"{offset}={value}"
);
}
}
#[test]
fn bad_links_are_rejected() {
let s = seal(&payload(), None).unwrap();
for frag in
["", "k=", "k=abc", "x=1", &s.fragment[..44], &format!("{}A", s.fragment), &s.fragment.replace('k', "K")]
{
assert_eq!(open(&s.blob, frag, None).unwrap_err(), ShareError::BadLink, "{frag:?}");
}
// A leading '#' (location.hash) is accepted.
assert!(open(&s.blob, &format!("#{}", s.fragment), None).is_ok());
}
#[test]
fn size_limit() {
let big = Payload { notes: Some(SecretString::new("x".repeat(70_000))), ..payload() };
assert_eq!(seal(&big, None).unwrap_err(), ShareError::TooLarge);
let mut blob = seal(&payload(), None).unwrap().blob.clone();
blob.resize(64 * 1024 + 1, 0);
assert_eq!(open(&blob, "k=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", None).unwrap_err(), ShareError::Malformed);
}
#[test]
fn every_link_key_and_nonce_is_fresh() {
let a = seal(&payload(), None).unwrap();
let b = seal(&payload(), None).unwrap();
assert_ne!(a.fragment, b.fragment);
assert_ne!(a.blob[5..29], b.blob[5..29]);
}
#[test]
fn payload_from_item_leaves_out_empty_fields_totp_and_autotype() {
let mut item = Item::new(ItemType::WebLogin, "GitHub", 0);
item.set("username", "mark", 0);
item.set("password", "hunter2", 0);
item.set("totp", "JBSWY3DPEHPK3PXP", 0);
item.set("autotype-match", "exe:firefox.exe", 0);
item.notes = "recovery codes in the safe".into();
let p = Payload::from_item(&item);
assert_eq!(p.title, "GitHub");
assert_eq!(p.kind.as_deref(), Some("web-login"));
let names: Vec<_> = p.fields.iter().map(|f| f.name.as_str()).collect();
assert_eq!(names, ["username", "password"]);
assert!(p.fields[1].secret && !p.fields[0].secret);
assert_eq!(p.notes.as_ref().map(|n| n.expose()), Some("recovery codes in the safe"));
}
#[test]
fn secrets_are_redacted_in_debug() {
let s = seal(&payload(), Some(&pw("pw"))).unwrap();
let out = format!("{:?} {:?}", s, payload());
assert!(!out.contains("correct-horse") && !out.contains(&s.fragment[2..]), "{out}");
assert!(out.contains("[redacted]"), "{out}");
}