Compare commits
10 Commits
feature/kdbx
...
v0.10.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 4e386e8113 | |||
| 92ab8a0d63 | |||
| bf661a7338 | |||
| 510d5eecd1 | |||
| 06410ab3be | |||
| cd2963392d | |||
| 59fdfa26ef | |||
| 6c6ffd33c0 | |||
| 2a146f342d | |||
| 38c458d21b |
@@ -1,3 +1,4 @@
|
|||||||
# Keep the EFF list byte-for-byte as published (its sha256 is in SOURCES.md).
|
# Keep the EFF list byte-for-byte as published (its sha256 is in SOURCES.md).
|
||||||
crates/custos-gen/wordlists/eff_large_wordlist.txt -text
|
crates/custos-gen/wordlists/eff_large_wordlist.txt -text
|
||||||
*.sh text eol=lf
|
*.sh text eol=lf
|
||||||
|
crates/custos-sign/tests/fixtures/** -text
|
||||||
|
|||||||
@@ -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.
|
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`
|
- 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).
|
→ 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
+114
-11
@@ -45,7 +45,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
|
checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64ct",
|
"base64ct",
|
||||||
"blake2",
|
"blake2 0.11.0",
|
||||||
"cpufeatures 0.3.1",
|
"cpufeatures 0.3.1",
|
||||||
"password-hash",
|
"password-hash",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
@@ -102,6 +102,15 @@ version = "2.13.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
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]]
|
[[package]]
|
||||||
name = "blake2"
|
name = "blake2"
|
||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
@@ -320,7 +329,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-gen"
|
name = "custos-gen"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
@@ -332,7 +341,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-kdbx"
|
name = "custos-kdbx"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"argon2",
|
"argon2",
|
||||||
@@ -353,7 +362,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-keys"
|
name = "custos-keys"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
@@ -366,11 +375,11 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-qr"
|
name = "custos-qr"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-seal"
|
name = "custos-seal"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
"hkdf",
|
"hkdf",
|
||||||
@@ -383,7 +392,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-share"
|
name = "custos-share"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
@@ -398,41 +407,63 @@ dependencies = [
|
|||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "custos-sign"
|
||||||
|
version = "0.10.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]]
|
[[package]]
|
||||||
name = "custos-totp"
|
name = "custos-totp"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
"hmac 0.13.0",
|
"hmac 0.13.0",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
"sha1",
|
"sha1 0.11.0",
|
||||||
"sha2 0.11.1",
|
"sha2 0.11.1",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-vault"
|
name = "custos-vault"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"argon2",
|
"argon2",
|
||||||
"bip39",
|
"bip39",
|
||||||
"chacha20poly1305",
|
"chacha20poly1305",
|
||||||
|
"custos-sign",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
"ed25519-dalek",
|
"ed25519-dalek",
|
||||||
"hkdf",
|
"hkdf",
|
||||||
|
"minisign-verify",
|
||||||
"rand 0.10.3",
|
"rand 0.10.3",
|
||||||
|
"rsa",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"sha2 0.10.9",
|
||||||
"sha2 0.11.1",
|
"sha2 0.11.1",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"thiserror",
|
"thiserror",
|
||||||
|
"x509-cert",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "custos-wasm"
|
name = "custos-wasm"
|
||||||
version = "0.7.0"
|
version = "0.10.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"custos-qr",
|
"custos-qr",
|
||||||
"custos-seal",
|
"custos-seal",
|
||||||
@@ -440,6 +471,7 @@ dependencies = [
|
|||||||
"custos-totp",
|
"custos-totp",
|
||||||
"custos-vault",
|
"custos-vault",
|
||||||
"data-encoding",
|
"data-encoding",
|
||||||
|
"getrandom 0.2.17",
|
||||||
"getrandom 0.4.3",
|
"getrandom 0.4.3",
|
||||||
"qrcode",
|
"qrcode",
|
||||||
"serde",
|
"serde",
|
||||||
@@ -460,10 +492,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"const-oid 0.9.6",
|
"const-oid 0.9.6",
|
||||||
|
"der_derive",
|
||||||
|
"flagset",
|
||||||
"pem-rfc7468",
|
"pem-rfc7468",
|
||||||
"zeroize",
|
"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]]
|
[[package]]
|
||||||
name = "digest"
|
name = "digest"
|
||||||
version = "0.10.7"
|
version = "0.10.7"
|
||||||
@@ -579,6 +624,12 @@ version = "0.2.9"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "flagset"
|
||||||
|
version = "0.4.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "flate2"
|
name = "flate2"
|
||||||
version = "1.1.10"
|
version = "1.1.10"
|
||||||
@@ -737,6 +788,12 @@ version = "2.8.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "minisign-verify"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "miniz_oxide"
|
name = "miniz_oxide"
|
||||||
version = "0.9.1"
|
version = "0.9.1"
|
||||||
@@ -1159,6 +1216,17 @@ dependencies = [
|
|||||||
"zmij",
|
"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]]
|
[[package]]
|
||||||
name = "sha1"
|
name = "sha1"
|
||||||
version = "0.11.0"
|
version = "0.11.0"
|
||||||
@@ -1340,6 +1408,27 @@ version = "1.13.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
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]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
@@ -1410,6 +1499,20 @@ dependencies = [
|
|||||||
"zeroize",
|
"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]]
|
[[package]]
|
||||||
name = "zerocopy"
|
name = "zerocopy"
|
||||||
version = "0.8.63"
|
version = "0.8.63"
|
||||||
|
|||||||
+7
-1
@@ -3,7 +3,7 @@ resolver = "3"
|
|||||||
members = ["crates/*"]
|
members = ["crates/*"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.8.0"
|
version = "0.10.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MPL-2.0"
|
license = "MPL-2.0"
|
||||||
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic"
|
||||||
@@ -23,3 +23,9 @@ sha2 = "0.11"
|
|||||||
hkdf = "0.13"
|
hkdf = "0.13"
|
||||||
data-encoding = "2"
|
data-encoding = "2"
|
||||||
percent-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
|
||||||
|
|||||||
@@ -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"] }
|
||||||
@@ -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}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
@@ -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).
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
a 32-byte authenticode digest!!!
|
||||||
Binary file not shown.
@@ -0,0 +1,2 @@
|
|||||||
|
untrusted comment: minisign encrypted secret key
|
||||||
|
RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxBvPgUoXv/LZDCnnxOD2qjtAzgKzt2QB+BBy+4kjkKJHj7TUGad2U26fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
untrusted comment: minisign public key F2BF174A81CF1BC4
|
||||||
|
RWTEG8+BShe/8m6fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
Domi release test payload: not a real 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.
@@ -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());
|
||||||
|
}
|
||||||
@@ -20,6 +20,12 @@ data-encoding.workspace = true
|
|||||||
# The Domi identity (docs/IDENTITY.md): the mnemonic and the root key.
|
# The Domi identity (docs/IDENTITY.md): the mnemonic and the root key.
|
||||||
bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] }
|
bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] }
|
||||||
ed25519-dalek = { 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]
|
[dev-dependencies]
|
||||||
tempfile = "3"
|
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"
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
|
//! The Domi identity's root key (docs/IDENTITY.md). It lives in the vault body and never leaves it: nothing
|
||||||
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates.
|
//! here or on [`Vault`] returns it, and the vault signs nothing with it but subkey certificates and
|
||||||
|
//! revocations of keys the person revoked. It derives each app's backup secret from it.
|
||||||
//!
|
//!
|
||||||
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
|
//! Creating it is a typestate, so the mnemonic is always shown before the root exists:
|
||||||
//!
|
//!
|
||||||
@@ -46,6 +47,13 @@ use zeroize::Zeroizing;
|
|||||||
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
|
/// The root signs `CERT_DOMAIN ‖ tbs`, and only a `tbs` that starts with `CERT_MAGIC ‖ its public key`.
|
||||||
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
const CERT_DOMAIN: &[u8] = b"tessera cert v1\0";
|
||||||
const CERT_MAGIC: &[u8] = b"TSC1";
|
const CERT_MAGIC: &[u8] = b"TSC1";
|
||||||
|
/// And `REVOKE_DOMAIN ‖ tbs`, only for a `tbs` that starts with `REVOKE_MAGIC ‖ its public key ‖ a key the
|
||||||
|
/// person revoked ‖ that key's revoked_at` (Fundamentum docs/TESSERA.md §12).
|
||||||
|
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
|
||||||
|
const REVOKE_MAGIC: &[u8] = b"TRV1";
|
||||||
|
/// magic 4, root 32, subkey 32, revoked_at 8, part 2, parts 2, count 4.
|
||||||
|
const REVOKE_HEADER: usize = 84;
|
||||||
|
const BACKUP_SALT: &[u8] = b"tessera backup v1";
|
||||||
const WORDS: usize = 24;
|
const WORDS: usize = 24;
|
||||||
|
|
||||||
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
|
/// Step 1: fresh entropy. Nothing is derived from it until the words have been shown.
|
||||||
@@ -111,6 +119,26 @@ impl Enrollment {
|
|||||||
display(&words);
|
display(&words);
|
||||||
Shown { entropy: self.entropy, challenge: random_challenge() }
|
Shown { entropy: self.entropy, challenge: random_challenge() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Restores an identity from its whole phrase, typed back (docs/IDENTITY.md, "Restoring it"): all 24
|
||||||
|
/// words prove more than three. Any case, any spacing. Anything that is not 24 English BIP39 words with a
|
||||||
|
/// valid checksum is [`Error::NotAMnemonic`], which names no word.
|
||||||
|
pub fn restore(phrase: &str) -> Result<Confirmed, Error> {
|
||||||
|
// Room for lowercasing without a reallocation that would leave a copy behind.
|
||||||
|
let mut joined = Zeroizing::new(String::with_capacity(phrase.len() * 3 + 1));
|
||||||
|
for (i, w) in phrase.split_whitespace().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
joined.push(' ');
|
||||||
|
}
|
||||||
|
joined.extend(w.chars().flat_map(char::to_lowercase));
|
||||||
|
}
|
||||||
|
if joined.split(' ').count() != WORDS {
|
||||||
|
return Err(Error::NotAMnemonic);
|
||||||
|
}
|
||||||
|
let m =
|
||||||
|
bip39::Mnemonic::parse_in_normalized(bip39::Language::English, &joined).map_err(|_| Error::NotAMnemonic)?;
|
||||||
|
Ok(Confirmed { secret: crypto::domi_root_secret(&m) })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Shown {
|
impl Shown {
|
||||||
@@ -165,7 +193,7 @@ impl fmt::Debug for Confirmed {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
|
/// A cert the vault signed, for display (docs/IDENTITY.md). A record, not a trust list.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct Issued {
|
pub struct Issued {
|
||||||
/// `app` or `device`.
|
/// `app` or `device`.
|
||||||
pub kind: String,
|
pub kind: String,
|
||||||
@@ -180,6 +208,12 @@ pub struct Issued {
|
|||||||
pub not_after: u64,
|
pub not_after: u64,
|
||||||
/// Unix milliseconds.
|
/// Unix milliseconds.
|
||||||
pub issued: i64,
|
pub issued: i64,
|
||||||
|
/// Unix seconds: when the person revoked the key (core 0.10.0).
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub revoked_at: Option<u64>,
|
||||||
|
/// The signed `TRV1` statements, base64url, once an app sent the events to keep.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub revocation: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The identity in an unlocked vault.
|
/// The identity in an unlocked vault.
|
||||||
@@ -212,6 +246,45 @@ impl Root {
|
|||||||
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
|
||||||
|
let names_me = tbs.len() >= REVOKE_HEADER && &tbs[..4] == REVOKE_MAGIC && tbs[4..36] == self.public;
|
||||||
|
if !names_me {
|
||||||
|
return Err(Error::NotARevocation);
|
||||||
|
}
|
||||||
|
let subkey = data_encoding::BASE64URL_NOPAD.encode(&tbs[36..68]);
|
||||||
|
let at = u64::from_be_bytes(tbs[68..76].try_into().expect("8 bytes"));
|
||||||
|
if !self.issued.iter().any(|i| i.subkey == subkey && i.revoked_at == Some(at)) {
|
||||||
|
return Err(Error::NotARevocation);
|
||||||
|
}
|
||||||
|
let msg = Zeroizing::new([REVOKE_DOMAIN, tbs].concat());
|
||||||
|
Ok(crypto::ed25519_sign(&self.secret, &msg))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Marks every cert of `subkey` revoked; keeps the earliest time if one was marked before.
|
||||||
|
pub(crate) fn mark_revoked(&mut self, subkey: &str, at: u64) -> Result<u64, Error> {
|
||||||
|
let mut certs = self.issued.iter().filter(|i| i.subkey == subkey).peekable();
|
||||||
|
if certs.peek().is_none() {
|
||||||
|
return Err(Error::UnknownKey);
|
||||||
|
}
|
||||||
|
let at = certs.filter_map(|i| i.revoked_at).min().unwrap_or(at);
|
||||||
|
self.issued.iter_mut().filter(|i| i.subkey == subkey).for_each(|i| i.revoked_at = Some(at));
|
||||||
|
Ok(at)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
|
||||||
|
let mut certs = self.issued.iter_mut().filter(|i| i.subkey == subkey).peekable();
|
||||||
|
if certs.peek().is_none() {
|
||||||
|
return Err(Error::UnknownKey);
|
||||||
|
}
|
||||||
|
certs.for_each(|i| i.revocation = statements.clone());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `HKDF-SHA256(salt "tessera backup v1", ikm = root secret, info = app id)` (docs/IDENTITY.md).
|
||||||
|
pub(crate) fn backup_secret(&self, app_id: &str) -> Zeroizing<[u8; KEY_LEN]> {
|
||||||
|
crypto::hkdf(self.secret.as_ref(), BACKUP_SALT, app_id.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn json(&self) -> RootJson {
|
pub(crate) fn json(&self) -> RootJson {
|
||||||
RootJson {
|
RootJson {
|
||||||
root: SecretString::new(hex(self.secret.as_ref())),
|
root: SecretString::new(hex(self.secret.as_ref())),
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ pub mod identity;
|
|||||||
mod item;
|
mod item;
|
||||||
mod save;
|
mod save;
|
||||||
mod secret;
|
mod secret;
|
||||||
|
pub mod signing;
|
||||||
|
|
||||||
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms};
|
||||||
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
|
pub use save::{CrashPoint, save_atomic, save_atomic_crashing};
|
||||||
@@ -70,6 +71,16 @@ pub enum Error {
|
|||||||
NotACert,
|
NotACert,
|
||||||
#[error("those words are not the ones in the recovery phrase")]
|
#[error("those words are not the ones in the recovery phrase")]
|
||||||
WrongWords,
|
WrongWords,
|
||||||
|
#[error("these are not the 24 words of a recovery phrase: check each word and their order")]
|
||||||
|
NotAMnemonic,
|
||||||
|
#[error("the Domi identity signs a revocation only for a key revoked in Custos, at the time it was revoked")]
|
||||||
|
NotARevocation,
|
||||||
|
#[error("the Domi identity did not certify this key")]
|
||||||
|
UnknownKey,
|
||||||
|
#[error("this vault already has {0} signing keys")]
|
||||||
|
SigningExists(&'static str),
|
||||||
|
#[error("signing keys: {0}")]
|
||||||
|
Signing(String),
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
Io(#[from] std::io::Error),
|
Io(#[from] std::io::Error),
|
||||||
}
|
}
|
||||||
@@ -261,6 +272,8 @@ struct Body {
|
|||||||
factors: Vec<FactorJson>,
|
factors: Vec<FactorJson>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
identity: Option<identity::RootJson>,
|
identity: Option<identity::RootJson>,
|
||||||
|
#[serde(default)]
|
||||||
|
signing: Option<signing::StoreJson>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
/// What `to_bytes` serializes: borrows the items instead of cloning every secret.
|
||||||
@@ -272,6 +285,8 @@ struct BodyRef<'a> {
|
|||||||
factors: Vec<FactorJson>,
|
factors: Vec<FactorJson>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
identity: Option<identity::RootJson>,
|
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.
|
/// An unlocked vault: the vault key and the decrypted items, both wiped on drop.
|
||||||
@@ -286,6 +301,8 @@ pub struct Vault {
|
|||||||
kdf_new: KdfParams,
|
kdf_new: KdfParams,
|
||||||
/// The Domi identity's root key (docs/IDENTITY.md), never handed out.
|
/// The Domi identity's root key (docs/IDENTITY.md), never handed out.
|
||||||
identity: Option<identity::Root>,
|
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 {
|
impl fmt::Debug for Vault {
|
||||||
@@ -385,6 +402,7 @@ impl Vault {
|
|||||||
factors: Vec::new(),
|
factors: Vec::new(),
|
||||||
kdf_new: kdf,
|
kdf_new: kdf,
|
||||||
identity: None,
|
identity: None,
|
||||||
|
signing: signing::Store::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -401,6 +419,7 @@ impl Vault {
|
|||||||
factors: Vec::new(),
|
factors: Vec::new(),
|
||||||
kdf_new: kdf,
|
kdf_new: kdf,
|
||||||
identity: None,
|
identity: None,
|
||||||
|
signing: signing::Store::default(),
|
||||||
};
|
};
|
||||||
v.add_factor(a, label_a)?;
|
v.add_factor(a, label_a)?;
|
||||||
v.add_factor(b, label_b)?;
|
v.add_factor(b, label_b)?;
|
||||||
@@ -433,6 +452,7 @@ impl Vault {
|
|||||||
factors: vec![rec],
|
factors: vec![rec],
|
||||||
kdf_new: KdfParams::DEFAULT,
|
kdf_new: KdfParams::DEFAULT,
|
||||||
identity: None,
|
identity: None,
|
||||||
|
signing: signing::Store::default(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -554,7 +574,20 @@ impl Vault {
|
|||||||
Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?),
|
Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?),
|
||||||
None => None,
|
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
|
/// Wraps the vault key for device unlock with key material only this device can produce (e.g. a
|
||||||
@@ -588,6 +621,7 @@ impl Vault {
|
|||||||
items: &self.items,
|
items: &self.items,
|
||||||
factors: self.factors.iter().map(FactorRec::json).collect(),
|
factors: self.factors.iter().map(FactorRec::json).collect(),
|
||||||
identity: self.identity.as_ref().map(identity::Root::json),
|
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())))?;
|
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);
|
let sealed = crypto::seal(&self.key, &body_nonce, &json, &out);
|
||||||
@@ -800,4 +834,27 @@ impl Vault {
|
|||||||
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
|
self.identity.as_mut().ok_or(Error::NoIdentity)?.issued.push(issued);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The person revoked the key `subkey` (base64url): marks every cert of it. Returns the revocation time in
|
||||||
|
/// effect, the earlier one if it was marked before. The caller saves the vault.
|
||||||
|
pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error> {
|
||||||
|
self.identity.as_mut().ok_or(Error::NoIdentity)?.mark_revoked(subkey, revoked_at)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ed25519 with the root over `"tessera revoke v1\0" ‖ tbs`, for a `tbs` that starts with `TRV1`, this
|
||||||
|
/// root's public key, a key marked revoked and its `revoked_at` ([`Error::NotARevocation`] otherwise).
|
||||||
|
pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error> {
|
||||||
|
self.identity.as_ref().ok_or(Error::NoIdentity)?.sign_revocation(tbs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keeps the signed statements (base64url `TRV1`) with every cert of `subkey`. The caller saves the vault.
|
||||||
|
pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error> {
|
||||||
|
self.identity.as_mut().ok_or(Error::NoIdentity)?.record_revocation(subkey, statements)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The backup secret of the app `app_id` (docs/IDENTITY.md): derived from the root, handed to that app
|
||||||
|
/// only. The caller checks `app_id` (a-z, 0-9, `-`) and the app's right to it.
|
||||||
|
pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error> {
|
||||||
|
Ok(self.identity.as_ref().ok_or(Error::NoIdentity)?.backup_secret(app_id))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -128,6 +128,8 @@ fn the_identity_survives_saving_in_both_versions() {
|
|||||||
not_before: 1,
|
not_before: 1,
|
||||||
not_after: 2,
|
not_after: 2,
|
||||||
issued: 3,
|
issued: 3,
|
||||||
|
revoked_at: Some(4),
|
||||||
|
revocation: vec!["VFJWMQ".into()],
|
||||||
};
|
};
|
||||||
// Version 1.
|
// Version 1.
|
||||||
let mut v = vault();
|
let mut v = vault();
|
||||||
@@ -165,8 +167,176 @@ fn a_record_needs_an_identity() {
|
|||||||
not_before: 0,
|
not_before: 0,
|
||||||
not_after: 1,
|
not_after: 1,
|
||||||
issued: 0,
|
issued: 0,
|
||||||
|
..Issued::default()
|
||||||
};
|
};
|
||||||
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
|
assert!(matches!(v.domi_record(i), Err(Error::NoIdentity)));
|
||||||
|
assert!(matches!(v.domi_mark_revoked("x", 1), Err(Error::NoIdentity)));
|
||||||
|
assert!(matches!(v.domi_backup_secret("fiscus"), Err(Error::NoIdentity)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- v1.1: restoring, revoking, the backup secret (docs/IDENTITY.md) ----
|
||||||
|
|
||||||
|
const ZERO_PHRASE: &str = "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||||
|
abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon \
|
||||||
|
abandon art";
|
||||||
|
const REVOKE_DOMAIN: &[u8] = b"tessera revoke v1\0";
|
||||||
|
const SUBKEY_9: &str = "CQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk"; // [9; 32]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_24_words_restore_the_same_root() {
|
||||||
|
let mut v = vault();
|
||||||
|
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v).unwrap();
|
||||||
|
assert_eq!(v.domi_root_public().unwrap().to_vec(), b64url(ROOT_PUB_ZERO));
|
||||||
|
// Any case, any spacing, as long as the words are right.
|
||||||
|
let mut w = vault();
|
||||||
|
let messy = format!(" {}\n", ZERO_PHRASE.to_uppercase().replace(' ', " \t"));
|
||||||
|
Enrollment::restore(&messy).unwrap().import(&mut w).unwrap();
|
||||||
|
assert_eq!(w.domi_root_public(), v.domi_root_public());
|
||||||
|
// And from words that were shown: the same root as enrolling.
|
||||||
|
let mut e = vault();
|
||||||
|
let words = enrol(&mut e, [42; 32]);
|
||||||
|
let mut r = vault();
|
||||||
|
Enrollment::restore(&words.join(" ")).unwrap().import(&mut r).unwrap();
|
||||||
|
assert_eq!(r.domi_root_public(), e.domi_root_public());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wrong_phrase_restores_nothing_and_names_no_word() {
|
||||||
|
let bad_checksum = ZERO_PHRASE.replace("art", "abandon");
|
||||||
|
let short = "abandon ".repeat(11) + "about";
|
||||||
|
let typo = ZERO_PHRASE.replacen("abandon", "abandn", 1);
|
||||||
|
for phrase in [bad_checksum.as_str(), short.as_str(), typo.as_str(), "", "art"] {
|
||||||
|
let e = Enrollment::restore(phrase).map(|_| ()).unwrap_err();
|
||||||
|
assert!(matches!(e, Error::NotAMnemonic), "{phrase}");
|
||||||
|
let shown = format!("{e} {e:?}");
|
||||||
|
assert!(!shown.contains("abandon") && !shown.contains("art "), "{shown}");
|
||||||
|
}
|
||||||
|
// Into a vault that has one already: refused, the old one stays.
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [5; 32]);
|
||||||
|
let before = v.domi_root_public();
|
||||||
|
assert!(matches!(Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut v), Err(Error::IdentityExists)));
|
||||||
|
assert_eq!(v.domi_root_public(), before);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A revocation's to-be-signed bytes as tessera makes them: TRV1 ‖ root ‖ subkey ‖ revoked_at ‖ part ‖
|
||||||
|
/// parts ‖ count ‖ hashes.
|
||||||
|
fn trv1(root: &[u8; 32], subkey: &[u8; 32], revoked_at: u64) -> Vec<u8> {
|
||||||
|
let mut t = b"TRV1".to_vec();
|
||||||
|
t.extend_from_slice(root);
|
||||||
|
t.extend_from_slice(subkey);
|
||||||
|
t.extend_from_slice(&revoked_at.to_be_bytes());
|
||||||
|
t.extend_from_slice(&0u16.to_be_bytes());
|
||||||
|
t.extend_from_slice(&1u16.to_be_bytes());
|
||||||
|
t.extend_from_slice(&1u32.to_be_bytes());
|
||||||
|
t.extend_from_slice(&[7; 32]);
|
||||||
|
t
|
||||||
|
}
|
||||||
|
|
||||||
|
fn issued_to(subkey: &str, app_id: &str) -> Issued {
|
||||||
|
Issued {
|
||||||
|
kind: "app".into(),
|
||||||
|
app_id: app_id.into(),
|
||||||
|
purpose: "sync".into(),
|
||||||
|
subkey: subkey.into(),
|
||||||
|
label: "fiscus.exe".into(),
|
||||||
|
not_before: 1,
|
||||||
|
not_after: 2,
|
||||||
|
issued: 3,
|
||||||
|
..Issued::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_root_signs_a_revocation_only_for_a_key_the_person_revoked() {
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [0; 32]);
|
||||||
|
let root = v.domi_root_public().unwrap();
|
||||||
|
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
||||||
|
// Issued, but not revoked yet: refused.
|
||||||
|
let t = trv1(&root, &[9; 32], 1000);
|
||||||
|
assert!(matches!(v.domi_sign_revocation(&t), Err(Error::NotARevocation)));
|
||||||
|
// An unknown key cannot be marked.
|
||||||
|
assert!(matches!(v.domi_mark_revoked("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", 1000), Err(Error::UnknownKey)));
|
||||||
|
|
||||||
|
// A renewal issued a second cert for the same key: marking covers both, and the first time stays.
|
||||||
|
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
||||||
|
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 1000).unwrap(), 1000);
|
||||||
|
assert_eq!(v.domi_mark_revoked(SUBKEY_9, 2000).unwrap(), 1000, "the first revocation time stays");
|
||||||
|
assert!(v.domi_issued().iter().all(|i| i.revoked_at == Some(1000)));
|
||||||
|
|
||||||
|
let sig = v.domi_sign_revocation(&t).unwrap();
|
||||||
|
let vk = VerifyingKey::from_bytes(&root).unwrap();
|
||||||
|
vk.verify_strict(&[REVOKE_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).unwrap();
|
||||||
|
assert!(
|
||||||
|
vk.verify_strict(&[CERT_DOMAIN, &t].concat(), &Signature::from_bytes(&sig)).is_err(),
|
||||||
|
"not a cert signature"
|
||||||
|
);
|
||||||
|
|
||||||
|
// Another time, another key, another root, a cert, garbage, the bare prefix: refused.
|
||||||
|
for bad in [
|
||||||
|
trv1(&root, &[9; 32], 999),
|
||||||
|
trv1(&root, &[10; 32], 1000),
|
||||||
|
trv1(&[1; 32], &[9; 32], 1000),
|
||||||
|
tbs(&root),
|
||||||
|
b"pay 100 CZK to mallory".to_vec(),
|
||||||
|
t[..76].to_vec(),
|
||||||
|
] {
|
||||||
|
assert!(matches!(v.domi_sign_revocation(&bad), Err(Error::NotARevocation)), "{bad:?}");
|
||||||
|
}
|
||||||
|
// And the cert signer never signs a revocation.
|
||||||
|
assert!(matches!(v.domi_sign_cert(&t), Err(Error::NotACert)));
|
||||||
|
|
||||||
|
// The statements are kept with every cert of the key, and survive a save.
|
||||||
|
v.domi_record_revocation(SUBKEY_9, vec!["first".into(), "second".into()]).unwrap();
|
||||||
|
assert!(matches!(
|
||||||
|
v.domi_record_revocation("CgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo", vec![]),
|
||||||
|
Err(Error::UnknownKey)
|
||||||
|
));
|
||||||
|
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
||||||
|
assert!(back.domi_issued().iter().all(|i| i.revoked_at == Some(1000) && i.revocation == ["first", "second"]));
|
||||||
|
assert_eq!(back.domi_sign_revocation(&t).unwrap(), sig);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cert_without_a_revocation_is_saved_as_before() {
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [0; 32]);
|
||||||
|
v.domi_record(issued_to(SUBKEY_9, "fiscus")).unwrap();
|
||||||
|
let json = serde_json::to_string(&v.domi_issued()[0]).unwrap();
|
||||||
|
assert!(!json.contains("revoked_at") && !json.contains("revocation"), "{json}");
|
||||||
|
// And a record from core 0.7.0, without the two members, reads.
|
||||||
|
let old: Issued = serde_json::from_str(
|
||||||
|
r#"{"kind":"app","app_id":"fiscus","purpose":"sync","subkey":"x","label":"l","not_before":1,"not_after":2,"issued":3}"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!((old.revoked_at, old.revocation.len()), (None, 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_backup_secret_matches_fundamentum() {
|
||||||
|
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||||
|
let mut v = vault();
|
||||||
|
enrol(&mut v, [0; 32]);
|
||||||
|
let secret = v.domi_backup_secret("fiscus").unwrap();
|
||||||
|
let expand = |info: &[u8]| {
|
||||||
|
let mut out = [0u8; 32];
|
||||||
|
hkdf::Hkdf::<sha2::Sha256>::from_prk(secret.as_ref()).unwrap().expand(info, &mut out).unwrap();
|
||||||
|
out
|
||||||
|
};
|
||||||
|
// Fundamentum docs/TESSERA.md §12.
|
||||||
|
assert_eq!(expand(b"mailbox").to_vec(), b64url("IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU"));
|
||||||
|
let key = expand(b"seal");
|
||||||
|
let tag = chacha20poly1305::XChaCha20Poly1305::new_from_slice(&key)
|
||||||
|
.unwrap()
|
||||||
|
.encrypt(&chacha20poly1305::XNonce::try_from(&[0u8; 24][..]).unwrap(), Payload { msg: b"", aad: b"" })
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(tag, b64url("ci_JRbtsx5prR83KT9Y7LA"));
|
||||||
|
// One per app, the same from the restored words.
|
||||||
|
assert_ne!(*v.domi_backup_secret("calenda").unwrap(), *secret);
|
||||||
|
let mut r = vault();
|
||||||
|
Enrollment::restore(ZERO_PHRASE).unwrap().import(&mut r).unwrap();
|
||||||
|
assert_eq!(*r.domi_backup_secret("fiscus").unwrap(), *secret);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -206,13 +376,19 @@ fn the_identity_surface_is_locked() {
|
|||||||
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
|
"identity.rs: pub fn challenge(&self) -> [usize; 3]",
|
||||||
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
|
"identity.rs: pub fn confirm(self, words: &[&str; 3]) -> Result<Confirmed, (Shown, Error)>",
|
||||||
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
|
"identity.rs: pub fn import(self, vault: &mut Vault) -> Result<[u8; 32], Error>",
|
||||||
|
"identity.rs: pub fn restore(phrase: &str) -> Result<Confirmed, Error>",
|
||||||
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
|
"identity.rs: pub fn show(self, display: impl FnOnce(&[&str])) -> Shown",
|
||||||
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
|
"identity.rs: pub fn with_entropy(entropy: [u8; 32]) -> Enrollment",
|
||||||
|
// The app's own backup secret, derived: by design (docs/IDENTITY.md), never the root.
|
||||||
|
"lib.rs: pub fn domi_backup_secret(&self, app_id: &str) -> Result<Zeroizing<[u8; 32]>, Error>",
|
||||||
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
|
"lib.rs: pub fn domi_created(&self) -> Option<i64>",
|
||||||
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
|
"lib.rs: pub fn domi_issued(&self) -> &[identity::Issued]",
|
||||||
|
"lib.rs: pub fn domi_mark_revoked(&mut self, subkey: &str, revoked_at: u64) -> Result<u64, Error>",
|
||||||
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
|
"lib.rs: pub fn domi_record(&mut self, issued: identity::Issued) -> Result<(), Error>",
|
||||||
|
"lib.rs: pub fn domi_record_revocation(&mut self, subkey: &str, statements: Vec<String>) -> Result<(), Error>",
|
||||||
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
|
"lib.rs: pub fn domi_root_public(&self) -> Option<[u8; 32]>",
|
||||||
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
"lib.rs: pub fn domi_sign_cert(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
||||||
|
"lib.rs: pub fn domi_sign_revocation(&self, tbs: &[u8]) -> Result<[u8; 64], Error>",
|
||||||
];
|
];
|
||||||
want.sort();
|
want.sort();
|
||||||
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
|
assert_eq!(got, want, "review the identity surface: it must never return the root secret");
|
||||||
|
|||||||
@@ -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());
|
||||||
|
}
|
||||||
@@ -23,3 +23,5 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] }
|
|||||||
|
|
||||||
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
[target.'cfg(target_arch = "wasm32")'.dependencies]
|
||||||
getrandom = "0.4"
|
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"] }
|
||||||
|
|||||||
@@ -473,6 +473,14 @@ mod abi {
|
|||||||
Ok(())
|
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)]
|
#[unsafe(no_mangle)]
|
||||||
pub extern "C" fn alloc(len: usize) -> *mut u8 {
|
pub extern "C" fn alloc(len: usize) -> *mut u8 {
|
||||||
if len == 0 {
|
if len == 0 {
|
||||||
|
|||||||
+4
-1
@@ -119,13 +119,16 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed:
|
|||||||
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
|
- `fields` is an ordered list; a name may repeat (several `url`s). Unknown names are kept as custom fields.
|
||||||
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
|
- `history` keeps the previous value of a secret field each time it changes (newest last, at most 20 per item).
|
||||||
- Readers ignore JSON members they do not know, so later versions can add them.
|
- Readers ignore JSON members they do not know, so later versions can add them.
|
||||||
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md).
|
- `identity` (optional, core 0.7.0): the Domi identity's root key and the certs it issued (docs/IDENTITY.md);
|
||||||
|
since core 0.10.0 a cert may carry `revoked_at` and `revocation`.
|
||||||
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
|
An older Custos drops it when it saves, so every Custos that saves the vault must be 0.7.0 or later.
|
||||||
- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path,
|
- `folder` (optional item member, core 0.8.0): a list of folder names, outermost first (a KeePass group path,
|
||||||
docs/KDBX.md). Absent or empty = no folder.
|
docs/KDBX.md). Absent or empty = no folder.
|
||||||
- `attachments` (optional item member, core 0.8.0): `[{"name": "id_rsa", "data": "<base64>"}]`, files kept with
|
- `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.
|
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.
|
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)
|
### Item types and their fields (v1)
|
||||||
|
|
||||||
|
|||||||
+34
-5
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
|
Every Domi app gets its own subkey, certified by **one root Ed25519 key per person**. The root key lives in
|
||||||
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
|
the vault and never leaves it: no function of this crate returns it, and the vault signs nothing with it but
|
||||||
subkey certificates. The certificate format, the match code and verification are in Fundamentum
|
subkey certificates and revocations of keys the person revoked. The certificate format, the match code and verification are in Fundamentum
|
||||||
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
|
(`crates/tessera`, `docs/TESSERA.md`); this page is the vault side.
|
||||||
|
|
||||||
## Creating it: the order is mandatory
|
## Creating it: the order is mandatory
|
||||||
@@ -31,6 +31,12 @@ is `Clone` or `Serialize`; each prints `[redacted]`.
|
|||||||
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
|
Test vector: entropy `00` × 32 → `abandon` × 23 + `art` → root public key
|
||||||
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
|
`vCrwX9p44un1ftQLgJtuaVQ0qPWbFfzNjgrlDkL4TKs` (base64url). Fundamentum pins the same value.
|
||||||
|
|
||||||
|
### Restoring it from the 24 words (core 0.10.0)
|
||||||
|
`Enrollment::restore(phrase)` takes the whole phrase, typed back, and gives a `Confirmed`: the person typed
|
||||||
|
all 24 words, which proves more than three. The words are checked against the BIP39 English list and its
|
||||||
|
checksum (any case, any spacing between them); anything else is `Error::NotAMnemonic`, which names no word.
|
||||||
|
The same words give the same root, so every app and every group trusts it again.
|
||||||
|
|
||||||
## In the vault file
|
## In the vault file
|
||||||
|
|
||||||
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
|
A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it open as before:
|
||||||
@@ -42,13 +48,19 @@ A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it op
|
|||||||
"created": 1793000000000,
|
"created": 1793000000000,
|
||||||
"issued": [
|
"issued": [
|
||||||
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
|
{ "kind": "app", "app_id": "fiscus", "purpose": "sync", "subkey": "<base64url>", "label": "fiscus.exe",
|
||||||
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000 }
|
"not_before": 1793000000, "not_after": 1824536000, "issued": 1793000000000,
|
||||||
|
"revoked_at": 1795000000, "revocation": ["<base64url TRV1>"] }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
|
- `issued` records each cert the vault signed, for *Domi identity → apps and devices*. It is a record, not
|
||||||
a trust list: revocation is v1.1.
|
a trust list.
|
||||||
|
- `revoked_at` (Unix seconds, core 0.10.0) is set when the person revokes the key; `revocation` holds the
|
||||||
|
signed statements once they exist. Both are left out until then. A renewed key has several certs: all of
|
||||||
|
them are marked.
|
||||||
|
- **A Custos older than core 0.10.0 drops `revoked_at` and `revocation` when it saves the vault**, so a
|
||||||
|
revocation in progress would have to be started again.
|
||||||
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
|
- **An older Custos drops the member when it saves the vault** (it ignores members it does not know). Every
|
||||||
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
|
Custos that saves this vault must run core 0.7.0 or later. The mnemonic recovers the root either way.
|
||||||
|
|
||||||
@@ -59,9 +71,26 @@ A body member next to `items` (docs/FORMAT.md, "Body"); old vaults without it op
|
|||||||
| `Vault::domi_root_public()` | the root public key, if there is an identity |
|
| `Vault::domi_root_public()` | the root public key, if there is an identity |
|
||||||
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
|
| `Vault::domi_sign_cert(tbs)` | Ed25519 over `"tessera cert v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TSC1` followed by this root's public key |
|
||||||
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
|
| `Vault::domi_issued()`, `domi_record(issued)` | the record of issued certs |
|
||||||
|
| `Vault::domi_mark_revoked(subkey, at)` | the person revoked this key: marks every cert of it, returns the time in effect (the first one, if it was marked before) |
|
||||||
|
| `Vault::domi_sign_revocation(tbs)` | Ed25519 over `"tessera revoke v1\0" ‖ tbs`. Refuses a `tbs` that does not start with `TRV1`, this root's public key, a key marked revoked and that key's `revoked_at` |
|
||||||
|
| `Vault::domi_record_revocation(subkey, statements)` | keeps the signed statements with the key's certs |
|
||||||
|
| `Vault::domi_backup_secret(app_id)` | the app's backup secret (below) |
|
||||||
|
|
||||||
The prefix check means the vault is not a general signing oracle: whatever the app hands it, the result
|
The prefix checks mean the vault is not a general signing oracle: whatever the app hands it, the result
|
||||||
can only ever verify as a certificate naming this root.
|
can only ever verify as a certificate naming this root, or as a revocation of a key the person revoked, at
|
||||||
|
the time they did. The two domains differ, so neither can pass for the other. Statement format: Fundamentum
|
||||||
|
docs/TESSERA.md §12.
|
||||||
|
|
||||||
|
### The backup secret (core 0.10.0)
|
||||||
|
```
|
||||||
|
backup secret = HKDF-SHA256(salt = "tessera backup v1", ikm = the root secret, info = app id)
|
||||||
|
```
|
||||||
|
Custos hands an app its own (Domi pipe `backup_key`, behind the app's namespace grant); the app seals its
|
||||||
|
backup with it and names its backup mailbox from it (Fundamentum docs/TESSERA.md §12). It comes back from
|
||||||
|
the 24 words alone. The caller passes a valid app id (a-z, 0-9, `-`). Test vector, shared with Fundamentum:
|
||||||
|
the zero-entropy root, app `fiscus` → `HKDF-Expand(secret, "mailbox")` =
|
||||||
|
`IygCOrh-ibO6-KY5AXQ9Prl2SyPWQIyZZ-anffcbMCU`, and XChaCha20-Poly1305 with
|
||||||
|
`HKDF-Expand(secret, "seal")`, a zero nonce and empty input = `ci_JRbtsx5prR83KT9Y7LA` (the tag).
|
||||||
|
|
||||||
## What it does not protect
|
## What it does not protect
|
||||||
|
|
||||||
|
|||||||
+146
@@ -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.
|
||||||
@@ -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" }
|
||||||
Reference in New Issue
Block a user