Files
CustosPublic/crates/custos-share/src/lib.rs
T

297 lines
10 KiB
Rust

//! 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 })
}