Compare commits

...

8 Commits

36 changed files with 3022 additions and 13 deletions
+1
View File
@@ -1,3 +1,4 @@
# Keep the EFF list byte-for-byte as published (its sha256 is in SOURCES.md).
crates/custos-gen/wordlists/eff_large_wordlist.txt -text
*.sh text eol=lf
crates/custos-sign/tests/fixtures/** -text
+4
View File
@@ -51,3 +51,7 @@ On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C:
first, then a test, then the code.
- Branch → PR on Gitea (token in `$GITEA_TOKEN`, never echoed) → self-review in the PR body → merge `--no-ff`
→ push → `git rev-parse HEAD origin/main` → tag `vX.Y.Z` (the private app pins tags).
## Known traps
- `cargo fmt --all` reformats files that are not rustfmt-clean on `main` (custos-keys, custos-seal, custos-wasm and
some tests): run `rustfmt --edition 2024 <file>` on the files you changed, so a PR carries no unrelated churn.
Generated
+131 -11
View File
@@ -45,7 +45,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
dependencies = [
"base64ct",
"blake2",
"blake2 0.11.0",
"cpufeatures 0.3.1",
"password-hash",
"zeroize",
@@ -102,6 +102,15 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "blake2"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
dependencies = [
"digest 0.10.7",
]
[[package]]
name = "blake2"
version = "0.11.0"
@@ -318,9 +327,16 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "custos-browser"
version = "0.9.0"
dependencies = [
"zeroize",
]
[[package]]
name = "custos-gen"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"custos-vault",
"data-encoding",
@@ -332,7 +348,7 @@ dependencies = [
[[package]]
name = "custos-kdbx"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"aes",
"argon2",
@@ -353,7 +369,7 @@ dependencies = [
[[package]]
name = "custos-keys"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"custos-vault",
"ed25519-dalek",
@@ -364,13 +380,23 @@ dependencies = [
"thiserror",
]
[[package]]
name = "custos-native"
version = "0.9.0"
dependencies = [
"custos-browser",
"serde_json",
"windows-sys",
"zeroize",
]
[[package]]
name = "custos-qr"
version = "0.7.0"
version = "0.9.0"
[[package]]
name = "custos-seal"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"chacha20poly1305",
"hkdf",
@@ -383,7 +409,7 @@ dependencies = [
[[package]]
name = "custos-share"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"argon2",
"chacha20poly1305",
@@ -398,41 +424,63 @@ dependencies = [
"zeroize",
]
[[package]]
name = "custos-sign"
version = "0.9.0"
dependencies = [
"blake2 0.10.6",
"data-encoding",
"ed25519-dalek",
"minisign-verify",
"rand 0.10.3",
"rand_core 0.6.4",
"rsa",
"sha2 0.10.9",
"thiserror",
"x509-cert",
"zeroize",
]
[[package]]
name = "custos-totp"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"custos-vault",
"data-encoding",
"hmac 0.13.0",
"percent-encoding",
"sha1",
"sha1 0.11.0",
"sha2 0.11.1",
"zeroize",
]
[[package]]
name = "custos-vault"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"argon2",
"bip39",
"chacha20poly1305",
"custos-sign",
"data-encoding",
"ed25519-dalek",
"hkdf",
"minisign-verify",
"rand 0.10.3",
"rsa",
"serde",
"serde_json",
"sha2 0.10.9",
"sha2 0.11.1",
"tempfile",
"thiserror",
"x509-cert",
"zeroize",
]
[[package]]
name = "custos-wasm"
version = "0.7.0"
version = "0.9.0"
dependencies = [
"custos-qr",
"custos-seal",
@@ -440,6 +488,7 @@ dependencies = [
"custos-totp",
"custos-vault",
"data-encoding",
"getrandom 0.2.17",
"getrandom 0.4.3",
"qrcode",
"serde",
@@ -460,10 +509,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
dependencies = [
"const-oid 0.9.6",
"der_derive",
"flagset",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "der_derive"
version = "0.7.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "digest"
version = "0.10.7"
@@ -579,6 +641,12 @@ version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
[[package]]
name = "flagset"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
[[package]]
name = "flate2"
version = "1.1.10"
@@ -737,6 +805,12 @@ version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "minisign-verify"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
@@ -1159,6 +1233,17 @@ dependencies = [
"zmij",
]
[[package]]
name = "sha1"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"
dependencies = [
"cfg-if",
"cpufeatures 0.2.17",
"digest 0.10.7",
]
[[package]]
name = "sha1"
version = "0.11.0"
@@ -1340,6 +1425,27 @@ version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "tls_codec"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
dependencies = [
"tls_codec_derive",
"zeroize",
]
[[package]]
name = "tls_codec_derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "typenum"
version = "1.20.1"
@@ -1410,6 +1516,20 @@ dependencies = [
"zeroize",
]
[[package]]
name = "x509-cert"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94"
dependencies = [
"const-oid 0.9.6",
"der",
"sha1 0.10.7",
"signature",
"spki",
"tls_codec",
]
[[package]]
name = "zerocopy"
version = "0.8.63"
+7 -1
View File
@@ -3,7 +3,7 @@ resolver = "3"
members = ["crates/*"]
[workspace.package]
version = "0.8.0"
version = "0.9.0"
edition = "2024"
license = "MPL-2.0"
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
@@ -23,3 +23,9 @@ sha2 = "0.11"
hkdf = "0.13"
data-encoding = "2"
percent-encoding = "2"
# RSA-3072 key generation (custos-sign) takes minutes unoptimised; these keep `cargo test` usable.
[profile.dev.package.num-bigint-dig]
opt-level = 3
[profile.dev.package.rsa]
opt-level = 3
+10
View File
@@ -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
+66
View File
@@ -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());
}
}
+281
View File
@@ -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)
);
}
}
+15
View File
@@ -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"] }
+240
View File
@@ -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 }));
}
}
+27
View File
@@ -0,0 +1,27 @@
[package]
name = "custos-sign"
description = "Custos Domi: release signatures without the key leaving the vault (minisign, SHA256SUMS, Authenticode digests) and the household CA"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
[dependencies]
thiserror.workspace = true
zeroize.workspace = true
data-encoding.workspace = true
# The RustCrypto generation custos-keys already uses (digest 0.10, signature 2).
ed25519-dalek = "2"
rsa = { version = "0.9", default-features = false, features = ["sha2", "u64_digit"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
blake2 = "0.10"
x509-cert = { version = "0.2.5", features = ["builder"] }
# rsa 0.9 generates keys through rand_core 0.6; the bytes come from `rand`'s SysRng (lib.rs, `OsRng06`).
rand_core = "0.6"
rand.workspace = true
[dev-dependencies]
minisign-verify = "0.3"
x509-cert = { version = "0.2.5", features = ["builder"] }
rsa = { version = "0.9", features = ["sha2"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
+53
View File
@@ -0,0 +1,53 @@
//! For tools/signing/interop.ps1 only: makes **throwaway test keys** in a temp folder and signs with them, so the
//! real minisign, signtool and osslsigncode can check what this crate produces. The vault never does this: there,
//! keys are made inside the vault and only signatures come out.
//!
//! interop ca <dir> root.cer, root.pem, leaf.cer, leaf.key.der (test only)
//! interop authenticode <leaf.key.der> <file.dig> writes <file.dig>.signed
//! interop minisign <dir> <file> <dir>/minisign.pub, <file>.minisig
//! interop manifest <dir> <SHA256SUMS> <SHA256SUMS>.minisig, with the key in <dir>
use std::fs;
use std::path::Path;
use custos_sign::*;
use data_encoding::BASE64;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let arg = |i: usize| args.get(i).map(String::as_str).expect("missing argument");
match arg(0) {
"ca" => {
let dir = Path::new(arg(1));
fs::create_dir_all(dir).unwrap();
let root = new_root("Domi Interop Test Root", 1).unwrap();
let leaf = new_code_signing("Domi Interop Test Signing", 1, &root.secret, &root.cert_der).unwrap();
fs::write(dir.join("root.cer"), &root.cert_der).unwrap();
fs::write(dir.join("root.pem"), cert_pem(&root.cert_der)).unwrap();
fs::write(dir.join("leaf.cer"), &leaf.cert_der).unwrap();
fs::write(dir.join("leaf.key.der"), leaf.secret.expose()).unwrap();
}
"authenticode" => {
let key = RsaSecret::from_pkcs8_der(fs::read(arg(1)).unwrap()).unwrap();
let dig = fs::read_to_string(arg(2)).unwrap();
let digest = BASE64.decode(dig.trim().as_bytes()).unwrap();
let sig = authenticode(&key, &digest).unwrap();
fs::write(format!("{}.signed", arg(2)), BASE64.encode(&sig)).unwrap();
}
"minisign" | "manifest" => {
let dir = Path::new(arg(1));
let file = Path::new(arg(2));
let key = new_ed25519();
fs::write(dir.join("minisign.pub"), minisign_public(&key.public, &key.key_id)).unwrap();
let data = fs::read(file).unwrap();
let name = file.file_name().unwrap().to_str().unwrap();
let sig = if arg(0) == "manifest" {
manifest(&key.secret, &key.key_id, std::str::from_utf8(&data).unwrap(), 1_793_750_000).unwrap()
} else {
minisign(&key.secret, &key.key_id, &blake2b512(&data), name, 1_793_750_000).unwrap()
};
fs::write(format!("{}.minisig", file.display()), sig).unwrap();
}
other => panic!("unknown command {other}"),
}
}
+362
View File
@@ -0,0 +1,362 @@
//! Custos Domi · signing: the signature formats docs/SIGNING.md describes, over digests, so the file never has to
//! reach the vault and the key never has to leave it.
//!
//! - 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).
//!
//! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`.
use std::fmt;
use std::str::FromStr;
use std::time::Duration;
use blake2::{Blake2b512, Digest};
use data_encoding::BASE64;
use ed25519_dalek::{Signer as _, SigningKey};
use rand::rand_core::UnwrapErr;
use rand::rngs::SysRng;
use rsa::RsaPrivateKey;
use rsa::pkcs1v15;
use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey};
use rsa::signature::hazmat::PrehashSigner;
use sha2_010::Sha256;
use x509_cert::Certificate;
use x509_cert::builder::{Builder, CertificateBuilder, Profile};
use x509_cert::der::{Decode, Encode};
use x509_cert::ext::pkix::ExtendedKeyUsage;
use x509_cert::name::Name;
use x509_cert::serial_number::SerialNumber;
use x509_cert::spki::SubjectPublicKeyInfoOwned;
use x509_cert::time::Validity;
use zeroize::Zeroizing;
/// Authenticode's code-signing purpose (RFC 5280 id-kp-codeSigning).
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;
const DAY: u64 = 24 * 60 * 60;
/// The largest manifest Custos signs (docs/SIGNING.md).
pub const MAX_MANIFEST: usize = 32 * 1024;
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum Error {
#[error("the digest must be {0} bytes")]
DigestLength(usize),
#[error("the file name cannot be used in a signature: {0}")]
FileName(&'static str),
#[error("the manifest is not in canonical SHA256SUMS form: line {line}: {why}")]
Manifest { line: usize, why: &'static str },
#[error("the key cannot be read")]
BadKey,
#[error("the certificate cannot be built or read")]
Certificate,
}
/// An Ed25519 seed. Wiped on drop; never printed.
pub struct Ed25519Secret(Zeroizing<[u8; 32]>);
impl Ed25519Secret {
pub fn from_bytes(seed: [u8; 32]) -> Self {
Ed25519Secret(Zeroizing::new(seed))
}
/// The seed, for storing in the vault body. Only the vault calls this.
pub fn expose(&self) -> &[u8; 32] {
&self.0
}
pub fn public(&self) -> [u8; 32] {
SigningKey::from_bytes(&self.0).verifying_key().to_bytes()
}
}
impl fmt::Debug for Ed25519Secret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// An RSA private key as PKCS#8 DER. Wiped on drop; never printed.
pub struct RsaSecret(Zeroizing<Vec<u8>>);
impl RsaSecret {
pub fn from_pkcs8_der(der: Vec<u8>) -> Result<Self, Error> {
let der = Zeroizing::new(der);
RsaPrivateKey::from_pkcs8_der(&der).map_err(|_| Error::BadKey)?;
Ok(RsaSecret(der))
}
/// The PKCS#8 DER, for storing in the vault body. Only the vault calls this.
pub fn expose(&self) -> &[u8] {
&self.0
}
fn key(&self) -> Result<RsaPrivateKey, Error> {
RsaPrivateKey::from_pkcs8_der(&self.0).map_err(|_| Error::BadKey)
}
}
impl fmt::Debug for RsaSecret {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("[redacted]")
}
}
/// Fills `buf` from the OS CSPRNG through `rand`'s `SysRng`, as the rest of the workspace does (the browser build
/// routes it to `crypto.getRandomValues`).
fn fill(buf: &mut [u8]) {
rand::Rng::fill_bytes(&mut UnwrapErr(SysRng), buf);
}
/// rand_core 0.6's interface, which `rsa` 0.9 generates keys with, over [`fill`].
struct OsRng06;
impl rand_core::RngCore for OsRng06 {
fn next_u32(&mut self) -> u32 {
let mut b = [0u8; 4];
fill(&mut b);
u32::from_le_bytes(b)
}
fn next_u64(&mut self) -> u64 {
let mut b = [0u8; 8];
fill(&mut b);
u64::from_le_bytes(b)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
fill(dest);
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
fill(dest);
Ok(())
}
}
impl rand_core::CryptoRng for OsRng06 {}
// ---- minisign ----
/// A new Ed25519 key with a random minisign key id.
pub struct NewEd25519 {
pub secret: Ed25519Secret,
pub public: [u8; 32],
pub key_id: [u8; 8],
}
pub fn new_ed25519() -> NewEd25519 {
let mut seed = Zeroizing::new([0u8; 32]);
fill(&mut *seed);
let mut key_id = [0u8; 8];
fill(&mut key_id);
let secret = Ed25519Secret(seed);
let public = secret.public();
NewEd25519 { secret, public, key_id }
}
/// minisign prints a key id as one little-endian u64 in upper-case hex.
pub fn key_id_hex(key_id: &[u8; 8]) -> String {
format!("{:016X}", u64::from_le_bytes(*key_id))
}
/// The BLAKE2b-512 of `data`: what a prehashed minisign signature signs.
pub fn blake2b512(data: &[u8]) -> [u8; 64] {
Blake2b512::digest(data).into()
}
/// `minisign.pub`: the public key file minisign `-V -p` and Tauri (base64 of it) read.
pub fn minisign_public(public: &[u8; 32], key_id: &[u8; 8]) -> String {
let mut raw = Vec::with_capacity(42);
raw.extend_from_slice(b"Ed");
raw.extend_from_slice(key_id);
raw.extend_from_slice(public);
format!("untrusted comment: minisign public key {}\n{}\n", key_id_hex(key_id), BASE64.encode(&raw))
}
/// A prehashed minisign signature file over a file whose BLAKE2b-512 is `digest`.
/// The trusted comment is `timestamp:<unix seconds>\tfile:<file>\thashed`, as minisign writes it.
pub fn minisign(
secret: &Ed25519Secret,
key_id: &[u8; 8],
digest: &[u8],
file: &str,
timestamp: u64,
) -> Result<String, Error> {
let digest: &[u8; 64] = digest.try_into().map_err(|_| Error::DigestLength(64))?;
check_file_name(file)?;
let key = SigningKey::from_bytes(&secret.0);
let signature = key.sign(digest).to_bytes();
let trusted = format!("timestamp:{timestamp}\tfile:{file}\thashed");
let mut global_msg = Vec::with_capacity(64 + trusted.len());
global_msg.extend_from_slice(&signature);
global_msg.extend_from_slice(trusted.as_bytes());
let global = key.sign(&global_msg).to_bytes();
let mut line = Vec::with_capacity(74);
line.extend_from_slice(b"ED");
line.extend_from_slice(key_id);
line.extend_from_slice(&signature);
Ok(format!(
"untrusted comment: signature from Custos key {}\n{}\ntrusted comment: {trusted}\n{}\n",
key_id_hex(key_id),
BASE64.encode(&line),
BASE64.encode(&global)
))
}
fn check_file_name(file: &str) -> Result<(), Error> {
if file.is_empty() {
return Err(Error::FileName("empty"));
}
if file.len() > 255 {
return Err(Error::FileName("longer than 255 bytes"));
}
if file.chars().any(char::is_control) {
return Err(Error::FileName("control characters"));
}
if file.contains(['/', '\\']) {
return Err(Error::FileName("a path, not a file name"));
}
Ok(())
}
// ---- the SHA256SUMS manifest ----
/// Checks that `text` is a canonical `SHA256SUMS` (docs/SIGNING.md): `<64 lower hex> <name>\n` lines, names
/// without `/`, `\`, control characters or a leading `-`, unique, sorted by bytes, at least one line.
pub fn manifest_check(text: &str) -> Result<(), Error> {
let err = |line: usize, why: &'static str| Err(Error::Manifest { line, why });
if text.len() > MAX_MANIFEST {
return err(0, "larger than 32 KiB");
}
if text.is_empty() {
return err(0, "empty");
}
if !text.ends_with('\n') {
return err(text.lines().count(), "the last line has no newline");
}
let mut prev: Option<&str> = None;
for (i, line) in text.split_terminator('\n').enumerate() {
let n = i + 1;
if line.ends_with('\r') {
return err(n, "CRLF line ending");
}
let Some((hash, name)) = line.split_once(" ") else {
return err(n, "not `<sha256> <name>`");
};
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
return err(n, "the hash is not 64 lower-case hex digits");
}
if name.is_empty()
|| name.starts_with(['-', ' ', '*'])
|| name.contains(['/', '\\'])
|| name.chars().any(char::is_control)
{
return err(n, "not a plain file name");
}
if prev.is_some_and(|p| p.as_bytes() >= name.as_bytes()) {
return err(n, "names are not sorted and unique");
}
prev = Some(name);
}
Ok(())
}
/// Signs a canonical manifest as minisign (file name `SHA256SUMS`).
pub fn manifest(secret: &Ed25519Secret, key_id: &[u8; 8], text: &str, timestamp: u64) -> Result<String, Error> {
manifest_check(text)?;
minisign(secret, key_id, &blake2b512(text.as_bytes()), "SHA256SUMS", timestamp)
}
// ---- Authenticode ----
/// RSA PKCS#1 v1.5 with the SHA-256 DigestInfo over the 32 bytes of signtool's `.dig` (384 bytes for RSA-3072):
/// what goes, base64-encoded, into `.dig.signed`.
pub fn authenticode(secret: &RsaSecret, digest: &[u8]) -> Result<Vec<u8>, Error> {
if digest.len() != 32 {
return Err(Error::DigestLength(32));
}
let key = pkcs1v15::SigningKey::<Sha256>::new(secret.key()?);
let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?;
Ok(Box::<[u8]>::from(sig).into_vec())
}
// ---- the household CA ----
/// A new RSA-3072 key and its certificate.
pub struct NewCert {
pub secret: RsaSecret,
pub cert_der: Vec<u8>,
}
fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> {
let key = RsaPrivateKey::new(&mut OsRng06, RSA_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))))
}
fn serial() -> Result<SerialNumber, Error> {
let mut bytes = [0u8; 16];
fill(&mut bytes);
bytes[0] &= 0x7f; // positive
bytes[0] |= 0x01; // and without a leading zero byte
SerialNumber::new(&bytes).map_err(|_| Error::Certificate)
}
fn name(cn: &str) -> Result<Name, Error> {
if cn.is_empty() || cn.len() > 64 || cn.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#']) {
return Err(Error::Certificate);
}
Name::from_str(&format!("CN={cn},O=Domi")).map_err(|_| Error::Certificate)
}
fn spki(key: &RsaPrivateKey) -> Result<SubjectPublicKeyInfoOwned, Error> {
let der = key.to_public_key().to_public_key_der().map_err(|_| Error::Certificate)?;
SubjectPublicKeyInfoOwned::from_der(der.as_bytes()).map_err(|_| Error::Certificate)
}
/// 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 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)?;
let builder = CertificateBuilder::new(Profile::Root, serial()?, validity, name(cn)?, 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)? })
}
/// 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 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 {
issuer: issuer_cert.tbs_certificate.subject.clone(),
enable_key_agreement: false,
enable_key_encipherment: false,
};
let mut builder = CertificateBuilder::new(profile, serial()?, validity, name(cn)?, spki(&key)?, &signer)
.map_err(|_| Error::Certificate)?;
builder.add_extension(&ExtendedKeyUsage(vec![CODE_SIGNING])).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)? })
}
/// A certificate as PEM, for tools that want text.
pub fn cert_pem(der: &[u8]) -> String {
let b64 = BASE64.encode(der);
let mut out = String::from("-----BEGIN CERTIFICATE-----\n");
for chunk in b64.as_bytes().chunks(64) {
out.push_str(std::str::from_utf8(chunk).expect("base64 is ASCII"));
out.push('\n');
}
out.push_str("-----END CERTIFICATE-----\n");
out
}
/// The SHA-256 (hex) of `bytes`, for the audit log.
pub fn sha256_hex(bytes: &[u8]) -> String {
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
}
+6
View File
@@ -0,0 +1,6 @@
Throwaway **test keys** for the known-answer tests in `../kat.rs`. They sign nothing real and are not secret.
- `minisign.key`, `minisign.pub`: made by minisign 0.12 (`minisign -G -W`, unencrypted);
`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).
+1
View File
@@ -0,0 +1 @@
a 32-byte authenticode digest!!!
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign encrypted secret key
RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxBvPgUoXv/LZDCnnxOD2qjtAzgKzt2QB+BBy+4kjkKJHj7TUGad2U26fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign public key F2BF174A81CF1BC4
RWTEG8+BShe/8m6fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7
+1
View File
@@ -0,0 +1 @@
Domi release test payload: not a real file.
+4
View File
@@ -0,0 +1,4 @@
untrusted comment: signature from minisign secret key
RUTEG8+BShe/8k8Vdth34r/l/IFsZ8pkM0jYtPdZhh0DM64A4TS0EKmGNrkj5Pu2Xwc2tIyuRxlM7v4EBYvg56e31UQelhhc2QY=
trusted comment: timestamp:1700000000 file:payload.bin hashed
dt96Kkj7fBuSn8yp9AA3Ggx3FFf5G6Ta6MnGjyP//1FsvNhJtwd2Mh3dgDLwJqXPggz+P3mJgFrfFvg53CohAg==
Binary file not shown.
+177
View File
@@ -0,0 +1,177 @@
//! 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`.
//! tools/signing/interop.ps1 checks the other direction with the real minisign, signtool and osslsigncode.
use std::fs;
use std::path::PathBuf;
use custos_sign::*;
use data_encoding::BASE64;
use x509_cert::Certificate;
use x509_cert::der::{Decode, Encode};
fn fixture(name: &str) -> Vec<u8> {
fs::read(PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(name)).unwrap()
}
fn text(name: &str) -> String {
String::from_utf8(fixture(name)).unwrap()
}
/// The seed and key id of minisign's unencrypted secret key file.
fn minisign_key() -> (Ed25519Secret, [u8; 8]) {
let file = text("minisign.key");
let raw = BASE64.decode(file.lines().nth(1).unwrap().as_bytes()).unwrap();
assert_eq!(&raw[0..2], b"Ed");
assert_eq!(&raw[2..4], &[0, 0], "the fixture key must be unencrypted");
// sig_alg 2, kdf_alg 2, cksum_alg 2, salt 32, opslimit 8, memlimit 8, then key id 8 and seed ‖ public 64.
let key_id: [u8; 8] = raw[54..62].try_into().unwrap();
let seed: [u8; 32] = raw[62..94].try_into().unwrap();
(Ed25519Secret::from_bytes(seed), key_id)
}
#[test]
fn minisign_signature_equals_the_real_minisigns() {
let (secret, key_id) = minisign_key();
let ours = minisign(&secret, &key_id, &blake2b512(&fixture("payload.bin")), "payload.bin", 1_700_000_000).unwrap();
let theirs = text("payload.bin.minisig");
// The untrusted comment is free text; the signature, the trusted comment and the global signature are not.
let tail = |s: &str| s.lines().skip(1).map(String::from).collect::<Vec<_>>();
assert_eq!(tail(&ours), tail(&theirs));
assert!(ours.ends_with('\n'));
}
#[test]
fn the_public_key_file_equals_the_real_minisigns() {
let (secret, key_id) = minisign_key();
let ours = minisign_public(&secret.public(), &key_id);
assert_eq!(ours, text("minisign.pub"));
}
#[test]
fn minisign_verify_accepts_our_signatures_and_rejects_a_changed_file() {
// minisign-verify is what Tauri's updater checks signatures with.
let (secret, key_id) = minisign_key();
let public = minisign_verify::PublicKey::decode(&text("minisign.pub")).unwrap();
let data = b"the installer bytes";
let sig = minisign(&secret, &key_id, &blake2b512(data), "Arca_0.2.0_x64-setup.exe", 1_793_750_000).unwrap();
let sig = minisign_verify::Signature::decode(&sig).unwrap();
public.verify(data, &sig, false).unwrap();
assert!(public.verify(b"another file", &sig, false).is_err());
assert_eq!(sig.trusted_comment(), "timestamp:1793750000\tfile:Arca_0.2.0_x64-setup.exe\thashed");
}
#[test]
fn a_manifest_is_signed_over_its_own_text() {
let (secret, key_id) = minisign_key();
let sums =
format!("{} Arca_0.2.0_x64-setup.exe\n{} Arca_0.2.0_x64-setup.exe.sig\n", "a".repeat(64), "0".repeat(64));
let sig = manifest(&secret, &key_id, &sums, 1_793_750_000).unwrap();
let public = minisign_verify::PublicKey::decode(&text("minisign.pub")).unwrap();
public.verify(sums.as_bytes(), &minisign_verify::Signature::decode(&sig).unwrap(), false).unwrap();
assert!(sig.contains("\tfile:SHA256SUMS\t"));
}
#[test]
fn only_a_canonical_manifest_is_signed() {
let h = "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3";
assert!(manifest_check(&format!("{h} a.exe\n{h} b.exe\n")).is_ok());
let bad = [
("", "empty"),
(&*format!("{h} b.exe\n{h} a.exe\n"), "sorted"),
(&*format!("{h} a.exe\n{h} a.exe\n"), "sorted and unique"),
(&*format!("{} a.exe\n", h.to_uppercase()), "lower-case"),
(&*format!("{h} a.exe\r\n"), "CRLF"),
(&*format!("{h} a.exe"), "no newline"),
(&*format!("{h} a.exe\n"), "not `<sha256> <name>`"),
(&*format!("{h} *a.exe\n"), "not `<sha256> <name>`"),
(&*format!("{h} dir/a.exe\n"), "plain file name"),
(&*format!("{h} -rf\n"), "plain file name"),
(&*format!("{} a.exe\n", &h[..63]), "64 lower-case"),
];
for (t, why) in bad {
let e = manifest_check(t).unwrap_err().to_string();
assert!(e.contains(why), "{t:?}: {e}");
}
let big = format!("{h} {}\n", "x".repeat(MAX_MANIFEST));
assert!(manifest_check(&big).unwrap_err().to_string().contains("32 KiB"));
}
#[test]
fn authenticode_signature_equals_openssls() {
let key = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
let ours = authenticode(&key, &fixture("digest.bin")).unwrap();
assert_eq!(ours.len(), 384);
assert_eq!(ours, fixture("digest.openssl.sig"));
assert_eq!(authenticode(&key, &[0u8; 31]).unwrap_err(), Error::DigestLength(32));
assert_eq!(authenticode(&key, &[0u8; 64]).unwrap_err(), Error::DigestLength(32));
}
#[test]
fn digests_and_file_names_are_checked() {
let (secret, key_id) = minisign_key();
assert_eq!(minisign(&secret, &key_id, &[0u8; 32], "a", 1).unwrap_err(), Error::DigestLength(64));
for bad in ["", "dir/a.exe", "a\\b", "a\nb", "tab\there"] {
assert!(matches!(minisign(&secret, &key_id, &[0u8; 64], bad, 1), Err(Error::FileName(_))), "{bad:?}");
}
}
#[test]
fn the_household_ca_issues_a_code_signing_leaf() {
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::Verifier;
use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage};
let root = new_root("Domi Household Root CA", 10).unwrap();
let rkey = RsaSecret::from_pkcs8_der(root.secret.expose().to_vec()).unwrap();
let leaf = new_code_signing("Domi Code Signing", 2, &rkey, &root.cert_der).unwrap();
let rc = Certificate::from_der(&root.cert_der).unwrap();
let lc = Certificate::from_der(&leaf.cert_der).unwrap();
assert_eq!(rc.tbs_certificate.subject.to_string(), "CN=Domi Household Root CA,O=Domi");
assert_eq!(rc.tbs_certificate.issuer, rc.tbs_certificate.subject);
assert_eq!(lc.tbs_certificate.issuer, rc.tbs_certificate.subject);
let years = |c: &Certificate| {
let v = &c.tbs_certificate.validity;
(v.not_after.to_unix_duration().as_secs() - v.not_before.to_unix_duration().as_secs()) / (365 * 86_400)
};
assert_eq!((years(&rc), years(&lc)), (10, 2));
let (_, bc) = rc.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(bc.ca);
let (_, bc) = lc.tbs_certificate.get::<BasicConstraints>().unwrap().unwrap();
assert!(!bc.ca);
let (_, eku) = lc.tbs_certificate.get::<ExtendedKeyUsage>().unwrap().unwrap();
assert_eq!(eku.0.iter().map(|o| o.to_string()).collect::<Vec<_>>(), vec!["1.3.6.1.5.5.7.3.3"]);
// The leaf is signed by the root's key, and the leaf's key is the one in its certificate.
let rpub = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&rc.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
let sig = Signature::try_from(lc.signature.raw_bytes()).unwrap();
rpub.verify(&lc.tbs_certificate.to_der().unwrap(), &sig).unwrap();
let digest = [7u8; 32];
let lsig = authenticode(&leaf.secret, &digest).unwrap();
let lpub = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&lc.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
use rsa::signature::hazmat::PrehashVerifier;
lpub.verify_prehash(&digest, &Signature::try_from(lsig.as_slice()).unwrap()).unwrap();
assert!(cert_pem(&root.cert_der).starts_with("-----BEGIN CERTIFICATE-----\n"));
}
#[test]
fn secrets_never_print() {
let (secret, _) = minisign_key();
let rsa = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap();
assert_eq!(format!("{secret:?}"), "[redacted]");
assert_eq!(format!("{rsa:?}"), "[redacted]");
let made = new_ed25519();
assert_eq!(format!("{:?}", made.secret), "[redacted]");
assert_eq!(made.public, made.secret.public());
}
+6
View File
@@ -20,6 +20,12 @@ data-encoding.workspace = true
# The Domi identity (docs/IDENTITY.md): the mnemonic and the root key.
bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] }
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
# Signing keys for releases (docs/SIGNING.md).
custos-sign = { path = "../custos-sign" }
[dev-dependencies]
tempfile = "3"
minisign-verify = "0.3"
rsa = { version = "0.9", features = ["sha2"] }
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
x509-cert = "0.2.5"
+29 -1
View File
@@ -23,6 +23,7 @@ pub mod identity;
mod item;
mod save;
mod secret;
pub mod signing;
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
@@ -70,6 +71,10 @@ pub enum Error {
NotACert,
#[error("those words are not the ones in the recovery phrase")]
WrongWords,
#[error("this vault already has {0} signing keys")]
SigningExists(&'static str),
#[error("signing keys: {0}")]
Signing(String),
#[error("{0}")]
Io(#[from] std::io::Error),
}
@@ -261,6 +266,8 @@ struct Body {
factors: Vec<FactorJson>,
#[serde(default)]
identity: Option<identity::RootJson>,
#[serde(default)]
signing: Option<signing::StoreJson>,
}
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
@@ -272,6 +279,8 @@ struct BodyRef<'a> {
factors: Vec<FactorJson>,
#[serde(skip_serializing_if = "Option::is_none")]
identity: Option<identity::RootJson>,
#[serde(skip_serializing_if = "Option::is_none")]
signing: Option<signing::StoreJson>,
}
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
@@ -286,6 +295,8 @@ pub struct Vault {
kdf_new: KdfParams,
/// The Domi identity's root key (docs/IDENTITY.md), never handed out.
identity: Option<identity::Root>,
/// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out.
signing: signing::Store,
}
impl fmt::Debug for Vault {
@@ -385,6 +396,7 @@ impl Vault {
factors: Vec::new(),
kdf_new: kdf,
identity: None,
signing: signing::Store::default(),
})
}
@@ -401,6 +413,7 @@ impl Vault {
factors: Vec::new(),
kdf_new: kdf,
identity: None,
signing: signing::Store::default(),
};
v.add_factor(a, label_a)?;
v.add_factor(b, label_b)?;
@@ -433,6 +446,7 @@ impl Vault {
factors: vec![rec],
kdf_new: KdfParams::DEFAULT,
identity: None,
signing: signing::Store::default(),
})
}
@@ -554,7 +568,20 @@ impl Vault {
Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?),
None => None,
};
Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new, identity })
let signing = match body.signing {
Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?,
None => signing::Store::default(),
};
Ok(Vault {
key,
version: header.version,
slots: header.slots,
items: body.items,
factors,
kdf_new,
identity,
signing,
})
}
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
@@ -588,6 +615,7 @@ impl Vault {
items: &self.items,
factors: self.factors.iter().map(FactorRec::json).collect(),
identity: self.identity.as_ref().map(identity::Root::json),
signing: self.signing.json(),
};
serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?;
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
+718
View File
@@ -0,0 +1,718 @@
//! Signing keys for releases and the audit log of every request (docs/SIGNING.md): the vault body member
//! `signing`. A key's secret is used inside this module and never handed out: the public API returns
//! public keys, certificates, signatures and audit entries only.
use std::fmt;
use custos_sign::{Ed25519Secret, RsaSecret};
use serde::{Deserialize, Serialize};
use crate::{Error, SecretBytes, Vault};
/// What a request may be refused with. Every refusal names why, and none carries key material.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Refusal {
#[error("there is no signing key `{0}`")]
NoKey(String),
#[error("{0}")]
OutOfScope(String),
#[error("{0}")]
Invalid(String),
#[error("`{0}` is a release key: it signs only after Mark approves")]
NeedsApproval(String),
}
impl Refusal {
/// The audit outcome this refusal is recorded as.
pub fn outcome(&self) -> Outcome {
match self {
Refusal::OutOfScope(_) => Outcome::OutOfScope,
Refusal::NeedsApproval(_) => Outcome::Refused,
Refusal::NoKey(_) | Refusal::Invalid(_) => Outcome::Invalid,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
Release,
Test,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum KeyKind {
Ed25519,
RootCa,
CodeSigning,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SignKind {
Minisign,
Manifest,
Authenticode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Via {
Local,
Remote,
}
/// What the build says it is signing. Shown on the card and kept in the audit log; Custos cannot check it
/// against the file (docs/SIGNING.md, the wrong-file risk).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Context {
pub repo: String,
pub commit: String,
pub pipeline: String,
pub step: String,
/// `manual`, `push` or `tag`. A test key never signs for `tag`.
pub trigger: String,
pub file: String,
pub size: u64,
pub sha256: String,
}
/// A signing request, from the Domi pipe or the factor service's mailbox.
#[derive(Debug, Clone, PartialEq, Eq)]
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.
pub digest: Vec<u8>,
/// The `SHA256SUMS` text, for a manifest.
pub manifest: Option<String>,
pub context: Context,
pub via: Via,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Approval {
/// Mark approved this request on the card.
Mark,
/// Nobody was asked: allowed for test keys only.
Auto,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Outcome {
Approved,
Auto,
Refused,
Expired,
OutOfScope,
Invalid,
}
/// One audit entry. Append-only: nothing edits or removes one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditEntry {
pub at: i64,
pub key: String,
pub kind: SignKind,
pub outcome: Outcome,
pub via: Via,
#[serde(flatten)]
pub context: Context,
/// SHA-256 (hex) of what was returned, for signed outcomes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
/// Why, for refusals the vault decided.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
/// 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).
pub bytes: Vec<u8>,
pub sha256: String,
}
/// A key as the app may see it: public parts only.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyView {
pub id: String,
pub kind: KeyKind,
pub role: Role,
pub name: String,
pub created: i64,
pub pipelines: Vec<String>,
pub repos: Vec<String>,
/// Test keys are approved automatically (within scope, never for a `tag` trigger).
pub auto_approve: bool,
/// minisign's key id (hex, as minisign prints it), for Ed25519 keys.
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.
pub cert: Option<Vec<u8>>,
pub issuer: Option<String>,
}
enum Secret {
Ed25519(Ed25519Secret),
Rsa(RsaSecret),
}
struct Key {
id: String,
kind: KeyKind,
role: Role,
name: String,
secret: Secret,
public: Option<[u8; 32]>,
key_id: Option<[u8; 8]>,
cert: Option<Vec<u8>>,
issuer: Option<String>,
created: i64,
pipelines: Vec<String>,
repos: Vec<String>,
}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Key").field("id", &self.id).field("kind", &self.kind).field("secret", &"[redacted]").finish()
}
}
/// The keys and the log, in the vault.
#[derive(Debug, Default)]
pub(crate) struct Store {
keys: Vec<Key>,
audit: Vec<AuditEntry>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct KeyJson {
id: String,
kind: KeyKind,
role: Role,
name: String,
secret: SecretBytes,
#[serde(default, skip_serializing_if = "Option::is_none")]
public: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
key_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cert: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
issuer: Option<String>,
created: i64,
#[serde(default)]
pipelines: Vec<String>,
#[serde(default)]
repos: Vec<String>,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct StoreJson {
#[serde(default)]
keys: Vec<KeyJson>,
#[serde(default)]
audit: Vec<AuditEntry>,
}
fn b64(bytes: &[u8]) -> String {
data_encoding::BASE64.encode(bytes)
}
fn unb64(s: &str) -> Option<Vec<u8>> {
data_encoding::BASE64.decode(s.as_bytes()).ok()
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn unhex8(s: &str) -> Option<[u8; 8]> {
if s.len() != 16 {
return None;
}
let mut out = [0u8; 8];
for (i, o) in out.iter_mut().enumerate() {
*o = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?;
}
Some(out)
}
impl Store {
pub(crate) fn is_empty(&self) -> bool {
self.keys.is_empty() && self.audit.is_empty()
}
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
let mut keys = Vec::new();
for k in j.keys {
let secret = match k.kind {
KeyKind::Ed25519 => {
let seed: [u8; 32] = k.secret.expose().try_into().ok()?;
Secret::Ed25519(Ed25519Secret::from_bytes(seed))
}
KeyKind::RootCa | KeyKind::CodeSigning => {
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
}
};
let public = match &k.public {
Some(p) => Some(unb64(p)?.try_into().ok()?),
None => None,
};
// The stored public key must be the secret's, as for the identity root.
if let (Secret::Ed25519(s), Some(p)) = (&secret, public) {
if s.public() != p {
return None;
}
}
let key_id = match &k.key_id {
Some(h) => Some(unhex8(h)?),
None => None,
};
let cert = match &k.cert {
Some(c) => Some(unb64(c)?),
None => None,
};
keys.push(Key {
id: k.id,
kind: k.kind,
role: k.role,
name: k.name,
secret,
public,
key_id,
cert,
issuer: k.issuer,
created: k.created,
pipelines: k.pipelines,
repos: k.repos,
});
}
Some(Store { keys, audit: j.audit })
}
pub(crate) fn json(&self) -> Option<StoreJson> {
if self.is_empty() {
return None;
}
let keys = self
.keys
.iter()
.map(|k| KeyJson {
id: k.id.clone(),
kind: k.kind,
role: k.role,
name: k.name.clone(),
secret: SecretBytes::new(match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
}),
public: k.public.map(|p| b64(&p)),
key_id: k.key_id.map(|i| hex(&i)),
cert: k.cert.as_ref().map(|c| b64(c)),
issuer: k.issuer.clone(),
created: k.created,
pipelines: k.pipelines.clone(),
repos: k.repos.clone(),
})
.collect();
Some(StoreJson { keys, audit: self.audit.clone() })
}
fn get(&self, id: &str) -> Option<&Key> {
self.keys.iter().find(|k| k.id == id)
}
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
fn clean_list(list: &[String]) -> Result<Vec<String>, Error> {
let mut out: Vec<String> = Vec::new();
for x in list.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) {
if x.len() > 100 || x.chars().any(char::is_control) {
return Err(Error::Signing("a pipeline or repo name is not usable".into()));
}
if !out.iter().any(|o| o == x) {
out.push(x.to_string());
}
}
Ok(out)
}
impl Vault {
/// Creates the release set (`domi-release`, `domi-root`, `domi-code-signing`) or the test set (`domi-test`,
/// `domi-test-root`, `domi-test-code-signing`). The caller saves. Slow: two RSA-3072 keys.
pub fn signing_create(
&mut self,
role: Role,
pipelines: &[String],
repos: &[String],
now: i64,
) -> Result<Vec<String>, Error> {
if self.signing.keys.iter().any(|k| k.role == role) {
return Err(Error::SigningExists(match role {
Role::Release => "release",
Role::Test => "test",
}));
}
let pipelines = clean_list(pipelines)?;
let repos = clean_list(repos)?;
let (ed_id, root_id, leaf_id, ed_name, root_name, leaf_name) = match role {
Role::Release => (
"domi-release",
"domi-root",
"domi-code-signing",
"Domi release",
"Domi Household Root CA",
"Domi Code Signing",
),
Role::Test => (
"domi-test",
"domi-test-root",
"domi-test-code-signing",
"Domi test",
"Domi Test Root (never trusted)",
"Domi Test Code Signing",
),
};
let ed = custos_sign::new_ed25519();
let root = custos_sign::new_root(root_name, 10).map_err(|e| Error::Signing(e.to_string()))?;
let leaf = custos_sign::new_code_signing(leaf_name, 2, &root.secret, &root.cert_der)
.map_err(|e| Error::Signing(e.to_string()))?;
let key = |id: &str, kind, name: &str, secret, cert, issuer: Option<&str>, scoped: bool| Key {
id: id.into(),
kind,
role,
name: name.into(),
secret,
public: None,
key_id: None,
cert,
issuer: issuer.map(String::from),
created: now,
pipelines: if scoped { pipelines.clone() } else { Vec::new() },
repos: if scoped { repos.clone() } else { Vec::new() },
};
let mut ed_key = key(ed_id, KeyKind::Ed25519, ed_name, Secret::Ed25519(ed.secret), None, None, true);
ed_key.public = Some(ed.public);
ed_key.key_id = Some(ed.key_id);
let root_key =
key(root_id, KeyKind::RootCa, root_name, Secret::Rsa(root.secret), Some(root.cert_der), None, false);
let leaf_key = key(
leaf_id,
KeyKind::CodeSigning,
leaf_name,
Secret::Rsa(leaf.secret),
Some(leaf.cert_der),
Some(root_id),
true,
);
self.signing.keys.extend([ed_key, root_key, leaf_key]);
Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()])
}
/// Every signing key, public parts only.
pub fn signing_keys(&self) -> Vec<KeyView> {
self.signing
.keys
.iter()
.map(|k| KeyView {
id: k.id.clone(),
kind: k.kind,
role: k.role,
name: k.name.clone(),
created: k.created,
pipelines: k.pipelines.clone(),
repos: k.repos.clone(),
auto_approve: k.role == Role::Test && k.kind != KeyKind::RootCa,
key_id: k.key_id.map(|i| custos_sign::key_id_hex(&i)),
minisign_public: match (k.public, k.key_id) {
(Some(p), Some(i)) => Some(custos_sign::minisign_public(&p, &i)),
_ => None,
},
cert: k.cert.clone(),
issuer: k.issuer.clone(),
})
.collect()
}
/// Changes who may ask for a key. The caller saves.
pub fn signing_set_scope(&mut self, id: &str, pipelines: &[String], repos: &[String]) -> Result<(), Error> {
let (pipelines, repos) = (clean_list(pipelines)?, clean_list(repos)?);
let k = self
.signing
.keys
.iter_mut()
.find(|k| k.id == id)
.ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
if k.kind == KeyKind::RootCa {
return Err(Error::Signing("a root CA signs no requests, so it has no scope".into()));
}
k.pipelines = pipelines;
k.repos = repos;
Ok(())
}
/// A key's certificate (DER): public, for installing the root or giving signtool the leaf.
pub fn signing_export_cert(&self, id: &str) -> Result<Vec<u8>, Error> {
let k = self.signing.get(id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
k.cert.clone().ok_or_else(|| Error::Signing(format!("`{id}` has no certificate")))
}
/// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline
/// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card.
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
let fits = matches!(
(k.kind, req.kind),
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest)
| (KeyKind::CodeSigning, SignKind::Authenticode)
);
if k.kind == KeyKind::RootCa {
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
}
if !fits {
return Err(Refusal::Invalid(format!("`{}` cannot make {:?} signatures", k.id, req.kind)));
}
match req.kind {
SignKind::Minisign if req.digest.len() != 64 => {
return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into()));
}
SignKind::Authenticode if req.digest.len() != 32 => {
return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".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()))?;
}
_ => {}
}
let file = &req.context.file;
if req.kind != SignKind::Manifest
&& (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control))
{
return Err(Refusal::Invalid("the file name is missing or not a plain name".into()));
}
if !in_scope(&k.pipelines, &req.context.pipeline) {
return Err(Refusal::OutOfScope(format!("pipeline `{}` may not use `{}`", req.context.pipeline, k.id)));
}
if !in_scope(&k.repos, &req.context.repo) {
return Err(Refusal::OutOfScope(format!("repo `{}` may not use `{}`", req.context.repo, k.id)));
}
if k.role == Role::Test && req.context.trigger == "tag" {
return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id)));
}
Ok(self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists"))
}
/// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only.
/// A refusal is recorded too. The caller saves.
pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result<Signed, Refusal> {
let view = match self.signing_check(req) {
Ok(v) => v,
Err(r) => {
self.signing_record(req, r.outcome(), Some(r.to_string()), None, now);
return Err(r);
}
};
if approval == Approval::Auto && !view.auto_approve {
let r = Refusal::NeedsApproval(req.key.clone());
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
}
let k = self.signing.get(&req.key).expect("checked");
let seconds = (now.max(0) / 1000) as u64;
let bytes = match (&k.secret, req.kind) {
(Secret::Ed25519(s), SignKind::Minisign) => custos_sign::minisign(
s,
&k.key_id.expect("ed25519 keys have an id"),
&req.digest,
&req.context.file,
seconds,
)
.map(String::into_bytes),
(Secret::Ed25519(s), SignKind::Manifest) => custos_sign::manifest(
s,
&k.key_id.expect("ed25519 keys have an id"),
req.manifest.as_deref().unwrap_or_default(),
seconds,
)
.map(String::into_bytes),
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
_ => unreachable!("signing_check matched the key to the kind"),
};
let bytes = match bytes {
Ok(b) => b,
Err(e) => {
let r = Refusal::Invalid(e.to_string());
self.signing_record(req, Outcome::Invalid, Some(r.to_string()), None, now);
return Err(r);
}
};
let sha256 = custos_sign::sha256_hex(&bytes);
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
Ok(Signed { bytes, sha256 })
}
/// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves.
pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, now: i64) {
let outcome = match outcome {
Outcome::Approved | Outcome::Auto => Outcome::Refused,
o => o,
};
self.signing_record(req, outcome, reason, None, now);
}
fn signing_record(
&mut self,
req: &Request,
outcome: Outcome,
reason: Option<String>,
signature: Option<String>,
now: i64,
) {
let mut context = req.context.clone();
if req.kind == SignKind::Manifest {
context.file = "SHA256SUMS".into();
}
self.signing.audit.push(AuditEntry {
at: now,
key: req.key.clone(),
kind: req.kind,
outcome,
via: req.via,
context,
signature,
reason,
});
}
/// Every request any key was named in, oldest first.
pub fn signing_audit(&self) -> &[AuditEntry] {
&self.signing.audit
}
}
#[cfg(test)]
mod tests {
//! Mandatory test 2 for the core: no API path returns a private key. It lives here because only this module can
//! see the secrets to look for.
use super::*;
use crate::{KdfParams, SecretString};
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn req(key: &str, kind: SignKind, digest: usize) -> Request {
Request {
key: key.into(),
kind,
digest: vec![5; digest],
manifest: None,
context: Context {
repo: "Arca".into(),
pipeline: "release".into(),
trigger: "tag".into(),
file: "a.exe".into(),
..Default::default()
},
via: Via::Local,
}
}
#[test]
fn no_api_path_returns_a_private_key() {
let mut v =
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.signing_create(Role::Release, &s(&["*"]), &s(&["*"]), 1).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), 1).unwrap();
let secrets: Vec<Vec<u8>> = v
.signing
.keys
.iter()
.map(|k| match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
})
.collect();
assert_eq!(secrets.len(), 6);
// 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.
let mut out = String::new();
let views = v.signing_keys();
out += &serde_json::to_string(&views).unwrap();
out += &format!("{views:?}{:?}", v.signing);
for k in &views {
if let Ok(c) = v.signing_export_cert(&k.id) {
out += &data_encoding::HEXLOWER.encode(&c);
}
}
let mut reqs =
vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)];
reqs.push(req("domi-root", SignKind::Authenticode, 32));
reqs.push(req("domi-test", SignKind::Minisign, 64));
for r in &reqs {
out += &format!("{:?}", v.signing_check(r));
for approval in [Approval::Mark, Approval::Auto] {
match v.signing_sign(r, approval, 2) {
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
Err(e) => out += &format!("{e:?}{e}"),
}
}
}
out += &serde_json::to_string(v.signing_audit()).unwrap();
out += &format!("{:?}", v.signing_audit());
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
for secret in &secrets {
for enc in [
data_encoding::HEXLOWER.encode(secret),
data_encoding::HEXUPPER.encode(secret),
data_encoding::BASE64.encode(secret),
data_encoding::BASE64URL_NOPAD.encode(secret),
] {
assert!(!out.contains(&enc), "a secret appears in an output");
}
}
// Partial copies too: every 16-byte window of the numbers that are actually private. (A PKCS#8 RSA key
// also holds the public modulus and DER headers, which the certificate rightly shows.)
for private in private_parts(&secrets) {
for w in private.windows(16).step_by(8) {
assert!(!out.contains(&data_encoding::HEXLOWER.encode(w)), "part of a secret appears in an output");
assert!(!out.contains(&data_encoding::BASE64.encode(w)[..20]), "part of a secret appears in an output");
}
}
}
/// Ed25519 seeds as they are; for RSA the private exponent and the primes.
fn private_parts(secrets: &[Vec<u8>]) -> Vec<Vec<u8>> {
use rsa::pkcs8::DecodePrivateKey;
use rsa::traits::PrivateKeyParts;
let mut out = Vec::new();
for s in secrets {
if s.len() == 32 {
out.push(s.clone());
} else {
let k = rsa::RsaPrivateKey::from_pkcs8_der(s).unwrap();
out.push(k.d().to_bytes_be());
out.extend(k.primes().iter().map(|p| p.to_bytes_be()));
}
}
assert!(out.len() >= 2 + 4 * 3, "seeds, exponents and primes");
out
}
}
+207
View File
@@ -0,0 +1,207 @@
//! Mandatory tests for signing keys (docs/SIGNING.md): scope (4) and the audit log through a reopen (6). That no API
//! path returns a private key (2) is a unit test in src/signing.rs, which can see the stored secrets; the app tests
//! it again over its pipe ops and mailbox messages.
use custos_vault::signing::{Approval, AuditEntry, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{Error, KdfParams, SecretString, Vault};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn vault_with_keys() -> Vault {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca", "Fabrica"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v
}
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: "Arca_0.2.0_x64-setup.exe".into(),
size: 25_145_977,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
}
}
fn minisign_req(key: &str, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Minisign,
digest: vec![7; 64],
manifest: None,
context: c,
via: Via::Local,
}
}
fn authenticode_req(key: &str, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Authenticode,
digest: vec![9; 32],
manifest: None,
context: c,
via: Via::Remote,
}
}
#[test]
fn the_release_and_test_sets_are_made_once_each() {
let mut v = vault_with_keys();
let keys = v.signing_keys();
let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect();
assert_eq!(
ids,
["domi-release", "domi-root", "domi-code-signing", "domi-test", "domi-test-root", "domi-test-code-signing"]
);
assert_eq!(keys[1].kind, KeyKind::RootCa);
assert_eq!(keys[2].issuer.as_deref(), Some("domi-root"));
assert_eq!(keys[5].issuer.as_deref(), Some("domi-test-root"));
assert!(!keys[0].auto_approve && !keys[2].auto_approve);
assert!(keys[3].auto_approve && keys[5].auto_approve && !keys[4].auto_approve);
assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
// The root's certificate is exported; a key without one is not.
assert_eq!(v.signing_export_cert("domi-root").unwrap(), keys[1].cert.clone().unwrap());
assert!(v.signing_export_cert("domi-release").is_err());
}
#[test]
fn every_kind_signs_and_verifies() {
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::hazmat::PrehashVerifier;
use x509_cert::der::{Decode, Encode};
let mut v = vault_with_keys();
let data = b"the installer";
let mut req = minisign_req("domi-release", ctx("release", "Arca", "tag"));
req.digest = custos_sign::blake2b512(data).to_vec();
let sig = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
let public = minisign_verify::PublicKey::decode(v.signing_keys()[0].minisign_public.as_deref().unwrap()).unwrap();
let text = String::from_utf8(sig.bytes.clone()).unwrap();
public.verify(data, &minisign_verify::Signature::decode(&text).unwrap(), false).unwrap();
assert_eq!(sig.sha256, custos_sign::sha256_hex(&sig.bytes));
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64));
let man = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums.clone()), ..req.clone() };
let msig = v.signing_sign(&man, Approval::Mark, NOW).unwrap();
public
.verify(
sums.as_bytes(),
&minisign_verify::Signature::decode(std::str::from_utf8(&msig.bytes).unwrap()).unwrap(),
false,
)
.unwrap();
let auth = authenticode_req("domi-code-signing", ctx("release", "Arca", "tag"));
let asig = v.signing_sign(&auth, Approval::Mark, NOW).unwrap();
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("domi-code-signing").unwrap()).unwrap();
let key = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
&cert.tbs_certificate.subject_public_key_info.to_der().unwrap(),
)
.unwrap();
key.verify_prehash(&auth.digest, &Signature::try_from(asig.bytes.as_slice()).unwrap()).unwrap();
}
#[test]
fn a_pipeline_or_repo_off_the_list_is_refused_even_when_approved() {
let mut v = vault_with_keys();
for c in [ctx("nightly", "Arca", "tag"), ctx("release", "Custos", "tag")] {
let req = minisign_req("domi-release", c);
assert!(matches!(v.signing_check(&req), Err(Refusal::OutOfScope(_))));
assert!(matches!(v.signing_sign(&req, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
}
let leaf = authenticode_req("domi-code-signing", ctx("release", "Custos", "tag"));
assert!(
matches!(v.signing_sign(&leaf, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))),
"the leaf has the same scope"
);
// Widening the scope takes an explicit change.
v.signing_set_scope("domi-release", &s(&["release", "nightly"]), &s(&["Arca"])).unwrap();
assert!(v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW).is_ok());
assert!(v.signing_set_scope("domi-root", &s(&["*"]), &s(&["*"])).is_err());
}
#[test]
fn release_keys_never_sign_without_mark_and_test_keys_never_sign_a_tag() {
let mut v = vault_with_keys();
let r = v.signing_sign(&minisign_req("domi-release", ctx("release", "Arca", "tag")), Approval::Auto, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
let t = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW);
assert!(t.is_ok());
let tag = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "tag")), Approval::Auto, NOW);
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
let leaf =
v.signing_sign(&authenticode_req("domi-test-code-signing", ctx("ci", "Arca", "push")), Approval::Auto, NOW);
assert!(leaf.is_ok());
}
#[test]
fn malformed_requests_and_the_root_are_refused() {
let mut v = vault_with_keys();
let mut short = minisign_req("domi-release", ctx("release", "Arca", "tag"));
short.digest = vec![0; 32];
let wrong_key = authenticode_req("domi-release", ctx("release", "Arca", "tag"));
let root = authenticode_req("domi-root", ctx("release", "Arca", "tag"));
let mut path = minisign_req("domi-release", ctx("release", "Arca", "tag"));
path.context.file = "..\\evil.exe".into();
let man =
Request { kind: SignKind::Manifest, manifest: Some("not sums\n".into()), digest: vec![], ..short.clone() };
let none = minisign_req("nope", ctx("release", "Arca", "tag"));
for r in [&short, &wrong_key, &root, &path, &man] {
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
}
assert!(matches!(v.signing_sign(&none, Approval::Mark, NOW), Err(Refusal::NoKey(_))));
}
#[test]
fn the_audit_log_records_every_outcome_and_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault_with_keys();
let rel = minisign_req("domi-release", ctx("release", "Arca", "tag"));
let signed = v.signing_sign(&rel, Approval::Mark, NOW).unwrap();
v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW + 1).unwrap();
v.signing_refuse(&rel, Outcome::Refused, None, NOW + 2);
v.signing_refuse(&rel, Outcome::Expired, Some("no answer in 5 minutes".into()), NOW + 3);
let _ = v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW + 4);
let _ = v.signing_sign(&minisign_req("nope", ctx("release", "Arca", "tag")), Approval::Mark, NOW + 5);
// A refusal can never be recorded as a signature.
v.signing_refuse(&rel, Outcome::Approved, None, NOW + 6);
v.save(&path).unwrap();
let reopened = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
let audit: &[AuditEntry] = reopened.signing_audit();
let outcomes: Vec<Outcome> = audit.iter().map(|e| e.outcome).collect();
assert_eq!(
outcomes,
[
Outcome::Approved,
Outcome::Auto,
Outcome::Refused,
Outcome::Expired,
Outcome::OutOfScope,
Outcome::Invalid,
Outcome::Refused
]
);
assert_eq!(audit[0].signature.as_deref(), Some(signed.sha256.as_str()));
assert!(audit[2..].iter().all(|e| e.signature.is_none()));
assert_eq!(audit[0].context, ctx("release", "Arca", "tag"));
assert_eq!(audit[0].via, Via::Local);
assert_eq!(audit[3].reason.as_deref(), Some("no answer in 5 minutes"));
assert_eq!(reopened.signing_audit(), v.signing_audit());
// The keys came back too, and still sign.
let mut reopened = reopened;
assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok());
}
+2
View File
@@ -23,3 +23,5 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
getrandom = "0.4"
# rand_core 0.6 (custos-sign, through custos-vault) uses getrandom 0.2: the same browser CSPRNG (lib.rs, `fill_v02`).
getrandom02 = { package = "getrandom", version = "0.2", features = ["custom"] }
+8
View File
@@ -473,6 +473,14 @@ mod abi {
Ok(())
}
/// The same for getrandom 0.2, which rand_core 0.6 (custos-sign's RSA and X.509 crates) is built on. The
/// browser never makes signing keys, but the crates must link.
fn fill_v02(dest: &mut [u8]) -> Result<(), getrandom02::Error> {
unsafe { random_fill(dest.as_mut_ptr(), dest.len()) };
Ok(())
}
getrandom02::register_custom_getrandom!(fill_v02);
#[unsafe(no_mangle)]
pub extern "C" fn alloc(len: usize) -> *mut u8 {
if len == 0 {
+2
View File
@@ -126,6 +126,8 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
- `attachments` (optional item member, core 0.8.0): `[{"name": "id_rsa", "data": "<base64>"}]`, files kept with
the item (imported from KeePass). The data counts as secret: it is never logged or printed.
An older Custos drops `folder` and `attachments` when it saves.
- `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request
(docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later.
### Item types and their fields (v1)
+146
View File
@@ -0,0 +1,146 @@
# Signing keys (core 0.9.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
records it. This page is the contract for the keys, the signature kinds and the audit log.
## Where the keys live
In the vault body, next to `identity` (FORMAT.md), as the optional member `signing`:
```json
"signing": {
"keys": [
{ "id": "domi-release", "kind": "ed25519", "role": "release", "name": "Domi release",
"secret": "<base64>", "public": "<base64>", "keyId": "<16 hex>", "created": 1793750000000,
"pipelines": ["release"], "repos": ["Arca", "Fabrica"] },
{ "id": "domi-root", "kind": "root-ca", "role": "release", "name": "Domi Household Root CA",
"secret": "<base64>", "cert": "<base64 DER>", "created": 1793750000000, "pipelines": [], "repos": [] },
{ "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing",
"secret": "<base64>", "cert": "<base64 DER>", "issuer": "domi-root", "created": 1793750000000,
"pipelines": ["release"], "repos": ["Arca"] }
],
"audit": [
{ "at": 1793750100000, "key": "domi-release", "kind": "minisign", "outcome": "approved", "via": "local",
"repo": "Arca", "commit": "6925d0cb08b9…", "pipeline": "release", "step": "sign", "trigger": "tag",
"file": "Arca_0.1.0_x64-setup.exe", "size": 25145977, "sha256": "c4995c6e…", "signature": "<sha256 hex>" }
]
}
```
Why a body member and not new item types: item types are a closed list, so an older Custos (or the web vault on an
older core) would refuse a whole vault that has an item of a new type; and an item's fields can be revealed,
copied, shared, exported to KeePass and edited, which are all paths a signing key must never take. A body member is
ignored by older readers (FORMAT.md, "Readers ignore JSON members they do not know") and is reachable only through
the functions below. As with `identity`, an older Custos drops `signing` when it saves: every Custos that saves the
vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vault up.
### Keys
| `kind` | Key | Signs | Created |
| :-- | :-- | :-- | :-- |
| `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest` | 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 |
`role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root` and `domi-code-signing`.
*Create test keys* makes `domi-test` (Ed25519) and `domi-test-code-signing`, a leaf issued by its own
`domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is
never trusted by Mark's PCs.
`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).
Certificates:
- root: subject and issuer `CN=<name>, O=Domi`, `basicConstraints` CA (critical), `keyUsage` keyCertSign + cRLSign
(critical), subject key identifier;
- leaf: subject `CN=<name>, O=Domi`, `basicConstraints` not a CA, `keyUsage` digitalSignature + nonRepudiation,
`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.
## Signature kinds
A request names a key, a kind and what to sign. Custos never receives the file.
| `kind` | The request carries | Custos returns |
| :-- | :-- | :-- |
| `minisign` | `digest`: BLAKE2b-512 of the file (64 bytes) | a `.minisig` file (prehashed, `ED`) |
| `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` |
### minisign
minisign's format (`jedisct1.github.io/minisign`), the **prehashed** variant, the one current minisign writes by
default and Tauri's updater (minisign-verify) checks:
```
untrusted comment: signature from Custos key <KEYID>
base64("ED" ‖ key_id ‖ ed25519(BLAKE2b-512(file)))
trusted comment: timestamp:<unix seconds> file:<file name> hashed
base64(ed25519(signature ‖ trusted comment text))
```
`key_id` is the key's 8 bytes as stored; `<KEYID>` is them as one little-endian u64 in upper-case hex, as minisign
prints it. The trusted comment text is what follows `trusted comment: `, without the newline. Every line ends in `\n`.
The public key file is `untrusted comment: minisign public key <KEYID>` and `base64("Ed" ‖ key_id ‖ public)`.
Tauri's updater wants the same two files one level further wrapped: its `pubkey` and each `.sig` are the base64 of
the whole minisign text. That wrapping is the build's job.
### manifest
`SHA256SUMS` in one canonical form, so the same set of files always gives the same bytes: one line per file,
`<64 lower-case hex> <name>\n` (two spaces), names without `/`, `\`, control characters or leading `-`, unique,
sorted by their UTF-8 bytes, no empty file. Custos checks the form, hashes the text itself and signs it as `minisign`
(file name `SHA256SUMS`). A text in any other form is refused, not normalised.
### authenticode
The file is signed by Windows' own tools in three steps, so the key stays in Custos:
1. `signtool sign /dg <dir> /fd sha256 /f <leaf.cer> <file>` writes `<file>.dig` (the base64 of the 32-byte SHA-256
of the signature's authenticated attributes, no newline) and `<file>.p7u` (the unsigned PKCS#7).
2. Custos signs those 32 bytes: RSA PKCS#1 v1.5 with the SHA-256 DigestInfo. The build writes the base64 of the
384 bytes, no newline, to `<file>.dig.signed`.
3. `signtool sign /di <dir> <file>` puts the signature in; `signtool timestamp /tr <url> /td sha256 <file>` adds a
timestamp.
Checked on 2026-11-04 with signtool 10.0.26100 and a throwaway RSA-3072 key: the result verifies with
`osslsigncode verify -CAfile <root>`; `signtool verify /pa` on a machine that does not trust the root fails only
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.
## 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
one entry, whatever happened:
| `outcome` | |
| :-- | :-- |
| `approved` | Mark approved; signed |
| `auto` | a test key; signed without asking |
| `refused` | Mark refused |
| `expired` | nobody answered within 5 minutes |
| `out-of-scope` | the pipeline or repo is not on the key's lists (whether or not it was approved) |
| `invalid` | the request was malformed (wrong digest length, a manifest not in canonical form, a kind the key cannot do) |
`signature` is the SHA-256 (hex) of what was returned, for the signed outcomes. `via` is `local` (the Domi pipe) or
`remote` (the factor service's mailbox). The entry is part of the vault, so it survives a reopen and travels with it.
## The API (custos-vault)
```
Vault::signing_create(role, pipelines, repos, now) -> ids // release or test set
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
Vault::signing_minisign_public(id) -> minisign.pub text
Vault::signing_check(&request) -> Ok | Refusal // before asking Mark
Vault::signing_sign(&request, Approval::{Mark, Auto}, now) -> Signed // checks again, signs, records
Vault::signing_refuse(&request, outcome, now) // records refused / expired
Vault::signing_audit() -> [AuditEntry]
```
No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.
+91
View File
@@ -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;
});
+173
View File
@@ -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;
});
})();
+38
View File
@@ -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.10.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'"
}
}
+77
View File
@@ -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;
}
+20
View File
@@ -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>
+50
View File
@@ -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();
+65
View File
@@ -0,0 +1,65 @@
# Checks custos-sign against the real tools (docs/SIGNING.md, mandatory test 1):
# minisign -V on a minisign signature and on a signed SHA256SUMS;
# signtool /dg -> custos-sign -> signtool /di on an exe, then osslsigncode verify against the test root,
# and signtool verify /pa (which passes only where the test root is trusted; it is not installed by this script).
# Needs: Windows SDK signtool; WSL Debian with Nix (minisign, osslsigncode come from nixpkgs).
# Usage: powershell -File tools/signing/interop.ps1 [-Exe <unsigned exe to sign a copy of>]
param([string]$Exe = "")
# Exit codes decide; PowerShell 5.1 would turn a tool's expected stderr into a terminating error under 'Stop'.
$ErrorActionPreference = 'Continue'
$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$work = Join-Path ([System.IO.Path]::GetTempPath()) ("custos-sign-interop-" + [guid]::NewGuid())
New-Item -ItemType Directory $work | Out-Null
$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" | Sort-Object FullName | Select-Object -Last 1
if (-not $signtool) { throw "signtool not found (Windows SDK)" }
$failed = 0
function Check($name, $ok) { if ($ok) { "PASS $name" } else { "FAIL $name"; $script:failed++ } }
function InWsl($cmd) {
$w = (wsl -d Debian --exec wslpath -a ($work -replace '\\', '/')).Trim()
wsl -d Debian --exec bash -lc "cd '$w' && $cmd"
}
try {
Push-Location $root
cargo build -q --release -p custos-sign --example interop
if ($LASTEXITCODE -ne 0) { throw "cargo build failed" }
$tool = Join-Path $root "target\release\examples\interop.exe"
Pop-Location
# minisign
Set-Content -NoNewline -Encoding ascii (Join-Path $work "payload.bin") "Domi interop payload"
& $tool minisign $work (Join-Path $work "payload.bin")
InWsl "nix shell nixpkgs#minisign -c minisign -Vm payload.bin -p minisign.pub" | Out-Host
Check "minisign -V accepts a custos-sign signature" ($LASTEXITCODE -eq 0)
InWsl "printf 'tampered' >> payload.bin; nix shell nixpkgs#minisign -c minisign -Vm payload.bin -p minisign.pub" 2>$null | Out-Null
Check "minisign -V rejects it on a changed file" ($LASTEXITCODE -ne 0)
$sums = "{0} a.exe`n{1} b.exe`n" -f ('a' * 64), ('b' * 64)
[System.IO.File]::WriteAllText((Join-Path $work "SHA256SUMS"), $sums)
& $tool manifest $work (Join-Path $work "SHA256SUMS")
InWsl "nix shell nixpkgs#minisign -c minisign -Vm SHA256SUMS -p minisign.pub" | Out-Host
Check "minisign -V accepts a signed SHA256SUMS" ($LASTEXITCODE -eq 0)
# Authenticode through signtool's digest signing
$ca = Join-Path $work "ca"
& $tool ca $ca
if (-not $Exe) { $Exe = (Get-Command cargo).Source }
$target = Join-Path $work "app.exe"
Copy-Item $Exe $target
$dg = Join-Path $work "dg"
New-Item -ItemType Directory $dg | Out-Null
& $signtool.FullName sign /dg $dg /fd sha256 /f (Join-Path $ca "leaf.cer") $target | Out-Host
Check "signtool /dg wrote the digest" (Test-Path (Join-Path $dg "app.exe.dig"))
& $tool authenticode (Join-Path $ca "leaf.key.der") (Join-Path $dg "app.exe.dig")
& $signtool.FullName sign /di $dg $target | Out-Host
Check "signtool /di took the signed digest" ($LASTEXITCODE -eq 0)
InWsl "nix shell nixpkgs#osslsigncode -c osslsigncode verify -CAfile ca/root.pem -in app.exe" | Out-Host
Check "osslsigncode verifies the signature to the test root" ($LASTEXITCODE -eq 0)
$v = & $signtool.FullName verify /pa $target 2>&1 | Out-String
$trusted = $LASTEXITCODE -eq 0
if ($trusted) { "PASS signtool verify /pa (the test root is trusted here)" }
elseif ($v -match "not trusted by the trust provider|could not be built to a trusted root") { "NOTE signtool verify /pa: the signature is whole; the test root is not trusted on this machine" }
else { Check "signtool verify /pa" $false; $v }
} finally {
Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue
}
if ($failed) { "$failed check(s) failed"; exit 1 } else { "all checks passed" }