[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:
@@ -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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user