Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1292c09d02 | |||
| a45d1054f0 | |||
| 4e8fb6a8f5 | |||
| aa5b692651 | |||
| 6f4075f7e3 | |||
| 54ce09ce61 | |||
| 045f1f5d00 | |||
| 82698bd9e5 | |||
| 68a1f1344d | |||
| ac69cf4638 |
@@ -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.15.0"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-gen"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -341,7 +348,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-kdbx"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"argon2",
|
||||
@@ -362,7 +369,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-keys"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"ed25519-dalek",
|
||||
@@ -373,13 +380,23 @@ dependencies = [
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-native"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"custos-browser",
|
||||
"serde_json",
|
||||
"windows-sys",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "custos-qr"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
|
||||
[[package]]
|
||||
name = "custos-seal"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"chacha20poly1305",
|
||||
"hkdf",
|
||||
@@ -392,7 +409,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-share"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"chacha20poly1305",
|
||||
@@ -409,7 +426,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-sign"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"blake2 0.10.6",
|
||||
"data-encoding",
|
||||
@@ -428,7 +445,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-totp"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"custos-vault",
|
||||
"data-encoding",
|
||||
@@ -441,7 +458,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-vault"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"argon2",
|
||||
"bip39",
|
||||
@@ -465,7 +482,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "custos-wasm"
|
||||
version = "0.12.0"
|
||||
version = "0.15.0"
|
||||
dependencies = [
|
||||
"custos-qr",
|
||||
"custos-seal",
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
||||
members = ["crates/*"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.12.0"
|
||||
version = "0.15.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 }));
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,9 @@
|
||||
//! - minisign (prehashed `ED`, what minisign and Tauri's updater verify) over a BLAKE2b-512 digest;
|
||||
//! - a canonical `SHA256SUMS` manifest, checked here and signed as minisign;
|
||||
//! - Authenticode: RSA PKCS#1 v1.5 over the 32-byte digest `signtool sign /dg` writes;
|
||||
//! - the household CA: a self-signed RSA-3072 root and a code-signing leaf it issues (X.509 v3).
|
||||
//! - the household CA: a self-signed RSA-3072 root and a code-signing leaf it issues (X.509 v3);
|
||||
//! - Android APKs: an RSA-4096 key with a self-signed certificate, signing the SHA-512 digests of the APK
|
||||
//! Signature Scheme v2/v3 signed data with RSA PKCS#1 v1.5 (apksig does the APK itself, on the build's side).
|
||||
//!
|
||||
//! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`.
|
||||
|
||||
@@ -21,7 +23,7 @@ use rsa::RsaPrivateKey;
|
||||
use rsa::pkcs1v15;
|
||||
use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey};
|
||||
use rsa::signature::hazmat::PrehashSigner;
|
||||
use sha2_010::Sha256;
|
||||
use sha2_010::{Sha256, Sha512};
|
||||
use x509_cert::Certificate;
|
||||
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
|
||||
use x509_cert::der::{Decode, Encode};
|
||||
@@ -36,6 +38,12 @@ use zeroize::Zeroizing;
|
||||
const CODE_SIGNING: x509_cert::der::oid::ObjectIdentifier =
|
||||
x509_cert::der::oid::ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.3");
|
||||
const RSA_BITS: usize = 3072;
|
||||
/// An Android app's signing key: RSA-4096. apksig signs with SHA512withRSA for any RSA key over 3072 bits.
|
||||
pub const ANDROID_RSA_BITS: usize = 4096;
|
||||
/// An Android app's certificate is valid this long: the key can never change for the app's whole life.
|
||||
pub const ANDROID_YEARS: u64 = 100;
|
||||
/// One `apk` request carries 1 to this many SHA-512 digests (v2 and v3 are two).
|
||||
pub const MAX_APK_DIGESTS: usize = 4;
|
||||
const DAY: u64 = 24 * 60 * 60;
|
||||
/// The largest manifest Custos signs (docs/SIGNING.md).
|
||||
pub const MAX_MANIFEST: usize = 32 * 1024;
|
||||
@@ -54,6 +62,8 @@ pub enum Error {
|
||||
Certificate,
|
||||
#[error("the approval cannot be signed: {0}")]
|
||||
Approval(&'static str),
|
||||
#[error("an APK request is 1 to 4 SHA-512 digests of 64 bytes each")]
|
||||
ApkDigests,
|
||||
}
|
||||
|
||||
/// An Ed25519 seed. Wiped on drop; never printed.
|
||||
@@ -290,8 +300,8 @@ pub struct NewCert {
|
||||
pub cert_der: Vec<u8>,
|
||||
}
|
||||
|
||||
fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> {
|
||||
let key = RsaPrivateKey::new(&mut OsRng06, RSA_BITS).map_err(|_| Error::BadKey)?;
|
||||
fn new_rsa(bits: usize) -> Result<(RsaPrivateKey, RsaSecret), Error> {
|
||||
let key = RsaPrivateKey::new(&mut OsRng06, bits).map_err(|_| Error::BadKey)?;
|
||||
let der = key.to_pkcs8_der().map_err(|_| Error::BadKey)?.as_bytes().to_vec();
|
||||
Ok((key, RsaSecret(Zeroizing::new(der))))
|
||||
}
|
||||
@@ -318,7 +328,7 @@ fn spki(key: &RsaPrivateKey) -> Result<SubjectPublicKeyInfoOwned, Error> {
|
||||
|
||||
/// A self-signed root CA, valid for `years` years from now.
|
||||
pub fn new_root(cn: &str, years: u64) -> Result<NewCert, Error> {
|
||||
let (key, secret) = new_rsa()?;
|
||||
let (key, secret) = new_rsa(RSA_BITS)?;
|
||||
let spki = spki(&key)?;
|
||||
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
|
||||
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
|
||||
@@ -331,7 +341,7 @@ pub fn new_root(cn: &str, years: u64) -> Result<NewCert, Error> {
|
||||
/// A code-signing leaf issued by `issuer`, valid for `years` years from now.
|
||||
pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: &[u8]) -> Result<NewCert, Error> {
|
||||
let issuer_cert = Certificate::from_der(issuer_cert).map_err(|_| Error::Certificate)?;
|
||||
let (key, secret) = new_rsa()?;
|
||||
let (key, secret) = new_rsa(RSA_BITS)?;
|
||||
let signer = pkcs1v15::SigningKey::<Sha256>::new(issuer.key()?);
|
||||
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
|
||||
let profile = Profile::Leaf {
|
||||
@@ -346,6 +356,59 @@ pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: &
|
||||
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
|
||||
}
|
||||
|
||||
// ---- Android APKs ----
|
||||
|
||||
/// One attribute value of an Android certificate's subject: 1 to 64 bytes, no characters RFC 4514 would have to
|
||||
/// escape, no control characters, no space at either end.
|
||||
fn subject_part(s: &str) -> Result<&str, Error> {
|
||||
let bad = s.is_empty()
|
||||
|| s.len() > 64
|
||||
|| s.trim() != s
|
||||
|| s.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#'])
|
||||
|| s.chars().any(char::is_control);
|
||||
if bad { Err(Error::Certificate) } else { Ok(s) }
|
||||
}
|
||||
|
||||
/// A new Android app signing key: RSA-4096 and a self-signed X.509 v3 certificate `CN=<cn>, O=<o>, C=<c>` valid
|
||||
/// [`ANDROID_YEARS`] years from now, an end-entity certificate (not a CA, key usage digitalSignature +
|
||||
/// nonRepudiation, no extended key usage). `c` is a two-letter country code. Slow: one RSA-4096 key.
|
||||
pub fn new_android(cn: &str, o: &str, c: &str) -> Result<NewCert, Error> {
|
||||
let (cn, o) = (subject_part(cn)?, subject_part(o)?);
|
||||
if c.len() != 2 || !c.bytes().all(|b| b.is_ascii_uppercase()) {
|
||||
return Err(Error::Certificate);
|
||||
}
|
||||
// RFC 4514 order: the string names the most specific part first, the certificate encodes C, O, CN.
|
||||
let subject = Name::from_str(&format!("CN={cn},O={o},C={c}")).map_err(|_| Error::Certificate)?;
|
||||
let (key, secret) = new_rsa(ANDROID_RSA_BITS)?;
|
||||
let spki = spki(&key)?;
|
||||
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
|
||||
let validity =
|
||||
Validity::from_now(Duration::from_secs(ANDROID_YEARS * 365 * DAY)).map_err(|_| Error::Certificate)?;
|
||||
// A leaf issued by itself: self-signed, but without the CA extensions of a root.
|
||||
let profile =
|
||||
Profile::Leaf { issuer: subject.clone(), enable_key_agreement: false, enable_key_encipherment: false };
|
||||
let builder = CertificateBuilder::new(profile, serial()?, validity, subject, spki, &signer)
|
||||
.map_err(|_| Error::Certificate)?;
|
||||
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
|
||||
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
|
||||
}
|
||||
|
||||
/// RSA PKCS#1 v1.5 with the SHA-512 DigestInfo over each 64-byte digest in `digests` (1 to [`MAX_APK_DIGESTS`],
|
||||
/// concatenated): the signatures, concatenated in the same order, for APK Signature Scheme v2 and v3
|
||||
/// (`RSA_PKCS1_V1_5_WITH_SHA512`, what apksig picks for an RSA key over 3072 bits).
|
||||
pub fn apk(secret: &RsaSecret, digests: &[u8]) -> Result<Vec<u8>, Error> {
|
||||
if digests.is_empty() || digests.len() % 64 != 0 || digests.len() > 64 * MAX_APK_DIGESTS {
|
||||
return Err(Error::ApkDigests);
|
||||
}
|
||||
let key = pkcs1v15::SigningKey::<Sha512>::new(secret.key()?);
|
||||
let mut out = Vec::new();
|
||||
for digest in digests.chunks(64) {
|
||||
let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?;
|
||||
out.extend_from_slice(&Box::<[u8]>::from(sig));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// A certificate as PEM, for tools that want text.
|
||||
pub fn cert_pem(der: &[u8]) -> String {
|
||||
let b64 = BASE64.encode(der);
|
||||
|
||||
+2
@@ -4,3 +4,5 @@ Throwaway **test keys** for the known-answer tests in `../kat.rs`. They sign not
|
||||
`payload.bin.minisig`: `minisign -S -m payload.bin -t "timestamp:1700000000<TAB>file:payload.bin<TAB>hashed"`.
|
||||
- `rsa3072.pk8.der`: `openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072`, then `openssl pkcs8 -topk8 -nocrypt`;
|
||||
`digest.openssl.sig`: `openssl pkeyutl -sign -in digest.bin -pkeyopt digest:sha256` (PKCS#1 v1.5).
|
||||
- `digest512.bin` (64 random bytes) and `digest512.openssl.sig`: `openssl pkeyutl -sign -inkey rsa3072.pk8.der -keyform DER
|
||||
-in digest512.bin -pkeyopt digest:sha512` (PKCS#1 v1.5 with the SHA-512 DigestInfo: the `apk` kind).
|
||||
|
||||
BIN
Binary file not shown.
Binary file not shown.
@@ -1,6 +1,7 @@
|
||||
//! Mandatory test 1 (docs/SIGNING.md): known answers for every signature kind, from tools that are not this crate.
|
||||
//! The fixtures are throwaway test keys: `minisign.key` was made by minisign 0.12 (`-G -W`, unencrypted) and
|
||||
//! `payload.bin.minisig` signed by it; `rsa3072.pk8.der` and `digest.openssl.sig` by `openssl pkeyutl`.
|
||||
//! `payload.bin.minisig` signed by it; `rsa3072.pk8.der`, `digest.openssl.sig` and `digest512.openssl.sig` by
|
||||
//! `openssl pkeyutl`.
|
||||
//! tools/signing/interop.ps1 checks the other direction with the real minisign, signtool and osslsigncode.
|
||||
|
||||
use std::fs;
|
||||
@@ -108,6 +109,80 @@ fn authenticode_signature_equals_openssls() {
|
||||
assert_eq!(authenticode(&key, &[0u8; 64]).unwrap_err(), Error::DigestLength(32));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apk_signatures_equal_openssls_sha512_pkcs1() {
|
||||
// The PKCS#1 v1.5 SHA-512 DigestInfo does not depend on the key size: the 3072-bit fixture checks it.
|
||||
let key = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
|
||||
let digest = fixture("digest512.bin");
|
||||
let expected = fixture("digest512.openssl.sig");
|
||||
assert_eq!(apk(&key, &digest).unwrap(), expected);
|
||||
// Two digests (v2 and v3): two signatures, in order.
|
||||
let mut two = digest.clone();
|
||||
two.extend(custos_sign::sha256_hex(&digest).as_bytes()); // any other 64 bytes
|
||||
let both = apk(&key, &two).unwrap();
|
||||
assert_eq!(both.len(), 2 * 384);
|
||||
assert_eq!(&both[..384], expected.as_slice());
|
||||
assert_eq!(both[384..].to_vec(), apk(&key, &two[64..]).unwrap());
|
||||
for bad in [0usize, 32, 63, 65, 64 * 5] {
|
||||
assert_eq!(apk(&key, &vec![1u8; bad]).unwrap_err(), Error::ApkDigests, "{bad}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_android_key_is_rsa_4096_with_a_self_signed_end_entity_certificate_for_100_years() {
|
||||
use rsa::RsaPublicKey;
|
||||
use rsa::pkcs1v15::{Signature, VerifyingKey};
|
||||
use rsa::pkcs8::DecodePublicKey;
|
||||
use rsa::signature::Verifier;
|
||||
use rsa::signature::hazmat::PrehashVerifier;
|
||||
use rsa::traits::PublicKeyParts;
|
||||
use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage, KeyUsage};
|
||||
|
||||
let made = new_android("Postea", "Marek Novak", "CZ").unwrap();
|
||||
let c = Certificate::from_der(&made.cert_der).unwrap();
|
||||
assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ");
|
||||
assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject, "self-signed");
|
||||
let v = &c.tbs_certificate.validity;
|
||||
let days = (v.not_after.to_unix_duration().as_secs() - v.not_before.to_unix_duration().as_secs()) / 86_400;
|
||||
assert_eq!(days, 100 * 365);
|
||||
let (_, bc) = c.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
|
||||
assert!(!bc.ca, "not a CA");
|
||||
assert!(c.tbs_certificate.get::<KeyUsage>().unwrap().is_some());
|
||||
assert!(c.tbs_certificate.get::<ExtendedKeyUsage>().unwrap().is_none(), "no extended key usage");
|
||||
|
||||
let spki = c.tbs_certificate.subject_public_key_info.to_der().unwrap();
|
||||
assert_eq!(RsaPublicKey::from_public_key_der(&spki).unwrap().n().bits(), 4096);
|
||||
// Signed by its own key, and that key makes the APK signatures.
|
||||
let sha256 = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(&spki).unwrap();
|
||||
sha256
|
||||
.verify(&c.tbs_certificate.to_der().unwrap(), &Signature::try_from(c.signature.raw_bytes()).unwrap())
|
||||
.unwrap();
|
||||
let digests = [3u8; 128];
|
||||
let sigs = apk(&made.secret, &digests).unwrap();
|
||||
assert_eq!(sigs.len(), 2 * 512);
|
||||
let sha512 = VerifyingKey::<sha2_010::Sha512>::from_public_key_der(&spki).unwrap();
|
||||
for (d, s) in digests.chunks(64).zip(sigs.chunks(512)) {
|
||||
sha512.verify_prehash(d, &Signature::try_from(s).unwrap()).unwrap();
|
||||
}
|
||||
// An Android key is not an Authenticode key, but the function cannot tell: the vault keeps them apart.
|
||||
assert_eq!(format!("{:?}", made.secret), "[redacted]");
|
||||
|
||||
for (cn, o, c) in [
|
||||
("", "O", "CZ"),
|
||||
("A,B", "O", "CZ"),
|
||||
(" Postea", "O", "CZ"),
|
||||
("Postea", "O=x", "CZ"),
|
||||
("Postea", "O", "cz"),
|
||||
("Postea", "O", "CZE"),
|
||||
(
|
||||
"Postea", "O
|
||||
", "CZ",
|
||||
),
|
||||
] {
|
||||
assert!(matches!(new_android(cn, o, c), Err(Error::Certificate)), "{cn:?} {o:?} {c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn digests_and_file_names_are_checked() {
|
||||
let (secret, key_id) = minisign_key();
|
||||
|
||||
@@ -690,6 +690,37 @@ impl Vault {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A machine-key vault: one device factor opens it alone (a Claude Code store, or Custos's hands-off vault
|
||||
/// before it is taken over).
|
||||
pub fn opens_with_machine_key(&self) -> bool {
|
||||
self.is_store()
|
||||
}
|
||||
|
||||
/// *Take over the vault* (Custos docs/12_hands_off.md, section 6): adds the master password as a factor paired
|
||||
/// with the device key, removes the PC-only access, and ticks the items that end unattended work. Returns the
|
||||
/// password factor's id. Only on a machine-key vault, once. The caller saves.
|
||||
pub fn take_over(&mut self, password: &SecretString, kdf: KdfParams, now: i64) -> Result<String, Error> {
|
||||
if !self.is_store() {
|
||||
return Err(Error::FactorRejected);
|
||||
}
|
||||
let slots = self.slots.clone();
|
||||
let kdf_was = self.kdf_new;
|
||||
// Without its single slot the vault is an ordinary version-2 vault with one factor; the password pairs with it.
|
||||
self.slots.retain(|s| s.kind != format::SLOT_SINGLE);
|
||||
self.kdf_new = kdf;
|
||||
match self.add_factor(Unlock::Password(password), "Master password") {
|
||||
Ok(id) => {
|
||||
self.security_taken_over(now);
|
||||
Ok(id)
|
||||
}
|
||||
Err(e) => {
|
||||
self.slots = slots;
|
||||
self.kdf_new = kdf_was;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_store(&self) -> bool {
|
||||
self.slots.iter().any(|s| s.kind == format::SLOT_SINGLE)
|
||||
}
|
||||
|
||||
@@ -29,6 +29,12 @@ pub enum Item {
|
||||
NoSsh,
|
||||
/// The phone approves this PC.
|
||||
PhoneApproves,
|
||||
/// Turn off auto-connect (Custos docs/12_hands_off.md).
|
||||
NoAutoConnect,
|
||||
/// Never accept unattended: a new connect opens no Setup window.
|
||||
NoUnattended,
|
||||
/// Sign only with a card.
|
||||
CardSigning,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -61,6 +67,16 @@ pub enum Action {
|
||||
Unticked,
|
||||
SshConnected,
|
||||
TotpMoved,
|
||||
/// Connected by itself at start (`detail`: where and as whom).
|
||||
AutoConnected,
|
||||
/// A setup run stored items without a card (`detail`: the run and the item names).
|
||||
UnattendedStored,
|
||||
/// One of those items was removed (`detail`: the run and the item).
|
||||
SetupItemRemoved,
|
||||
/// Signed without a card (`detail`: the key, the kind, the run and the file).
|
||||
UnattendedSigned,
|
||||
/// *Take over the vault*: a master password added, the PC-only access removed.
|
||||
TakenOver,
|
||||
}
|
||||
|
||||
/// What *Connect via SSH* needs.
|
||||
@@ -103,6 +119,10 @@ pub struct SecurityEntry {
|
||||
/// How an undo was confirmed, for `unticked`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auth: Option<Auth>,
|
||||
/// What a note says (`auto-connected`, `unattended-stored`, `setup-item-removed`, `unattended-signed`): names,
|
||||
/// never a value. At most 500 characters, no control characters.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
|
||||
/// Everything *Settings → Security* shows.
|
||||
@@ -152,6 +172,14 @@ fn kept_ok(list: &[String]) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A note's detail: 1 to 500 characters, no control characters. The error names the rule, never the text.
|
||||
fn detail_ok(d: &str) -> Result<(), Error> {
|
||||
if !(1..=500).contains(&d.chars().count()) || d.chars().any(char::is_control) {
|
||||
return Err(Error::Security("a note is 1 to 500 characters without control characters"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn trim(audit: &mut Vec<SecurityEntry>) {
|
||||
if audit.len() > AUDIT_LIMIT {
|
||||
audit.drain(..audit.len() - AUDIT_LIMIT);
|
||||
@@ -200,7 +228,7 @@ impl State {
|
||||
}
|
||||
|
||||
fn push(&mut self, at: i64, action: Action, item: Option<Item>, auth: Option<Auth>) {
|
||||
self.audit.push(SecurityEntry { at, action, item, auth });
|
||||
self.audit.push(SecurityEntry { at, action, item, auth, detail: None });
|
||||
trim(&mut self.audit);
|
||||
}
|
||||
|
||||
@@ -246,6 +274,89 @@ pub fn totp_offer_allowed(ticked: &BTreeSet<Item>) -> bool {
|
||||
!ticked.contains(&Item::TotpOnPhone)
|
||||
}
|
||||
|
||||
/// The Provisio namespaces a setup run may fill without a card (Custos docs/12_hands_off.md, section 3).
|
||||
pub const UNATTENDED_NAMESPACES: [&str; 5] = ["arca/", "custos/", "fabrica/", "aula/", "gitea/"];
|
||||
|
||||
/// A setup run's id: `setup-` and 1 to 58 of `[A-Za-z0-9._-]`.
|
||||
pub fn is_setup_run(run: &str) -> bool {
|
||||
run.strip_prefix("setup-").is_some_and(|rest| {
|
||||
(1..=58).contains(&rest.len()) && rest.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether Custos may connect to the factor service by itself (at start, with no device token).
|
||||
pub fn auto_connect_allowed(level: Level, ticked: &BTreeSet<Item>) -> bool {
|
||||
level != Level::Hardened && !ticked.contains(&Item::NoAutoConnect) && !ticked.contains(&Item::NoSsh)
|
||||
}
|
||||
|
||||
/// Whether a new connection opens the Setup window.
|
||||
pub fn setup_on_connect(ticked: &BTreeSet<Item>) -> bool {
|
||||
!ticked.contains(&Item::NoUnattended) && !ticked.contains(&Item::NoSsh)
|
||||
}
|
||||
|
||||
/// Ask or offer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Verb {
|
||||
Ask,
|
||||
Offer,
|
||||
}
|
||||
|
||||
/// Where a Provisio line goes.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Store {
|
||||
Vault,
|
||||
Claude,
|
||||
Display,
|
||||
}
|
||||
|
||||
/// A Provisio line as the unattended rule sees it.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ProvisionAsk<'a> {
|
||||
pub verb: Verb,
|
||||
/// `--generate`: Custos makes the value.
|
||||
pub generate: bool,
|
||||
/// The item exists already (an ask would read it, an offer would replace it).
|
||||
pub exists: bool,
|
||||
pub store: Store,
|
||||
pub item: &'a str,
|
||||
/// An offer of kind `totp`.
|
||||
pub totp: bool,
|
||||
}
|
||||
|
||||
/// Whether a Provisio line is answered without a card: a setup run, in Setup, new items in the allowed namespaces.
|
||||
pub fn unattended_provision(level: Level, ticked: &BTreeSet<Item>, run: &str, req: &ProvisionAsk) -> bool {
|
||||
if level != Level::Setup || !is_setup_run(run) || ticked.contains(&Item::NoUnattended) || req.exists {
|
||||
return false;
|
||||
}
|
||||
if req.totp && !totp_offer_allowed(ticked) {
|
||||
return false;
|
||||
}
|
||||
match (req.store, req.verb) {
|
||||
// The Claude Code store takes the names the server offers; it is never read this way.
|
||||
(Store::Claude, Verb::Offer) => true,
|
||||
(Store::Vault, Verb::Ask) if !req.generate => false,
|
||||
(Store::Vault, _) => UNATTENDED_NAMESPACES
|
||||
.iter()
|
||||
.any(|ns| req.item.strip_prefix(ns).is_some_and(|rest| !rest.is_empty() && !rest.contains(".."))),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a run's signature is made without a card: a machine-key vault (not taken over), the release kinds.
|
||||
pub fn unattended_sign(
|
||||
level: Level,
|
||||
ticked: &BTreeSet<Item>,
|
||||
machine_key_vault: bool,
|
||||
kind: &str,
|
||||
has_run: bool,
|
||||
) -> bool {
|
||||
machine_key_vault
|
||||
&& has_run
|
||||
&& level != Level::Hardened
|
||||
&& !ticked.contains(&Item::CardSigning)
|
||||
&& matches!(kind, "minisign" | "manifest" | "authenticode" | "approval")
|
||||
}
|
||||
|
||||
/// Whether *Sign & release*, *Accept*, *Accept all* and approvals ask for Windows Hello first.
|
||||
pub fn hello_for_approvals(ticked: &BTreeSet<Item>) -> bool {
|
||||
ticked.contains(&Item::HelloApprovals)
|
||||
@@ -340,6 +451,34 @@ impl Vault {
|
||||
self.security.kept_scope.take()
|
||||
}
|
||||
|
||||
/// Records a note with its detail: `auto-connected`, `unattended-stored`, `setup-item-removed` or
|
||||
/// `unattended-signed`. The caller saves.
|
||||
pub fn security_note(&mut self, action: Action, detail: &str, now: i64) -> Result<(), Error> {
|
||||
if !matches!(
|
||||
action,
|
||||
Action::AutoConnected | Action::UnattendedStored | Action::SetupItemRemoved | Action::UnattendedSigned
|
||||
) {
|
||||
return Err(Error::Security(
|
||||
"only auto-connected, unattended-stored, setup-item-removed and unattended-signed are notes",
|
||||
));
|
||||
}
|
||||
detail_ok(detail)?;
|
||||
let st = &mut self.security;
|
||||
st.notice_expiry(now);
|
||||
st.audit.push(SecurityEntry { at: now, action, item: None, auth: None, detail: Some(detail.to_owned()) });
|
||||
trim(&mut st.audit);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The take-over's half in this member: ticks the items that end unattended work and writes `taken-over`.
|
||||
pub(crate) fn security_taken_over(&mut self, now: i64) {
|
||||
self.security.notice_expiry(now);
|
||||
for item in [Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning] {
|
||||
self.security_tick(item, now);
|
||||
}
|
||||
self.security.push(now, Action::TakenOver, None, None);
|
||||
}
|
||||
|
||||
/// Records `ssh-connected` or `totp-moved`; the other actions are written by the calls above. The caller saves.
|
||||
pub fn security_record(&mut self, action: Action, item: Option<Item>, now: i64) -> Result<(), Error> {
|
||||
if !matches!(action, Action::SshConnected | Action::TotpMoved) {
|
||||
|
||||
@@ -49,6 +49,8 @@ pub enum KeyKind {
|
||||
Ed25519,
|
||||
RootCa,
|
||||
CodeSigning,
|
||||
/// An Android app's signing key (core 0.14.0): RSA-4096 and a self-signed certificate; signs `apk` only.
|
||||
Android,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -59,6 +61,9 @@ pub enum SignKind {
|
||||
Authenticode,
|
||||
/// A deploy approval's canonical JSON, signed as minisign by `domi-approve` only (core 0.12.0).
|
||||
Approval,
|
||||
/// APK Signature Scheme v2/v3: 1 to 4 SHA-512 digests, signed with RSA PKCS#1 v1.5, by an Android key only
|
||||
/// (core 0.14.0).
|
||||
Apk,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -92,7 +97,8 @@ pub struct Context {
|
||||
pub struct Request {
|
||||
pub key: String,
|
||||
pub kind: SignKind,
|
||||
/// BLAKE2b-512 of the file (minisign) or signtool's 32-byte digest (authenticode). Empty for a manifest.
|
||||
/// BLAKE2b-512 of the file (minisign), signtool's 32-byte digest (authenticode), or 1 to 4 SHA-512 digests of
|
||||
/// an APK's signed data, concatenated (apk). Empty for a manifest or an approval.
|
||||
pub digest: Vec<u8>,
|
||||
/// The `SHA256SUMS` text, for a manifest.
|
||||
pub manifest: Option<String>,
|
||||
@@ -148,7 +154,8 @@ pub struct AuditEntry {
|
||||
/// A signature handed back to the build.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Signed {
|
||||
/// The `.minisig` text (minisign, manifest) or the raw RSA signature (authenticode).
|
||||
/// The `.minisig` text (minisign, manifest, approval), the raw RSA signature (authenticode) or the raw RSA
|
||||
/// signatures, concatenated in the order of the digests (apk).
|
||||
pub bytes: Vec<u8>,
|
||||
pub sha256: String,
|
||||
}
|
||||
@@ -170,7 +177,7 @@ pub struct KeyView {
|
||||
pub key_id: Option<String>,
|
||||
/// The `minisign.pub` text, for Ed25519 keys.
|
||||
pub minisign_public: Option<String>,
|
||||
/// The certificate (DER), for root and code-signing keys.
|
||||
/// The certificate (DER), for root, code-signing and Android keys.
|
||||
pub cert: Option<Vec<u8>>,
|
||||
pub issuer: Option<String>,
|
||||
}
|
||||
@@ -275,7 +282,7 @@ impl Store {
|
||||
let seed: [u8; 32] = k.secret.expose().try_into().ok()?;
|
||||
Secret::Ed25519(Ed25519Secret::from_bytes(seed))
|
||||
}
|
||||
KeyKind::RootCa | KeyKind::CodeSigning => {
|
||||
KeyKind::RootCa | KeyKind::CodeSigning | KeyKind::Android => {
|
||||
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
|
||||
}
|
||||
};
|
||||
@@ -297,6 +304,10 @@ impl Store {
|
||||
Some(c) => Some(unb64(c)?),
|
||||
None => None,
|
||||
};
|
||||
// An Android key is nothing without its certificate: the app is identified by it forever.
|
||||
if k.kind == KeyKind::Android && cert.is_none() {
|
||||
return None;
|
||||
}
|
||||
keys.push(Key {
|
||||
id: k.id,
|
||||
kind: k.kind,
|
||||
@@ -372,6 +383,22 @@ fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key {
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`Vault::signing_create_android`] makes: the key's id and name, the certificate's subject, its role and
|
||||
/// who may ask. The key is RSA-4096 and the certificate is valid [`custos_sign::ANDROID_YEARS`] years.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AndroidKey {
|
||||
/// `[a-z0-9-]{1,64}`, e.g. `postea-android`; not the id of a key the vault has.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
/// The certificate's subject: common name, organisation, two-letter country code.
|
||||
pub cn: String,
|
||||
pub o: String,
|
||||
pub c: String,
|
||||
pub role: Role,
|
||||
pub pipelines: Vec<String>,
|
||||
pub repos: Vec<String>,
|
||||
}
|
||||
|
||||
fn in_scope(list: &[String], what: &str) -> bool {
|
||||
list.iter().any(|x| x == "*" || x == what)
|
||||
}
|
||||
@@ -399,7 +426,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",
|
||||
@@ -472,7 +500,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")
|
||||
@@ -484,6 +516,49 @@ impl Vault {
|
||||
Ok(APPROVE_KEY.into())
|
||||
}
|
||||
|
||||
/// Creates an Android app signing key (core 0.14.0): RSA-4096 and a self-signed certificate. A release key
|
||||
/// always asks; a test key signs without asking, never for a `tag`. The caller saves. Slow: one RSA-4096 key.
|
||||
pub fn signing_create_android(&mut self, spec: &AndroidKey, now: i64) -> Result<String, Error> {
|
||||
let id = spec.id.as_str();
|
||||
if id.is_empty()
|
||||
|| id.len() > 64
|
||||
|| !id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||
{
|
||||
return Err(Error::Signing("a key id is 1 to 64 of a-z, 0-9 and -".into()));
|
||||
}
|
||||
if self.signing.get(id).is_some() {
|
||||
return Err(Error::Signing(format!("there is a key `{id}` already")));
|
||||
}
|
||||
let name = spec.name.trim();
|
||||
if name.is_empty() || name.len() > 100 || name.chars().any(char::is_control) {
|
||||
return Err(Error::Signing("the key's name is not usable".into()));
|
||||
}
|
||||
let (pipelines, repos) = (clean_list(&spec.pipelines)?, clean_list(&spec.repos)?);
|
||||
let made = custos_sign::new_android(&spec.cn, &spec.o, &spec.c).map_err(|e| match e {
|
||||
custos_sign::Error::Certificate => Error::Signing(
|
||||
"the certificate's name is not usable (1-64 characters without , + = \" \\ < > ; # and no space at \
|
||||
either end, and a two-letter country code)"
|
||||
.into(),
|
||||
),
|
||||
e => Error::Signing(e.to_string()),
|
||||
})?;
|
||||
self.signing.keys.push(Key {
|
||||
id: id.into(),
|
||||
kind: KeyKind::Android,
|
||||
role: spec.role,
|
||||
name: name.into(),
|
||||
secret: Secret::Rsa(made.secret),
|
||||
public: None,
|
||||
key_id: None,
|
||||
cert: Some(made.cert_der),
|
||||
issuer: None,
|
||||
created: now,
|
||||
pipelines,
|
||||
repos,
|
||||
});
|
||||
Ok(id.into())
|
||||
}
|
||||
|
||||
/// Every signing key, public parts only.
|
||||
pub fn signing_keys(&self) -> Vec<KeyView> {
|
||||
self.signing
|
||||
@@ -553,6 +628,7 @@ impl Vault {
|
||||
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY,
|
||||
(KeyKind::Ed25519, SignKind::Approval) => approver,
|
||||
(KeyKind::CodeSigning, SignKind::Authenticode) => true,
|
||||
(KeyKind::Android, SignKind::Apk) => true,
|
||||
_ => false,
|
||||
};
|
||||
if k.kind == KeyKind::RootCa {
|
||||
@@ -579,6 +655,13 @@ impl Vault {
|
||||
SignKind::Authenticode if req.digest.len() != 32 => {
|
||||
return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into()));
|
||||
}
|
||||
SignKind::Apk
|
||||
if req.digest.is_empty()
|
||||
|| req.digest.len() % 64 != 0
|
||||
|| req.digest.len() > 64 * custos_sign::MAX_APK_DIGESTS =>
|
||||
{
|
||||
return Err(Refusal::Invalid("an APK request is 1 to 4 SHA-512 digests: 64 bytes each".into()));
|
||||
}
|
||||
SignKind::Manifest => {
|
||||
let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?;
|
||||
custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?;
|
||||
@@ -670,6 +753,7 @@ impl Vault {
|
||||
)
|
||||
.map(String::into_bytes),
|
||||
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
|
||||
(Secret::Rsa(s), SignKind::Apk) => custos_sign::apk(s, &req.digest),
|
||||
_ => unreachable!("signing_check matched the key to the kind"),
|
||||
};
|
||||
let bytes = match bytes {
|
||||
@@ -805,6 +889,19 @@ mod tests {
|
||||
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
||||
v.signing_create(Role::Release, &s(&["*"]), &s(&["*"]), 1).unwrap();
|
||||
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), 1).unwrap();
|
||||
for (id, role) in [("postea-android", Role::Release), ("domi-test-android", Role::Test)] {
|
||||
let spec = AndroidKey {
|
||||
id: id.into(),
|
||||
name: id.into(),
|
||||
cn: "Postea".into(),
|
||||
o: "Marek Novak".into(),
|
||||
c: "CZ".into(),
|
||||
role,
|
||||
pipelines: s(&["*"]),
|
||||
repos: s(&["*"]),
|
||||
};
|
||||
v.signing_create_android(&spec, 1).unwrap();
|
||||
}
|
||||
let secrets: Vec<Vec<u8>> = v
|
||||
.signing
|
||||
.keys
|
||||
@@ -814,7 +911,7 @@ mod tests {
|
||||
Secret::Rsa(s) => s.expose().to_vec(),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(secrets.len(), 7, "the release set with domi-approve, and the test set");
|
||||
assert_eq!(secrets.len(), 9, "the release set with domi-approve, the test set, two Android keys");
|
||||
|
||||
// Every public way out: views (serialised and printed), certificates, minisign public keys, checks,
|
||||
// signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store.
|
||||
@@ -839,6 +936,10 @@ mod tests {
|
||||
));
|
||||
reqs.push(approve);
|
||||
reqs.push(req("domi-approve", SignKind::Minisign, 64));
|
||||
reqs.push(req("postea-android", SignKind::Apk, 128));
|
||||
reqs.push(req("domi-test-android", SignKind::Apk, 64));
|
||||
reqs.push(req("postea-android", SignKind::Authenticode, 32));
|
||||
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] {
|
||||
@@ -852,6 +953,12 @@ mod tests {
|
||||
v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved),
|
||||
"an approval was signed too"
|
||||
);
|
||||
assert!(
|
||||
v.signing_audit()
|
||||
.iter()
|
||||
.any(|e| e.kind == SignKind::Apk && e.key == "postea-android" && e.outcome == Outcome::Approved),
|
||||
"and an APK"
|
||||
);
|
||||
out += &serde_json::to_string(v.signing_audit()).unwrap();
|
||||
out += &format!("{:?}", v.signing_audit());
|
||||
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
|
||||
|
||||
@@ -0,0 +1,265 @@
|
||||
//! Android APK signing keys (core 0.14.0, docs/SIGNING.md "apk"): the key and its certificate, the `apk` kind and
|
||||
//! nothing else, scope, the test-key rules, malformed requests, the audit through a reopen, and never unattended.
|
||||
//! That no API path returns an Android key's private half is part of the unit test in src/signing.rs.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use custos_vault::security::{self, Level};
|
||||
use custos_vault::signing::{AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
|
||||
use custos_vault::{Error, KdfParams, SecretString, Vault};
|
||||
use rsa::pkcs1v15::{Signature, VerifyingKey};
|
||||
use rsa::pkcs8::DecodePublicKey;
|
||||
use rsa::signature::hazmat::PrehashVerifier;
|
||||
use x509_cert::der::{Decode, Encode};
|
||||
|
||||
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
const NOW: i64 = 1_793_750_000_000;
|
||||
const REPO: &str = "mnovak/Postea";
|
||||
|
||||
fn s(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
fn spec(id: &str, role: Role, pipelines: &[&str], repos: &[&str]) -> AndroidKey {
|
||||
AndroidKey {
|
||||
id: id.into(),
|
||||
name: if role == Role::Release { "Postea Android".into() } else { "Domi test Android".into() },
|
||||
cn: if role == Role::Release { "Postea".into() } else { "Domi Test Android".into() },
|
||||
o: if role == Role::Release { "Marek Novak".into() } else { "Domi".into() },
|
||||
c: "CZ".into(),
|
||||
role,
|
||||
pipelines: s(pipelines),
|
||||
repos: s(repos),
|
||||
}
|
||||
}
|
||||
|
||||
/// A vault with the release and test sets, `postea-android` (release, `mnovak/Postea`) and `domi-test-android`
|
||||
/// (test, any). Two RSA-4096 keys are made once and the vault reopened from its bytes for each test.
|
||||
fn vault() -> Vault {
|
||||
static BYTES: OnceLock<Vec<u8>> = OnceLock::new();
|
||||
let bytes = BYTES.get_or_init(|| {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap();
|
||||
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).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();
|
||||
v.to_bytes().unwrap()
|
||||
});
|
||||
Vault::open(bytes, &SecretString::from("pw")).unwrap()
|
||||
}
|
||||
|
||||
fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
|
||||
Context {
|
||||
repo: repo.into(),
|
||||
commit: "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1".into(),
|
||||
pipeline: pipeline.into(),
|
||||
step: "sign".into(),
|
||||
trigger: trigger.into(),
|
||||
file: "Postea-1.0.0.apk".into(),
|
||||
size: 9_876_543,
|
||||
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
|
||||
version: "1.0.0".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn apk_req(key: &str, digests: usize, c: Context) -> Request {
|
||||
Request {
|
||||
key: key.into(),
|
||||
kind: SignKind::Apk,
|
||||
digest: (0..digests * 64).map(|i| (i % 251) as u8).collect(),
|
||||
manifest: None,
|
||||
approval: None,
|
||||
run: Some("r-7".into()),
|
||||
context: c,
|
||||
via: Via::Local,
|
||||
}
|
||||
}
|
||||
|
||||
fn release() -> Context {
|
||||
ctx("release", REPO, "tag")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_android_key_has_its_certificate_and_no_secret_in_its_view() {
|
||||
let v = vault();
|
||||
let keys = v.signing_keys();
|
||||
let k = keys.iter().find(|k| k.id == "postea-android").unwrap();
|
||||
assert_eq!((k.kind, k.role, k.auto_approve), (KeyKind::Android, Role::Release, false));
|
||||
assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&[REPO])));
|
||||
assert_eq!((k.issuer.clone(), k.key_id.clone(), k.minisign_public.clone()), (None, None, None));
|
||||
let cert = v.signing_export_cert("postea-android").unwrap();
|
||||
assert_eq!(k.cert.as_deref(), Some(cert.as_slice()));
|
||||
let c = x509_cert::Certificate::from_der(&cert).unwrap();
|
||||
assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ");
|
||||
assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject);
|
||||
let t = keys.iter().find(|k| k.id == "domi-test-android").unwrap();
|
||||
assert_eq!((t.kind, t.role, t.auto_approve), (KeyKind::Android, Role::Test, true));
|
||||
// Both serialise as the closed value `android`.
|
||||
assert!(serde_json::to_string(k).unwrap().contains(r#""kind":"android""#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_and_names_are_checked_and_an_id_is_made_once() {
|
||||
let mut v = vault();
|
||||
let again = v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW);
|
||||
assert!(matches!(again, Err(Error::Signing(m)) if m.contains("already")));
|
||||
let taken = v.signing_create_android(&spec("domi-release", Role::Release, &["release"], &[REPO]), NOW);
|
||||
assert!(matches!(taken, Err(Error::Signing(_))), "an id of another kind");
|
||||
for bad in ["", "Postea", "postea android", "postea/android", &"x".repeat(65)] {
|
||||
let r = v.signing_create_android(&spec(bad, Role::Release, &["release"], &[REPO]), NOW);
|
||||
assert!(matches!(r, Err(Error::Signing(_))), "{bad:?}");
|
||||
}
|
||||
let mut odd = spec("odd-android", Role::Release, &["release"], &[REPO]);
|
||||
odd.c = "Czechia".into();
|
||||
assert!(matches!(v.signing_create_android(&odd, NOW), Err(Error::Signing(m)) if m.contains("country")));
|
||||
assert_eq!(v.signing_keys().len(), 9, "nothing was added");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_apk_request_signs_every_digest_with_sha512_pkcs1_and_the_certificates_key() {
|
||||
let mut v = vault();
|
||||
let req = apk_req("postea-android", 2, release());
|
||||
assert!(v.signing_check(&req).is_ok());
|
||||
let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
|
||||
assert_eq!(signed.bytes.len(), 2 * 512, "two RSA-4096 signatures");
|
||||
assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes));
|
||||
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("postea-android").unwrap()).unwrap();
|
||||
let spki = cert.tbs_certificate.subject_public_key_info.to_der().unwrap();
|
||||
let key = VerifyingKey::<sha2_010::Sha512>::from_public_key_der(&spki).unwrap();
|
||||
for (d, sig) in req.digest.chunks(64).zip(signed.bytes.chunks(512)) {
|
||||
key.verify_prehash(d, &Signature::try_from(sig).unwrap()).unwrap();
|
||||
}
|
||||
// One request, one audit entry, whatever the number of digests.
|
||||
let a = v.signing_audit().last().unwrap();
|
||||
assert_eq!((a.key.as_str(), a.kind, a.outcome), ("postea-android", SignKind::Apk, Outcome::Approved));
|
||||
assert_eq!((a.context.file.as_str(), a.run.as_deref()), ("Postea-1.0.0.apk", Some("r-7")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_android_key_signs_only_apks_and_only_android_keys_sign_apks() {
|
||||
let mut v = vault();
|
||||
let mut exe = apk_req("postea-android", 0, release());
|
||||
exe.kind = SignKind::Authenticode;
|
||||
exe.digest = vec![9; 32];
|
||||
let mut minisign = exe.clone();
|
||||
minisign.kind = SignKind::Minisign;
|
||||
minisign.digest = vec![9; 64];
|
||||
let leaf = Request {
|
||||
key: "domi-code-signing".into(),
|
||||
context: ctx("release", "Arca", "tag"),
|
||||
..apk_req("", 1, release())
|
||||
};
|
||||
let ed =
|
||||
Request { key: "domi-release".into(), context: ctx("release", "Arca", "tag"), ..apk_req("", 1, release()) };
|
||||
let root = Request { key: "domi-root".into(), ..apk_req("", 1, release()) };
|
||||
let test_leaf = Request { key: "domi-test-code-signing".into(), ..apk_req("", 1, ctx("ci", REPO, "push")) };
|
||||
for r in [&exe, &minisign, &leaf, &ed, &root, &test_leaf] {
|
||||
assert!(matches!(v.signing_check(r), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
|
||||
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
|
||||
}
|
||||
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_repo_or_pipeline_is_out_of_scope_even_when_approved() {
|
||||
let mut v = vault();
|
||||
for c in [ctx("release", "mnovak/Arca", "tag"), ctx("release", "Postea", "tag"), ctx("nightly", REPO, "tag")] {
|
||||
let r = apk_req("postea-android", 2, c);
|
||||
assert!(matches!(v.signing_check(&r), Err(Refusal::OutOfScope(_))));
|
||||
assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
|
||||
}
|
||||
assert_eq!(v.signing_audit().iter().filter(|e| e.outcome == Outcome::OutOfScope).count(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_release_key_always_needs_mark_and_the_test_twin_signs_alone_but_never_a_tag() {
|
||||
let mut v = vault();
|
||||
let r = v.signing_sign(&apk_req("postea-android", 2, release()), Approval::Auto, NOW);
|
||||
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
|
||||
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
|
||||
let t = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "manual")), Approval::Auto, NOW).unwrap();
|
||||
assert_eq!(t.bytes.len(), 1024);
|
||||
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Auto);
|
||||
let tag = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "tag")), Approval::Auto, NOW);
|
||||
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_apk_requests_are_refused() {
|
||||
let mut v = vault();
|
||||
let mut cases = Vec::new();
|
||||
for n in [0usize, 1, 32, 63, 65, 64 * 5] {
|
||||
let mut r = apk_req("postea-android", 0, release());
|
||||
r.digest = vec![1; n];
|
||||
if n != 1 {
|
||||
cases.push(r);
|
||||
}
|
||||
}
|
||||
let mut no_file = apk_req("postea-android", 2, release());
|
||||
no_file.context.file = String::new();
|
||||
let mut path = apk_req("postea-android", 2, release());
|
||||
path.context.file = "out\\Postea.apk".into();
|
||||
let mut stray = apk_req("postea-android", 2, release());
|
||||
stray.approval = Some("{}".into());
|
||||
let mut bad_run = apk_req("postea-android", 2, release());
|
||||
bad_run.run = Some("r 7".into());
|
||||
cases.extend([no_file, path, stray, bad_run]);
|
||||
for r in &cases {
|
||||
assert!(
|
||||
matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))),
|
||||
"{} bytes {:?}",
|
||||
r.digest.len(),
|
||||
r.context.file
|
||||
);
|
||||
}
|
||||
assert_eq!(v.signing_audit().len(), cases.len());
|
||||
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refused_and_expired_apk_requests_are_recorded_and_everything_survives_a_reopen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("v.custos");
|
||||
let mut v = vault();
|
||||
let req = apk_req("postea-android", 2, release());
|
||||
v.signing_refuse(&req, Outcome::Refused, Some("Mark refused this signature".into()), NOW);
|
||||
v.signing_refuse(&req, Outcome::Expired, None, NOW + 1);
|
||||
let signed = v.signing_sign(&req, Approval::Mark, NOW + 2).unwrap();
|
||||
v.save(&path).unwrap();
|
||||
|
||||
let mut back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(back.signing_audit(), v.signing_audit());
|
||||
let outcomes: Vec<Outcome> = back.signing_audit().iter().map(|e| e.outcome).collect();
|
||||
assert_eq!(outcomes, [Outcome::Refused, Outcome::Expired, Outcome::Approved]);
|
||||
assert_eq!(back.signing_audit()[2].signature.as_deref(), Some(signed.sha256.as_str()));
|
||||
assert_eq!(back.signing_keys(), v.signing_keys());
|
||||
// The same key: a reopened vault makes the same (deterministic PKCS#1 v1.5) signatures.
|
||||
assert_eq!(back.signing_sign(&req, Approval::Mark, NOW + 3).unwrap().bytes, signed.bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apk_requests_are_never_signed_unattended_even_on_the_hands_off_vault() {
|
||||
// `unattended_sign` is a closed list of kinds: `apk` is not on it, so an APK always shows the card.
|
||||
for level in [Level::Setup, Level::Standard] {
|
||||
assert!(!security::unattended_sign(level, &BTreeSet::new(), true, "apk", true));
|
||||
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,210 @@
|
||||
//! Hands off (Custos docs/12_hands_off.md): a machine-key vault that Custos opens itself, the rules for auto-connect,
|
||||
//! the unattended setup run and unattended signing, and *Take over the vault*.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use custos_vault::security::{
|
||||
Action, Item, Level, ProvisionAsk, Store, Verb, auto_connect_allowed, is_setup_run, setup_on_connect,
|
||||
unattended_provision, unattended_sign,
|
||||
};
|
||||
use custos_vault::{Error, FactorKind, KdfParams, SecretString, Unlock, Vault};
|
||||
|
||||
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
const NOW: i64 = 1_793_750_000_000;
|
||||
const PC: [u8; 32] = [7; 32];
|
||||
|
||||
fn none() -> BTreeSet<Item> {
|
||||
BTreeSet::new()
|
||||
}
|
||||
fn ticked(items: &[Item]) -> BTreeSet<Item> {
|
||||
items.iter().copied().collect()
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- take over
|
||||
|
||||
#[test]
|
||||
fn a_machine_key_vault_is_taken_over_with_a_master_password() {
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
assert!(v.opens_with_machine_key());
|
||||
// The hands-off vault holds the release set (with the approval key) from its first start.
|
||||
v.signing_create(custos_vault::signing::Role::Release, &[], &[], NOW).unwrap();
|
||||
|
||||
let id = v.take_over(&SecretString::from("a long password"), FAST, NOW).expect("taken over");
|
||||
assert!(!v.opens_with_machine_key());
|
||||
assert!(v.factors().iter().any(|f| f.id == id && f.kind == FactorKind::Password));
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
|
||||
// This PC alone no longer opens it; the password and this PC do, and the keys are still there.
|
||||
assert!(Vault::open_machine_store(&bytes, &PC).is_err(), "the PC-only access is gone");
|
||||
let pw = SecretString::from("a long password");
|
||||
let w = Vault::open_with(&bytes, Unlock::Password(&pw), Unlock::Material(FactorKind::Device, &PC))
|
||||
.expect("two factors");
|
||||
assert!(w.same_key_as(&v));
|
||||
assert_eq!(w.signing_keys().len(), v.signing_keys().len());
|
||||
assert!(!w.signing_keys().is_empty());
|
||||
|
||||
// Unattended work is turned off, and it is audited.
|
||||
let view = w.security_view(NOW);
|
||||
assert!(view.ticked.contains(&Item::NoAutoConnect));
|
||||
assert!(view.ticked.contains(&Item::NoUnattended));
|
||||
assert!(view.ticked.contains(&Item::CardSigning));
|
||||
assert_eq!(view.level, Level::Hardened);
|
||||
assert!(view.audit.iter().any(|e| e.action == Action::TakenOver));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_machine_key_vault_is_taken_over_and_only_once() {
|
||||
let mut user = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
assert!(!user.opens_with_machine_key());
|
||||
assert!(user.take_over(&SecretString::from("a long password"), FAST, NOW).is_err());
|
||||
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
v.take_over(&SecretString::from("a long password"), FAST, NOW).unwrap();
|
||||
assert!(v.take_over(&SecretString::from("another long one"), FAST, NOW).is_err(), "once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn after_the_take_over_a_phone_can_be_added_as_for_any_vault() {
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
assert!(v.add_factor(Unlock::Material(FactorKind::Approval, &[3; 32]), "phone").is_err(), "not before");
|
||||
v.take_over(&SecretString::from("a long password"), FAST, NOW).unwrap();
|
||||
v.add_factor(Unlock::Material(FactorKind::Approval, &[3; 32]), "phone").expect("after");
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
assert!(
|
||||
Vault::open_with(
|
||||
&bytes,
|
||||
Unlock::Material(FactorKind::Device, &PC),
|
||||
Unlock::Material(FactorKind::Approval, &[3; 32])
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_carry_their_detail_and_refuse_other_actions() {
|
||||
let mut v = Vault::create_machine_store(&PC, "MARK-PC").unwrap();
|
||||
v.security_note(Action::AutoConnected, "Connected to 192.168.100.217 as MARK-PC", NOW).unwrap();
|
||||
v.security_note(Action::UnattendedStored, "setup-1: arca/authelia-mark, arca/totp-mark", NOW).unwrap();
|
||||
v.security_note(Action::SetupItemRemoved, "setup-1: arca/totp-mark", NOW).unwrap();
|
||||
v.security_note(Action::UnattendedSigned, "domi-release minisign run r42 Arca_0.3.0_x64-setup.exe", NOW).unwrap();
|
||||
assert!(v.security_note(Action::Ticked, "x", NOW).is_err());
|
||||
assert!(v.security_note(Action::AutoConnected, "line\nbreak", NOW).is_err(), "no control characters");
|
||||
assert!(v.security_note(Action::AutoConnected, &"x".repeat(501), NOW).is_err(), "at most 500 characters");
|
||||
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let w = Vault::open_machine_store(&bytes, &PC).unwrap();
|
||||
let audit = w.security_view(NOW).audit;
|
||||
assert_eq!(audit.len(), 4);
|
||||
assert_eq!(audit[0].detail.as_deref(), Some("Connected to 192.168.100.217 as MARK-PC"));
|
||||
assert_eq!(audit[3].action, Action::UnattendedSigned);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- auto-connect and the Setup window
|
||||
|
||||
#[test]
|
||||
fn auto_connect_runs_in_setup_and_standard_and_stops_when_hardened() {
|
||||
assert!(auto_connect_allowed(Level::Setup, &none()));
|
||||
assert!(auto_connect_allowed(Level::Standard, &none()));
|
||||
assert!(!auto_connect_allowed(Level::Hardened, &ticked(&[Item::HelloApprovals])));
|
||||
assert!(!auto_connect_allowed(Level::Setup, &ticked(&[Item::NoAutoConnect])), "the item holds in Setup too");
|
||||
assert!(!auto_connect_allowed(Level::Setup, &ticked(&[Item::NoSsh])), "no SSH implies no auto-connect");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_connect_opens_setup_unless_unattended_is_off() {
|
||||
assert!(setup_on_connect(&none()));
|
||||
assert!(!setup_on_connect(&ticked(&[Item::NoUnattended])));
|
||||
assert!(!setup_on_connect(&ticked(&[Item::NoSsh])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setup_runs_are_named_setup_dash_something_short() {
|
||||
assert!(is_setup_run("setup-1"));
|
||||
assert!(is_setup_run("setup-2026-11-05.first_run"));
|
||||
assert!(is_setup_run(&format!("setup-{}", "a".repeat(58))));
|
||||
assert!(!is_setup_run(&format!("setup-{}", "a".repeat(59))));
|
||||
assert!(!is_setup_run("setup-"));
|
||||
assert!(!is_setup_run("setup-a b"));
|
||||
assert!(!is_setup_run("setup-a/b"));
|
||||
assert!(!is_setup_run("Setup-1"));
|
||||
assert!(!is_setup_run("r42"));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the unattended setup run
|
||||
|
||||
fn ask(item: &str) -> ProvisionAsk<'_> {
|
||||
ProvisionAsk { verb: Verb::Ask, generate: true, exists: false, store: Store::Vault, item, totp: false }
|
||||
}
|
||||
fn offer(item: &str) -> ProvisionAsk<'_> {
|
||||
ProvisionAsk { verb: Verb::Offer, generate: false, exists: false, store: Store::Vault, item, totp: false }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_setup_run_in_setup_takes_new_items_in_the_allowed_namespaces() {
|
||||
for item in ["arca/authelia-mark", "custos/x", "fabrica/hub-token", "aula/admin", "gitea/read-token"] {
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &ask(item)), "{item}");
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &offer(item)), "{item}");
|
||||
}
|
||||
let totp = ProvisionAsk { totp: true, ..offer("arca/totp-mark") };
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &totp));
|
||||
let claude = ProvisionAsk { store: Store::Claude, ..offer("fabrica-hub-token") };
|
||||
assert!(unattended_provision(Level::Setup, &none(), "setup-1", &claude), "the Claude store's names");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_else_waits_for_a_card() {
|
||||
let s = |l, t: &BTreeSet<Item>, run, r: &ProvisionAsk| unattended_provision(l, t, run, r);
|
||||
let n = none();
|
||||
// Existing items, asks without --generate, replacing offers.
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { exists: true, ..ask("arca/x") }), "an existing item");
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { generate: false, ..ask("arca/x") }), "no --generate");
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { exists: true, ..offer("arca/x") }), "a replacing offer");
|
||||
// Namespaces.
|
||||
for item in ["mark/bank", "domi/root", "arcax/y", "arca", "../arca/x", "ARCA/x"] {
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ask(item)), "{item}");
|
||||
}
|
||||
// Display offers, and asks from the Claude store.
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { store: Store::Display, ..offer("arca/totp-mark") }));
|
||||
assert!(!s(Level::Setup, &n, "setup-1", &ProvisionAsk { store: Store::Claude, ..ask("fabrica-hub-token") }));
|
||||
// The run and the level.
|
||||
assert!(!s(Level::Setup, &n, "r42", &ask("arca/x")), "not a setup run");
|
||||
assert!(!s(Level::Standard, &n, "setup-1", &ask("arca/x")), "after the window");
|
||||
assert!(!s(Level::Hardened, &ticked(&[Item::NarrowScope]), "setup-1", &ask("arca/x")));
|
||||
// Items that turn it off.
|
||||
assert!(!s(Level::Setup, &ticked(&[Item::NoUnattended]), "setup-1", &ask("arca/x")));
|
||||
let totp = ProvisionAsk { totp: true, ..offer("arca/totp-mark") };
|
||||
assert!(!s(Level::Setup, &ticked(&[Item::TotpOnPhone]), "setup-1", &totp), "the TOTP lives on the phone");
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- unattended signing
|
||||
|
||||
#[test]
|
||||
fn a_machine_key_vault_signs_run_requests_of_the_release_kinds_without_a_card() {
|
||||
for kind in ["minisign", "manifest", "authenticode", "approval"] {
|
||||
assert!(unattended_sign(Level::Standard, &none(), true, kind, true), "{kind}");
|
||||
assert!(unattended_sign(Level::Setup, &none(), true, kind, true), "{kind} in Setup");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_waits_for_a_card_otherwise() {
|
||||
assert!(!unattended_sign(Level::Standard, &none(), false, "minisign", true), "taken over");
|
||||
assert!(!unattended_sign(Level::Standard, &none(), true, "minisign", false), "no run");
|
||||
assert!(!unattended_sign(Level::Standard, &none(), true, "ssh", true), "another kind");
|
||||
assert!(!unattended_sign(Level::Hardened, &ticked(&[Item::CardSigning]), true, "minisign", true));
|
||||
assert!(!unattended_sign(Level::Hardened, &ticked(&[Item::HelloApprovals]), true, "minisign", true), "hardened");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_new_items_round_trip_and_can_be_undone() {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
for item in [Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning] {
|
||||
assert!(v.security_tick(item, NOW));
|
||||
}
|
||||
let bytes = v.to_bytes().unwrap();
|
||||
let mut w = Vault::open(&bytes, &SecretString::from("pw")).unwrap();
|
||||
assert_eq!(w.security_view(NOW).ticked, ticked(&[Item::NoAutoConnect, Item::NoUnattended, Item::CardSigning]));
|
||||
assert!(w.security_untick(Item::CardSigning, custos_vault::security::Auth::Hello, NOW));
|
||||
assert!(!w.security_view(NOW).ticked.contains(&Item::CardSigning));
|
||||
let _ = Error::Corrupted;
|
||||
}
|
||||
@@ -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.
|
||||
@@ -10,6 +10,13 @@ on, Custos writes it as v2 only.
|
||||
A **machine store** (the Claude Code store) is the one exception: a separate file whose vault key is
|
||||
wrapped by one device key alone, so a program can open it unattended. It never holds the user's secrets.
|
||||
|
||||
**Taking over a machine-key vault** (core 0.13.0, Custos's hands-off vault): `Vault::take_over(password)` adds the
|
||||
master password as a factor paired with the device key and removes the single slot, in one step. From then on it is
|
||||
an ordinary version-2 vault: two factors open it, the device key alone does not, and factors are added as for any
|
||||
vault (a phone, a TOTP backup). Only a machine-key vault is taken over, and only once; `opens_with_machine_key()`
|
||||
says which it is. The take-over also ticks `no-auto-connect`, `no-unattended` and `card-signing` and writes
|
||||
`taken-over` (FORMAT.md, "The security member").
|
||||
|
||||
## Keys
|
||||
|
||||
```
|
||||
|
||||
+15
-4
@@ -140,7 +140,9 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
|
||||
**Values older cores refuse.** A reader refuses a file whose closed lists hold a value it does not know (see each
|
||||
member), so these values, new in core 0.12.0, make a vault unreadable for a core before 0.12.0 once they are
|
||||
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.
|
||||
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.
|
||||
|
||||
### The provision audit (core 0.11.0)
|
||||
|
||||
@@ -181,7 +183,7 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos,
|
||||
- Readers ignore members of an entry they do not know. A file whose `provision` has an `outcome`, `direction` or
|
||||
`store` this core does not know does not open (`Corrupted`), as for `signing`.
|
||||
|
||||
### The security member (core 0.12.0)
|
||||
### The security member (core 0.12.0; hands-off values 0.13.0)
|
||||
|
||||
```json
|
||||
"security": {
|
||||
@@ -202,9 +204,9 @@ an outcome; a code the server then refuses (its exit 10) is not seen by Custos,
|
||||
| :-- | :-- |
|
||||
| `setup` | optional: the last Setup window, Unix milliseconds; `until` is 2 hours after `started` |
|
||||
| `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` |
|
||||
| `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?}`; `action` is `setup-started`, `setup-finished`, `setup-expired`, `ticked`, `unticked`, `ssh-connected` or `totp-moved`; `item` a checklist item (with `ticked`, `unticked`); `auth` is `hello` or `password` (with `unticked`) |
|
||||
| `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 |
|
||||
|
||||
The **level** is computed, never stored:
|
||||
|
||||
@@ -218,6 +220,15 @@ the first change after it, not by reading.
|
||||
|
||||
- **Append-only** like `provision`: the API adds entries and lists them; the log keeps the newest 5 000.
|
||||
- Absent while nothing was ever set, so a vault without it is written exactly as before.
|
||||
- The values new in core 0.13.0 make a vault unreadable for a core before 0.13.0 once one is written, as the
|
||||
0.12.0 values did before.
|
||||
- **Hands-off rules** (core 0.13.0, `security`): `is_setup_run` (`setup-` and 1–58 of `[A-Za-z0-9._-]`),
|
||||
`auto_connect_allowed` (not Hardened, neither `no-auto-connect` nor `no-ssh`), `setup_on_connect` (neither
|
||||
`no-unattended` nor `no-ssh`), `unattended_provision` (in Setup, a setup run, `no-unattended` not ticked, never an
|
||||
existing item: an `ask --generate` or an `offer` into `arca/`, `custos/`, `fabrica/`, `aula/`, `gitea/`, an offer
|
||||
into the Claude Code store, a TOTP offer unless `totp-on-phone`; never `display`) and `unattended_sign` (a
|
||||
machine-key vault, a request with a run, not Hardened, `card-signing` not ticked, the kinds `minisign`,
|
||||
`manifest`, `authenticode`, `approval`; never `apk`, core 0.14.0). The app enforces them; the server never decides.
|
||||
- Readers ignore members they do not know. A file whose `security` has an item, action or auth this core does not
|
||||
know, a window whose `until` is not after `started`, `finished` without `setup`, or a kept scope that breaks the
|
||||
rules above does not open (`Corrupted`).
|
||||
|
||||
+44
-2
@@ -1,4 +1,4 @@
|
||||
# Signing keys (core 0.9.0; deploy approvals 0.12.0)
|
||||
# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.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
|
||||
@@ -46,6 +46,7 @@ vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vaul
|
||||
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest`; `domi-approve` only `approval` | random |
|
||||
| `root-ca` | RSA-3072; `secret` is PKCS#8 DER; `cert` a self-signed X.509 v3 CA certificate, valid 10 years | only the leaf it issues, at creation; never a request | random |
|
||||
| `code-signing` | RSA-3072; `secret` PKCS#8 DER; `cert` an X.509 v3 leaf issued by `issuer`, valid 2 years, EKU code signing | `authenticode` | random |
|
||||
| `android` (core 0.14.0) | RSA-4096; `secret` PKCS#8 DER; `cert` a self-signed X.509 v3 certificate, valid 100 years, no EKU, under no root | only `apk` | random |
|
||||
|
||||
`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root`, `domi-code-signing` and
|
||||
(since core 0.12.0) `domi-approve` ("Domi deploy approval"), the Ed25519 key that signs deploy approvals, with the
|
||||
@@ -55,6 +56,16 @@ release keys' scope. A vault whose release keys were made by an older core gets
|
||||
`domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is
|
||||
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,
|
||||
for the app's whole life. Its loss ends the app's updates for good, and there is no phrase to recover it from (the
|
||||
vault has none), so **the vault must have two backups off the PC before the first real signature**. Its public
|
||||
half is the certificate (`signing_export_cert`).
|
||||
|
||||
`pipelines` and `repos` list who may ask (pipeline names, repository folder names; `*` means any). A request from
|
||||
a pipeline or repo not on its key's lists is refused **even when approved**. Release keys always need approval.
|
||||
Test keys are approved automatically, but only for requests whose `trigger` is not `tag` (a manual run, a push).
|
||||
@@ -66,6 +77,9 @@ Certificates:
|
||||
`extKeyUsage` codeSigning, subject and authority key identifiers; both signed with sha256WithRSAEncryption.
|
||||
The root's certificate (public part only) is exported as DER (`.cer`) to install as Trusted Root and Trusted
|
||||
Publisher.
|
||||
- android: subject and issuer `CN=<cn>, O=<o>, C=<c>` (encoded C, O, CN; `C` a PrintableString), validity 100 × 365
|
||||
days, `basicConstraints` not a CA, `keyUsage` digitalSignature + nonRepudiation, subject and authority key
|
||||
identifiers (both of its own key), no `extKeyUsage`; sha256WithRSAEncryption by its own key.
|
||||
|
||||
## Signature kinds
|
||||
|
||||
@@ -77,6 +91,7 @@ A request names a key, a kind and what to sign. Custos never receives the file.
|
||||
| `manifest` | `manifest`: the `SHA256SUMS` text itself (≤ 32 KiB, canonical, see below) | a `.minisig` file over it |
|
||||
| `authenticode` | `digest`: the 32-byte SHA-256 in signtool's `.dig` | the RSA PKCS#1 v1.5 signature (384 bytes) for `.dig.signed` |
|
||||
| `approval` | `approval`: a deploy approval's canonical JSON (at most 8 KiB, see below), and `run` | a `.minisig` file over it |
|
||||
| `apk` (core 0.14.0) | `digest`: 1 to 4 SHA-512 digests of APK Signature Scheme signed data, concatenated (64·n bytes) | the n RSA PKCS#1 v1.5 signatures (512 bytes each), concatenated in the same order |
|
||||
|
||||
Any request may carry a `run` (`[A-Za-z0-9._-]{1,64}`, core 0.12.0): the build's run id, so the app can show every
|
||||
request of one run on one card. It is kept in the audit entry. A malformed `run` is `invalid`; `approval` text on a
|
||||
@@ -158,6 +173,28 @@ Checked on 2026-11-04 with signtool 10.0.26100 and a throwaway RSA-3072 key: the
|
||||
with "terminated in a root certificate which is not trusted", and a wrong signature gives "No signature found".
|
||||
`signtool verify /pa` on a machine that trusts the root is the last check, done where the root is installed.
|
||||
|
||||
### apk (core 0.14.0)
|
||||
|
||||
An APK is signed by Google's apksig (`apksigner.jar` from the Android SDK build-tools) on the build's side; Custos
|
||||
signs only what apksig's signer would sign. APK Signature Scheme v2 and v3 each sign one *signed data* block (the
|
||||
APK's content digests, the certificate, attributes; v3 adds the SDK range), so a v2+v3 APK needs two signatures.
|
||||
apksig picks `RSA_PKCS1_V1_5_WITH_SHA512` (`SHA512withRSA`) for every RSA key over 3072 bits and has no way to
|
||||
choose otherwise, so the kind takes **SHA-512** digests and signs each with the SHA-512 DigestInfo:
|
||||
|
||||
- `digest` is 64·n bytes, n from 1 to 4: the SHA-512 of each signed data block, in the order the build wants the
|
||||
signatures back. Anything else is `invalid`. The context's `file` (the APK's name) is required, as for minisign.
|
||||
- The answer is the n signatures concatenated, 512 bytes each for RSA-4096. One request, one card line, one audit
|
||||
entry (its `signature` is the SHA-256 of all of them), so a release run raises **one** card for its APK.
|
||||
- `apk` is signed only by an `android` key, and an `android` key signs nothing else: an Authenticode key cannot sign
|
||||
an APK and an Android key cannot sign an exe (`invalid`).
|
||||
- `apk` is not one of the kinds the hands-off vault may sign without a card (FORMAT.md, `unattended_sign`): an
|
||||
Android key cannot be revoked or replaced, so its signatures always ask.
|
||||
|
||||
The client (`custos-sign apk`, in the app's repository) runs apksig twice: once with a stand-in signer that records
|
||||
the digests and answers with placeholder signatures (the signed data does not depend on the signatures), then, with
|
||||
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.
|
||||
|
||||
## 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
|
||||
@@ -177,7 +214,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.** Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind
|
||||
**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).
|
||||
|
||||
Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind
|
||||
`approval` is a value they do not know, so a core before 0.12.0 refuses a vault that holds one (`Corrupted`): once a
|
||||
vault has recorded an approval request, every Custos that opens it must be on core 0.12.0 or later.
|
||||
|
||||
@@ -186,6 +227,7 @@ vault has recorded an approval request, every Custos that opens it must be on co
|
||||
```
|
||||
Vault::signing_create(role, pipelines, repos, now) -> ids // release (with domi-approve) or test set
|
||||
Vault::signing_add_approve(now) -> "domi-approve" // for release keys made before 0.12.0
|
||||
Vault::signing_create_android(&AndroidKey, now) -> id // one Android key (core 0.14.0)
|
||||
Vault::signing_keys() -> [SigningKeyView] // public parts only
|
||||
Vault::signing_set_scope(id, pipelines, repos)
|
||||
Vault::signing_export_cert(id) -> DER // a certificate, never a key
|
||||
|
||||
@@ -69,6 +69,10 @@ just as plainly, what it does not.
|
||||
password, the TOTP code or a PC.
|
||||
- **An approval is only as careful as the person approving.** Compare the six-digit match code on both
|
||||
screens; a request you did not start is someone else's.
|
||||
- **Losing the vault loses its signing keys.** They never leave it, so no backup holds them but a backup of the
|
||||
vault itself, and there is no phrase to rebuild them from. Most can be replaced with new keys; an Android app's
|
||||
key (docs/SIGNING.md, `android`) cannot: Android accepts updates only from the same certificate, so its loss ends
|
||||
that app's updates for good. Keep two copies of the vault off the PC before the first real signature.
|
||||
|
||||
## Design rules that follow from this
|
||||
|
||||
|
||||
@@ -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