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

523 lines
21 KiB
Rust

//! 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).
//!
//! Two factors (docs/FACTORS.md, docs/SEAL.md): the page asks for a one-time key (`recipient`), sends its
//! public half to the factor service, and passes the sealed answer back in `open_with`. The key's secret
//! half never leaves this module. A paired phone keeps its approval material wrapped with its passkey's
//! PRF output (`phone_enrol`, `phone_approve`); unwrapped, it exists only inside one call.
use custos_seal::Recipient;
use custos_share::{Payload, ShareError};
use custos_vault::{FactorKind, Item, ItemType, SecretString, Unlock, 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) };
/// One-time keys waiting for a sealed answer, by their public key (base64). Each is used once.
static RECIPIENTS: RefCell<Vec<(String, Recipient)>> = const { RefCell::new(Vec::new()) };
}
/// At most this many one-time keys wait at once; the oldest goes first.
const MAX_RECIPIENTS: usize = 8;
/// The at-rest context of a phone's approval material, wrapped with its passkey's PRF output.
const PHONE_APPROVAL: &[u8] = b"custos phone approval v1";
/// One factor given to `open_with`.
#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")]
enum FactorIn {
Password { password: SecretString },
/// A factor service's or a device's answer, sealed to a key from `recipient` (`pub`) for `context`.
Sealed { factor: FactorKind, r#pub: String, sealed: String, context: String },
/// Material the page holds itself: a passkey's PRF output (base64).
Material { factor: FactorKind, material: SecretString },
}
#[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>,
},
/// The format version and the factors (id, type) of a vault, from its header alone.
Factors {
vault: String,
},
/// A new one-time key: `{pub, match}`.
Recipient,
/// The match code of a public key (base64), for example a requesting device's.
MatchCode {
r#pub: String,
},
/// Opens a version-2 vault with two different factors.
OpenWith {
vault: String,
factors: Vec<FactorIn>,
},
/// Pairs this phone with a PC that waits with the one-time key `pub`: makes the phone's approval
/// material and seals it with the passkey's PRF output (`prf`, base64) to the PC for `context`.
/// Returns the box, its sender code, and the material wrapped with the PRF output (`wrapped`).
PhoneEnrol {
r#pub: String,
context: String,
label: String,
prf: SecretString,
},
/// Approves a request: unwraps this phone's approval material with the PRF output and seals it to
/// the requester's key for `context` (`approval:<factor>:<request id>`).
PhoneApprove {
wrapped: String,
prf: SecretString,
r#pub: String,
context: String,
},
/// Pairs this phone as a Domi device (Custos docs/07_domi_identity.md): seals its device label and its
/// Ed25519 device public key (`device`, base64url, made non-extractable by the page) to the PC that
/// waits with `pub`, for `domi-pair:<id>`. Returns the box and its sender code. Nothing secret goes in.
DomiPair {
r#pub: String,
id: String,
label: String,
device: String,
},
}
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",
ItemType::KeyPair => "private-key",
}
}
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,
ItemType::KeyPair => Some("public-key"),
}
}
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 b64(s: &str) -> Option<Zeroizing<Vec<u8>>> {
BASE64.decode(s.as_bytes()).ok().map(Zeroizing::new)
}
fn key32(s: &SecretString) -> Option<Zeroizing<[u8; 32]>> {
let v = b64(s.expose())?;
let a: [u8; 32] = v.as_slice().try_into().ok()?;
Some(Zeroizing::new(a))
}
fn take_recipient(public: &str) -> Option<Recipient> {
RECIPIENTS.with_borrow_mut(|r| r.iter().position(|(p, _)| p == public).map(|i| r.remove(i).1))
}
/// The material for one factor; a password stays a password.
enum Given {
Password(SecretString),
Material(FactorKind, Zeroizing<Vec<u8>>),
}
fn given(f: FactorIn) -> Result<Given, String> {
match f {
FactorIn::Password { password } => Ok(Given::Password(password)),
FactorIn::Material { factor, material } => {
Ok(Given::Material(factor, b64(material.expose()).ok_or("A malformed factor.")?))
}
FactorIn::Sealed { factor, r#pub, sealed, context } => {
let me = take_recipient(&r#pub).ok_or("That request expired. Ask again.")?;
let sealed = b64(&sealed).ok_or("A malformed answer.")?;
let m = me.open(&sealed, context.as_bytes()).map_err(|e| e.to_string())?;
Ok(Given::Material(factor, m))
}
}
}
fn unlock(g: &Given) -> Unlock<'_> {
match g {
Given::Password(p) => Unlock::Password(p),
Given::Material(k, m) => Unlock::Material(*k, m),
}
}
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),
}
}
Request::Factors { vault } => {
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
match (Vault::version_of(&bytes), Vault::factor_ids(&bytes)) {
(Ok(version), Ok(ids)) => json!({
"ok": true,
"version": version,
"factors": ids.iter().map(|(id, kind)| json!({ "id": id, "kind": kind })).collect::<Vec<_>>(),
}),
(Err(e), _) | (_, Err(e)) => err(e),
}
}
Request::Recipient => {
let me = Recipient::generate();
let public = BASE64.encode(&me.public());
let code = me.match_code();
RECIPIENTS.with_borrow_mut(|r| {
if r.len() >= MAX_RECIPIENTS {
r.remove(0);
}
r.push((public.clone(), me));
});
json!({ "ok": true, "pub": public, "match": code })
}
Request::MatchCode { r#pub } => match b64(&r#pub) {
Some(p) if p.len() == 32 => json!({ "ok": true, "match": custos_seal::match_code(&p) }),
_ => err("Not a valid public key."),
},
Request::OpenWith { vault, factors } => {
let Some(bytes) = b64(&vault) else { return err("The vault file is damaged.") };
let mut factors = factors.into_iter();
let (Some(a), Some(b), None) = (factors.next(), factors.next(), factors.next()) else {
return err("Choose two different factors.");
};
let (a, b) = match (given(a), given(b)) {
(Ok(a), Ok(b)) => (a, b),
(Err(e), _) | (_, Err(e)) => return err(e),
};
match Vault::open_with(&bytes, unlock(&a), unlock(&b)) {
Ok(v) => {
let out = items(&v);
VAULT.set(Some(v));
out
}
Err(e) => err(e),
}
}
Request::PhoneEnrol { r#pub, context, label, prf } => {
let (Some(public), Some(prf_key)) = (b64(&r#pub), key32(&prf)) else { return err("A malformed request.") };
let material = custos_seal::random_bytes();
let plain = Zeroizing::new(
json!({ "label": label, "passkey": prf.expose(), "approval": BASE64.encode(material.as_ref()) })
.to_string(),
);
match custos_seal::seal(&public, context.as_bytes(), plain.as_bytes()) {
Ok(sealed) => json!({
"ok": true,
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
"sealed": BASE64.encode(&sealed),
"wrapped": BASE64.encode(&custos_seal::seal_at_rest(&prf_key, PHONE_APPROVAL, material.as_ref())),
}),
Err(e) => err(e),
}
}
Request::DomiPair { r#pub, id, label, device } => {
let device_ok = data_encoding::BASE64URL_NOPAD.decode(device.as_bytes()).is_ok_and(|d| d.len() == 32);
let id_ok = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { return err("A malformed request.") };
let label: String = label.trim().chars().filter(|c| !c.is_control()).take(40).collect();
let plain = json!({ "label": label, "device": device }).to_string();
match custos_seal::seal(&public, format!("domi-pair:{id}").as_bytes(), plain.as_bytes()) {
Ok(sealed) => json!({
"ok": true,
"code": custos_seal::sender_code(&sealed).unwrap_or_default(),
"sealed": BASE64.encode(&sealed),
}),
Err(e) => err(e),
}
}
Request::PhoneApprove { wrapped, prf, r#pub, context } => {
let (Some(wrapped), Some(prf_key), Some(public)) = (b64(&wrapped), key32(&prf), b64(&r#pub)) else {
return err("A malformed request.");
};
let Ok(material) = custos_seal::open_at_rest(&prf_key, PHONE_APPROVAL, &wrapped) else {
return err("This passkey does not belong to this phone's pairing.");
};
match custos_seal::seal(&public, context.as_bytes(), &material) {
Ok(sealed) => json!({ "ok": true, "sealed": BASE64.encode(&sealed) }),
Err(e) => err(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(())
}
/// The same for getrandom 0.2, which rand_core 0.6 (custos-sign's RSA and X.509 crates) is built on. The
/// browser never makes signing keys, but the crates must link.
fn fill_v02(dest: &mut [u8]) -> Result<(), getrandom02::Error> {
unsafe { random_fill(dest.as_mut_ptr(), dest.len()) };
Ok(())
}
getrandom02::register_custom_getrandom!(fill_v02);
#[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
}
}