Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 95613f4ed0 | |||
| 2d04f32f57 | |||
| 1292c09d02 | |||
| a45d1054f0 | |||
| 4e8fb6a8f5 | |||
| aa5b692651 | |||
| 6f4075f7e3 |
@@ -15,6 +15,9 @@ crates/custos-seal sealed boxes (X25519 + XChaCha20-Poly1305) for factor mate
|
||||
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
|
||||
crates/custos-kdbx KeePass import (KDBX 3.1, 4) and export (KDBX 4); tools/kdbx/interop.sh checks it with keepassxc-cli
|
||||
crates/custos-browser which login belongs on which page (origins, no fuzzy matching), native messaging frames
|
||||
crates/custos-native the browser extension's native messaging host: three ops, rebuilt, to custos.exe's pipe only
|
||||
extension/ the MV3 extension for Edge and Chrome (fixed id jchkapmceepdnlhagfppeckggaecdcmn)
|
||||
docs/FORMAT.md the vault file format, version 1 (versioned; change it before the code)
|
||||
docs/FACTORS.md version 2: any two factors open the vault; the machine store
|
||||
docs/KEYS.md secret keys, API keys and key pairs
|
||||
@@ -23,6 +26,7 @@ docs/SHARE.md the share blob and link format (versioned like FORMAT.md)
|
||||
docs/THREAT_MODEL.md what is and is not protected
|
||||
docs/IDENTITY.md the Domi identity: the root key in the vault, the mnemonic order, signing certs
|
||||
docs/KDBX.md KeePass files: reading, writing, limits, the item mapping and what does not survive
|
||||
docs/BROWSER.md the browser extension: pieces, matching rule, messages, registration, threat model
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
Generated
+27
-10
@@ -327,9 +327,16 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-browser"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-gen"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -341,7 +348,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-kdbx"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"argon2",
|
||||
@@ -362,7 +369,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-keys"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"ed25519-dalek",
|
||||
@@ -373,13 +380,23 @@ dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-native"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"custos-browser",
|
||||
"serde_json",
|
||||
"windows-sys",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-qr"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
|
||||
[[package]]
|
||||
name = "custos-seal"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"chacha20poly1305",
|
||||
"hkdf",
|
||||
@@ -392,7 +409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-share"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
@@ -409,7 +426,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-sign"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"blake2 0.10.6",
|
||||
"data-encoding",
|
||||
@@ -428,7 +445,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-totp"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -441,7 +458,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-vault"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"bip39",
|
||||
@@ -465,7 +482,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-wasm"
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
dependencies = [
|
||||
"custos-qr",
|
||||
"custos-seal",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.14.0"
|
||||
version = "0.16.0"
|
||||
edition = "2024"
|
||||
license = "MPL-2.0"
|
||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||
|
||||
@@ -12,6 +12,7 @@ password and secret manager: everything that touches plaintext or keys.
|
||||
| `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) |
|
||||
| `custos-kdbx` | KeePass import (KDBX 3.1 and 4) and export (KDBX 4), checked against KeePassXC ([`docs/KDBX.md`](docs/KDBX.md)) |
|
||||
| `custos-browser`, `custos-native`, `extension/` | The Edge/Chrome extension, its native messaging host and the rule for which login belongs on which page ([`docs/BROWSER.md`](docs/BROWSER.md)) |
|
||||
|
||||
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,10 @@
|
||||
[package]
|
||||
name = "custos-browser"
|
||||
description = "Custos in the browser: which login may be filled into which page, and Chrome's native messaging frames"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
zeroize.workspace = true
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Chrome's native messaging frames: a 32-bit length in native byte order (little-endian on every machine
|
||||
//! Custos runs on), then that many bytes of UTF-8 JSON. Messages to the host are capped here at 64 KiB (the
|
||||
//! desktop's pipe limit); Chrome itself refuses messages to the browser over 1 MB.
|
||||
//!
|
||||
//! Frames can hold a login's password: they are `Zeroizing`, so the bytes are wiped when dropped.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// The largest message the extension may send to the host.
|
||||
pub const MAX_TO_HOST: usize = 64 * 1024;
|
||||
/// The largest message Chrome accepts from a host.
|
||||
pub const MAX_TO_BROWSER: usize = 1024 * 1024;
|
||||
|
||||
/// Reads one frame. `Ok(None)` when the browser closed the stream (the extension disconnected).
|
||||
pub fn read_frame(r: &mut impl Read) -> io::Result<Option<Zeroizing<Vec<u8>>>> {
|
||||
let mut len = [0u8; 4];
|
||||
match r.read_exact(&mut len) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
let n = u32::from_le_bytes(len) as usize;
|
||||
if n > MAX_TO_HOST {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
|
||||
}
|
||||
let mut buf = Zeroizing::new(vec![0u8; n]);
|
||||
r.read_exact(&mut buf)?;
|
||||
Ok(Some(buf))
|
||||
}
|
||||
|
||||
/// Writes one frame and flushes it (Chrome reads frame by frame).
|
||||
pub fn write_frame(w: &mut impl Write, msg: &[u8]) -> io::Result<()> {
|
||||
if msg.len() > MAX_TO_BROWSER {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidData, "message too large"));
|
||||
}
|
||||
w.write_all(&(msg.len() as u32).to_le_bytes())?;
|
||||
w.write_all(msg)?;
|
||||
w.flush()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn frames_round_trip_and_oversized_ones_are_refused() {
|
||||
let mut out = Vec::new();
|
||||
write_frame(&mut out, br#"{"op":"browser_status"}"#).unwrap();
|
||||
write_frame(&mut out, b"{}").unwrap();
|
||||
assert_eq!(&out[..4], &23u32.to_le_bytes());
|
||||
let mut r = &out[..];
|
||||
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), br#"{"op":"browser_status"}"#);
|
||||
assert_eq!(read_frame(&mut r).unwrap().unwrap().as_slice(), b"{}");
|
||||
assert!(read_frame(&mut r).unwrap().is_none(), "end of stream is the extension going away");
|
||||
// A length over the limit is refused before anything is allocated.
|
||||
let big = ((MAX_TO_HOST + 1) as u32).to_le_bytes();
|
||||
assert_eq!(read_frame(&mut &big[..]).unwrap_err().kind(), io::ErrorKind::InvalidData);
|
||||
// A frame cut short is an error, not a short message.
|
||||
let mut cut = 10u32.to_le_bytes().to_vec();
|
||||
cut.extend_from_slice(b"{}");
|
||||
assert!(read_frame(&mut &cut[..]).is_err());
|
||||
assert!(write_frame(&mut Vec::new(), &vec![b' '; MAX_TO_BROWSER + 1]).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! What the browser extension may fill where (docs/BROWSER.md). The extension and its native host live in
|
||||
//! this public repository; the rules that decide which login goes into which page live here too, so the
|
||||
//! desktop app and anyone reviewing the extension apply the same ones.
|
||||
//!
|
||||
//! - [`Origin`]: a page's origin as the browser reports it (never as the page claims).
|
||||
//! - [`login_matches`]: does a login's stored URL belong to that origin? Its host or a subdomain of it,
|
||||
//! same scheme, same port when the login names one. Never a "similar" name, so look-alike domains
|
||||
//! (`paypa1.com`, `paypal.com.evil.net`) never match.
|
||||
//! - [`framing`]: Chrome's native messaging frames (a 4-byte little-endian length, then JSON).
|
||||
//!
|
||||
//! ```
|
||||
//! use custos_browser::{login_matches, Origin};
|
||||
//! let page = Origin::parse("https://accounts.github.com/login?return=/")?;
|
||||
//! assert!(login_matches("https://github.com", &page).is_some());
|
||||
//! assert!(login_matches("https://github.com.evil.net", &page).is_none());
|
||||
//! # Ok::<(), custos_browser::OriginError>(())
|
||||
//! ```
|
||||
|
||||
pub mod framing;
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// A page's origin: scheme, host (lowercase, no trailing dot) and port (the scheme's default when absent).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Origin {
|
||||
pub scheme: Scheme,
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Scheme {
|
||||
Https,
|
||||
Http,
|
||||
}
|
||||
|
||||
impl Scheme {
|
||||
fn default_port(self) -> u16 {
|
||||
match self {
|
||||
Scheme::Https => 443,
|
||||
Scheme::Http => 80,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum OriginError {
|
||||
/// Not an `http(s)://host…` URL.
|
||||
NotWeb,
|
||||
/// A host that is empty, too long or has characters a host cannot have.
|
||||
BadHost,
|
||||
BadPort,
|
||||
}
|
||||
|
||||
impl fmt::Display for OriginError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
OriginError::NotWeb => "not a web address",
|
||||
OriginError::BadHost => "not a valid host",
|
||||
OriginError::BadPort => "not a valid port",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for OriginError {}
|
||||
|
||||
/// Splits `scheme://host:port/…` (userinfo refused: `https://bank.com@evil.net` must not read as bank.com).
|
||||
fn split(url: &str, default: Option<Scheme>) -> Result<(Scheme, String, Option<u16>), OriginError> {
|
||||
let url = url.trim();
|
||||
let (scheme, rest) = match url.split_once("://") {
|
||||
Some((s, rest)) => match s.to_ascii_lowercase().as_str() {
|
||||
"https" => (Scheme::Https, rest),
|
||||
"http" => (Scheme::Http, rest),
|
||||
_ => return Err(OriginError::NotWeb),
|
||||
},
|
||||
None => (default.ok_or(OriginError::NotWeb)?, url),
|
||||
};
|
||||
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
|
||||
if authority.contains('@') {
|
||||
return Err(OriginError::BadHost);
|
||||
}
|
||||
let (host, port) = if let Some(v6) = authority.strip_prefix('[') {
|
||||
let (h, after) = v6.split_once(']').ok_or(OriginError::BadHost)?;
|
||||
(format!("[{}]", h.to_ascii_lowercase()), after.strip_prefix(':'))
|
||||
} else {
|
||||
match authority.rsplit_once(':') {
|
||||
Some((h, p)) => (h.to_ascii_lowercase(), Some(p)),
|
||||
None => (authority.to_ascii_lowercase(), None),
|
||||
}
|
||||
};
|
||||
let host = host.trim_end_matches('.').to_string();
|
||||
let ok = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_' | '[' | ']' | ':');
|
||||
if host.is_empty() || host.len() > 253 || !host.chars().all(ok) || host.contains("..") {
|
||||
return Err(OriginError::BadHost);
|
||||
}
|
||||
let port = match port {
|
||||
None | Some("") => None,
|
||||
Some(p) => Some(
|
||||
p.parse::<u16>()
|
||||
.map_err(|_| OriginError::BadPort)
|
||||
.and_then(|n| if n == 0 { Err(OriginError::BadPort) } else { Ok(n) })?,
|
||||
),
|
||||
};
|
||||
Ok((scheme, host, port))
|
||||
}
|
||||
|
||||
impl Origin {
|
||||
/// A page URL as the browser reports it (`sender.url`, the tab's URL).
|
||||
pub fn parse(url: &str) -> Result<Origin, OriginError> {
|
||||
let (scheme, host, port) = split(url, None)?;
|
||||
Ok(Origin { scheme, port: port.unwrap_or(scheme.default_port()), host })
|
||||
}
|
||||
|
||||
fn is_loopback(&self) -> bool {
|
||||
self.host == "localhost"
|
||||
|| self.host.ends_with(".localhost")
|
||||
|| self.host == "127.0.0.1"
|
||||
|| self.host == "[::1]"
|
||||
}
|
||||
|
||||
fn is_ip(&self) -> bool {
|
||||
self.host.starts_with('[')
|
||||
|| self.host.split('.').all(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit()))
|
||||
}
|
||||
|
||||
/// May a login be filled into this page at all? Only over https, or plain http on this machine.
|
||||
pub fn fillable(&self) -> bool {
|
||||
self.scheme == Scheme::Https || self.is_loopback()
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Origin {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let scheme = match self.scheme {
|
||||
Scheme::Https => "https",
|
||||
Scheme::Http => "http",
|
||||
};
|
||||
if self.port == self.scheme.default_port() {
|
||||
write!(f, "{scheme}://{}", self.host)
|
||||
} else {
|
||||
write!(f, "{scheme}://{}:{}", self.host, self.port)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How well a login's URL fits a page, best first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Match {
|
||||
/// The page is on the login's host itself (`www.` counts as the host).
|
||||
Exact,
|
||||
/// The page is on a subdomain of the login's host (`accounts.github.com` for `github.com`).
|
||||
Subdomain,
|
||||
}
|
||||
|
||||
/// Does the login stored with `item_url` belong on `page`? `None` when it must not be offered there.
|
||||
///
|
||||
/// A stored URL without a scheme (`github.com/login`) means https. The page must be fillable, the schemes
|
||||
/// equal, the port equal when the stored URL names one (else the page's must be the scheme's default), and
|
||||
/// the page's host the login's host or a subdomain of it. A login for a bare top-level name (`com`) or for
|
||||
/// an IP address matches only that exact host.
|
||||
pub fn login_matches(item_url: &str, page: &Origin) -> Option<Match> {
|
||||
if !page.fillable() {
|
||||
return None;
|
||||
}
|
||||
let (scheme, host, port) = split(item_url, Some(Scheme::Https)).ok()?;
|
||||
if scheme != page.scheme || port.unwrap_or(scheme.default_port()) != page.port {
|
||||
return None;
|
||||
}
|
||||
let strip = |h: &str| h.strip_prefix("www.").map(str::to_string).unwrap_or_else(|| h.to_string());
|
||||
let (item, at) = (strip(&host), strip(&page.host));
|
||||
if item == at {
|
||||
return Some(Match::Exact);
|
||||
}
|
||||
if page.is_ip() || !item.contains('.') || item.starts_with('[') {
|
||||
return None;
|
||||
}
|
||||
at.strip_suffix(&item).filter(|rest| rest.ends_with('.')).map(|_| Match::Subdomain)
|
||||
}
|
||||
|
||||
/// The best match among a login's URLs.
|
||||
pub fn best_match<'a>(urls: impl IntoIterator<Item = &'a str>, page: &Origin) -> Option<Match> {
|
||||
urls.into_iter().filter_map(|u| login_matches(u, page)).min()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn page(u: &str) -> Origin {
|
||||
Origin::parse(u).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origins_parse_as_the_browser_reports_them() {
|
||||
assert_eq!(
|
||||
page("https://GitHub.com./login?x=1#y"),
|
||||
Origin { scheme: Scheme::Https, host: "github.com".into(), port: 443 }
|
||||
);
|
||||
assert_eq!(page("http://localhost:5173/").port, 5173);
|
||||
assert_eq!(page("https://[::1]:8443/").host, "[::1]");
|
||||
assert_eq!(page("https://bank.cz").to_string(), "https://bank.cz");
|
||||
assert_eq!(page("http://127.0.0.1:8080/a").to_string(), "http://127.0.0.1:8080");
|
||||
for bad in [
|
||||
"ftp://x.cz",
|
||||
"file:///C:/a.html",
|
||||
"chrome-extension://abc/",
|
||||
"javascript:alert(1)",
|
||||
"about:blank",
|
||||
"https://",
|
||||
"https://a..b.cz/",
|
||||
"https://bank.cz:99999/",
|
||||
"https://bank.cz:0/",
|
||||
"https://bad host.cz/",
|
||||
] {
|
||||
assert!(Origin::parse(bad).is_err(), "{bad}");
|
||||
}
|
||||
// Userinfo is refused outright: it is how look-alike links hide their real host.
|
||||
assert_eq!(Origin::parse("https://bank.cz@evil.net/"), Err(OriginError::BadHost));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_login_matches_its_host_and_its_subdomains_only() {
|
||||
let gh = page("https://github.com/login");
|
||||
assert_eq!(login_matches("https://github.com", &gh), Some(Match::Exact));
|
||||
assert_eq!(login_matches("github.com/login", &gh), Some(Match::Exact), "no scheme means https");
|
||||
assert_eq!(login_matches("https://www.github.com/", &gh), Some(Match::Exact));
|
||||
assert_eq!(login_matches("https://github.com", &page("https://www.github.com/")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("https://github.com", &page("https://gist.github.com/")), Some(Match::Subdomain));
|
||||
// A login for a subdomain does not go to its parent or its siblings.
|
||||
assert_eq!(login_matches("https://gist.github.com", &gh), None);
|
||||
assert_eq!(login_matches("https://gist.github.com", &page("https://api.github.com/")), None);
|
||||
// Look-alikes never match.
|
||||
for evil in [
|
||||
"https://github.com.evil.net/",
|
||||
"https://evilgithub.com/",
|
||||
"https://github.co/",
|
||||
"https://githuh.com/",
|
||||
"https://xn--gthub-cta.com/",
|
||||
] {
|
||||
assert_eq!(login_matches("https://github.com", &page(evil)), None, "{evil}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scheme_port_and_plain_http_are_strict() {
|
||||
// Never over plain http on the internet, even for a login saved with http.
|
||||
assert_eq!(login_matches("http://intranet.example", &page("http://intranet.example/")), None);
|
||||
// On this machine plain http is fine, with the port the login names.
|
||||
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:5173/login")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("http://localhost:5173", &page("http://localhost:8080/")), None);
|
||||
assert_eq!(login_matches("http://localhost", &page("http://localhost:8080/")), None);
|
||||
// An https login does not go to the http page of the same host, nor the other way round.
|
||||
assert_eq!(login_matches("https://localhost", &page("http://localhost/")), None);
|
||||
assert_eq!(
|
||||
login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa:5001/")),
|
||||
Some(Match::Exact)
|
||||
);
|
||||
assert_eq!(login_matches("https://nas.home.arpa:5001", &page("https://nas.home.arpa/")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bare_names_and_addresses_match_exactly_only() {
|
||||
assert_eq!(login_matches("https://192.168.1.1", &page("https://192.168.1.1/")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("https://168.1.1", &page("https://192.168.1.1/")), None);
|
||||
assert_eq!(login_matches("https://cz", &page("https://bank.cz/")), None);
|
||||
assert_eq!(login_matches("https://[::1]", &page("https://[::1]/")), Some(Match::Exact));
|
||||
assert_eq!(login_matches("not a url at all", &page("https://bank.cz/")), None);
|
||||
assert_eq!(login_matches("", &page("https://bank.cz/")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_best_of_several_urls_wins() {
|
||||
let p = page("https://www.github.com/");
|
||||
assert_eq!(best_match(["https://gitlab.com", "https://github.com"], &p), Some(Match::Exact));
|
||||
assert_eq!(best_match(["https://gitlab.com"], &p), None);
|
||||
assert_eq!(
|
||||
best_match(["https://github.com", "https://www.github.com"], &page("https://gist.github.com/")),
|
||||
Some(Match::Subdomain)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "custos-native"
|
||||
description = "Custos's native messaging host: the browser extension's way to the desktop Custos"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
custos-browser = { path = "../custos-browser" }
|
||||
serde_json.workspace = true
|
||||
zeroize.workspace = true
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_IO", "Win32_System_Pipes", "Win32_System_Threading"] }
|
||||
@@ -0,0 +1,240 @@
|
||||
//! custos-native: the browser extension's native messaging host (docs/BROWSER.md). Edge or Chrome starts it
|
||||
//! when the extension connects, and talks to it over stdin/stdout in native messaging frames. It forwards
|
||||
//! three requests to the desktop Custos over its Domi pipe and returns the answers:
|
||||
//!
|
||||
//! - `browser_status`: is Custos running and unlocked;
|
||||
//! - `browser_match { origin }`: the logins for a page (title, username; never a password);
|
||||
//! - `browser_fill { id, origin }`: one login's username, password and 2FA code, when it matches the page.
|
||||
//!
|
||||
//! The host adds nothing and decides nothing: Custos checks the origin against the login and asks the
|
||||
//! user once whether this host may use web logins. It forwards only those three requests, rebuilt from
|
||||
//! their known fields, so the extension cannot reach Custos's other Domi requests through it. It refuses
|
||||
//! a pipe that is not served by custos.exe.
|
||||
|
||||
use std::io::{self, Write};
|
||||
|
||||
use custos_browser::framing::{read_frame, write_frame};
|
||||
use serde_json::{Value, json};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
const PIPE: &str = r"\\.\pipe\custos-domi";
|
||||
const OPS: &[&str] = &["browser_status", "browser_match", "browser_fill"];
|
||||
|
||||
/// The request Custos gets: only known fields, of the right types.
|
||||
fn rebuild(msg: &[u8]) -> Result<Value, &'static str> {
|
||||
let v: Value = serde_json::from_slice(msg).map_err(|_| "bad_request")?;
|
||||
let op = v.get("op").and_then(Value::as_str).filter(|o| OPS.contains(o)).ok_or("bad_request")?;
|
||||
let mut out = json!({ "op": op, "app": "Custos for your browser" });
|
||||
if op != "browser_status" {
|
||||
let origin = v.get("origin").and_then(Value::as_str).filter(|o| o.len() <= 2048).ok_or("bad_request")?;
|
||||
out["origin"] = origin.into();
|
||||
}
|
||||
if op == "browser_fill" {
|
||||
let id = v.get("id").and_then(Value::as_str).filter(|i| i.len() <= 128).ok_or("bad_request")?;
|
||||
out["id"] = id.into();
|
||||
}
|
||||
// The extension's own request number comes back with the answer, so it can pair them.
|
||||
if let Some(n) = v.get("seq").and_then(Value::as_u64) {
|
||||
out["seq"] = n.into();
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn error(code: &str, seq: Option<u64>) -> Vec<u8> {
|
||||
serde_json::to_vec(&json!({ "ok": false, "error": code, "seq": seq })).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn answer(msg: &[u8], pipe: &str) -> Zeroizing<Vec<u8>> {
|
||||
let seq = serde_json::from_slice::<Value>(msg).ok().and_then(|v| v.get("seq").and_then(Value::as_u64));
|
||||
let req = match rebuild(msg) {
|
||||
Ok(r) => r,
|
||||
Err(code) => return Zeroizing::new(error(code, seq)),
|
||||
};
|
||||
let bytes = Zeroizing::new(serde_json::to_vec(&req).unwrap_or_default());
|
||||
match pipe::call(pipe, &bytes) {
|
||||
Ok(resp) => {
|
||||
// Custos does not know the extension's request number: put it back.
|
||||
let Ok(mut v) = serde_json::from_slice::<Value>(&resp) else {
|
||||
return Zeroizing::new(error("bad_answer", seq));
|
||||
};
|
||||
if let (Some(obj), Some(n)) = (v.as_object_mut(), seq) {
|
||||
obj.insert("seq".into(), n.into());
|
||||
}
|
||||
let out = Zeroizing::new(serde_json::to_vec(&v).unwrap_or_default());
|
||||
zeroize_json(v);
|
||||
out
|
||||
}
|
||||
Err(code) => Zeroizing::new(error(code, seq)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Wipes the strings of a parsed answer (it can hold a password) before dropping it.
|
||||
fn zeroize_json(v: Value) {
|
||||
use zeroize::Zeroize;
|
||||
match v {
|
||||
Value::String(mut s) => s.zeroize(),
|
||||
Value::Array(a) => a.into_iter().for_each(zeroize_json),
|
||||
Value::Object(o) => o.into_iter().for_each(|(_, v)| zeroize_json(v)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Tests point the host at another Custos.
|
||||
let pipe = std::env::var("CUSTOS_PIPE").unwrap_or_else(|_| PIPE.to_string());
|
||||
let (mut stdin, stdout) = (io::stdin().lock(), io::stdout());
|
||||
loop {
|
||||
let msg = match read_frame(&mut stdin) {
|
||||
Ok(Some(m)) => m,
|
||||
// The extension disconnected, or sent something that is not a frame: done.
|
||||
Ok(None) | Err(_) => return,
|
||||
};
|
||||
let out = answer(&msg, &pipe);
|
||||
let mut w = stdout.lock();
|
||||
if write_frame(&mut w, &out).is_err() || w.flush().is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod pipe {
|
||||
use std::time::Duration;
|
||||
|
||||
use windows_sys::Win32::Foundation::{
|
||||
CloseHandle, ERROR_FILE_NOT_FOUND, ERROR_PIPE_BUSY, GENERIC_READ, GENERIC_WRITE, GetLastError, HANDLE,
|
||||
INVALID_HANDLE_VALUE,
|
||||
};
|
||||
use windows_sys::Win32::Storage::FileSystem::{CreateFileW, OPEN_EXISTING, ReadFile, WriteFile};
|
||||
use windows_sys::Win32::System::Pipes::{
|
||||
GetNamedPipeServerProcessId, PIPE_READMODE_MESSAGE, SetNamedPipeHandleState, WaitNamedPipeW,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,
|
||||
};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
struct Handle(HANDLE);
|
||||
impl Drop for Handle {
|
||||
fn drop(&mut self) {
|
||||
unsafe { CloseHandle(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
fn server_exe(h: HANDLE) -> Option<String> {
|
||||
unsafe {
|
||||
let mut pid = 0u32;
|
||||
if GetNamedPipeServerProcessId(h, &mut pid) == 0 {
|
||||
return None;
|
||||
}
|
||||
let p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
|
||||
if p.is_null() {
|
||||
return None;
|
||||
}
|
||||
let p = Handle(p);
|
||||
let mut buf = vec![0u16; 1024];
|
||||
let mut len = buf.len() as u32;
|
||||
let ok = QueryFullProcessImageNameW(p.0, 0, buf.as_mut_ptr(), &mut len);
|
||||
(ok != 0).then(|| String::from_utf16_lossy(&buf[..len as usize]))
|
||||
}
|
||||
}
|
||||
|
||||
/// One request, one answer. The error is a code the extension shows as a sentence.
|
||||
pub fn call(name: &str, request: &[u8]) -> Result<Zeroizing<Vec<u8>>, &'static str> {
|
||||
let w = wide(name);
|
||||
unsafe {
|
||||
let mut h = INVALID_HANDLE_VALUE;
|
||||
// Busy: every instance is in use. Not found: Custos is between instances for a moment, or not running.
|
||||
for _ in 0..50 {
|
||||
h = CreateFileW(
|
||||
w.as_ptr(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
0,
|
||||
std::ptr::null(),
|
||||
OPEN_EXISTING,
|
||||
0,
|
||||
std::ptr::null_mut(),
|
||||
);
|
||||
if h != INVALID_HANDLE_VALUE {
|
||||
break;
|
||||
}
|
||||
match GetLastError() {
|
||||
ERROR_PIPE_BUSY => {
|
||||
WaitNamedPipeW(w.as_ptr(), 200);
|
||||
}
|
||||
ERROR_FILE_NOT_FOUND => std::thread::sleep(Duration::from_millis(20)),
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
if h == INVALID_HANDLE_VALUE {
|
||||
return Err("not_running");
|
||||
}
|
||||
let h = Handle(h);
|
||||
// Anything else serving this pipe could collect passwords: only custos.exe gets the request.
|
||||
if !server_exe(h.0).unwrap_or_default().to_lowercase().ends_with("\\custos.exe") {
|
||||
return Err("not_custos");
|
||||
}
|
||||
let mode = PIPE_READMODE_MESSAGE;
|
||||
SetNamedPipeHandleState(h.0, &mode, std::ptr::null(), std::ptr::null());
|
||||
let mut n = 0u32;
|
||||
if WriteFile(h.0, request.as_ptr(), request.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
|
||||
return Err("not_running");
|
||||
}
|
||||
let mut buf = Zeroizing::new(vec![0u8; 64 * 1024]);
|
||||
if ReadFile(h.0, buf.as_mut_ptr(), buf.len() as u32, &mut n, std::ptr::null_mut()) == 0 {
|
||||
return Err("no_answer");
|
||||
}
|
||||
buf.truncate(n as usize);
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod pipe {
|
||||
pub fn call(_: &str, _: &[u8]) -> Result<zeroize::Zeroizing<Vec<u8>>, &'static str> {
|
||||
Err("not_running")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_the_three_browser_requests_pass_rebuilt_from_known_fields() {
|
||||
let fill = rebuild(br#"{"op":"browser_fill","id":"abc","origin":"https://github.com","seq":7,"ref":"domi://arca/x","namespace":"arca"}"#).unwrap();
|
||||
assert_eq!(
|
||||
fill,
|
||||
json!({ "op": "browser_fill", "id": "abc", "origin": "https://github.com", "seq": 7, "app": "Custos for your browser" })
|
||||
);
|
||||
assert_eq!(rebuild(br#"{"op":"browser_status"}"#).unwrap()["op"], "browser_status");
|
||||
assert!(rebuild(br#"{"op":"browser_match","origin":"https://a.cz"}"#).is_ok());
|
||||
// Custos's other Domi requests never pass through the browser's host.
|
||||
for other in [
|
||||
r#"{"op":"get","ref":"domi://arca/rclone-config-pass"}"#,
|
||||
r#"{"op":"list","namespace":"arca"}"#,
|
||||
r#"{"op":"set","ref":"domi://x/y","value":"v"}"#,
|
||||
r#"{"op":"subkey"}"#,
|
||||
] {
|
||||
assert_eq!(rebuild(other.as_bytes()), Err("bad_request"), "{other}");
|
||||
}
|
||||
// Missing or wrong fields.
|
||||
assert!(rebuild(br#"{"op":"browser_fill","origin":"https://a.cz"}"#).is_err());
|
||||
assert!(rebuild(br#"{"op":"browser_match","origin":5}"#).is_err());
|
||||
assert!(rebuild(b"not json").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_custos_the_answer_says_so_and_keeps_the_request_number() {
|
||||
let out = answer(br#"{"op":"browser_status","seq":3}"#, r"\\.\pipe\custos-test-nobody-here");
|
||||
let v: Value = serde_json::from_slice(&out).unwrap();
|
||||
assert_eq!(v, json!({ "ok": false, "error": "not_running", "seq": 3 }));
|
||||
let bad: Value = serde_json::from_slice(&answer(br#"{"op":"get","seq":4}"#, PIPE)).unwrap();
|
||||
assert_eq!(bad, json!({ "ok": false, "error": "bad_request", "seq": 4 }));
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,11 @@ pub enum Action {
|
||||
UnattendedSigned,
|
||||
/// *Take over the vault*: a master password added, the PC-only access removed.
|
||||
TakenOver,
|
||||
/// A standing approval was granted on a card (core 0.16.0; `detail`: the rule's repository, key, kind, pipeline
|
||||
/// and origin). Written by [`Vault::standing_grant`] only.
|
||||
StandingGranted,
|
||||
/// A standing approval was revoked (`detail`: the same). Written by [`Vault::standing_revoke`] only.
|
||||
StandingRevoked,
|
||||
}
|
||||
|
||||
/// What *Connect via SSH* needs.
|
||||
@@ -232,6 +237,20 @@ impl State {
|
||||
trim(&mut self.audit);
|
||||
}
|
||||
|
||||
/// Whether a checklist item is ticked.
|
||||
pub(crate) fn is_ticked(&self, item: Item) -> bool {
|
||||
self.ticked.contains(&item)
|
||||
}
|
||||
|
||||
/// `standing-granted` or `standing-revoked`, with the rule as its detail (cut to what a note may hold).
|
||||
pub(crate) fn standing_note(&mut self, action: Action, detail: &str, now: i64) {
|
||||
debug_assert!(matches!(action, Action::StandingGranted | Action::StandingRevoked));
|
||||
let detail: String = detail.chars().filter(|c| !c.is_control()).take(500).collect();
|
||||
self.notice_expiry(now);
|
||||
self.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail) });
|
||||
trim(&mut self.audit);
|
||||
}
|
||||
|
||||
/// Before any change: a window that ended on its own is written down once, as `setup-expired` at `now` and
|
||||
/// `finished` = `until`.
|
||||
fn notice_expiry(&mut self, now: i64) {
|
||||
@@ -724,6 +743,83 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A vault whose release key has signed once and has one standing approval, used once (core 0.16.0).
|
||||
fn vault_with_a_standing_approval() -> Vault {
|
||||
use crate::signing::{Approval, Context, Request, Role, SignKind, Via};
|
||||
let mut v = vault();
|
||||
v.signing_create(Role::Release, &["release".to_string()], &["Arca".to_string()], NOW).unwrap();
|
||||
let r = Request {
|
||||
key: "domi-release".into(),
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![1; 64],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: Some("r-42".into()),
|
||||
context: Context {
|
||||
repo: "Arca".into(),
|
||||
pipeline: "release".into(),
|
||||
file: "a.exe".into(),
|
||||
..Default::default()
|
||||
},
|
||||
via: Via::Local,
|
||||
};
|
||||
v.signing_sign(&r, Approval::Mark, NOW).unwrap();
|
||||
v.standing_grant(&r, NOW + 1).unwrap();
|
||||
v.signing_sign(&r, Approval::Standing, NOW + 2).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_reader_refuses_a_vault_in_which_a_standing_approval_was_granted() {
|
||||
let v = vault_with_a_standing_approval();
|
||||
let json = body_json(&v);
|
||||
assert!(json.contains(r#""standing":[{"id":""#) && json.contains(r#""outcome":"standing""#), "{json}");
|
||||
assert!(json.contains(r#""action":"standing-granted""#), "{json}");
|
||||
// Core 0.11.0 does not know the outcome or the action: it refuses the file rather than misread it.
|
||||
assert!(serde_json::from_str::<BodyV0_11>(&json).is_err());
|
||||
// The rules alone it would ignore: with the outcome it knows, its signing parser takes the member.
|
||||
let plain = json.replace(r#""outcome":"standing""#, r#""outcome":"approved""#);
|
||||
let body: serde_json::Value = serde_json::from_str(&plain).unwrap();
|
||||
let old: SigningV0_11 = serde_json::from_value(body["signing"].clone()).unwrap();
|
||||
assert_eq!(old.audit.len(), 2);
|
||||
// This core reads it back the same.
|
||||
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.standing_rules(), v.standing_rules());
|
||||
assert_eq!(back.standing_rules()[0].uses, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_standing_approval_makes_the_vault_refuse_to_open() {
|
||||
let v = vault_with_a_standing_approval();
|
||||
let json = body_json(&v);
|
||||
assert!(Vault::open(&with_body(&v, &json), &SecretString::from("pw")).is_ok());
|
||||
let id = v.standing_rules()[0].id.clone();
|
||||
let shape = r#""kind":"minisign","pipeline":"release","via":"local""#;
|
||||
let cases = [
|
||||
// A rule edited to name another repository, pipeline, kind or origin no longer has its id.
|
||||
(
|
||||
r#""repo":"Arca","key":"domi-release","keyCreated""#.to_string(),
|
||||
r#""repo":"Fabrica","key":"domi-release","keyCreated""#.to_string(),
|
||||
),
|
||||
(shape.to_string(), r#""kind":"minisign","pipeline":"deploy","via":"local""#.to_string()),
|
||||
(shape.to_string(), r#""kind":"apk","pipeline":"release","via":"local""#.to_string()),
|
||||
(shape.to_string(), r#""kind":"minisign","pipeline":"release","via":"remote""#.to_string()),
|
||||
(shape.to_string(), r#""kind":"sigstore","pipeline":"release","via":"local""#.to_string()),
|
||||
(format!(r#""id":"{id}""#), r#""id":"0000000000000000""#.to_string()),
|
||||
// Targets belong to approvals only.
|
||||
(
|
||||
r#""via":"local","granted""#.to_string(),
|
||||
r#""via":"local","targets":["deploy to nixos-vm"],"granted""#.to_string(),
|
||||
),
|
||||
];
|
||||
for (from, to) in cases {
|
||||
assert!(json.contains(&from), "{from} in {json}");
|
||||
let bad = json.replacen(&from, &to, 1);
|
||||
let r = Vault::open(&with_body(&v, &bad), &SecretString::from("pw"));
|
||||
assert!(matches!(r, Err(Error::Corrupted)), "{to}: {r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_or_broken_security_values_make_the_vault_refuse_to_open() {
|
||||
let mut v = vault();
|
||||
|
||||
@@ -116,12 +116,16 @@ pub enum Approval {
|
||||
Mark,
|
||||
/// Nobody was asked: allowed for test keys only.
|
||||
Auto,
|
||||
/// Nobody was asked: a standing approval Mark granted fits the request (core 0.16.0). Refused when none does.
|
||||
Standing,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Outcome {
|
||||
Approved,
|
||||
/// Signed without asking: a standing approval fitted (core 0.16.0).
|
||||
Standing,
|
||||
Auto,
|
||||
Refused,
|
||||
Expired,
|
||||
@@ -151,6 +155,34 @@ pub struct AuditEntry {
|
||||
pub run: Option<String>,
|
||||
}
|
||||
|
||||
/// A standing approval (core 0.16.0, docs/SIGNING.md): what Mark allowed for good, when, and how often it was used.
|
||||
/// Nothing in it is secret.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct StandingRule {
|
||||
/// 16 hex characters: the SHA-256 of repo, key, kind, pipeline and via, joined by newlines, cut short.
|
||||
pub id: String,
|
||||
pub repo: String,
|
||||
pub key: String,
|
||||
/// The key's `created`: a key made later under the same id does not inherit the rule.
|
||||
pub key_created: i64,
|
||||
pub kind: SignKind,
|
||||
pub pipeline: String,
|
||||
pub via: Via,
|
||||
/// For an approval: the deploy targets the rule was granted for.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub targets: Vec<String>,
|
||||
/// Unix milliseconds.
|
||||
pub granted: i64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub last_used: Option<i64>,
|
||||
#[serde(default)]
|
||||
pub uses: u64,
|
||||
}
|
||||
|
||||
/// At most this many standing approvals in a vault.
|
||||
pub const STANDING_MAX: usize = 256;
|
||||
|
||||
/// A signature handed back to the build.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Signed {
|
||||
@@ -213,6 +245,7 @@ impl fmt::Debug for Key {
|
||||
pub(crate) struct Store {
|
||||
keys: Vec<Key>,
|
||||
audit: Vec<AuditEntry>,
|
||||
standing: Vec<StandingRule>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
@@ -244,6 +277,9 @@ pub(crate) struct StoreJson {
|
||||
keys: Vec<KeyJson>,
|
||||
#[serde(default)]
|
||||
audit: Vec<AuditEntry>,
|
||||
/// Standing approvals (core 0.16.0); absent while there are none.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
standing: Vec<StandingRule>,
|
||||
}
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
@@ -271,7 +307,7 @@ fn unhex8(s: &str) -> Option<[u8; 8]> {
|
||||
|
||||
impl Store {
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.keys.is_empty() && self.audit.is_empty()
|
||||
self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
|
||||
@@ -323,7 +359,10 @@ impl Store {
|
||||
repos: k.repos,
|
||||
});
|
||||
}
|
||||
Some(Store { keys, audit: j.audit })
|
||||
if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) {
|
||||
return None;
|
||||
}
|
||||
Some(Store { keys, audit: j.audit, standing: j.standing })
|
||||
}
|
||||
|
||||
pub(crate) fn json(&self) -> Option<StoreJson> {
|
||||
@@ -351,7 +390,7 @@ impl Store {
|
||||
repos: k.repos.clone(),
|
||||
})
|
||||
.collect();
|
||||
Some(StoreJson { keys, audit: self.audit.clone() })
|
||||
Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() })
|
||||
}
|
||||
|
||||
fn get(&self, id: &str) -> Option<&Key> {
|
||||
@@ -399,6 +438,52 @@ pub struct AndroidKey {
|
||||
pub repos: Vec<String>,
|
||||
}
|
||||
|
||||
/// A name in a rule: 1 to 100 characters, no control characters (as a key's scope lists hold them).
|
||||
fn name_ok(x: &str) -> bool {
|
||||
(1..=100).contains(&x.chars().count()) && !x.chars().any(char::is_control)
|
||||
}
|
||||
|
||||
fn kind_word(kind: SignKind) -> &'static str {
|
||||
match kind {
|
||||
SignKind::Minisign => "minisign",
|
||||
SignKind::Manifest => "manifest",
|
||||
SignKind::Authenticode => "authenticode",
|
||||
SignKind::Approval => "approval",
|
||||
SignKind::Apk => "apk",
|
||||
}
|
||||
}
|
||||
|
||||
fn via_word(via: Via) -> &'static str {
|
||||
match via {
|
||||
Via::Local => "local",
|
||||
Via::Remote => "remote",
|
||||
}
|
||||
}
|
||||
|
||||
/// A rule's id: one per repository, key, kind, pipeline and origin.
|
||||
fn rule_id(repo: &str, key: &str, kind: SignKind, pipeline: &str, via: Via) -> String {
|
||||
let joined = [repo, key, kind_word(kind), pipeline, via_word(via)].join("\n");
|
||||
custos_sign::sha256_hex(joined.as_bytes())[..16].to_string()
|
||||
}
|
||||
|
||||
/// A stored rule is what [`Vault::standing_grant`] could have written; anything else makes the vault refuse to open.
|
||||
fn rule_ok(r: &StandingRule) -> bool {
|
||||
r.id == rule_id(&r.repo, &r.key, r.kind, &r.pipeline, r.via)
|
||||
&& name_ok(&r.repo)
|
||||
&& name_ok(&r.pipeline)
|
||||
&& (1..=64).contains(&r.key.len())
|
||||
&& (r.via == Via::Local || r.kind == SignKind::Approval)
|
||||
&& (r.kind == SignKind::Approval) == !r.targets.is_empty()
|
||||
&& r.targets.len() <= 64
|
||||
&& r.targets.iter().all(|t| (1..=80).contains(&t.chars().count()) && !t.chars().any(char::is_control))
|
||||
}
|
||||
|
||||
/// What a rule says, for the security audit: names only.
|
||||
fn rule_words(r: &StandingRule) -> String {
|
||||
let targets = if r.targets.is_empty() { String::new() } else { format!(" ({} targets)", r.targets.len()) };
|
||||
format!("{} {} {} pipeline {} {}{targets}", r.repo, r.key, kind_word(r.kind), r.pipeline, via_word(r.via))
|
||||
}
|
||||
|
||||
fn in_scope(list: &[String], what: &str) -> bool {
|
||||
list.iter().any(|x| x == "*" || x == what)
|
||||
}
|
||||
@@ -426,7 +511,8 @@ impl Vault {
|
||||
repos: &[String],
|
||||
now: i64,
|
||||
) -> Result<Vec<String>, Error> {
|
||||
if self.signing.keys.iter().any(|k| k.role == role) {
|
||||
// An Android key (core 0.14.0) is a key of its own, not part of a set: it never counts as the set.
|
||||
if self.signing.keys.iter().any(|k| k.role == role && k.kind != KeyKind::Android) {
|
||||
return Err(Error::SigningExists(match role {
|
||||
Role::Release => "release",
|
||||
Role::Test => "test",
|
||||
@@ -499,7 +585,11 @@ impl Vault {
|
||||
if self.signing.get(APPROVE_KEY).is_some() {
|
||||
return Err(Error::SigningExists("approval"));
|
||||
}
|
||||
let release = self.signing.keys.iter().filter(|k| k.role == Role::Release && k.kind != KeyKind::RootCa);
|
||||
let release = self
|
||||
.signing
|
||||
.keys
|
||||
.iter()
|
||||
.filter(|k| k.role == Role::Release && !matches!(k.kind, KeyKind::RootCa | KeyKind::Android));
|
||||
let model = self
|
||||
.signing
|
||||
.get("domi-release")
|
||||
@@ -721,6 +811,12 @@ impl Vault {
|
||||
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
}
|
||||
let rule = self.standing_rule_for(req, now).map(|r| r.id);
|
||||
if approval == Approval::Standing && rule.is_none() {
|
||||
let r = Refusal::NeedsApproval(req.key.clone());
|
||||
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
}
|
||||
let k = self.signing.get(&req.key).expect("checked");
|
||||
let seconds = seconds(now);
|
||||
let bytes = match (&k.secret, req.kind) {
|
||||
@@ -760,15 +856,25 @@ impl Vault {
|
||||
}
|
||||
};
|
||||
let sha256 = custos_sign::sha256_hex(&bytes);
|
||||
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
|
||||
let outcome = match approval {
|
||||
Approval::Auto => Outcome::Auto,
|
||||
Approval::Mark => Outcome::Approved,
|
||||
Approval::Standing => Outcome::Standing,
|
||||
};
|
||||
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
|
||||
if let (Approval::Standing, Some(id)) = (approval, rule)
|
||||
&& let Some(r) = self.signing.standing.iter_mut().find(|r| r.id == id)
|
||||
{
|
||||
r.uses += 1;
|
||||
r.last_used = Some(now);
|
||||
}
|
||||
Ok(Signed { bytes, sha256 })
|
||||
}
|
||||
|
||||
/// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves.
|
||||
pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, now: i64) {
|
||||
let outcome = match outcome {
|
||||
Outcome::Approved | Outcome::Auto => Outcome::Refused,
|
||||
Outcome::Approved | Outcome::Auto | Outcome::Standing => Outcome::Refused,
|
||||
o => o,
|
||||
};
|
||||
self.signing_record(req, outcome, reason, None, now);
|
||||
@@ -822,6 +928,131 @@ impl Vault {
|
||||
});
|
||||
}
|
||||
|
||||
/// What a rule for `req` would name, when `req` could be signed and may be covered by one at all: the key's
|
||||
/// `created`, the repository and pipeline as the scope check reads them, and an approval's targets.
|
||||
fn standing_shape(&self, req: &Request, now: i64) -> Result<(i64, String, String, Vec<String>), Error> {
|
||||
let no = |why: &str| Error::Signing(why.into());
|
||||
let (view, approval) = self.check(req, now).map_err(|r| Error::Signing(r.to_string()))?;
|
||||
if req.run.is_none() {
|
||||
return Err(no("a standing approval is for requests that name a run"));
|
||||
}
|
||||
if req.via == Via::Remote && req.kind != SignKind::Approval {
|
||||
return Err(no("a release signature the server runner asks for always needs a card"));
|
||||
}
|
||||
if self.security.is_ticked(crate::security::Item::CardSigning) {
|
||||
return Err(no("Sign only with a card is ticked"));
|
||||
}
|
||||
let (repo, pipeline, targets) = match approval {
|
||||
Some(a) => (a.repo, a.pipeline, a.targets),
|
||||
None => (req.context.repo.clone(), req.context.pipeline.clone(), Vec::new()),
|
||||
};
|
||||
if !name_ok(&repo) || !name_ok(&pipeline) {
|
||||
return Err(no("the repository or pipeline is not a usable name"));
|
||||
}
|
||||
Ok((view.created, repo, pipeline, targets))
|
||||
}
|
||||
|
||||
/// Whether `req`, which Mark is approving on a card, may start a standing approval (docs/SIGNING.md, "Standing
|
||||
/// approvals"); the error says why not, in words for the card.
|
||||
pub fn standing_can_grant(&self, req: &Request, now: i64) -> Result<(), Error> {
|
||||
self.standing_shape(req, now)?;
|
||||
let k = self.signing.get(&req.key).expect("checked");
|
||||
if k.role != Role::Release {
|
||||
return Err(Error::Signing("a test key signs without asking: it needs no standing approval".into()));
|
||||
}
|
||||
// A key's first signature is never the one that starts a rule.
|
||||
let signed = |e: &AuditEntry| {
|
||||
e.key == k.id && e.at >= k.created && matches!(e.outcome, Outcome::Approved | Outcome::Standing)
|
||||
};
|
||||
if !self.signing.audit.iter().any(signed) {
|
||||
return Err(Error::Signing(format!(
|
||||
"`{}` has never signed: its first signature needs a card of its own",
|
||||
k.id
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Stores the standing approval for `req` (or adds an approval's targets to the one there is) and writes
|
||||
/// `standing-granted` to the security audit. Call it before signing the request Mark approved. The caller saves.
|
||||
pub fn standing_grant(&mut self, req: &Request, now: i64) -> Result<StandingRule, Error> {
|
||||
self.standing_can_grant(req, now)?;
|
||||
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now)?;
|
||||
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
|
||||
let at = self.signing.standing.iter().position(|r| r.id == id);
|
||||
// The same combination again keeps its rule (and its count) unless the key under that id is another one.
|
||||
let mut rule = match at.map(|i| self.signing.standing[i].clone()).filter(|r| r.key_created == key_created) {
|
||||
Some(r) => r,
|
||||
None => StandingRule {
|
||||
id,
|
||||
repo,
|
||||
key: req.key.clone(),
|
||||
key_created,
|
||||
kind: req.kind,
|
||||
pipeline,
|
||||
via: req.via,
|
||||
targets: Vec::new(),
|
||||
granted: now,
|
||||
last_used: None,
|
||||
uses: 0,
|
||||
},
|
||||
};
|
||||
// Any target Mark sees on this card joins the ones he allowed before.
|
||||
for t in targets {
|
||||
if !rule.targets.contains(&t) {
|
||||
rule.targets.push(t);
|
||||
}
|
||||
}
|
||||
// Never stored in a form this core would refuse to read back; what was there stays as it was.
|
||||
if !rule_ok(&rule) {
|
||||
return Err(Error::Signing("this request cannot be written as a standing approval".into()));
|
||||
}
|
||||
match at {
|
||||
Some(i) => self.signing.standing[i] = rule.clone(),
|
||||
None if self.signing.standing.len() >= STANDING_MAX => {
|
||||
return Err(Error::Signing("there are 256 standing approvals already: revoke one first".into()));
|
||||
}
|
||||
None => self.signing.standing.push(rule.clone()),
|
||||
}
|
||||
self.security.standing_note(crate::security::Action::StandingGranted, &rule_words(&rule), now);
|
||||
Ok(rule)
|
||||
}
|
||||
|
||||
/// The standing approval `req` fits, if one does: the request passes [`Vault::signing_check_at`], names a run,
|
||||
/// and equals the rule in repository, pipeline, key, kind and origin (an approval: its targets are the rule's).
|
||||
pub fn standing_rule_for(&self, req: &Request, now: i64) -> Option<StandingRule> {
|
||||
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now).ok()?;
|
||||
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
|
||||
self.signing
|
||||
.standing
|
||||
.iter()
|
||||
.find(|r| {
|
||||
r.id == id
|
||||
&& r.repo == repo
|
||||
&& r.key == req.key
|
||||
&& r.key_created == key_created
|
||||
&& r.kind == req.kind
|
||||
&& r.pipeline == pipeline
|
||||
&& r.via == req.via
|
||||
&& targets.iter().all(|t| r.targets.contains(t))
|
||||
})
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// The standing approvals, oldest first.
|
||||
pub fn standing_rules(&self) -> Vec<StandingRule> {
|
||||
self.signing.standing.clone()
|
||||
}
|
||||
|
||||
/// Removes a standing approval, audited `standing-revoked`. False when there is none with this id. The caller
|
||||
/// saves.
|
||||
pub fn standing_revoke(&mut self, id: &str, now: i64) -> bool {
|
||||
let Some(i) = self.signing.standing.iter().position(|r| r.id == id) else { return false };
|
||||
let rule = self.signing.standing.remove(i);
|
||||
self.security.standing_note(crate::security::Action::StandingRevoked, &rule_words(&rule), now);
|
||||
true
|
||||
}
|
||||
|
||||
/// Every request any key was named in, oldest first.
|
||||
pub fn signing_audit(&self) -> &[AuditEntry] {
|
||||
&self.signing.audit
|
||||
@@ -878,6 +1109,27 @@ mod tests {
|
||||
assert_eq!(back.signing_keys(), views);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_made_again_under_the_same_id_does_not_inherit_the_rule() {
|
||||
let mut v =
|
||||
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), 1).unwrap();
|
||||
let r = Request { run: Some("r-1".into()), ..req("domi-release", SignKind::Minisign, 64) };
|
||||
v.signing_sign(&r, Approval::Mark, 2).unwrap();
|
||||
v.standing_grant(&r, 3).unwrap();
|
||||
assert!(v.standing_rule_for(&r, 4).is_some());
|
||||
// The same id, made at another time (no API does this; a rule must not depend on that).
|
||||
v.signing.keys.iter_mut().find(|k| k.id == "domi-release").unwrap().created = 10;
|
||||
assert!(v.standing_rule_for(&r, 11).is_none(), "the rule names the key it was granted for");
|
||||
assert!(matches!(v.signing_sign(&r, Approval::Standing, 11), Err(Refusal::NeedsApproval(_))));
|
||||
// The old key's signatures do not count as the new key's first one either.
|
||||
assert!(v.standing_grant(&r, 12).is_err());
|
||||
v.signing_sign(&r, Approval::Mark, 13).unwrap();
|
||||
let again = v.standing_grant(&r, 14).unwrap();
|
||||
assert_eq!((again.key_created, again.granted, again.uses), (10, 14, 0));
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_api_path_returns_a_private_key() {
|
||||
let mut v =
|
||||
@@ -937,13 +1189,20 @@ mod tests {
|
||||
reqs.push(req("domi-code-signing", SignKind::Apk, 64));
|
||||
for r in &reqs {
|
||||
out += &format!("{:?}", v.signing_check(r));
|
||||
for approval in [Approval::Mark, Approval::Auto] {
|
||||
for approval in [Approval::Mark, Approval::Auto, Approval::Standing] {
|
||||
match v.signing_sign(r, approval, 2) {
|
||||
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
|
||||
Err(e) => out += &format!("{e:?}{e}"),
|
||||
}
|
||||
// A standing approval for the same request with a run, once the key has signed (core 0.16.0).
|
||||
let with_run = Request { run: r.run.clone().or(Some("r-1".into())), ..r.clone() };
|
||||
out += &format!("{:?}{:?}", v.standing_can_grant(&with_run, 2), v.standing_grant(&with_run, 2));
|
||||
out += &format!("{:?}", v.standing_rule_for(&with_run, 2));
|
||||
}
|
||||
}
|
||||
assert!(v.standing_rules().len() >= 3, "rules were granted: {:?}", v.standing_rules());
|
||||
out += &serde_json::to_string(&v.standing_rules()).unwrap();
|
||||
out += &format!("{:?}{:?}", v.standing_rules(), v.security_view(3).audit);
|
||||
assert!(
|
||||
v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved),
|
||||
"an approval was signed too"
|
||||
|
||||
@@ -246,3 +246,20 @@ fn apk_requests_are_never_signed_unattended_even_on_the_hands_off_vault() {
|
||||
assert!(security::unattended_sign(level, &BTreeSet::new(), true, "authenticode", true));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_android_key_made_first_does_not_count_as_the_release_or_test_set() {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW).unwrap();
|
||||
v.signing_create_android(&spec("domi-test-android", Role::Test, &["*"], &["*"]), NOW).unwrap();
|
||||
// No release set yet: there is nothing to add an approval key to, and the Android key is no model for one.
|
||||
assert!(matches!(v.signing_add_approve(NOW), Err(Error::Signing(_))));
|
||||
let ids = v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap();
|
||||
assert_eq!(ids, ["domi-release", "domi-root", "domi-code-signing", "domi-approve"]);
|
||||
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
|
||||
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
|
||||
let keys = v.signing_keys();
|
||||
let approve = keys.iter().find(|k| k.id == "domi-approve").unwrap();
|
||||
assert_eq!(approve.repos, s(&["Arca"]), "the release set's scope, not Postea's");
|
||||
assert_eq!(keys.len(), 9);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
//! Standing approvals (core 0.16.0, docs/SIGNING.md "Standing approvals"): a rule Mark grants from a request he is
|
||||
//! approving, for one repository, key, kind, pipeline and origin. A later request that fits is signed without
|
||||
//! asking and recorded as `standing`; everything else still needs him.
|
||||
|
||||
use custos_vault::security::{Action, Auth, Item};
|
||||
use custos_vault::signing::{AndroidKey, Approval, Context, Outcome, Refusal, Request, Role, SignKind, Via};
|
||||
use custos_vault::{KdfParams, SecretString, Vault};
|
||||
|
||||
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
const NOW: i64 = 1_793_750_000_000;
|
||||
const COMMIT: &str = "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1";
|
||||
|
||||
fn s(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
/// The release set for the pipelines `release` and `deploy` of Arca, Aula and Fabrica, and the test set.
|
||||
fn vault() -> Vault {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.signing_create(Role::Release, &s(&["release", "deploy"]), &s(&["Arca", "Aula", "Fabrica"]), NOW).unwrap();
|
||||
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
fn ctx(pipeline: &str, repo: &str) -> Context {
|
||||
Context {
|
||||
repo: repo.into(),
|
||||
commit: COMMIT.into(),
|
||||
pipeline: pipeline.into(),
|
||||
step: "sign".into(),
|
||||
trigger: "tag".into(),
|
||||
file: "Arca_0.7.0_x64-setup.exe".into(),
|
||||
size: 25_145_977,
|
||||
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
|
||||
version: "0.7.0".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn minisign(repo: &str, pipeline: &str, run: &str) -> Request {
|
||||
Request {
|
||||
key: "domi-release".into(),
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![7; 64],
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: Some(run.into()),
|
||||
context: ctx(pipeline, repo),
|
||||
via: Via::Local,
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticode(repo: &str, run: &str) -> Request {
|
||||
Request {
|
||||
key: "domi-code-signing".into(),
|
||||
kind: SignKind::Authenticode,
|
||||
digest: vec![9; 32],
|
||||
..minisign(repo, "release", run)
|
||||
}
|
||||
}
|
||||
|
||||
fn approval(repo: &str, run: &str, targets: &[&str], via: Via) -> Request {
|
||||
let targets = targets.iter().map(|t| format!("\"{t}\"")).collect::<Vec<_>>().join(",");
|
||||
let text = format!(
|
||||
r#"{{"v":1,"run":"{run}","repo":"{repo}","commit":"{COMMIT}","pipeline":"deploy","version":"0.7.0","targets":[{targets}],"expires":{}}}"#,
|
||||
NOW / 1000 + 600
|
||||
);
|
||||
Request {
|
||||
key: "domi-approve".into(),
|
||||
kind: SignKind::Approval,
|
||||
digest: vec![],
|
||||
manifest: None,
|
||||
approval: Some(text),
|
||||
run: Some(run.into()),
|
||||
context: Context {
|
||||
repo: repo.into(),
|
||||
pipeline: "deploy".into(),
|
||||
trigger: "manual".into(),
|
||||
..Default::default()
|
||||
},
|
||||
via,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark approves `req` on a card (the key's signature that must come before any rule).
|
||||
fn mark_signs(v: &mut Vault, req: &Request) {
|
||||
v.signing_sign(req, Approval::Mark, NOW).expect("signed with Mark's click");
|
||||
}
|
||||
|
||||
/// Mark approves `req` with *Always allow*: the rule first, then the signature.
|
||||
fn always(v: &mut Vault, req: &Request) -> String {
|
||||
let rule = v.standing_grant(req, NOW + 1).expect("granted");
|
||||
v.signing_sign(req, Approval::Mark, NOW + 1).unwrap();
|
||||
rule.id
|
||||
}
|
||||
|
||||
fn outcomes(v: &Vault) -> Vec<Outcome> {
|
||||
v.signing_audit().iter().map(|e| e.outcome).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_granted_rule_signs_the_next_matching_request_and_records_it() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
assert!(v.standing_rules().is_empty());
|
||||
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-2"), NOW).is_none(), "nothing fits before a grant");
|
||||
|
||||
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
let rules = v.standing_rules();
|
||||
assert_eq!(rules.len(), 1);
|
||||
let r = &rules[0];
|
||||
assert_eq!(
|
||||
(r.id.as_str(), r.repo.as_str(), r.key.as_str(), r.pipeline.as_str()),
|
||||
(id.as_str(), "Arca", "domi-release", "release")
|
||||
);
|
||||
assert_eq!((r.kind, r.via, r.granted, r.uses, r.last_used), (SignKind::Minisign, Via::Local, NOW + 1, 0, None));
|
||||
|
||||
// The next run: it fits, and signing with the rule records everything an approved entry holds.
|
||||
let next = minisign("Arca", "release", "r-3");
|
||||
assert_eq!(v.standing_rule_for(&next, NOW + 5).map(|r| r.id), Some(id.clone()));
|
||||
let signed = v.signing_sign(&next, Approval::Standing, NOW + 5).expect("signed by the rule");
|
||||
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Approved, Outcome::Standing]);
|
||||
let e = v.signing_audit().last().unwrap().clone();
|
||||
assert_eq!(e.context, ctx("release", "Arca"));
|
||||
assert_eq!(
|
||||
(e.key.as_str(), e.kind, e.via, e.run.as_deref(), e.at),
|
||||
("domi-release", SignKind::Minisign, Via::Local, Some("r-3"), NOW + 5)
|
||||
);
|
||||
assert_eq!(e.signature.as_deref(), Some(signed.sha256.as_str()));
|
||||
let r = &v.standing_rules()[0];
|
||||
assert_eq!((r.uses, r.last_used), (1, Some(NOW + 5)));
|
||||
|
||||
// Granting the same thing again makes no second rule and keeps the count.
|
||||
assert_eq!(v.standing_grant(&minisign("Arca", "release", "r-4"), NOW + 9).unwrap().id, id);
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
assert_eq!(v.standing_rules()[0].uses, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_repository_key_kind_pipeline_or_origin_does_not_fit() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
mark_signs(&mut v, &authenticode("Arca", "r-1"));
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
assert!(v.standing_rule_for(&minisign("Arca", "release", "r-3"), NOW).is_some());
|
||||
|
||||
let sums = format!("{} Arca_0.7.0_x64-setup.exe\n", "c".repeat(64));
|
||||
let cases: [(&str, Request); 5] = [
|
||||
("another repository", minisign("Fabrica", "release", "r-3")),
|
||||
("another pipeline", minisign("Arca", "deploy", "r-3")),
|
||||
("another key and kind", authenticode("Arca", "r-3")),
|
||||
(
|
||||
"another kind of the same key",
|
||||
Request {
|
||||
kind: SignKind::Manifest,
|
||||
digest: vec![],
|
||||
manifest: Some(sums),
|
||||
..minisign("Arca", "release", "r-3")
|
||||
},
|
||||
),
|
||||
("the server runner", Request { via: Via::Remote, ..minisign("Arca", "release", "r-3") }),
|
||||
];
|
||||
for (what, req) in cases {
|
||||
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}: the key itself would sign it");
|
||||
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
|
||||
let r = v.signing_sign(&req, Approval::Standing, NOW);
|
||||
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{what}: {r:?}");
|
||||
}
|
||||
assert_eq!(v.standing_rules()[0].uses, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_out_of_the_keys_scope_never_fits_and_narrowing_the_scope_stops_the_rule() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
// Out of scope today: no rule can be made for it.
|
||||
assert!(v.standing_grant(&minisign("Postea", "release", "r-2"), NOW).is_err());
|
||||
assert!(v.standing_grant(&minisign("Arca", "nightly", "r-2"), NOW).is_err());
|
||||
assert!(v.standing_rules().is_empty());
|
||||
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
// Mark narrows the key: Arca may no longer use it. The rule is still listed and no longer fits.
|
||||
v.signing_set_scope("domi-release", &s(&["release"]), &s(&["Fabrica"])).unwrap();
|
||||
let req = minisign("Arca", "release", "r-3");
|
||||
assert!(v.standing_rule_for(&req, NOW).is_none());
|
||||
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW), Err(Refusal::OutOfScope(_))));
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_request_without_a_run_never_fits() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let no_run = Request { run: None, ..minisign("Arca", "release", "x") };
|
||||
assert!(v.standing_grant(&no_run, NOW).is_err(), "and cannot start a rule");
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
assert!(v.standing_rule_for(&no_run, NOW).is_none());
|
||||
assert!(matches!(v.signing_sign(&no_run, Approval::Standing, NOW), Err(Refusal::NeedsApproval(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_keys_first_signature_cannot_start_a_rule() {
|
||||
let mut v = vault();
|
||||
let first = minisign("Arca", "release", "r-1");
|
||||
assert!(v.standing_can_grant(&first, NOW).is_err());
|
||||
assert!(v.standing_grant(&first, NOW).is_err(), "the key has never signed");
|
||||
assert!(v.standing_rules().is_empty());
|
||||
// A refused or expired card is not a signature either.
|
||||
v.signing_refuse(&first, Outcome::Refused, None, NOW);
|
||||
assert!(v.standing_grant(&first, NOW).is_err());
|
||||
// Mark signs once on the card; from then on the key can have a rule.
|
||||
mark_signs(&mut v, &first);
|
||||
assert!(v.standing_can_grant(&minisign("Arca", "release", "r-2"), NOW).is_ok());
|
||||
// Another key of the same vault has still never signed.
|
||||
assert!(v.standing_grant(&authenticode("Arca", "r-2"), NOW).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_test_key_and_a_server_runners_release_signature_cannot_start_a_rule() {
|
||||
let mut v = vault();
|
||||
let test = Request {
|
||||
key: "domi-test".into(),
|
||||
context: Context { trigger: "push".into(), ..ctx("ci", "Arca") },
|
||||
..minisign("Arca", "ci", "r-1")
|
||||
};
|
||||
v.signing_sign(&test, Approval::Auto, NOW).unwrap();
|
||||
assert!(v.standing_grant(&test, NOW).is_err(), "a test key signs without asking anyway");
|
||||
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let remote = Request { via: Via::Remote, ..minisign("Arca", "release", "r-2") };
|
||||
assert!(v.standing_can_grant(&remote, NOW).is_err());
|
||||
assert!(v.standing_grant(&remote, NOW).is_err(), "a release signature asked through the mailbox");
|
||||
assert!(v.standing_rules().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_approval_rule_holds_only_for_the_targets_it_was_granted_for() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
|
||||
let id = always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
|
||||
let r = &v.standing_rules()[0];
|
||||
assert_eq!((r.repo.as_str(), r.pipeline.as_str(), r.via), ("Aula", "deploy", Via::Remote));
|
||||
assert_eq!(r.targets, s(&["deploy to nixos-vm"]));
|
||||
|
||||
assert!(v.standing_rule_for(&approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Remote), NOW).is_some());
|
||||
// A target Mark has not seen, alone or next to the known one; another repository; the same from this PC.
|
||||
for (what, req) in [
|
||||
("a new target", approval("Aula", "r-3", &["publish to Aula"], Via::Remote)),
|
||||
(
|
||||
"a new target next to the old",
|
||||
approval("Aula", "r-3", &["deploy to nixos-vm", "publish to Aula"], Via::Remote),
|
||||
),
|
||||
("another repository", approval("Arca", "r-3", &["deploy to nixos-vm"], Via::Remote)),
|
||||
("this PC's pipe", approval("Aula", "r-3", &["deploy to nixos-vm"], Via::Local)),
|
||||
] {
|
||||
assert!(v.signing_check_at(&req, NOW).is_ok(), "{what}");
|
||||
assert!(v.standing_rule_for(&req, NOW).is_none(), "{what}");
|
||||
}
|
||||
// Granting again on a card that shows the new target adds it to the same rule.
|
||||
let wider = approval("Aula", "r-4", &["deploy to nixos-vm", "publish to Aula"], Via::Remote);
|
||||
assert_eq!(always(&mut v, &wider), id);
|
||||
assert_eq!(v.standing_rules().len(), 1);
|
||||
assert_eq!(v.standing_rules()[0].targets, s(&["deploy to nixos-vm", "publish to Aula"]));
|
||||
let signed =
|
||||
v.signing_sign(&approval("Aula", "r-5", &["publish to Aula"], Via::Remote), Approval::Standing, NOW + 9);
|
||||
assert!(signed.is_ok(), "{signed:?}");
|
||||
assert_eq!(v.signing_audit().last().unwrap().context.file, "approval-r-5.json");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_only_with_a_card_pauses_every_rule() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
let req = minisign("Arca", "release", "r-3");
|
||||
|
||||
v.security_tick(Item::CardSigning, NOW + 2);
|
||||
assert!(v.standing_rule_for(&req, NOW + 3).is_none());
|
||||
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 3), Err(Refusal::NeedsApproval(_))));
|
||||
assert!(v.standing_can_grant(&req, NOW + 3).is_err(), "and no new rule while it is ticked");
|
||||
assert_eq!(v.standing_rules().len(), 1, "the rule is kept, paused");
|
||||
// Other checklist items do not pause it.
|
||||
v.security_untick(Item::CardSigning, Auth::Hello, NOW + 4);
|
||||
v.security_tick(Item::NoAutoConnect, NOW + 4);
|
||||
assert!(v.standing_rule_for(&req, NOW + 5).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_revoked_rule_no_longer_fits_and_both_are_in_the_security_audit() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let id = always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
assert!(!v.standing_revoke("0000000000000000", NOW + 2), "no such rule");
|
||||
assert!(v.standing_revoke(&id, NOW + 3));
|
||||
assert!(!v.standing_revoke(&id, NOW + 4), "once");
|
||||
assert!(v.standing_rules().is_empty());
|
||||
|
||||
let req = minisign("Arca", "release", "r-3");
|
||||
assert!(v.standing_rule_for(&req, NOW + 5).is_none());
|
||||
assert!(matches!(v.signing_sign(&req, Approval::Standing, NOW + 5), Err(Refusal::NeedsApproval(_))));
|
||||
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
|
||||
|
||||
let notes: Vec<(Action, String)> = v
|
||||
.security_view(NOW + 6)
|
||||
.audit
|
||||
.into_iter()
|
||||
.filter(|e| matches!(e.action, Action::StandingGranted | Action::StandingRevoked))
|
||||
.map(|e| (e.action, e.detail.unwrap_or_default()))
|
||||
.collect();
|
||||
assert_eq!(notes.len(), 2, "{notes:?}");
|
||||
assert_eq!(notes[0].0, Action::StandingGranted);
|
||||
assert_eq!(notes[1].0, Action::StandingRevoked);
|
||||
for (_, d) in ¬es {
|
||||
assert!(
|
||||
d.contains("Arca") && d.contains("domi-release") && d.contains("minisign") && d.contains("release"),
|
||||
"{d}"
|
||||
);
|
||||
}
|
||||
// The public note call cannot write them.
|
||||
assert!(v.security_note(Action::StandingGranted, "x", NOW).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rules_and_the_standing_outcome_survive_a_reopen() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
mark_signs(&mut v, &approval("Aula", "r-1", &["deploy to nixos-vm"], Via::Remote));
|
||||
always(&mut v, &minisign("Arca", "release", "r-2"));
|
||||
always(&mut v, &approval("Aula", "r-2", &["deploy to nixos-vm"], Via::Remote));
|
||||
v.signing_sign(&minisign("Arca", "release", "r-3"), Approval::Standing, NOW + 5).unwrap();
|
||||
|
||||
let mut back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.standing_rules(), v.standing_rules());
|
||||
assert_eq!(back.standing_rules().len(), 2);
|
||||
assert_eq!(back.signing_audit(), v.signing_audit());
|
||||
// After the restart the rule still answers, and still only what it was granted for.
|
||||
assert!(back.signing_sign(&minisign("Arca", "release", "r-4"), Approval::Standing, NOW + 9).is_ok());
|
||||
assert!(back.standing_rule_for(&minisign("Fabrica", "release", "r-4"), NOW + 9).is_none());
|
||||
assert_eq!(back.standing_rules().iter().find(|r| r.repo == "Arca").unwrap().uses, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_with_standing_and_no_rule_is_refused_and_recorded() {
|
||||
let mut v = vault();
|
||||
mark_signs(&mut v, &minisign("Arca", "release", "r-1"));
|
||||
let req = minisign("Arca", "release", "r-2");
|
||||
let r = v.signing_sign(&req, Approval::Standing, NOW);
|
||||
assert!(matches!(r, Err(Refusal::NeedsApproval(_))), "{r:?}");
|
||||
assert_eq!(outcomes(&v), [Outcome::Approved, Outcome::Refused]);
|
||||
assert!(v.signing_audit()[1].signature.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_android_keys_rule_signs_its_apks_and_nothing_else() {
|
||||
let spec = AndroidKey {
|
||||
id: "postea-android".into(),
|
||||
name: "Postea Android".into(),
|
||||
cn: "Postea".into(),
|
||||
o: "Marek Novak".into(),
|
||||
c: "CZ".into(),
|
||||
role: Role::Release,
|
||||
pipelines: s(&["release"]),
|
||||
repos: s(&["mnovak/Postea"]),
|
||||
};
|
||||
let apk = |run: &str| Request {
|
||||
key: "postea-android".into(),
|
||||
kind: SignKind::Apk,
|
||||
digest: vec![3; 128],
|
||||
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Postea") },
|
||||
..minisign("mnovak/Postea", "release", run)
|
||||
};
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.signing_create_android(&spec, NOW).unwrap();
|
||||
// The first signature (the card says so) cannot be the one that starts the rule.
|
||||
assert!(v.standing_grant(&apk("r-1"), NOW).is_err());
|
||||
mark_signs(&mut v, &apk("r-1"));
|
||||
always(&mut v, &apk("r-2"));
|
||||
let signed = v.signing_sign(&apk("r-3"), Approval::Standing, NOW + 2).expect("an APK fits its rule");
|
||||
assert_eq!(signed.bytes.len(), 2 * 512, "v2 and v3, RSA-4096");
|
||||
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Standing);
|
||||
// Postea's rule says nothing about another repository: that is out of the key's scope, as before.
|
||||
let other = Request {
|
||||
context: Context { file: "Postea-1.0.0.apk".into(), ..ctx("release", "mnovak/Other") },
|
||||
..apk("r-4")
|
||||
};
|
||||
assert!(matches!(v.signing_sign(&other, Approval::Standing, NOW + 3), Err(Refusal::OutOfScope(_))));
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
# Custos in the browser
|
||||
|
||||
Version 1 of the browser extension: Chromium (Edge and Chrome) on Windows, logins only. Passkeys come later.
|
||||
The extension, its native host and the rule that decides which login belongs on which page are all in this
|
||||
public repository, so anyone can read what the browser side does. The desktop app (the private `Custos`
|
||||
repo) holds the vault and answers the host; its side is `docs/13_browser.md` there.
|
||||
|
||||
```
|
||||
page ─(content script)─► service worker ─(native messaging)─► custos-native.exe ─(\\.\pipe\custos-domi)─► custos.exe
|
||||
extension/content.js extension/background.js crates/custos-native the desktop app
|
||||
```
|
||||
|
||||
## The pieces
|
||||
|
||||
| Piece | What it does | What it never does |
|
||||
|:--|:--|:--|
|
||||
| `extension/content.js` | Finds login fields (password, username next to one, one-time code); on focus shows a small Custos button in a **closed** shadow root; on click asks for the logins of *its own frame*, and fills the one the person picks. | Fill without a click; read anything from Custos before the list is opened; trust what the page says about its own address. |
|
||||
| `extension/popup.*` | The toolbar popup: the logins for the active tab; a click asks the top frame's content script to fill. | Receive a password: the content script asks for the secrets itself. |
|
||||
| `extension/background.js` | Owns the one connection to the native host; turns each request into `browser_status`, `browser_match` or `browser_fill`, with the origin taken from **`sender.url`** (the frame's real URL, as the browser reports it). | Accept messages from pages or other extensions (`sender.id` must be its own). |
|
||||
| `crates/custos-native` | The native messaging host. Reads frames from stdin, **rebuilds** each request from its known fields (op, origin ≤ 2 KiB, id ≤ 128 bytes, seq), forwards it to the Custos pipe and returns the answer. | Forward any other Domi op (`get`, `list`, `sign`, …); talk to a pipe served by anything but `custos.exe`; keep a secret after the answer is written (frames and parsed answers are zeroized). |
|
||||
| `crates/custos-browser` | `Origin::parse`, `login_matches`, `best_match` (which login fits which page) and the native messaging framing. The desktop uses the same crate, so both sides apply one rule. | Fuzzy matching of any kind. |
|
||||
|
||||
## Which login goes where (`custos-browser`)
|
||||
|
||||
A page's origin is `scheme://host[:port]`, host lowercased, trailing dot removed. A login's stored `url`
|
||||
fields (an item may have several) match a page when:
|
||||
|
||||
1. the page is **fillable**: `https`, or plain `http` only on this machine (`localhost`, `*.localhost`,
|
||||
`127.0.0.1`, `[::1]`). Plain http on the internet is never filled, even for a login saved with `http://`;
|
||||
2. the schemes are equal (a stored URL without a scheme means `https`);
|
||||
3. the ports are equal (the stored URL's port, or the scheme's default when it names none);
|
||||
4. the page's host is the login's host (**exact**; `www.` counts as the host) or a subdomain of it
|
||||
(**subdomain**: `accounts.github.com` for `github.com`). A login for a subdomain never goes to its parent
|
||||
or to a sibling. A login for an IP address or a bare name (`cz`) matches only that exact host.
|
||||
|
||||
URLs with userinfo (`https://bank.cz@evil.net`) are refused outright. Look-alikes (`github.com.evil.net`,
|
||||
`githuh.com`, punycode twins) never match, because nothing is compared but labels. Exact matches are offered
|
||||
before subdomain matches, then by title; at most 50 logins per page.
|
||||
|
||||
## The messages
|
||||
|
||||
Native messaging frames: a 4-byte little-endian length, then UTF-8 JSON. The host accepts at most 64 KiB per
|
||||
message (the desktop pipe's limit). Every request may carry `seq` (a number); the answer carries it back.
|
||||
|
||||
| Extension → host | Host → Custos | Answer |
|
||||
|:--|:--|:--|
|
||||
| `{"op":"browser_status"}` | `{"op":"browser_status","app":"Custos for your browser"}` | `{"ok":true}` |
|
||||
| `{"op":"browser_match","origin":"https://github.com"}` | + `origin` | `{"ok":true,"logins":[{"id","title","username"}]}`: never a password |
|
||||
| `{"op":"browser_fill","id":"…","origin":"…"}` | + `origin`, `id` | `{"ok":true,"username","password","totp"}` only if that login matches `origin`, else `"error":"no_match"` |
|
||||
|
||||
Errors the extension turns into a sentence: `not_connected` (no host registered), `not_running`,
|
||||
`not_custos` (the pipe's server is not `custos.exe`: nothing was sent), `locked`, `denied`, `not_found`,
|
||||
`no_match`, `no_answer`, `bad_request`.
|
||||
|
||||
## What Custos checks (the desktop's side, summarised)
|
||||
|
||||
- The host is a Domi client like any other: Custos identifies it by its executable and asks the person once
|
||||
whether it may use **`web-logins/`**. That grant is the browser's only; no `domi://` ref may use the
|
||||
`web-logins` namespace and the browser ops reach nothing else.
|
||||
- Custos parses the origin again with `custos-browser` and checks the login against it on **every**
|
||||
`browser_fill`, whatever the extension asked for before.
|
||||
- Only items of type *Web login* are offered. A locked Custos waits for the unlock (up to a minute), then
|
||||
answers `locked`.
|
||||
|
||||
## Registration and the extension id
|
||||
|
||||
The extension's `manifest.json` carries a public `key`, which fixes its id to
|
||||
**`jchkapmceepdnlhagfppeckggaecdcmn`** however it is loaded (unpacked or packed). The desktop's *Connect*
|
||||
writes the host manifest with `"allowed_origins": ["chrome-extension://jchkapmceepdnlhagfppeckggaecdcmn/"]`
|
||||
and registers it under `HKCU\Software\Microsoft\Edge\NativeMessagingHosts\cz.marek_novak.custos` and
|
||||
`HKCU\Software\Google\Chrome\NativeMessagingHosts\cz.marek_novak.custos`, so only this extension can start
|
||||
the host. The private key that matches the public key is not in this repository; it is only needed to pack a
|
||||
`.crx` with the same id.
|
||||
|
||||
## Threat model, briefly
|
||||
|
||||
- A malicious **page** cannot ask for a login: content scripts run in an isolated world, the button and list
|
||||
are in a closed shadow root, the origin comes from the browser, and filling needs a click in Custos's own UI.
|
||||
A page *can* read what was filled into its own fields: that is what filling is.
|
||||
- A malicious **frame** on a good site is a different origin: it gets only its own origin's logins.
|
||||
- Another **extension** cannot message this one (`sender.id`), and cannot start the host (`allowed_origins`).
|
||||
- A program that **impersonates Custos** by creating the pipe first gets nothing: the host checks the pipe
|
||||
server's image path ends in `\custos.exe` before writing the request. (A process of the same user that can
|
||||
replace `custos.exe` is out of scope, as everywhere in Custos: docs/THREAT_MODEL.md.)
|
||||
- The extension holds no secret at rest and no state beyond the open native port.
|
||||
|
||||
## Not yet
|
||||
|
||||
Passkeys (WebAuthn through the extension), Firefox, saving new logins from the browser, filling cards.
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
cargo test -p custos-browser -p custos-native
|
||||
```
|
||||
|
||||
`custos-browser` covers origin parsing, look-alikes, ports and schemes, bare names and IPs, best-of-several and
|
||||
the frames; `custos-native` that only the three ops pass, rebuilt from known fields. The desktop repo has the
|
||||
pipe tests and an end-to-end run in Edge.
|
||||
+5
-2
@@ -142,7 +142,10 @@ member), so these values, new in core 0.12.0, make a vault unreadable for a core
|
||||
written: a `signing` audit entry of kind `approval` (docs/SIGNING.md), a `provision` entry with store `display` or
|
||||
outcome `confirmed`. A vault without them still opens in core 0.11.0. Core 0.14.0 adds two more: a `signing` key
|
||||
of kind `android` and an audit entry of kind `apk` (docs/SIGNING.md); a vault that holds either does not open in a
|
||||
core before 0.14.0.
|
||||
core before 0.14.0. Core 0.16.0 adds the `signing` audit outcome `standing` and the `security` actions
|
||||
`standing-granted` and `standing-revoked` (docs/SIGNING.md, "Standing approvals"): a vault in which a standing
|
||||
approval was ever granted does not open in a core before 0.16.0. The rules themselves (`signing.standing`) are a
|
||||
member older cores ignore and drop.
|
||||
|
||||
### The provision audit (core 0.11.0)
|
||||
|
||||
@@ -206,7 +209,7 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos,
|
||||
| `finished` | optional: when that window ended, by *Finish setup*, or `until` once its expiry was noticed |
|
||||
| `ticked` | the checklist items that are ticked: `totp-on-phone`, `hello-approvals`, `narrow-scope`, `rotate-setup`, `no-ssh`, `phone-approves`, and (core 0.13.0) `no-auto-connect`, `no-unattended`, `card-signing` |
|
||||
| `keptScope` | optional: the server scope prefixes *Narrow the server scope* replaced (`ask`, `offer`: at most 64 each, 1–200 characters, no control characters), kept for its undo |
|
||||
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes) names what happened, never a value: 1–500 characters, no control characters |
|
||||
| `audit` | `{at, action, item?, auth?, detail?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected`, `totp-moved`, or (core 0.13.0) `auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`, `taken-over`, or (core 0.16.0) `standing-granted`, `standing-revoked`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`); `detail` (core 0.13.0, the four notes; core 0.16.0, the two standing actions) names what happened, never a value: 1–500 characters, no control characters |
|
||||
|
||||
The **level** is computed, never stored:
|
||||
|
||||
|
||||
+59
-2
@@ -1,4 +1,4 @@
|
||||
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0)
|
||||
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.0; standing approvals 0.16.0)
|
||||
|
||||
Custos signs releases for Fabrica Domi · Artifex without a private key ever leaving the vault. A build asks for a
|
||||
signature over a **digest**; Custos checks who may ask, Mark approves with a match code, and the vault signs and
|
||||
@@ -58,6 +58,7 @@ never trusted by Mark's PCs.
|
||||
|
||||
*Create Android key* (`signing_create_android`, core 0.14.0) makes one Android app signing key at a time, with the
|
||||
id, name, certificate subject (`CN`, `O`, a two-letter `C`), role and scope the app gives it; an id is used once.
|
||||
An Android key is a key of its own, not part of a set: it never counts as the release or test set (core 0.14.1).
|
||||
The app makes `postea-android` (`CN=Postea, O=Marek Novak, C=CZ`, release, pipeline `release`, repo
|
||||
`mnovak/Postea`) and its test twin `domi-test-android` (`CN=Domi Test Android, O=Domi, C=CZ`, test). An Android
|
||||
key's certificate *is* the app's identity: Android accepts an update only when it is signed by the same certificate,
|
||||
@@ -194,6 +195,51 @@ the digests and answers with placeholder signatures (the signed data does not de
|
||||
Custos's answer, again with a signer that hands each recorded digest its signature, and refuses any digest it did
|
||||
not record. It verifies the result with apksig's verifier before it writes the APK.
|
||||
|
||||
## Standing approvals (core 0.16.0)
|
||||
|
||||
A release key always asks. A **standing approval** is Mark's answer kept: "always allow this, for this repository".
|
||||
It is a rule in `signing.standing`, made only from a request Mark is approving on a card, and a later request that
|
||||
fits it is signed without a card.
|
||||
|
||||
```json
|
||||
"standing": [
|
||||
{ "id": "5b0c1e0f6a2d4c11", "repo": "mnovak/Postea", "key": "postea-android", "keyCreated": 1793750000000,
|
||||
"kind": "apk", "pipeline": "release", "via": "local", "granted": 1794000000000, "lastUsed": 1794100000000, "uses": 3 },
|
||||
{ "id": "9d3e…", "repo": "Aula", "key": "domi-approve", "keyCreated": 1793750000000, "kind": "approval",
|
||||
"pipeline": "deploy", "via": "remote", "targets": ["deploy to nixos-vm"], "granted": 1794000000000, "uses": 0 }
|
||||
]
|
||||
```
|
||||
|
||||
**What a rule is.** Five things, all compared exactly (no `*`, no prefix): the repository and the pipeline as the
|
||||
scope check reads them (an approval's own `repo` and `pipeline`), the key (its id and its `created` time, so a key
|
||||
made later under the same id never inherits a rule), the kind, and `via` (the Domi pipe or the factor service's
|
||||
mailbox). A rule for an `approval` also keeps the targets it was granted for. `id` is the first 16 hex characters
|
||||
of the SHA-256 of `repo`, `key`, `kind`, `pipeline` and `via` joined by newlines, so one rule exists per
|
||||
combination. The trigger and the step are not part of a rule; they are in every audit entry.
|
||||
|
||||
**A request fits a rule** (`standing_rule_for`) when all of these hold:
|
||||
|
||||
- `signing_check` passes: a rule never widens a key's scope, and narrowing the scope afterwards stops the rule;
|
||||
- the request names a run;
|
||||
- repository, pipeline, key (id and `created`), kind and `via` equal the rule's;
|
||||
- for an approval, every target of the request is one of the rule's targets;
|
||||
- `via` is `local`, or the kind is `approval`: a release signature asked through the mailbox never fits a rule;
|
||||
- the checklist item `card-signing` (*Sign only with a card*) is not ticked.
|
||||
|
||||
**A rule is made** (`standing_grant`) only when the request would itself fit the rule being made, the key is a
|
||||
release key (a test key needs none), and **the key has signed before** (an `approved` or `standing` audit entry):
|
||||
a key's first signature is never the one that starts a rule. Granting again for an approval adds its targets to
|
||||
the rule. At most 256 rules. `standing_revoke` removes one. Granting and revoking are written to the security audit
|
||||
(`standing-granted`, `standing-revoked`, with the rule's fields as the detail).
|
||||
|
||||
**Signing with a rule** is `signing_sign(req, Approval::Standing, now)`: it checks the request, finds the rule
|
||||
(refusing with `NeedsApproval` when none fits), signs, records the outcome `standing` with everything an `approved`
|
||||
entry holds, and counts the use on the rule (`uses`, `lastUsed`).
|
||||
|
||||
Never covered by a rule, by construction: another repository, key, kind, pipeline or origin; a request out of the
|
||||
key's scope; a request without a run; a key's first signature; a deploy to a target the rule was not granted for;
|
||||
a release signature the server runner asks for; creating a key.
|
||||
|
||||
## The audit log
|
||||
|
||||
`audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets
|
||||
@@ -202,6 +248,7 @@ one entry, whatever happened:
|
||||
| `outcome` | |
|
||||
| :-- | :-- |
|
||||
| `approved` | Mark approved; signed |
|
||||
| `standing` | (core 0.16.0) a standing approval fitted; signed without asking |
|
||||
| `auto` | a test key; signed without asking |
|
||||
| `refused` | Mark refused |
|
||||
| `expired` | nobody answered within 5 minutes |
|
||||
@@ -213,6 +260,11 @@ one entry, whatever happened:
|
||||
(core 0.12.0) is the context's version, absent when empty. The entry is part of the vault, so it survives a reopen
|
||||
and travels with it.
|
||||
|
||||
**Compatibility (core 0.16.0).** A core before 0.16.0 ignores `standing` when it reads and drops it when it saves
|
||||
(the rules are gone and every request asks again). The audit outcome `standing` and the security actions
|
||||
`standing-granted` and `standing-revoked` are values it does not know: once a rule was granted, every Custos that
|
||||
opens the vault must be on core 0.16.0 or later (an older one refuses it as `Corrupted`).
|
||||
|
||||
**Compatibility.** A key of kind `android` and an audit entry of kind `apk` (core 0.14.0) are values a core
|
||||
before 0.14.0 does not know: once the vault holds an Android key, every Custos that opens it must be on core 0.14.0
|
||||
or later (an older one refuses the vault as `Corrupted`; the web vault, which never reads `signing`, is unaffected).
|
||||
@@ -233,9 +285,14 @@ Vault::signing_export_cert(id) -> DER //
|
||||
Vault::signing_minisign_public(id) -> minisign.pub text
|
||||
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark (the clock: now_ms)
|
||||
Vault::signing_check_at(&request, now) -> Ok | Refusal // the same at `now` (an approval's expiry)
|
||||
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
|
||||
Vault::signing_sign(&request, Approval::{Mark, Auto, Standing}, now) -> Signed // checks again, signs, records
|
||||
Vault::signing_refuse(&request, outcome, now) // records refused / expired
|
||||
Vault::signing_audit() -> [AuditEntry]
|
||||
Vault::standing_can_grant(&request, now) -> Ok | why not // may the card offer "always"? (0.16.0)
|
||||
Vault::standing_grant(&request, now) -> StandingRule // before signing the approved request
|
||||
Vault::standing_rule_for(&request, now) -> Option<StandingRule>
|
||||
Vault::standing_rules() -> [StandingRule]
|
||||
Vault::standing_revoke(id, now) -> bool
|
||||
```
|
||||
|
||||
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Custos's service worker (docs/BROWSER.md). It owns the connection to the native host and answers the
|
||||
// content scripts and the popup. The page origin it sends to Custos is always the browser's (`sender.url`,
|
||||
// the tab's URL), never what a page says about itself; Custos decides which logins belong to it.
|
||||
|
||||
const HOST = 'cz.marek_novak.custos';
|
||||
|
||||
/** The native host, connected on first use; Edge and Chrome keep the worker alive while it is open. */
|
||||
let port = null;
|
||||
let seq = 0;
|
||||
const waiting = new Map();
|
||||
|
||||
function connect() {
|
||||
if (port) return port;
|
||||
port = chrome.runtime.connectNative(HOST);
|
||||
port.onMessage.addListener((msg) => {
|
||||
const w = waiting.get(msg.seq);
|
||||
if (!w) return;
|
||||
waiting.delete(msg.seq);
|
||||
w(msg);
|
||||
});
|
||||
port.onDisconnect.addListener(() => {
|
||||
// Not registered, or the host exited: every open request fails the same way.
|
||||
const why = chrome.runtime.lastError?.message ?? '';
|
||||
const error = /not found|forbidden/i.test(why) ? 'not_connected' : 'not_running';
|
||||
for (const w of waiting.values()) w({ ok: false, error });
|
||||
waiting.clear();
|
||||
port = null;
|
||||
});
|
||||
return port;
|
||||
}
|
||||
|
||||
function ask(request) {
|
||||
return new Promise((resolve) => {
|
||||
const n = ++seq;
|
||||
waiting.set(n, resolve);
|
||||
try {
|
||||
connect().postMessage({ ...request, seq: n });
|
||||
} catch {
|
||||
waiting.delete(n);
|
||||
resolve({ ok: false, error: 'not_connected' });
|
||||
}
|
||||
// Custos may wait up to a minute for an unlock or an approval.
|
||||
setTimeout(() => {
|
||||
if (waiting.delete(n)) resolve({ ok: false, error: 'no_answer' });
|
||||
}, 75_000);
|
||||
});
|
||||
}
|
||||
|
||||
/** `https://host[:port]` of a page or frame URL; null for anything Custos never fills. */
|
||||
function originOf(url) {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (u.protocol !== 'https:' && u.protocol !== 'http:') return null;
|
||||
return u.origin;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
|
||||
// Only this extension's own pages and content scripts reach here; pages cannot send to it.
|
||||
if (sender.id !== chrome.runtime.id) return false;
|
||||
(async () => {
|
||||
switch (msg?.kind) {
|
||||
case 'status':
|
||||
return reply(await ask({ op: 'browser_status' }));
|
||||
case 'match': {
|
||||
// From a content script: the logins for the frame it runs in.
|
||||
const origin = originOf(sender.url);
|
||||
if (!origin) return reply({ ok: false, error: 'no_match' });
|
||||
return reply({ ...(await ask({ op: 'browser_match', origin })), origin });
|
||||
}
|
||||
case 'fill': {
|
||||
// The secrets go back to the frame that asked, and only if Custos agrees the login belongs there.
|
||||
const origin = originOf(sender.url);
|
||||
if (!origin || typeof msg.id !== 'string') return reply({ ok: false, error: 'no_match' });
|
||||
return reply(await ask({ op: 'browser_fill', id: msg.id, origin }));
|
||||
}
|
||||
case 'match-tab': {
|
||||
// From the popup: the logins for the active tab's page.
|
||||
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
|
||||
const origin = tab && originOf(tab.url);
|
||||
if (!origin) return reply({ ok: false, error: 'no_match', tab: tab?.id ?? null });
|
||||
return reply({ ...(await ask({ op: 'browser_match', origin })), origin, tab: tab.id });
|
||||
}
|
||||
default:
|
||||
return reply({ ok: false, error: 'bad_request' });
|
||||
}
|
||||
})();
|
||||
return true;
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
// Custos's content script (docs/BROWSER.md): finds login fields, offers the logins Custos has for this
|
||||
// frame's site, and fills the one the person picks. Nothing is filled without a click. The button and the
|
||||
// list live in a closed shadow root, out of the page's reach; logins are asked for only when the list opens.
|
||||
(() => {
|
||||
const SENTENCES = {
|
||||
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
|
||||
not_running: 'Custos is not running. Start it, then try again.',
|
||||
not_custos: 'Something other than Custos answered. Nothing was sent.',
|
||||
locked: 'Custos is locked. Unlock it, then try again.',
|
||||
denied: 'Custos did not allow this browser to use your logins.',
|
||||
not_found: 'That login is no longer in Custos.',
|
||||
no_match: 'That login does not belong to this site.',
|
||||
no_answer: 'Custos did not answer.',
|
||||
};
|
||||
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
|
||||
|
||||
const visible = (el) => {
|
||||
const r = el.getBoundingClientRect();
|
||||
const s = getComputedStyle(el);
|
||||
return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none' && !el.disabled && !el.readOnly;
|
||||
};
|
||||
const isText = (el) => el instanceof HTMLInputElement && ['text', 'email', 'tel'].includes(el.type);
|
||||
const isOtp = (el) =>
|
||||
el instanceof HTMLInputElement &&
|
||||
(el.autocomplete === 'one-time-code' || /(^|[^a-z])(otp|totp|2fa|mfa|one.?time|verification.?code)/i.test(`${el.name} ${el.id}`));
|
||||
const isUserName = (el) => isText(el) && /username|email/i.test(`${el.autocomplete} ${el.name} ${el.id} ${el.type}`);
|
||||
|
||||
/** The username field of a password field: the one the page marks, else the last text field before it. */
|
||||
function usernameFor(pw) {
|
||||
const inputs = [...(pw.form ?? document).querySelectorAll('input')].filter(visible);
|
||||
const marked = inputs.find((el) => isText(el) && /username|email/i.test(el.autocomplete));
|
||||
if (marked) return marked;
|
||||
for (let i = inputs.indexOf(pw) - 1; i >= 0; i--) if (isText(inputs[i]) && !isOtp(inputs[i])) return inputs[i];
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The fields a login fills, around `near` (the focused field) or on the whole page. */
|
||||
function fieldsAround(near) {
|
||||
const all = [...document.querySelectorAll('input')].filter(visible);
|
||||
const otp = (near && isOtp(near) ? near : null) ?? all.find(isOtp) ?? null;
|
||||
const scope = near?.form ? [...near.form.querySelectorAll('input')].filter(visible) : all;
|
||||
const pass = (near?.type === 'password' ? near : null) ?? scope.find((el) => el.type === 'password') ?? null;
|
||||
const user = pass ? usernameFor(pass) : ((near && isUserName(near) ? near : null) ?? scope.find(isUserName) ?? null);
|
||||
return { user, pass, otp };
|
||||
}
|
||||
|
||||
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
|
||||
function put(el, value) {
|
||||
if (!el || typeof value !== 'string' || !value) return;
|
||||
el.focus();
|
||||
setValue.call(el, value);
|
||||
el.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
el.dispatchEvent(new Event('change', { bubbles: true }));
|
||||
}
|
||||
|
||||
async function fill(id, near) {
|
||||
const r = await chrome.runtime.sendMessage({ kind: 'fill', id });
|
||||
if (!r?.ok) return say(r?.error);
|
||||
const f = fieldsAround(near);
|
||||
put(f.user, r.username);
|
||||
put(f.pass, r.password);
|
||||
if (f.otp) put(f.otp, r.totp);
|
||||
return null;
|
||||
}
|
||||
|
||||
// ---- the button and the list ----
|
||||
|
||||
const host = document.createElement('custos-fill');
|
||||
const root = host.attachShadow({ mode: 'closed' });
|
||||
root.innerHTML = `
|
||||
<style>
|
||||
:host { all: initial; }
|
||||
.chip, .menu { position: fixed; z-index: 2147483647; font: 13px/1.4 "Segoe UI", system-ui, sans-serif; }
|
||||
.chip { width: 24px; height: 24px; padding: 0; border: 1px solid #5d6573; border-radius: 6px; background: #15181d;
|
||||
cursor: pointer; display: grid; place-items: center; box-shadow: 0 2px 6px rgba(0,0,0,.35); }
|
||||
.chip:hover, .chip:focus-visible { border-color: #c9d1dc; outline: none; }
|
||||
.menu { min-width: 240px; max-width: 360px; padding: 6px; border: 1px solid #3a404b; border-radius: 10px;
|
||||
background: #15181d; color: #e8ebf0; box-shadow: 0 14px 32px rgba(0,0,0,.45); }
|
||||
.head { padding: 4px 8px 6px; color: #9aa3b1; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; }
|
||||
button.login { display: grid; width: 100%; padding: 7px 8px; border: 0; border-radius: 7px; background: none;
|
||||
color: inherit; text-align: left; cursor: pointer; font: inherit; }
|
||||
button.login:hover, button.login:focus-visible { background: #262b33; outline: none; }
|
||||
.title { font-weight: 600; }
|
||||
.user { color: #9aa3b1; font-size: 12px; }
|
||||
.note { padding: 6px 8px; color: #c9d1dc; }
|
||||
[hidden] { display: none !important; }
|
||||
</style>
|
||||
<button class="chip" type="button" title="Fill from Custos" aria-label="Fill from Custos" hidden>
|
||||
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M8 1.5l5 2v4c0 3.2-2.1 5.8-5 7-2.9-1.2-5-3.8-5-7v-4z"
|
||||
fill="none" stroke="#c9d1dc" stroke-width="1.5" stroke-linejoin="round"/><path d="M5.8 8l1.6 1.6L10.4 6.4" fill="none"
|
||||
stroke="#c9d1dc" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
|
||||
</button>
|
||||
<div class="menu" role="menu" aria-label="Custos logins" hidden></div>`;
|
||||
const chip = root.querySelector('.chip');
|
||||
const menu = root.querySelector('.menu');
|
||||
let field = null;
|
||||
|
||||
function place() {
|
||||
if (!field || !field.isConnected) return hide();
|
||||
const r = field.getBoundingClientRect();
|
||||
chip.style.left = `${Math.max(0, r.right - 28)}px`;
|
||||
chip.style.top = `${r.top + Math.max(0, (r.height - 24) / 2)}px`;
|
||||
menu.style.left = `${Math.max(4, r.left)}px`;
|
||||
menu.style.top = `${r.bottom + 4}px`;
|
||||
}
|
||||
|
||||
function hide() {
|
||||
chip.hidden = true;
|
||||
menu.hidden = true;
|
||||
field = null;
|
||||
}
|
||||
|
||||
function note(text) {
|
||||
menu.replaceChildren(Object.assign(document.createElement('div'), { className: 'note', textContent: text }));
|
||||
menu.hidden = false;
|
||||
}
|
||||
|
||||
async function open() {
|
||||
const target = field;
|
||||
note('Asking Custos…');
|
||||
const r = await chrome.runtime.sendMessage({ kind: 'match' });
|
||||
if (field !== target) return;
|
||||
if (!r?.ok) return note(say(r?.error));
|
||||
if (!r.logins.length) return note('Custos has no login for this site.');
|
||||
const head = Object.assign(document.createElement('div'), { className: 'head', textContent: 'Custos' });
|
||||
const items = r.logins.map((l) => {
|
||||
const b = Object.assign(document.createElement('button'), { className: 'login', type: 'button' });
|
||||
b.setAttribute('role', 'menuitem');
|
||||
b.append(
|
||||
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
|
||||
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
|
||||
);
|
||||
b.addEventListener('click', async () => {
|
||||
const why = await fill(l.id, target);
|
||||
if (why) note(why);
|
||||
else hide();
|
||||
});
|
||||
return b;
|
||||
});
|
||||
menu.replaceChildren(head, ...items);
|
||||
items[0]?.focus();
|
||||
}
|
||||
|
||||
chip.addEventListener('click', () => (menu.hidden ? void open() : (menu.hidden = true)));
|
||||
// A press inside the shadow root is a press on `host` for the page: keep the field's focus logic out of it.
|
||||
host.addEventListener('mousedown', (e) => e.preventDefault());
|
||||
|
||||
document.addEventListener(
|
||||
'focusin',
|
||||
(e) => {
|
||||
const el = e.target;
|
||||
if (!(el instanceof HTMLInputElement) || !visible(el)) return;
|
||||
if (el.type !== 'password' && !isOtp(el) && !(isText(el) && fieldsAround(el).pass) && !isUserName(el)) return;
|
||||
if (!host.isConnected) document.documentElement.append(host);
|
||||
field = el;
|
||||
menu.hidden = true;
|
||||
chip.hidden = false;
|
||||
place();
|
||||
},
|
||||
true,
|
||||
);
|
||||
document.addEventListener('keydown', (e) => e.key === 'Escape' && !menu.hidden && hide(), true);
|
||||
document.addEventListener('pointerdown', (e) => e.target !== host && e.target !== field && hide(), true);
|
||||
window.addEventListener('scroll', place, true);
|
||||
window.addEventListener('resize', place);
|
||||
|
||||
// The popup's choice, in the top frame: fill the page's login form.
|
||||
chrome.runtime.onMessage.addListener((msg, sender, reply) => {
|
||||
if (sender.id !== chrome.runtime.id || msg?.kind !== 'fill-now' || typeof msg.id !== 'string') return false;
|
||||
fill(msg.id, null).then((why) => reply({ ok: !why, error: why }));
|
||||
return true;
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "Custos",
|
||||
"short_name": "Custos",
|
||||
"description": "Fills your logins from the Custos on this computer, only into the site they belong to.",
|
||||
"version": "0.15.0",
|
||||
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs+NtlDNsfBr8q2WbrurbDDfX4rL2dTHsNZToKBKradRb5WZU3wjHAcBMsPlYCiqHF4c/KUyGQ33mpPb0aXA5l3w7n6JgMLHPQBbCw5v076ViF6NIE3a0LOoffDg9ZQmfIJcgjb9baX2qS8VaEFTsEzb/BgQ2Ewx/BPHwZaFeJkucBsIeRZnaPajdqViaNDQdq91VnxIoSGr21Sc+9ZxfZL288S6wATdlDYBUyUZZjVwggHfiwdDmQQMdnFtks2r38V25h+t3ruGCi2mArj8DO1so1oX/NulLNT+6VBP6r/ap228af3rNNcv7sPeriI90ORqzh4Lwni8Hq1lzKuXLrwIDAQAB",
|
||||
"minimum_chrome_version": "116",
|
||||
"permissions": [
|
||||
"nativeMessaging",
|
||||
"activeTab"
|
||||
],
|
||||
"background": {
|
||||
"service_worker": "background.js"
|
||||
},
|
||||
"action": {
|
||||
"default_title": "Custos",
|
||||
"default_popup": "popup.html"
|
||||
},
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": [
|
||||
"https://*/*",
|
||||
"http://localhost/*",
|
||||
"http://127.0.0.1/*",
|
||||
"http://*.localhost/*"
|
||||
],
|
||||
"js": [
|
||||
"content.js"
|
||||
],
|
||||
"all_frames": true,
|
||||
"run_at": "document_idle"
|
||||
}
|
||||
],
|
||||
"content_security_policy": {
|
||||
"extension_pages": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #101216;
|
||||
--panel: #15181d;
|
||||
--hover: #262b33;
|
||||
--line: #2b3038;
|
||||
--fg: #e8ebf0;
|
||||
--muted: #9aa3b1;
|
||||
--accent: #c9d1dc;
|
||||
}
|
||||
body {
|
||||
width: 320px;
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 13px/1.45 "Segoe UI", system-ui, sans-serif;
|
||||
}
|
||||
header {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
padding: 12px 14px 10px;
|
||||
border-bottom: 1px solid var(--line);
|
||||
background: var(--panel);
|
||||
}
|
||||
.wordmark {
|
||||
color: var(--accent);
|
||||
font-size: 12px;
|
||||
letter-spacing: 0.3em;
|
||||
}
|
||||
.site {
|
||||
overflow: hidden;
|
||||
color: var(--muted);
|
||||
white-space: nowrap;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
main {
|
||||
padding: 8px;
|
||||
}
|
||||
.note {
|
||||
margin: 6px 6px 10px;
|
||||
}
|
||||
.logins {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
.logins button {
|
||||
display: grid;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.logins button:hover,
|
||||
.logins button:focus-visible {
|
||||
background: var(--hover);
|
||||
outline: none;
|
||||
}
|
||||
.title {
|
||||
font-weight: 600;
|
||||
}
|
||||
.user {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
footer {
|
||||
padding: 8px 14px 12px;
|
||||
border-top: 1px solid var(--line);
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Custos</title>
|
||||
<link rel="stylesheet" href="popup.css">
|
||||
<script src="popup.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<span class="wordmark">CUSTOS</span>
|
||||
<span id="site" class="site"></span>
|
||||
</header>
|
||||
<main>
|
||||
<p id="note" class="note">Asking Custos…</p>
|
||||
<ul id="logins" class="logins" aria-label="Logins for this site"></ul>
|
||||
</main>
|
||||
<footer>Only logins saved for this site are offered here.</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,50 @@
|
||||
// The toolbar popup: the logins Custos has for the active tab's site; a click fills the page's login form
|
||||
// (the top frame's content script asks for the secrets itself, so they go only where they belong).
|
||||
const SENTENCES = {
|
||||
not_connected: 'Connect this browser in Custos first: Settings → Browser.',
|
||||
not_running: 'Custos is not running. Start it, then try again.',
|
||||
not_custos: 'Something other than Custos answered. Nothing was sent.',
|
||||
locked: 'Custos is locked. Unlock it, then try again.',
|
||||
denied: 'Custos did not allow this browser to use your logins.',
|
||||
not_found: 'That login is no longer in Custos.',
|
||||
no_match: 'Custos fills only web pages (https, or this computer).',
|
||||
no_answer: 'Custos did not answer.',
|
||||
};
|
||||
const say = (code) => SENTENCES[code] ?? 'Custos could not do that.';
|
||||
const note = document.getElementById('note');
|
||||
const list = document.getElementById('logins');
|
||||
|
||||
async function show() {
|
||||
const r = await chrome.runtime.sendMessage({ kind: 'match-tab' });
|
||||
if (r?.origin) document.getElementById('site').textContent = new URL(r.origin).host;
|
||||
if (!r?.ok) {
|
||||
note.textContent = say(r?.error);
|
||||
return;
|
||||
}
|
||||
if (!r.logins.length) {
|
||||
note.textContent = 'Custos has no login for this site.';
|
||||
return;
|
||||
}
|
||||
note.hidden = true;
|
||||
for (const l of r.logins) {
|
||||
const li = document.createElement('li');
|
||||
const b = Object.assign(document.createElement('button'), { type: 'button' });
|
||||
b.append(
|
||||
Object.assign(document.createElement('span'), { className: 'title', textContent: l.title }),
|
||||
Object.assign(document.createElement('span'), { className: 'user', textContent: l.username || '—' }),
|
||||
);
|
||||
b.addEventListener('click', async () => {
|
||||
const done = await chrome.tabs.sendMessage(r.tab, { kind: 'fill-now', id: l.id }, { frameId: 0 }).catch(() => null);
|
||||
if (done?.ok) window.close();
|
||||
else {
|
||||
note.hidden = false;
|
||||
note.textContent = done?.error ?? 'This page has no login form Custos can fill.';
|
||||
}
|
||||
});
|
||||
li.append(b);
|
||||
list.append(li);
|
||||
}
|
||||
list.querySelector('button')?.focus();
|
||||
}
|
||||
|
||||
void show();
|
||||
Reference in New Issue
Block a user