Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5ee1c0da6b |
@@ -0,0 +1,4 @@
|
||||
# The browser build takes its randomness from crypto.getRandomValues through getrandom's custom
|
||||
# backend (crates/custos-wasm/src/lib.rs, `random_fill`): no wasm-bindgen.
|
||||
[target.wasm32-unknown-unknown]
|
||||
rustflags = ['--cfg', 'getrandom_backend="custom"']
|
||||
@@ -10,7 +10,10 @@ crates/custos-vault file format, Argon2id + XChaCha20-Poly1305, atomic save, i
|
||||
crates/custos-gen memorable password, nickname, random, PIN, strict-site generators + wordlists
|
||||
crates/custos-totp TOTP / HOTP (RFC 6238 / 4226 vectors are tests), otpauth:// parsing
|
||||
crates/custos-qr QR payload strings (Wi-Fi escaping); rendering is the app's job
|
||||
crates/custos-share private share links: XChaCha20-Poly1305 blob, key in the URL fragment, optional password
|
||||
crates/custos-wasm the browser build (web vault + share page): JSON `call` ABI, no wasm-bindgen; js/custos.mjs
|
||||
docs/FORMAT.md the vault file format (versioned; change it before the code)
|
||||
docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
|
||||
docs/THREAT_MODEL.md what is and is not protected
|
||||
```
|
||||
|
||||
@@ -18,7 +21,12 @@ docs/THREAT_MODEL.md what is and is not protected
|
||||
```
|
||||
cargo test --workspace # all mandatory tests
|
||||
cargo test --workspace --release # same, faster Argon2
|
||||
# the browser build, with the server's toolchain (WSL + Nix here; nixpkgs rev as in the Custos flake):
|
||||
nix shell nixpkgs#cargo nixpkgs#rustc nixpkgs#stdenv.cc nixpkgs#lld -c \n cargo build --release --target wasm32-unknown-unknown -p custos-wasm
|
||||
node crates/custos-wasm/js/test.mjs <custos_wasm.wasm> [<vault> <password>] # the JS loader against it
|
||||
```
|
||||
- `.cargo/config.toml` selects getrandom's custom backend for wasm32: `random_fill` → `crypto.getRandomValues`.
|
||||
- WSL: run commands with `wsl -d Debian --exec bash -lc '…'`; plain `wsl -- …` expands `$VARS` too early.
|
||||
On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: is off limits).
|
||||
|
||||
## Rules
|
||||
|
||||
Generated
+43
-4
@@ -148,7 +148,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-gen"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"rand",
|
||||
@@ -159,11 +159,28 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-qr"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
|
||||
[[package]]
|
||||
name = "custos-share"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
"hkdf",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"thiserror",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-totp"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -176,7 +193,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-vault"
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
@@ -190,6 +207,22 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-wasm"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"custos-qr",
|
||||
"custos-share",
|
||||
"custos-totp",
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
"getrandom",
|
||||
"qrcode",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "data-encoding"
|
||||
version = "2.11.1"
|
||||
@@ -346,6 +379,12 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "qrcode"
|
||||
version = "0.14.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec"
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.47"
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.2.1"
|
||||
version = "0.3.0"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||
|
||||
@@ -9,6 +9,8 @@ password and secret manager: everything that touches plaintext or keys.
|
||||
| `custos-gen` | Memorable passwords (`Word7-Other3-Third9-Fourth2`), nicknames (`GitHub.Lantern.47`), random, PIN, strict-site |
|
||||
| `custos-totp` | TOTP (RFC 6238) and HOTP (RFC 4226), `otpauth://` URIs |
|
||||
| `custos-qr` | QR payloads: Wi-Fi join codes (escaped), plain secrets |
|
||||
| `custos-share` | Private share links: encrypted in the sender's app, key in the link's `#fragment`, optional password ([`docs/SHARE.md`](docs/SHARE.md)) |
|
||||
| `custos-wasm` | The same code compiled to WebAssembly for the web vault and the share page (no wasm-bindgen; `js/custos.mjs` is the whole JS side) |
|
||||
|
||||
Read [`docs/FORMAT.md`](docs/FORMAT.md) for the file format and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md)
|
||||
for what it does and does not protect. Report vulnerabilities as described in [`SECURITY.md`](SECURITY.md).
|
||||
|
||||
@@ -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
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "custos-wasm"
|
||||
description = "Custos in the browser: the web vault's and the share page's crypto, compiled to WebAssembly"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
custos-vault = { path = "../custos-vault" }
|
||||
custos-share = { path = "../custos-share" }
|
||||
custos-totp = { path = "../custos-totp" }
|
||||
custos-qr = { path = "../custos-qr" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
data-encoding.workspace = true
|
||||
zeroize.workspace = true
|
||||
qrcode = { version = "0.14", default-features = false, features = ["svg"] }
|
||||
|
||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||
getrandom = "0.4"
|
||||
@@ -0,0 +1,46 @@
|
||||
// The whole JavaScript side of custos-wasm (see src/lib.rs, "ABI"): load the module, give it the
|
||||
// browser's CSPRNG, and pass JSON requests in and out. The vault key never leaves WebAssembly memory.
|
||||
|
||||
/** @param {BufferSource | Response | Promise<Response>} source the custos_wasm.wasm bytes or a fetch of them */
|
||||
export async function loadCustos(source) {
|
||||
let memory;
|
||||
const env = {
|
||||
random_fill(ptr, len) {
|
||||
// getRandomValues fills at most 65,536 bytes per call.
|
||||
for (let off = 0; off < len; off += 65536) {
|
||||
crypto.getRandomValues(new Uint8Array(memory.buffer, ptr + off, Math.min(65536, len - off)));
|
||||
}
|
||||
},
|
||||
};
|
||||
const { instance } =
|
||||
source instanceof Response || source instanceof Promise
|
||||
? await WebAssembly.instantiateStreaming(source, { env })
|
||||
: await WebAssembly.instantiate(source, { env });
|
||||
const x = instance.exports;
|
||||
memory = x.memory;
|
||||
const enc = new TextEncoder();
|
||||
const dec = new TextDecoder();
|
||||
|
||||
/** Sends one request; resolves to the parsed response ({ok: true, …} or {ok: false, error}). */
|
||||
function call(request) {
|
||||
const bytes = enc.encode(JSON.stringify(request));
|
||||
const ptr = x.alloc(bytes.length);
|
||||
new Uint8Array(memory.buffer, ptr, bytes.length).set(bytes);
|
||||
bytes.fill(0);
|
||||
const packed = x.call(ptr, bytes.length); // frees and zeroes the request
|
||||
const outPtr = Number(packed >> 32n);
|
||||
const outLen = Number(packed & 0xffffffffn);
|
||||
const out = new Uint8Array(memory.buffer, outPtr, outLen);
|
||||
const text = dec.decode(out);
|
||||
x.dealloc(outPtr, outLen); // zeroes the response in WebAssembly memory
|
||||
return JSON.parse(text);
|
||||
}
|
||||
return { call };
|
||||
}
|
||||
|
||||
/** Base64 of bytes, for the `open` and `share_open` requests. */
|
||||
export function toBase64(bytes) {
|
||||
let s = '';
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
return btoa(s);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// node test.mjs <custos_wasm.wasm> [<vault file> <password>]: the JS loader against the real build.
|
||||
import fs from 'node:fs';
|
||||
import { loadCustos, toBase64 } from './custos.mjs';
|
||||
|
||||
const [wasmPath, vaultPath, password] = process.argv.slice(2);
|
||||
const c = await loadCustos(fs.readFileSync(wasmPath));
|
||||
const assert = (ok, msg) => { if (!ok) { console.error('FAIL', msg); process.exit(1); } };
|
||||
|
||||
const bad = c.call({ op: 'share_open', blob: 'Q1NIMQA=', fragment: 'k=x' });
|
||||
assert(!bad.ok && bad.code === 'Malformed', JSON.stringify(bad));
|
||||
assert(c.call({ op: 'items' }).error === 'The vault is locked.', 'locked');
|
||||
|
||||
if (vaultPath) {
|
||||
const t0 = performance.now();
|
||||
const r = c.call({ op: 'open', vault: toBase64(fs.readFileSync(vaultPath)), password });
|
||||
const ms = Math.round(performance.now() - t0);
|
||||
assert(r.ok, r.error);
|
||||
console.log(`unlocked ${r.items.length} items in ${ms} ms (WebAssembly, default KDF)`);
|
||||
const item = r.items.find((i) => i.hasMainSecret);
|
||||
for (const pw of [null, 'by-phone']) {
|
||||
const t1 = performance.now();
|
||||
const s = c.call({ op: 'share_seal', id: item.id, password: pw });
|
||||
assert(s.ok, s.error);
|
||||
const o = c.call({ op: 'share_open', blob: s.blob, fragment: s.fragment, password: pw });
|
||||
assert(o.ok && o.payload.title === item.title, JSON.stringify(o.error));
|
||||
console.log(`share ${pw ? 'with' : 'without'} password: sealed and opened in ${Math.round(performance.now() - t1)} ms`);
|
||||
}
|
||||
const fresh = new Set(Array.from({ length: 100 }, () => c.call({ op: 'share_seal', id: item.id }).fragment));
|
||||
assert(fresh.size === 100, 'link keys repeat: random_fill is broken');
|
||||
c.call({ op: 'lock' });
|
||||
}
|
||||
console.log('ok');
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Custos in the browser. The web vault and the share recipient page load this crate compiled to
|
||||
//! `wasm32-unknown-unknown`; everything that touches a key or plaintext happens here, in code from this
|
||||
//! public repository. The page's JavaScript only moves JSON in and out.
|
||||
//!
|
||||
//! # ABI (no wasm-bindgen)
|
||||
//! Exports:
|
||||
//! - `memory`
|
||||
//! - `alloc(len) -> ptr` and `dealloc(ptr, len)`; `dealloc` zeroes the bytes before freeing them.
|
||||
//! - `call(ptr, len) -> u64`: takes a JSON request the caller wrote into an `alloc`ed buffer (and frees it,
|
||||
//! zeroed), returns `(response_ptr << 32) | response_len`. The caller reads the JSON response and gives it
|
||||
//! back with `dealloc`.
|
||||
//!
|
||||
//! Import: `env.random_fill(ptr, len)`, which must fill the bytes from `crypto.getRandomValues`
|
||||
//! (getrandom's custom backend; `.cargo/config.toml` selects it for this target).
|
||||
//!
|
||||
//! Requests are `{"op": …, …}`; responses `{"ok": true, …}` or `{"ok": false, "error": "<message>"}`.
|
||||
//! See [`handle`] for the operations. One vault at a time is held here while unlocked; `lock` drops it
|
||||
//! (and with it the key, wiped).
|
||||
|
||||
use custos_share::{Payload, ShareError};
|
||||
use custos_vault::{Item, ItemType, SecretString, Vault};
|
||||
use data_encoding::BASE64;
|
||||
use qrcode::render::svg;
|
||||
use qrcode::{EcLevel, QrCode};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
use std::cell::RefCell;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
thread_local! {
|
||||
static VAULT: RefCell<Option<Vault>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(tag = "op", rename_all = "snake_case", rename_all_fields = "camelCase")]
|
||||
enum Request {
|
||||
/// `vault`: the `.custos` file, base64.
|
||||
Open {
|
||||
vault: String,
|
||||
password: SecretString,
|
||||
},
|
||||
Lock,
|
||||
Items,
|
||||
/// A field's value by name and index among fields of that name, or `name: "notes"`.
|
||||
Reveal {
|
||||
id: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
index: usize,
|
||||
},
|
||||
/// `now`: Unix seconds (WebAssembly has no clock of its own).
|
||||
Totp {
|
||||
id: String,
|
||||
now: u64,
|
||||
},
|
||||
/// A Wi-Fi item gives its join code, anything else its main secret.
|
||||
Qr {
|
||||
id: String,
|
||||
},
|
||||
ShareSeal {
|
||||
id: String,
|
||||
password: Option<SecretString>,
|
||||
},
|
||||
/// `blob`: base64, as the share server returned it.
|
||||
ShareOpen {
|
||||
blob: String,
|
||||
fragment: String,
|
||||
password: Option<SecretString>,
|
||||
},
|
||||
}
|
||||
|
||||
fn err(msg: impl ToString) -> Value {
|
||||
json!({ "ok": false, "error": msg.to_string() })
|
||||
}
|
||||
|
||||
/// The field *Copy* and the QR code use for each type (the desktop app's choice).
|
||||
pub fn primary_secret(kind: ItemType) -> &'static str {
|
||||
match kind {
|
||||
ItemType::WebLogin | ItemType::LocalApp | ItemType::Wifi => "password",
|
||||
ItemType::ApiCredential => "secret",
|
||||
ItemType::Card => "number",
|
||||
ItemType::SecureNote => "notes",
|
||||
}
|
||||
}
|
||||
|
||||
fn primary_user(kind: ItemType) -> Option<&'static str> {
|
||||
match kind {
|
||||
ItemType::WebLogin | ItemType::LocalApp => Some("username"),
|
||||
ItemType::ApiCredential => Some("key-id"),
|
||||
ItemType::Wifi => Some("ssid"),
|
||||
ItemType::Card => Some("cardholder"),
|
||||
ItemType::SecureNote => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn plain<'a>(item: &'a Item, name: &str) -> Option<&'a str> {
|
||||
item.field(name).filter(|f| !f.secret).map(|f| f.value.expose()).filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn value<'a>(item: &'a Item, name: &str, index: usize) -> Option<&'a SecretString> {
|
||||
if name == "notes" {
|
||||
return Some(&item.notes);
|
||||
}
|
||||
item.fields.iter().filter(|f| f.name == name).nth(index).map(|f| &f.value)
|
||||
}
|
||||
|
||||
/// An item for the page: non-secret field values, secret ones only as "has a value".
|
||||
fn view(item: &Item) -> Value {
|
||||
let urls: Vec<&str> =
|
||||
item.fields.iter().filter(|f| f.name == "url" && !f.value.is_empty()).map(|f| f.value.expose()).collect();
|
||||
let subtitle = primary_user(item.kind)
|
||||
.and_then(|n| plain(item, n))
|
||||
.or(plain(item, "service"))
|
||||
.or(plain(item, "target"))
|
||||
.or(urls.first().copied())
|
||||
.unwrap_or("");
|
||||
let mut seen = std::collections::HashMap::<&str, usize>::new();
|
||||
let fields: Vec<Value> = item
|
||||
.fields
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let n = seen.entry(f.name.as_str()).or_default();
|
||||
let index = *n;
|
||||
*n += 1;
|
||||
json!({
|
||||
"name": f.name,
|
||||
"index": index,
|
||||
"secret": f.secret,
|
||||
"hasValue": !f.value.is_empty(),
|
||||
"value": if f.secret { Value::Null } else { Value::from(f.value.expose()) },
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let main = primary_secret(item.kind);
|
||||
json!({
|
||||
"id": item.id,
|
||||
"kind": item.kind,
|
||||
"title": item.title,
|
||||
"subtitle": subtitle,
|
||||
"urls": urls,
|
||||
"tags": item.tags,
|
||||
"fields": fields,
|
||||
"hasNotes": !item.notes.is_empty(),
|
||||
"mainSecret": main,
|
||||
"hasMainSecret": value(item, main, 0).is_some_and(|v| !v.is_empty()),
|
||||
"hasTotp": item.field("totp").is_some_and(|f| !f.value.is_empty()),
|
||||
"modified": item.modified,
|
||||
})
|
||||
}
|
||||
|
||||
fn items(v: &Vault) -> Value {
|
||||
json!({ "ok": true, "items": v.items().iter().map(view).collect::<Vec<_>>() })
|
||||
}
|
||||
|
||||
fn with_item(id: &str, f: impl FnOnce(&Item) -> Value) -> Value {
|
||||
VAULT.with_borrow(|v| match v {
|
||||
None => err("The vault is locked."),
|
||||
Some(v) => match v.item(id) {
|
||||
None => err("Item not found."),
|
||||
Some(item) => f(item),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn qr_svg(payload: &str) -> Result<String, String> {
|
||||
let code = QrCode::with_error_correction_level(payload.as_bytes(), EcLevel::M).map_err(|e| e.to_string())?;
|
||||
Ok(code.render::<svg::Color>().min_dimensions(320, 320).quiet_zone(true).build())
|
||||
}
|
||||
|
||||
fn payload_json(p: &Payload) -> Value {
|
||||
json!({
|
||||
"title": p.title,
|
||||
"kind": p.kind,
|
||||
"fields": p.fields.iter().map(|f| json!({ "name": f.name, "value": f.value.expose(), "secret": f.secret })).collect::<Vec<_>>(),
|
||||
"notes": p.notes.as_ref().map(|n| n.expose()),
|
||||
})
|
||||
}
|
||||
|
||||
fn share_error(e: ShareError) -> Value {
|
||||
json!({ "ok": false, "error": e.to_string(), "code": format!("{e:?}") })
|
||||
}
|
||||
|
||||
/// Handles one request. Native code (and the tests) call this directly; the browser goes through `call`.
|
||||
pub fn handle(request: &[u8]) -> Value {
|
||||
let req: Request = match serde_json::from_slice(request) {
|
||||
Ok(r) => r,
|
||||
// serde's message can quote the input, which may hold a password: say only what failed.
|
||||
Err(_) => return err("Bad request."),
|
||||
};
|
||||
match req {
|
||||
Request::Open { vault, password } => {
|
||||
let Ok(bytes) = BASE64.decode(vault.as_bytes()) else { return err("The vault file is damaged.") };
|
||||
match Vault::open(&bytes, &password) {
|
||||
Ok(v) => {
|
||||
let out = items(&v);
|
||||
VAULT.set(Some(v));
|
||||
out
|
||||
}
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}
|
||||
Request::Lock => {
|
||||
VAULT.set(None);
|
||||
json!({ "ok": true })
|
||||
}
|
||||
Request::Items => VAULT.with_borrow(|v| v.as_ref().map(items).unwrap_or_else(|| err("The vault is locked."))),
|
||||
Request::Reveal { id, name, index } => with_item(&id, |item| match value(item, &name, index) {
|
||||
Some(v) => json!({ "ok": true, "value": v.expose() }),
|
||||
None => err("No such field."),
|
||||
}),
|
||||
Request::Totp { id, now } => with_item(&id, |item| {
|
||||
let Some(f) = item.field("totp").filter(|f| !f.value.is_empty()) else { return err("No 2FA code here.") };
|
||||
match custos_totp::Totp::parse(f.value.expose()) {
|
||||
Ok(t) => {
|
||||
json!({ "ok": true, "code": t.code_at(now), "secondsLeft": t.seconds_left(now), "period": t.period() })
|
||||
}
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}),
|
||||
Request::Qr { id } => with_item(&id, |item| {
|
||||
let f = |n: &str| item.field(n).map(|f| f.value.expose()).unwrap_or("");
|
||||
let (payload, wifi) = if item.kind == ItemType::Wifi {
|
||||
let p = custos_qr::wifi_payload(
|
||||
f("ssid"),
|
||||
f("password"),
|
||||
custos_qr::WifiSecurity::parse(f("security")),
|
||||
f("hidden") == "true",
|
||||
);
|
||||
(Zeroizing::new(p), true)
|
||||
} else {
|
||||
match value(item, primary_secret(item.kind), 0).filter(|v| !v.is_empty()) {
|
||||
Some(v) => (Zeroizing::new(custos_qr::secret_payload(v.expose())), false),
|
||||
None => return err("Nothing to show."),
|
||||
}
|
||||
};
|
||||
match qr_svg(&payload) {
|
||||
Ok(svg) => json!({ "ok": true, "svg": svg, "wifi": wifi }),
|
||||
Err(e) => err(e),
|
||||
}
|
||||
}),
|
||||
Request::ShareSeal { id, password } => with_item(&id, |item| {
|
||||
let password = password.filter(|p| !p.is_empty());
|
||||
match custos_share::seal(&Payload::from_item(item), password.as_ref()) {
|
||||
Ok(s) => json!({ "ok": true, "blob": BASE64.encode(&s.blob), "fragment": s.fragment.as_str() }),
|
||||
Err(e) => share_error(e),
|
||||
}
|
||||
}),
|
||||
Request::ShareOpen { blob, fragment, password } => {
|
||||
let Ok(bytes) = BASE64.decode(blob.as_bytes()) else { return share_error(ShareError::Malformed) };
|
||||
match custos_share::open(&bytes, &fragment, password.as_ref()) {
|
||||
Ok(p) => json!({ "ok": true, "payload": payload_json(&p) }),
|
||||
Err(e) => share_error(e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- the WebAssembly ABI ----------
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
mod abi {
|
||||
use std::alloc::{Layout, alloc as raw_alloc, dealloc as raw_dealloc};
|
||||
use zeroize::Zeroize;
|
||||
|
||||
#[link(wasm_import_module = "env")]
|
||||
unsafe extern "C" {
|
||||
fn random_fill(ptr: *mut u8, len: usize);
|
||||
}
|
||||
|
||||
/// getrandom's custom backend: the browser's CSPRNG.
|
||||
#[unsafe(no_mangle)]
|
||||
unsafe extern "Rust" fn __getrandom_v03_custom(dest: *mut u8, len: usize) -> Result<(), getrandom::Error> {
|
||||
unsafe { random_fill(dest, len) };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn alloc(len: usize) -> *mut u8 {
|
||||
if len == 0 {
|
||||
return std::ptr::NonNull::dangling().as_ptr();
|
||||
}
|
||||
unsafe { raw_alloc(Layout::from_size_align(len, 1).expect("layout")) }
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `ptr` and `len` must come from `alloc` or `call`, and be given back once.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn dealloc(ptr: *mut u8, len: usize) {
|
||||
if len == 0 {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
std::slice::from_raw_parts_mut(ptr, len).zeroize();
|
||||
raw_dealloc(ptr, Layout::from_size_align(len, 1).expect("layout"));
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `ptr`/`len` must be a buffer from `alloc` holding the request; `call` frees it.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn call(ptr: *mut u8, len: usize) -> u64 {
|
||||
let response = {
|
||||
let request = unsafe { std::slice::from_raw_parts(ptr, len) };
|
||||
super::handle(request)
|
||||
};
|
||||
unsafe { dealloc(ptr, len) };
|
||||
let mut bytes = serde_json::to_vec(&response).unwrap_or_else(|_| b"{\"ok\":false}".to_vec());
|
||||
drop(response);
|
||||
let out = alloc(bytes.len());
|
||||
unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len()) };
|
||||
let packed = ((out as u64) << 32) | bytes.len() as u64;
|
||||
bytes.zeroize();
|
||||
packed
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
//! The JSON operations the browser calls, run natively.
|
||||
|
||||
use custos_vault::{Field, Item, ItemType, KdfParams, SecretString, Vault};
|
||||
use data_encoding::BASE64;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
const PASSWORD: &str = "Test4-Vault7-Only2";
|
||||
const SECRET: &str = "s3cret-Ž!";
|
||||
|
||||
fn call(v: Value) -> Value {
|
||||
custos_wasm::handle(v.to_string().as_bytes())
|
||||
}
|
||||
|
||||
fn vault_b64() -> (String, String, String) {
|
||||
let mut v = Vault::create(&SecretString::from(PASSWORD), FAST).unwrap();
|
||||
let mut login = Item::new(ItemType::WebLogin, "GitHub", 0);
|
||||
login.set("username", "mark", 0);
|
||||
login.set("password", SECRET, 0);
|
||||
login.set("url", "https://github.com", 0);
|
||||
login.set("totp", "JBSWY3DPEHPK3PXP", 0);
|
||||
let login_id = login.id.clone();
|
||||
let mut wifi = Item::new(ItemType::Wifi, "Home", 0);
|
||||
wifi.set("ssid", "Domov", 0);
|
||||
wifi.set("password", SECRET, 0);
|
||||
wifi.set("security", "WPA", 0);
|
||||
wifi.add_field(Field::text("note", "2.4 GHz"));
|
||||
let wifi_id = wifi.id.clone();
|
||||
v.add(login);
|
||||
v.add(wifi);
|
||||
(BASE64.encode(&v.to_bytes().unwrap()), login_id, wifi_id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_list_reveal_lock() {
|
||||
let (vault, login, _) = vault_b64();
|
||||
let bad = call(json!({ "op": "open", "vault": vault, "password": "wrong" }));
|
||||
assert_eq!(bad["ok"], false);
|
||||
assert_eq!(bad["error"], "wrong password");
|
||||
|
||||
let r = call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
let text = r.to_string();
|
||||
assert!(!text.contains(SECRET) && !text.contains("JBSWY3DP"), "the list holds no secret values");
|
||||
let items = r["items"].as_array().unwrap();
|
||||
assert_eq!(items.len(), 2);
|
||||
let gh = items.iter().find(|i| i["id"] == login.as_str()).unwrap();
|
||||
assert_eq!(
|
||||
(gh["subtitle"].as_str(), gh["hasTotp"].as_bool(), gh["mainSecret"].as_str()),
|
||||
(Some("mark"), Some(true), Some("password"))
|
||||
);
|
||||
|
||||
let rv = call(json!({ "op": "reveal", "id": login, "name": "password" }));
|
||||
assert_eq!(rv["value"], SECRET);
|
||||
assert_eq!(call(json!({ "op": "reveal", "id": login, "name": "password", "index": 1 }))["ok"], false);
|
||||
|
||||
assert_eq!(call(json!({ "op": "lock" }))["ok"], true);
|
||||
let locked = call(json!({ "op": "reveal", "id": login, "name": "password" }));
|
||||
assert_eq!(locked["error"], "The vault is locked.");
|
||||
assert_eq!(call(json!({ "op": "items" }))["ok"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn totp_and_qr() {
|
||||
let (vault, login, wifi) = vault_b64();
|
||||
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
|
||||
let now = 1_800_000_000u64;
|
||||
let t = call(json!({ "op": "totp", "id": login, "now": now }));
|
||||
let expected = custos_totp::Totp::parse("JBSWY3DPEHPK3PXP").unwrap();
|
||||
assert_eq!(t["code"], expected.code_at(now));
|
||||
assert_eq!(t["secondsLeft"], expected.seconds_left(now));
|
||||
let q = call(json!({ "op": "qr", "id": wifi }));
|
||||
assert_eq!((q["ok"].as_bool(), q["wifi"].as_bool()), (Some(true), Some(true)));
|
||||
assert!(q["svg"].as_str().unwrap().starts_with("<?xml"));
|
||||
let q = call(json!({ "op": "qr", "id": login }));
|
||||
assert_eq!(q["wifi"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn share_seal_and_open() {
|
||||
let (vault, login, _) = vault_b64();
|
||||
call(json!({ "op": "open", "vault": vault, "password": PASSWORD }));
|
||||
for password in [None, Some("by-phone")] {
|
||||
let s = call(json!({ "op": "share_seal", "id": login, "password": password }));
|
||||
assert_eq!(s["ok"], true, "{s}");
|
||||
let (blob, fragment) = (s["blob"].as_str().unwrap(), s["fragment"].as_str().unwrap());
|
||||
assert!(!blob.contains(SECRET));
|
||||
let o = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": password }));
|
||||
assert_eq!(o["ok"], true, "{o}");
|
||||
let fields = o["payload"]["fields"].as_array().unwrap();
|
||||
let names: Vec<_> = fields.iter().map(|f| f["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names, ["username", "password", "url"], "no TOTP seed in a share");
|
||||
assert_eq!(fields[1]["value"], SECRET);
|
||||
if password.is_some() {
|
||||
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment, "password": "nope" }));
|
||||
assert_eq!(w["code"], "DecryptFailed");
|
||||
let w = call(json!({ "op": "share_open", "blob": blob, "fragment": fragment }));
|
||||
assert_eq!(w["code"], "PasswordRequired");
|
||||
}
|
||||
}
|
||||
// An empty password means none.
|
||||
let s = call(json!({ "op": "share_seal", "id": login, "password": "" }));
|
||||
assert!(!s["fragment"].as_str().unwrap().contains("p=1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_requests_never_echo_their_input() {
|
||||
let r = custos_wasm::handle(br#"{"op":"open","vault":"x","password":"hunter2","extra":"#);
|
||||
assert_eq!(r["error"], "Bad request.");
|
||||
let r = call(json!({ "op": "share_open", "blob": "!!", "fragment": "k=hunter2" }));
|
||||
assert!(!r.to_string().contains("hunter2"));
|
||||
}
|
||||
@@ -196,3 +196,7 @@ and an identical `.bak`. Leftover `.tmp` files are ignored and overwritten by th
|
||||
|
||||
A change that old readers would misread bumps `version`. Readers refuse versions they do not know rather
|
||||
than guess. Adding JSON members or new slot kinds does not need a bump.
|
||||
|
||||
## Share links
|
||||
|
||||
Shares are not vault files; their blob and link format is in `docs/SHARE.md`.
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
# Private share links (`custos-share`), format version 1
|
||||
|
||||
A share link hands one secret to someone who has no Custos. The sender's app (desktop or web) encrypts it;
|
||||
the share server stores only ciphertext; the key travels in the link's fragment, which browsers never send
|
||||
to a server.
|
||||
|
||||
```
|
||||
https://custos.example/s/<id>#k=<link key> no password
|
||||
https://custos.example/s/<id>#k=<link key>&p=1 the recipient also needs a password, told separately
|
||||
```
|
||||
|
||||
- `<id>`: chosen by the server (128 random bits, base64url, 22 characters). It is not secret.
|
||||
- `<link key>`: 32 random bytes from the OS CSPRNG, base64url without padding (43 characters).
|
||||
- `p=1` only tells the recipient page to ask for a password before it fetches anything. The blob's own
|
||||
flag decides; a link with `p=1` removed still needs the password.
|
||||
|
||||
## Keys
|
||||
|
||||
```
|
||||
no password: K = link key
|
||||
with password: P = Argon2id(password (UTF-8), salt, m, t, p) → 32 bytes
|
||||
K = HKDF-SHA256(salt = salt, ikm = link key ‖ P, info = "custos-share v1") → 32 bytes
|
||||
```
|
||||
Both the link and the password are needed; neither alone gives anything, and the server has neither.
|
||||
Default share KDF: m = 19 MiB (19,456 KiB), t = 2, p = 1 (OWASP's Argon2id minimum; it runs in a phone
|
||||
browser in about a second). It only has to slow down guessing by someone who already holds the link.
|
||||
|
||||
## Blob (what the server stores), all integers little-endian
|
||||
|
||||
| Offset | Size | Field |
|
||||
|:--|:--|:--|
|
||||
| 0 | 4 | magic `CSH1` |
|
||||
| 4 | 1 | flags: bit 0 = password; other bits must be 0 |
|
||||
| 5 | 28 | only if bit 0: `m_cost_kib` u32, `t_cost` u32, `p_cost` u32, salt (16 bytes) |
|
||||
| … | 24 | nonce |
|
||||
| … | rest | XChaCha20-Poly1305 ciphertext and 16-byte tag; AAD = every byte before it (magic to nonce) |
|
||||
|
||||
Limits a reader enforces before running Argon2: m from 8 MiB to 256 MiB, t from 1 to 16, p from 1 to 4.
|
||||
A whole blob is at most 64 KiB.
|
||||
|
||||
## Plaintext
|
||||
|
||||
UTF-8 JSON, `{"v":1,"title":"…","kind":"web-login","fields":[{"name":"password","value":"…","secret":true}],"notes":"…"}`.
|
||||
`kind` and `notes` may be missing. Built from an item by `Payload::from_item`, which leaves out empty
|
||||
fields, the TOTP seed (sharing it would hand over the second factor too) and the auto-type settings.
|
||||
|
||||
## Errors (none contains secret material)
|
||||
|
||||
| Error | When | Says |
|
||||
|:--|:--|:--|
|
||||
| `Malformed` | wrong magic, too short, unknown flags, too large | not a Custos share |
|
||||
| `BadLink` | fragment missing, not `k=` + 43 base64url characters | the link is incomplete |
|
||||
| `PasswordRequired` | the blob has the password flag and no password was given | — |
|
||||
| `UnsupportedKdf` | parameters outside the limits | — |
|
||||
| `DecryptFailed` | the tag does not verify: wrong key, wrong password, or any byte changed | never garbage: nothing is returned |
|
||||
|
||||
A wrong password and a tampered blob give the same `DecryptFailed`; the page says "wrong password, or the
|
||||
link or share is damaged".
|
||||
|
||||
## Server rules (the private app's share service implements them)
|
||||
|
||||
- Stores the blob, an expiry (1 hour, 1 day or 7 days; default 1 day) and a view count (default 1).
|
||||
- `open` returns the blob and counts one view; the last view deletes it. Expired, used up and unknown ids
|
||||
answer the same 404.
|
||||
- Logs only the id, the time and the status code. Never a body, never a full URL.
|
||||
|
||||
## The browser build (`custos-wasm`)
|
||||
|
||||
The web vault and the recipient page run this repository's code compiled to `wasm32-unknown-unknown`,
|
||||
with no wasm-bindgen: a JSON-in/JSON-out `call` export and a `random_fill` import backed by
|
||||
`crypto.getRandomValues` (getrandom's custom backend). The ABI is documented in `crates/custos-wasm/src/lib.rs`.
|
||||
@@ -16,6 +16,9 @@ just as plainly, what it does not.
|
||||
| Thief or sync server | The `.custos` file (any number of old versions) | Item count and sizes roughly (the ciphertext length), the KDF parameters. Nothing else. | XChaCha20-Poly1305 over the whole body; titles, URLs and usernames are inside it too. |
|
||||
| Offline guesser | The file and a GPU farm | One Argon2id evaluation (64 MiB, 20 passes by default, ≈ 0.75 s on a desktop CPU) per guess | A 4-word memorable password with digits (~65 bits) is out of reach; a weak master password is not. **The master password is the whole defence here.** |
|
||||
| Tamperer | Write access to the file | Can destroy it, or roll it back to an older version they saw. Cannot change, reorder, add or remove items unnoticed. | The header is the body's AAD; each slot's parameters are its wrap's AAD. |
|
||||
| Share server operator | Every share blob, its id, size, expiry, view count, the uploader's login and the recipients' IP addresses | Nothing of the secret | The key is in the link's `#fragment`, which browsers never send; the server stores ciphertext only (docs/SHARE.md). |
|
||||
| Someone who gets a share link | The link (chat history, a forwarded mail) | The secret, if the share still has views left; with a password share, also one Argon2id evaluation (19 MiB) per password guess | That is what a link is. Use 1 view (the default): once it is opened, it is gone, and the sender learns about interception when the recipient finds it used. |
|
||||
| Link-preview bot | The link, fetched by a chat app | Nothing; the view is not used | The page asks for a click on *Reveal* before it fetches the share. |
|
||||
| Someone who crashes the machine mid-save | — | Nothing | Atomic save: temp file, fsync, rename; the previous version is kept as `.bak`. |
|
||||
|
||||
## What is NOT protected
|
||||
@@ -41,6 +44,15 @@ just as plainly, what it does not.
|
||||
- **Metadata.** File size and modification times reveal roughly how much is stored and when it changed.
|
||||
- **Side channels.** No effort beyond what the RustCrypto crates provide (constant-time tag comparison).
|
||||
|
||||
- **The web vault trusts the server that serves its code.** In the browser, the page, its JavaScript and the
|
||||
WebAssembly come from the home server on every visit. Whoever controls that server (or its TLS
|
||||
certificate) can serve a modified page that sends the master password away the next time someone unlocks
|
||||
in the browser. The desktop app does not have this problem. Authelia keeps strangers out; it does not
|
||||
protect against the server itself. The same holds for the share page and the recipient.
|
||||
- **Browser memory.** In the web vault the key and the decrypted items live in WebAssembly memory, and a
|
||||
revealed or copied value passes through JavaScript strings, which cannot be wiped. Lock (or close the tab)
|
||||
when done.
|
||||
|
||||
## Design rules that follow from this
|
||||
|
||||
- No custom cryptography: Argon2id (`argon2`), XChaCha20-Poly1305 (`chacha20poly1305`), the OS CSPRNG
|
||||
|
||||
Reference in New Issue
Block a user