From 2a146f342d6c952b5b9235a38ba0de0f71d69b9f Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 00:09:05 +0100 Subject: [PATCH 1/6] [vault] Signing: docs/SIGNING.md (keys, signature kinds, audit log) and the FORMAT.md member, before the code --- docs/FORMAT.md | 2 + docs/SIGNING.md | 146 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 148 insertions(+) create mode 100644 docs/SIGNING.md diff --git a/docs/FORMAT.md b/docs/FORMAT.md index 8c74b88..326c030 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -126,6 +126,8 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: - `attachments` (optional item member, core 0.8.0): `[{"name": "id_rsa", "data": ""}]`, files kept with the item (imported from KeePass). The data counts as secret: it is never logged or printed. An older Custos drops `folder` and `attachments` when it saves. +- `signing` (optional, core 0.9.0): signing keys for releases and the audit log of every signing request + (docs/SIGNING.md). An older Custos drops it when it saves, so every Custos that saves the vault must be 0.9.0 or later. ### Item types and their fields (v1) diff --git a/docs/SIGNING.md b/docs/SIGNING.md new file mode 100644 index 0000000..32ad0bd --- /dev/null +++ b/docs/SIGNING.md @@ -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": "", "public": "", "keyId": "<16 hex>", "created": 1793750000000, + "pipelines": ["release"], "repos": ["Arca", "Fabrica"] }, + { "id": "domi-root", "kind": "root-ca", "role": "release", "name": "Domi Household Root CA", + "secret": "", "cert": "", "created": 1793750000000, "pipelines": [], "repos": [] }, + { "id": "domi-code-signing", "kind": "code-signing", "role": "release", "name": "Domi Code Signing", + "secret": "", "cert": "", "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": "" } + ] +} +``` + +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=, O=Domi`, `basicConstraints` CA (critical), `keyUsage` keyCertSign + cRLSign + (critical), subject key identifier; +- leaf: subject `CN=, O=Domi`, `basicConstraints` not a CA, `keyUsage` digitalSignature (critical), + `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 +base64("ED" ‖ key_id ‖ ed25519(BLAKE2b-512(file))) +trusted comment: timestamp: file: hashed +base64(ed25519(signature ‖ trusted comment text)) +``` + +`key_id` is the key's 8 bytes as stored; `` 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 ` 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> \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 /fd sha256 /f ` writes `.dig` (the base64 of the 32-byte SHA-256 + of the signature's authenticated attributes, no newline) and `.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 `.dig.signed`. +3. `signtool sign /di ` puts the signature in; `signtool timestamp /tr /td sha256 ` 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 `; `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. -- 2.53.0 From 6c6ffd33c0de74983f162baf09e471a4713edc83 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 00:15:33 +0100 Subject: [PATCH 2/6] [sign] Tests: known answers from the real minisign 0.12 and openssl, the household CA, canonical manifests --- .gitattributes | 1 + crates/custos-sign/Cargo.toml | 25 +++ crates/custos-sign/tests/fixtures/README.md | 6 + crates/custos-sign/tests/fixtures/digest.bin | 1 + .../tests/fixtures/digest.openssl.sig | Bin 0 -> 384 bytes .../custos-sign/tests/fixtures/minisign.key | 2 + .../custos-sign/tests/fixtures/minisign.pub | 2 + crates/custos-sign/tests/fixtures/payload.bin | 1 + .../tests/fixtures/payload.bin.minisig | 4 + .../tests/fixtures/rsa3072.pk8.der | Bin 0 -> 1794 bytes crates/custos-sign/tests/kat.rs | 176 ++++++++++++++++++ 11 files changed, 218 insertions(+) create mode 100644 crates/custos-sign/Cargo.toml create mode 100644 crates/custos-sign/tests/fixtures/README.md create mode 100644 crates/custos-sign/tests/fixtures/digest.bin create mode 100644 crates/custos-sign/tests/fixtures/digest.openssl.sig create mode 100644 crates/custos-sign/tests/fixtures/minisign.key create mode 100644 crates/custos-sign/tests/fixtures/minisign.pub create mode 100644 crates/custos-sign/tests/fixtures/payload.bin create mode 100644 crates/custos-sign/tests/fixtures/payload.bin.minisig create mode 100644 crates/custos-sign/tests/fixtures/rsa3072.pk8.der create mode 100644 crates/custos-sign/tests/kat.rs diff --git a/.gitattributes b/.gitattributes index 5f5df9f..e5f4172 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ # Keep the EFF list byte-for-byte as published (its sha256 is in SOURCES.md). crates/custos-gen/wordlists/eff_large_wordlist.txt -text *.sh text eol=lf +crates/custos-sign/tests/fixtures/** -text diff --git a/crates/custos-sign/Cargo.toml b/crates/custos-sign/Cargo.toml new file mode 100644 index 0000000..c90e0f3 --- /dev/null +++ b/crates/custos-sign/Cargo.toml @@ -0,0 +1,25 @@ +[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 = { version = "2", features = ["rand_core"] } +rsa = { version = "0.9", features = ["sha2"] } +sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] } +blake2 = "0.10" +x509-cert = { version = "0.2.5", features = ["builder"] } +rand_core = { version = "0.6", features = ["getrandom"] } + +[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"] } diff --git a/crates/custos-sign/tests/fixtures/README.md b/crates/custos-sign/tests/fixtures/README.md new file mode 100644 index 0000000..fbdba73 --- /dev/null +++ b/crates/custos-sign/tests/fixtures/README.md @@ -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:1700000000file:payload.binhashed"`. +- `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). diff --git a/crates/custos-sign/tests/fixtures/digest.bin b/crates/custos-sign/tests/fixtures/digest.bin new file mode 100644 index 0000000..1785d8b --- /dev/null +++ b/crates/custos-sign/tests/fixtures/digest.bin @@ -0,0 +1 @@ +a 32-byte authenticode digest!!! \ No newline at end of file diff --git a/crates/custos-sign/tests/fixtures/digest.openssl.sig b/crates/custos-sign/tests/fixtures/digest.openssl.sig new file mode 100644 index 0000000000000000000000000000000000000000..6d2981e7d9482da673cb8b945245eb4e9e64b027 GIT binary patch literal 384 zcmXrJvvBD)PWj^4rnMbab9trsodb2gyj}A0Xi;YSjlCh<{m;Is`*uhv74UT0*B8ul z@R{|OSw6+dStxyHU-^lJ@*6(Av)k@Af8xfn`G;&5t~%QqA**pW|3_i!w-=wvLysKJ zJ^S*dd8I7lovG?~*G$;V+94A9ws=$aRd>mB4V_(Ir>`}dWE$hzRq@s!_P%LFL;8U( zBP}tt%Cq%ssS*o63KmFtnJe#>(Rp7QoMyDc=*81nQU1%-e&p@>qjuVm>)d75#&F+v z0TLB^-9mj%rf$`mmfho78XP0-n64AUzdq-Wmfvr$2-Vx}%PsG(=C=D)sqpO{$J!oS z)+Colb6+m;*(WuRXYHL;@|o$2{O7+jXs@__`}V$bvbF^=>?Z`S#|Q+s2Zj3HuxH8R z+Hvip+6A+V3I`Yc%3bKWJRJMPbI4@Q3RR uzdmrj9{c>h)8XF4y1I*=hDEZom!G(}b?2OmHm$)s!lz`Joc+)F{W<`~q`9jA literal 0 HcmV?d00001 diff --git a/crates/custos-sign/tests/fixtures/minisign.key b/crates/custos-sign/tests/fixtures/minisign.key new file mode 100644 index 0000000..a913470 --- /dev/null +++ b/crates/custos-sign/tests/fixtures/minisign.key @@ -0,0 +1,2 @@ +untrusted comment: minisign encrypted secret key +RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAxBvPgUoXv/LZDCnnxOD2qjtAzgKzt2QB+BBy+4kjkKJHj7TUGad2U26fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= diff --git a/crates/custos-sign/tests/fixtures/minisign.pub b/crates/custos-sign/tests/fixtures/minisign.pub new file mode 100644 index 0000000..5a929a9 --- /dev/null +++ b/crates/custos-sign/tests/fixtures/minisign.pub @@ -0,0 +1,2 @@ +untrusted comment: minisign public key F2BF174A81CF1BC4 +RWTEG8+BShe/8m6fufPhzOCFF9AZps7DyYNRcA1poNz0wBTitny8hZc7 diff --git a/crates/custos-sign/tests/fixtures/payload.bin b/crates/custos-sign/tests/fixtures/payload.bin new file mode 100644 index 0000000..88b7416 --- /dev/null +++ b/crates/custos-sign/tests/fixtures/payload.bin @@ -0,0 +1 @@ +Domi release test payload: not a real file. diff --git a/crates/custos-sign/tests/fixtures/payload.bin.minisig b/crates/custos-sign/tests/fixtures/payload.bin.minisig new file mode 100644 index 0000000..a1d8dd0 --- /dev/null +++ b/crates/custos-sign/tests/fixtures/payload.bin.minisig @@ -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== diff --git a/crates/custos-sign/tests/fixtures/rsa3072.pk8.der b/crates/custos-sign/tests/fixtures/rsa3072.pk8.der new file mode 100644 index 0000000000000000000000000000000000000000..cebceb7154c9e672ef207df952f76f13fd673947 GIT binary patch literal 1794 zcmXqLV*AI$$Y8+B#;Mij(e|B}k&%&=fu)Ja#6Z}8cES38C z>wA81n19+5jjf-g#Z{K>$cQZHXX#j97N)zK>AjZ6{9x_%w+~ud|6h^qtzGX|dT|Te zzKXd8qLXqR=lWcfZS@!2)YpD={;m^$7axdPskPmD!?I^FYior&&ivYC7=5)MoWE!-2MEOz-gQnSAeINP6X>Cp&K`1=p)4)h}W` z$)*l#rqbMi@f*E_DTzFpYr+Nakc$6JuVBGH|x#VuJy?|z9#vfinwTv)X(s^ zs2ui=UlSyL3+$XKKY4;t%2EG2!3C?1ORw*I_;%@g^MemFr<|$3H8U@F#xXgE0}-6} zOgryvu=a>^Uh7@y)Hd(L(zk4!#IQveOC=P14=+Db7N6rl9J}`E|QI0*{uo#PSxe z=Pc7+m1B3J_LZA`d;Ha>c0YC3ow$0bv$JUet4+q)rh@rPLo&YwJQqsmes-2eV$rJk z98L^x;!HWZrt-3ipLQ&iT=9B>%B-WzQ``Tn-N~!7Bp^iSy#3Zl^Z!RD++vHqkm0T3 zDrmBa<>BEV!%|TXwmoK1+DS_+r#h|eb~?Fau3qPdRi7hYwD(r3=#))5_nJMdw|D=^ zrE7c-YVF`qig}^^^WMbhSo32gGXo2+?U2!MJ@Ul)r`GIn@u@D0%HEdnXw15?xBmR+ z^Zr(D$t#O4X9|C^*kOKX-|U#@Jo~2kGH-cWvwOnRv*#|X-!b7;-Sh_+xUT5FI$#&W z-FQ~xZ#-Lqg45UcF-y6o|7+l#A% ze?+x*-fNv5&0Z5QXSdhu<>E4Bx9UUt4#sk*GBqA#_?p!#-&G`c`NV_Q7R&YQ4@C8e z7z>2`k7Dh3Ss?$lDm$I0R#L>+MXQN>zw>2N(U(C?NAK5vTpTCLCfso99{0c4T=hLY z+d0gN3j5x@7I@lq`k=z^G}(7M_PBg_>G^u`4*O91<8GDD*d|19n{&OmXuIm;RlA2D zPIb)vGkgBMonF!L>seivO})6VDs`evNB61aH{!QV@wEKD*st03N7{sQeUlXRR&V$i zcCpk_wBWp@SoSxgK5iYM1i?cuCNq8#-#QoMhfAmD6vdp}{QBy#m$I)m8dV5=+a^4z zN2d9O=pn&B4f{?_*d2FNS-I_^-TTXZPi$WYFrH+5n0jc!s@k0m@<}{v#OCmB`EdLH zUOA@cyUpC^Pv@3dn>x4h>1FM^-CHfD{ASIvbz9x3wfV-8Rrjt{eKrq`xp2%~h5M!P zMeiw*OQxh6_C7b@p5&OtbB$TDU3y8WZ>inJQ&}ss7p?04t#*NB#^3F$?}j%j%Xdg0 znQJ!lWY{a^r3z|{%g=DV>CHZ{wZO4QovHDF;JFB&7u|E!eofVvzNedbXa84Q?$0?r zH5oHf^E-@0;*RuqWCx@@zGA!6sUj?R&87hEpQSMmBw|C9wReivv)nvzeB#E&3N6z_ zsUY><33J^(?_W^cN8zdK z#f`l;UzRXW2>t9Ft=1zSmV4G=DkvHbn-x37r)DgTN;O}5;41(}@?;$V literal 0 HcmV?d00001 diff --git a/crates/custos-sign/tests/kat.rs b/crates/custos-sign/tests/kat.rs new file mode 100644 index 0000000..7f2f6fe --- /dev/null +++ b/crates/custos-sign/tests/kat.rs @@ -0,0 +1,176 @@ +//! 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 { + 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::>(); + 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 ` `"), + (&*format!("{h} *a.exe\n"), "not ` `"), + (&*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::().unwrap().unwrap(); + assert!(bc.ca); + let (_, bc) = lc.tbs_certificate.get::().unwrap().unwrap(); + assert!(!bc.ca); + let (_, eku) = lc.tbs_certificate.get::().unwrap().unwrap(); + assert_eq!(eku.0.iter().map(|o| o.to_string()).collect::>(), 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::::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::::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()); +} -- 2.53.0 From 59fdfa26ef4226d535f44310012179b444454b2b Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 00:15:33 +0100 Subject: [PATCH 3/6] [sign] custos-sign: minisign (prehashed), SHA256SUMS, Authenticode digests, the household CA; tools/signing/interop.ps1 --- Cargo.lock | 118 ++++++++- Cargo.toml | 8 +- crates/custos-sign/examples/interop.rs | 53 ++++ crates/custos-sign/src/lib.rs | 330 +++++++++++++++++++++++++ docs/SIGNING.md | 2 +- tools/signing/interop.ps1 | 65 +++++ 6 files changed, 563 insertions(+), 13 deletions(-) create mode 100644 crates/custos-sign/examples/interop.rs create mode 100644 crates/custos-sign/src/lib.rs create mode 100644 tools/signing/interop.ps1 diff --git a/Cargo.lock b/Cargo.lock index 8f96149..98f91ca 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -45,7 +45,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" dependencies = [ "base64ct", - "blake2", + "blake2 0.11.0", "cpufeatures 0.3.1", "password-hash", "zeroize", @@ -102,6 +102,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "blake2" version = "0.11.0" @@ -320,7 +329,7 @@ dependencies = [ [[package]] name = "custos-gen" -version = "0.7.0" +version = "0.9.0" dependencies = [ "custos-vault", "data-encoding", @@ -332,7 +341,7 @@ dependencies = [ [[package]] name = "custos-kdbx" -version = "0.7.0" +version = "0.9.0" dependencies = [ "aes", "argon2", @@ -353,7 +362,7 @@ dependencies = [ [[package]] name = "custos-keys" -version = "0.7.0" +version = "0.9.0" dependencies = [ "custos-vault", "ed25519-dalek", @@ -366,11 +375,11 @@ dependencies = [ [[package]] name = "custos-qr" -version = "0.7.0" +version = "0.9.0" [[package]] name = "custos-seal" -version = "0.7.0" +version = "0.9.0" dependencies = [ "chacha20poly1305", "hkdf", @@ -383,7 +392,7 @@ dependencies = [ [[package]] name = "custos-share" -version = "0.7.0" +version = "0.9.0" dependencies = [ "argon2", "chacha20poly1305", @@ -398,22 +407,38 @@ dependencies = [ "zeroize", ] +[[package]] +name = "custos-sign" +version = "0.9.0" +dependencies = [ + "blake2 0.10.6", + "data-encoding", + "ed25519-dalek", + "minisign-verify", + "rand_core 0.6.4", + "rsa", + "sha2 0.10.9", + "thiserror", + "x509-cert", + "zeroize", +] + [[package]] name = "custos-totp" -version = "0.7.0" +version = "0.9.0" dependencies = [ "custos-vault", "data-encoding", "hmac 0.13.0", "percent-encoding", - "sha1", + "sha1 0.11.0", "sha2 0.11.1", "zeroize", ] [[package]] name = "custos-vault" -version = "0.7.0" +version = "0.9.0" dependencies = [ "argon2", "bip39", @@ -432,7 +457,7 @@ dependencies = [ [[package]] name = "custos-wasm" -version = "0.7.0" +version = "0.9.0" dependencies = [ "custos-qr", "custos-seal", @@ -460,10 +485,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", + "der_derive", + "flagset", "pem-rfc7468", "zeroize", ] +[[package]] +name = "der_derive" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "digest" version = "0.10.7" @@ -579,6 +617,12 @@ version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + [[package]] name = "flate2" version = "1.1.10" @@ -737,6 +781,12 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "minisign-verify" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "871285dc19d8d0ebe0eef3d0e99a205f2a71363b122632cbbfa4a6c370a960ce" + [[package]] name = "miniz_oxide" version = "0.9.1" @@ -1159,6 +1209,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha1" version = "0.11.0" @@ -1340,6 +1401,27 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" +[[package]] +name = "tls_codec" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b" +dependencies = [ + "tls_codec_derive", + "zeroize", +] + +[[package]] +name = "tls_codec_derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "typenum" version = "1.20.1" @@ -1410,6 +1492,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "x509-cert" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" +dependencies = [ + "const-oid 0.9.6", + "der", + "sha1 0.10.7", + "signature", + "spki", + "tls_codec", +] + [[package]] name = "zerocopy" version = "0.8.63" diff --git a/Cargo.toml b/Cargo.toml index 1c48dac..0df7650 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.8.0" +version = "0.9.0" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" @@ -23,3 +23,9 @@ sha2 = "0.11" hkdf = "0.13" data-encoding = "2" percent-encoding = "2" + +# RSA-3072 key generation (custos-sign) takes minutes unoptimised; these keep `cargo test` usable. +[profile.dev.package.num-bigint-dig] +opt-level = 3 +[profile.dev.package.rsa] +opt-level = 3 diff --git a/crates/custos-sign/examples/interop.rs b/crates/custos-sign/examples/interop.rs new file mode 100644 index 0000000..0086f6a --- /dev/null +++ b/crates/custos-sign/examples/interop.rs @@ -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 root.cer, root.pem, leaf.cer, leaf.key.der (test only) +//! interop authenticode writes .signed +//! interop minisign /minisign.pub, .minisig +//! interop manifest .minisig, with the key in + +use std::fs; +use std::path::Path; + +use custos_sign::*; +use data_encoding::BASE64; + +fn main() { + let args: Vec = 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}"), + } +} diff --git a/crates/custos-sign/src/lib.rs b/crates/custos-sign/src/lib.rs new file mode 100644 index 0000000..971f06e --- /dev/null +++ b/crates/custos-sign/src/lib.rs @@ -0,0 +1,330 @@ +//! 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_core::{OsRng, RngCore}; +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>); + +impl RsaSecret { + pub fn from_pkcs8_der(der: Vec) -> Result { + 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::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]") + } +} + +// ---- 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]); + OsRng.fill_bytes(&mut *seed); + let mut key_id = [0u8; 8]; + OsRng.fill_bytes(&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:\tfile:\thashed`, as minisign writes it. +pub fn minisign( + secret: &Ed25519Secret, + key_id: &[u8; 8], + digest: &[u8], + file: &str, + timestamp: u64, +) -> Result { + 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> \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 ` `"); + }; + 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 { + 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, Error> { + if digest.len() != 32 { + return Err(Error::DigestLength(32)); + } + let key = pkcs1v15::SigningKey::::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, +} + +fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> { + let key = RsaPrivateKey::new(&mut OsRng, 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 { + let mut bytes = [0u8; 16]; + OsRng.fill_bytes(&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 { + 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 { + 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 { + let (key, secret) = new_rsa()?; + let spki = spki(&key)?; + let signer = pkcs1v15::SigningKey::::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::().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 { + let issuer_cert = Certificate::from_der(issuer_cert).map_err(|_| Error::Certificate)?; + let (key, secret) = new_rsa()?; + let signer = pkcs1v15::SigningKey::::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::().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() +} diff --git a/docs/SIGNING.md b/docs/SIGNING.md index 32ad0bd..a7ca408 100644 --- a/docs/SIGNING.md +++ b/docs/SIGNING.md @@ -55,7 +55,7 @@ Test keys are approved automatically, but only for requests whose `trigger` is n Certificates: - root: subject and issuer `CN=, O=Domi`, `basicConstraints` CA (critical), `keyUsage` keyCertSign + cRLSign (critical), subject key identifier; -- leaf: subject `CN=, O=Domi`, `basicConstraints` not a CA, `keyUsage` digitalSignature (critical), +- leaf: subject `CN=, 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. diff --git a/tools/signing/interop.ps1 b/tools/signing/interop.ps1 new file mode 100644 index 0000000..76708b1 --- /dev/null +++ b/tools/signing/interop.ps1 @@ -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 ] +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" } -- 2.53.0 From cd2963392d8b0afd890f664a558ba270beb4806e Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 00:26:11 +0100 Subject: [PATCH 4/6] [vault] Signing: mandatory tests for scope, refusals and the audit log through a reopen --- crates/custos-vault/Cargo.toml | 6 + crates/custos-vault/src/signing.rs | 560 +++++++++++++++++++++++++++ crates/custos-vault/tests/signing.rs | 207 ++++++++++ 3 files changed, 773 insertions(+) create mode 100644 crates/custos-vault/src/signing.rs create mode 100644 crates/custos-vault/tests/signing.rs diff --git a/crates/custos-vault/Cargo.toml b/crates/custos-vault/Cargo.toml index 68dd804..4a2fdc9 100644 --- a/crates/custos-vault/Cargo.toml +++ b/crates/custos-vault/Cargo.toml @@ -20,6 +20,12 @@ data-encoding.workspace = true # The Domi identity (docs/IDENTITY.md): the mnemonic and the root key. bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] } ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] } +# Signing keys for releases (docs/SIGNING.md). +custos-sign = { path = "../custos-sign" } [dev-dependencies] tempfile = "3" +minisign-verify = "0.3" +rsa = { version = "0.9", features = ["sha2"] } +sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] } +x509-cert = "0.2.5" diff --git a/crates/custos-vault/src/signing.rs b/crates/custos-vault/src/signing.rs new file mode 100644 index 0000000..d56857f --- /dev/null +++ b/crates/custos-vault/src/signing.rs @@ -0,0 +1,560 @@ +//! 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, + /// The `SHA256SUMS` text, for a manifest. + pub manifest: Option, + 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, + /// Why, for refusals the vault decided. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub reason: Option, +} + +/// 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, + 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, + pub repos: Vec, + /// 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, + /// The `minisign.pub` text, for Ed25519 keys. + pub minisign_public: Option, + /// The certificate (DER), for root and code-signing keys. + pub cert: Option>, + pub issuer: Option, +} + +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>, + issuer: Option, + created: i64, + pipelines: Vec, + repos: Vec, +} + +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, + audit: Vec, +} + +#[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, + #[serde(default, skip_serializing_if = "Option::is_none")] + key_id: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + cert: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + issuer: Option, + created: i64, + #[serde(default)] + pipelines: Vec, + #[serde(default)] + repos: Vec, +} + +#[derive(Serialize, Deserialize)] +pub(crate) struct StoreJson { + #[serde(default)] + keys: Vec, + #[serde(default)] + audit: Vec, +} + +fn b64(bytes: &[u8]) -> String { + data_encoding::BASE64.encode(bytes) +} + +fn unb64(s: &str) -> Option> { + 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 { + 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 { + 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, Error> { + let mut out: Vec = 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, 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 { + 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, 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 { + 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 { + 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, 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, signature: Option, 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 + } +} diff --git a/crates/custos-vault/tests/signing.rs b/crates/custos-vault/tests/signing.rs new file mode 100644 index 0000000..ed11e22 --- /dev/null +++ b/crates/custos-vault/tests/signing.rs @@ -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 { + 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::::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 = audit.iter().map(|e| e.outcome).collect(); + assert_eq!( + outcomes, + [ + Outcome::Approved, + Outcome::Auto, + Outcome::Refused, + Outcome::Expired, + Outcome::OutOfScope, + Outcome::Invalid, + Outcome::Refused + ] + ); + assert_eq!(audit[0].signature.as_deref(), Some(signed.sha256.as_str())); + assert!(audit[2..].iter().all(|e| e.signature.is_none())); + assert_eq!(audit[0].context, ctx("release", "Arca", "tag")); + assert_eq!(audit[0].via, Via::Local); + assert_eq!(audit[3].reason.as_deref(), Some("no answer in 5 minutes")); + assert_eq!(reopened.signing_audit(), v.signing_audit()); + // The keys came back too, and still sign. + let mut reopened = reopened; + assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok()); +} -- 2.53.0 From 06410ab3bef1708135f0b402544ce778faa4c64e Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 00:26:11 +0100 Subject: [PATCH 5/6] [vault] Signing: the signing body member (release and test key sets, scope, sign-only API, append-only audit log); custos-sign draws from SysRng; the wasm build links getrandom 0.2 to the browser CSPRNG --- Cargo.lock | 7 + crates/custos-keys/src/lib.rs | 27 +++- crates/custos-keys/tests/mandatory.rs | 3 +- crates/custos-seal/src/lib.rs | 4 +- crates/custos-sign/Cargo.toml | 8 +- crates/custos-sign/src/lib.rs | 42 +++++- crates/custos-sign/tests/kat.rs | 3 +- crates/custos-vault/src/lib.rs | 30 ++++- crates/custos-vault/src/signing.rs | 182 ++++++++++++++++++++++++-- crates/custos-vault/tests/factors.rs | 38 +++++- crates/custos-wasm/Cargo.toml | 2 + crates/custos-wasm/src/lib.rs | 32 ++++- crates/custos-wasm/tests/factors.rs | 47 +++++-- 13 files changed, 373 insertions(+), 52 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 98f91ca..1a61dcc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -415,6 +415,7 @@ dependencies = [ "data-encoding", "ed25519-dalek", "minisign-verify", + "rand 0.10.3", "rand_core 0.6.4", "rsa", "sha2 0.10.9", @@ -443,15 +444,20 @@ dependencies = [ "argon2", "bip39", "chacha20poly1305", + "custos-sign", "data-encoding", "ed25519-dalek", "hkdf", + "minisign-verify", "rand 0.10.3", + "rsa", "serde", "serde_json", + "sha2 0.10.9", "sha2 0.11.1", "tempfile", "thiserror", + "x509-cert", "zeroize", ] @@ -465,6 +471,7 @@ dependencies = [ "custos-totp", "custos-vault", "data-encoding", + "getrandom 0.2.17", "getrandom 0.4.3", "qrcode", "serde", diff --git a/crates/custos-keys/src/lib.rs b/crates/custos-keys/src/lib.rs index 3dc5a7a..96eeab4 100644 --- a/crates/custos-keys/src/lib.rs +++ b/crates/custos-keys/src/lib.rs @@ -84,9 +84,11 @@ pub fn generate(alg: Algorithm, comment: &str) -> Result { /// An OpenSSH key keeps its own comment unless it has none. pub fn import(text: &str, comment: &str) -> Result { // Pasted or read from a Windows file: CRLF line ends. - let text = text.replace(" + let text = text.replace( + " ", " -"); +", + ); let text = text.trim(); let has = |label: &str| text.contains(&format!("-----BEGIN {label}-----")); if has("ENCRYPTED PRIVATE KEY") || text.contains("Proc-Type: 4,ENCRYPTED") { @@ -99,7 +101,9 @@ pub fn import(text: &str, comment: &str) -> Result { } let comment = if key.comment().is_empty() { comment.to_owned() } else { key.comment().to_owned() }; return match key.key_data() { - KeypairData::Ed25519(k) => from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment), + KeypairData::Ed25519(k) => { + from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment) + } KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private, .. }) => { from_p256(p256::SecretKey::from_slice(private.as_slice()).map_err(|_| KeyError::Invalid)?, &comment) } @@ -135,8 +139,13 @@ pub fn import(text: &str, comment: &str) -> Result { /// rebuilt from its components here. fn rsa_from_openssh(k: &RsaKeypair) -> Result { let n = |m: &ssh_key::Mpint| rsa::BigUint::try_from(m).map_err(|_| KeyError::Invalid); - let sk = rsa::RsaPrivateKey::from_components(n(&k.public.n)?, n(&k.public.e)?, n(&k.private.d)?, vec![n(&k.private.p)?, n(&k.private.q)?]) - .map_err(|_| KeyError::Invalid)?; + let sk = rsa::RsaPrivateKey::from_components( + n(&k.public.n)?, + n(&k.public.e)?, + n(&k.private.d)?, + vec![n(&k.private.p)?, n(&k.private.q)?], + ) + .map_err(|_| KeyError::Invalid)?; sk.validate().map_err(|_| KeyError::Invalid)?; Ok(sk) } @@ -169,7 +178,13 @@ fn from_rsa(sk: rsa::RsaPrivateKey, comment: &str) -> Result assemble(&format!("rsa-{bits}"), KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem, comment) } -fn assemble(algorithm: &str, data: KeypairData, private_pem: String, public_pem: String, comment: &str) -> Result { +fn assemble( + algorithm: &str, + data: KeypairData, + private_pem: String, + public_pem: String, + comment: &str, +) -> Result { let private = enc(PrivateKey::new(data, comment))?; let public = private.public_key(); Ok(KeyPair { diff --git a/crates/custos-keys/tests/mandatory.rs b/crates/custos-keys/tests/mandatory.rs index caeed88..415c3e9 100644 --- a/crates/custos-keys/tests/mandatory.rs +++ b/crates/custos-keys/tests/mandatory.rs @@ -87,7 +87,8 @@ fn every_private_key_format_imports_to_the_same_key() { for text in inputs { // Surrounding whitespace (a paste, a file with CRLF line ends) does not matter. let pasted = format!("\r\n {}\r\n", text.replace('\n', "\r\n")); - let i = custos_keys::import(&pasted, "deploy").unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap())); + let i = custos_keys::import(&pasted, "deploy") + .unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap())); assert_eq!((i.algorithm.as_str(), i.fingerprint.as_str()), (alg.name(), k.fingerprint.as_str()), "{alg:?}"); assert_eq!(i.public_pem, k.public_pem); } diff --git a/crates/custos-seal/src/lib.rs b/crates/custos-seal/src/lib.rs index 1bff122..b4a6a36 100644 --- a/crates/custos-seal/src/lib.rs +++ b/crates/custos-seal/src/lib.rs @@ -52,7 +52,9 @@ fn random() -> Zeroizing<[u8; N]> { fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> { let mut k = Zeroizing::new([0u8; 32]); - hkdf::Hkdf::::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length"); + hkdf::Hkdf::::new(Some(salt), ikm) + .expand(&info.concat(), k.as_mut()) + .expect("32 bytes is a valid HKDF length"); k } diff --git a/crates/custos-sign/Cargo.toml b/crates/custos-sign/Cargo.toml index c90e0f3..db09a50 100644 --- a/crates/custos-sign/Cargo.toml +++ b/crates/custos-sign/Cargo.toml @@ -11,12 +11,14 @@ thiserror.workspace = true zeroize.workspace = true data-encoding.workspace = true # The RustCrypto generation custos-keys already uses (digest 0.10, signature 2). -ed25519-dalek = { version = "2", features = ["rand_core"] } -rsa = { version = "0.9", features = ["sha2"] } +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"] } -rand_core = { version = "0.6", features = ["getrandom"] } +# 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" diff --git a/crates/custos-sign/src/lib.rs b/crates/custos-sign/src/lib.rs index 971f06e..156f0e4 100644 --- a/crates/custos-sign/src/lib.rs +++ b/crates/custos-sign/src/lib.rs @@ -15,7 +15,8 @@ use std::time::Duration; use blake2::{Blake2b512, Digest}; use data_encoding::BASE64; use ed25519_dalek::{Signer as _, SigningKey}; -use rand_core::{OsRng, RngCore}; +use rand::rand_core::UnwrapErr; +use rand::rngs::SysRng; use rsa::RsaPrivateKey; use rsa::pkcs1v15; use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey}; @@ -103,6 +104,37 @@ impl fmt::Debug for RsaSecret { } } +/// 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. @@ -114,9 +146,9 @@ pub struct NewEd25519 { pub fn new_ed25519() -> NewEd25519 { let mut seed = Zeroizing::new([0u8; 32]); - OsRng.fill_bytes(&mut *seed); + fill(&mut *seed); let mut key_id = [0u8; 8]; - OsRng.fill_bytes(&mut key_id); + fill(&mut key_id); let secret = Ed25519Secret(seed); let public = secret.public(); NewEd25519 { secret, public, key_id } @@ -257,14 +289,14 @@ pub struct NewCert { } fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> { - let key = RsaPrivateKey::new(&mut OsRng, RSA_BITS).map_err(|_| Error::BadKey)?; + 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 { let mut bytes = [0u8; 16]; - OsRng.fill_bytes(&mut bytes); + fill(&mut bytes); bytes[0] &= 0x7f; // positive bytes[0] |= 0x01; // and without a leading zero byte SerialNumber::new(&bytes).map_err(|_| Error::Certificate) diff --git a/crates/custos-sign/tests/kat.rs b/crates/custos-sign/tests/kat.rs index 7f2f6fe..a23f945 100644 --- a/crates/custos-sign/tests/kat.rs +++ b/crates/custos-sign/tests/kat.rs @@ -65,7 +65,8 @@ fn minisign_verify_accepts_our_signatures_and_rejects_a_changed_file() { #[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 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(); diff --git a/crates/custos-vault/src/lib.rs b/crates/custos-vault/src/lib.rs index 4df05f3..9955e30 100644 --- a/crates/custos-vault/src/lib.rs +++ b/crates/custos-vault/src/lib.rs @@ -23,6 +23,7 @@ pub mod identity; mod item; mod save; mod secret; +pub mod signing; pub use item::{Attachment, Field, HISTORY_LIMIT, HistoryEntry, Item, ItemType, new_id, now_ms}; pub use save::{CrashPoint, save_atomic, save_atomic_crashing}; @@ -70,6 +71,10 @@ pub enum Error { NotACert, #[error("those words are not the ones in the recovery phrase")] WrongWords, + #[error("this vault already has {0} signing keys")] + SigningExists(&'static str), + #[error("signing keys: {0}")] + Signing(String), #[error("{0}")] Io(#[from] std::io::Error), } @@ -261,6 +266,8 @@ struct Body { factors: Vec, #[serde(default)] identity: Option, + #[serde(default)] + signing: Option, } /// What `to_bytes` serializes: borrows the items instead of cloning every secret. @@ -272,6 +279,8 @@ struct BodyRef<'a> { factors: Vec, #[serde(skip_serializing_if = "Option::is_none")] identity: Option, + #[serde(skip_serializing_if = "Option::is_none")] + signing: Option, } /// An unlocked vault: the vault key and the decrypted items, both wiped on drop. @@ -286,6 +295,8 @@ pub struct Vault { kdf_new: KdfParams, /// The Domi identity's root key (docs/IDENTITY.md), never handed out. identity: Option, + /// Signing keys and their audit log (docs/SIGNING.md); no key is ever handed out. + signing: signing::Store, } impl fmt::Debug for Vault { @@ -385,6 +396,7 @@ impl Vault { factors: Vec::new(), kdf_new: kdf, identity: None, + signing: signing::Store::default(), }) } @@ -401,6 +413,7 @@ impl Vault { factors: Vec::new(), kdf_new: kdf, identity: None, + signing: signing::Store::default(), }; v.add_factor(a, label_a)?; v.add_factor(b, label_b)?; @@ -433,6 +446,7 @@ impl Vault { factors: vec![rec], kdf_new: KdfParams::DEFAULT, identity: None, + signing: signing::Store::default(), }) } @@ -554,7 +568,20 @@ impl Vault { Some(j) => Some(identity::Root::from_json(j).ok_or(Error::Corrupted)?), None => None, }; - Ok(Vault { key, version: header.version, slots: header.slots, items: body.items, factors, kdf_new, identity }) + let signing = match body.signing { + Some(j) => signing::Store::from_json(j).ok_or(Error::Corrupted)?, + None => signing::Store::default(), + }; + Ok(Vault { + key, + version: header.version, + slots: header.slots, + items: body.items, + factors, + kdf_new, + identity, + signing, + }) } /// Wraps the vault key for device unlock with key material only this device can produce (e.g. a @@ -588,6 +615,7 @@ impl Vault { items: &self.items, factors: self.factors.iter().map(FactorRec::json).collect(), identity: self.identity.as_ref().map(identity::Root::json), + signing: self.signing.json(), }; serde_json::to_writer(&mut *json, &body).map_err(|e| Error::Io(std::io::Error::other(e.to_string())))?; let sealed = crypto::seal(&self.key, &body_nonce, &json, &out); diff --git a/crates/custos-vault/src/signing.rs b/crates/custos-vault/src/signing.rs index d56857f..08b5b0a 100644 --- a/crates/custos-vault/src/signing.rs +++ b/crates/custos-vault/src/signing.rs @@ -353,7 +353,13 @@ fn clean_list(list: &[String]) -> Result, Error> { 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, Error> { + pub fn signing_create( + &mut self, + role: Role, + pipelines: &[String], + repos: &[String], + now: i64, + ) -> Result, Error> { if self.signing.keys.iter().any(|k| k.role == role) { return Err(Error::SigningExists(match role { Role::Release => "release", @@ -363,8 +369,22 @@ impl Vault { 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"), + 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()))?; @@ -387,8 +407,17 @@ impl Vault { 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); + 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()]) } @@ -421,7 +450,12 @@ impl Vault { /// 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}`")))?; + 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())); } @@ -442,7 +476,8 @@ impl Vault { 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) + (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))); @@ -499,10 +534,14 @@ impl Vault { 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::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"), @@ -536,7 +575,14 @@ impl Vault { self.signing_record(req, outcome, reason, None, now); } - fn signing_record(&mut self, req: &Request, outcome: Outcome, reason: Option, signature: Option, now: i64) { + fn signing_record( + &mut self, + req: &Request, + outcome: Outcome, + reason: Option, + signature: Option, + now: i64, + ) { let mut context = req.context.clone(); if req.kind == SignKind::Manifest { context.file = "SHA256SUMS".into(); @@ -558,3 +604,115 @@ impl Vault { &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 { + 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> = 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]) -> Vec> { + 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 + } +} diff --git a/crates/custos-vault/tests/factors.rs b/crates/custos-vault/tests/factors.rs index fcc7816..ab2530e 100644 --- a/crates/custos-vault/tests/factors.rs +++ b/crates/custos-vault/tests/factors.rs @@ -86,7 +86,9 @@ fn a_factor_is_added_and_removed_without_the_others() { // Only the new factor's material is needed: its pairs come from the factor keys in the body. let phone = v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap(); let bytes = v.to_bytes().unwrap(); - let mut v = open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); + let mut v = + open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)) + .unwrap(); let kinds: Vec<_> = v.factors().iter().map(|f| f.kind).collect(); assert_eq!(kinds, [FactorKind::Password, FactorKind::Device, FactorKind::Approval]); // A lost device: drop its factor; the other two still open, the device no longer helps. @@ -108,7 +110,8 @@ fn a_forgotten_password_is_replaced_with_two_other_factors() { let mut v = two_factor_vault(); v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap(); let bytes = v.to_bytes().unwrap(); - let mut v = open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap(); + let mut v = + open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap(); v.change_password(&pw("New9-Password4"), FAST).unwrap(); let bytes2 = v.to_bytes().unwrap(); let dev = || Unlock::Material(FactorKind::Device, &DEVICE); @@ -168,7 +171,14 @@ fn a_machine_store_opens_with_its_device_key_alone() { let user = two_factor_vault().to_bytes().unwrap(); assert!(!Vault::is_machine_store(&user).unwrap()); assert!(matches!(Vault::open_machine_store(&user, &DEVICE), Err(Error::NeedTwoFactors))); - assert!(Vault::open_with(&bytes, Unlock::Material(FactorKind::Device, &STORE), Unlock::Material(FactorKind::Device, &STORE)).is_err()); + assert!( + Vault::open_with( + &bytes, + Unlock::Material(FactorKind::Device, &STORE), + Unlock::Material(FactorKind::Device, &STORE) + ) + .is_err() + ); } #[test] @@ -178,10 +188,20 @@ fn limits_are_enforced() { v.add_factor(Unlock::Material(FactorKind::Device, &[100 + i; 32]), "extra").unwrap(); } assert_eq!(v.factors().len(), 8); - assert!(matches!(v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), Err(Error::TooManyFactors))); + assert!(matches!( + v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), + Err(Error::TooManyFactors) + )); // Every pair still opens with 8 factors (8 factor slots + 28 pair slots). let bytes = v.to_bytes().unwrap(); - assert!(open(&bytes, Unlock::Material(FactorKind::Device, &[100; 32]), Unlock::Material(FactorKind::Device, &[105; 32])).is_ok()); + assert!( + open( + &bytes, + Unlock::Material(FactorKind::Device, &[100; 32]), + Unlock::Material(FactorKind::Device, &[105; 32]) + ) + .is_ok() + ); } #[test] @@ -190,7 +210,10 @@ fn no_factor_material_in_debug_output() { let u = Unlock::Material(FactorKind::Device, &secret); let p = pw("Orbit7-Fable3"); let printed = format!("{u:?} {:?}", Unlock::Password(&p)); - assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), "{printed}"); + assert!( + !printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), + "{printed}" + ); let v = two_factor_vault(); let printed = format!("{v:?} {:?}", v.factors()); for f in v.factors() { @@ -207,7 +230,8 @@ fn the_key_pair_item_type_round_trips() { k.set("private-key", "-----BEGIN PRIVATE KEY-----\n…", 5); v.add(k); let bytes = v.to_bytes().unwrap(); - let back = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); + let back = + open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap(); assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret)); } diff --git a/crates/custos-wasm/Cargo.toml b/crates/custos-wasm/Cargo.toml index 47b5472..9c4bec2 100644 --- a/crates/custos-wasm/Cargo.toml +++ b/crates/custos-wasm/Cargo.toml @@ -23,3 +23,5 @@ qrcode = { version = "0.14", default-features = false, features = ["svg"] } [target.'cfg(target_arch = "wasm32")'.dependencies] getrandom = "0.4" +# rand_core 0.6 (custos-sign, through custos-vault) uses getrandom 0.2: the same browser CSPRNG (lib.rs, `fill_v02`). +getrandom02 = { package = "getrandom", version = "0.2", features = ["custom"] } diff --git a/crates/custos-wasm/src/lib.rs b/crates/custos-wasm/src/lib.rs index 1805bfb..db1e966 100644 --- a/crates/custos-wasm/src/lib.rs +++ b/crates/custos-wasm/src/lib.rs @@ -48,11 +48,21 @@ const PHONE_APPROVAL: &[u8] = b"custos phone approval v1"; #[derive(Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")] enum FactorIn { - Password { password: SecretString }, + Password { + password: SecretString, + }, /// A factor service's or a device's answer, sealed to a key from `recipient` (`pub`) for `context`. - Sealed { factor: FactorKind, r#pub: String, sealed: String, context: String }, + Sealed { + factor: FactorKind, + r#pub: String, + sealed: String, + context: String, + }, /// Material the page holds itself: a passkey's PRF output (base64). - Material { factor: FactorKind, material: SecretString }, + Material { + factor: FactorKind, + material: SecretString, + }, } #[derive(Deserialize)] @@ -426,8 +436,12 @@ pub fn handle(request: &[u8]) -> Value { } Request::DomiPair { r#pub, id, label, device } => { let device_ok = data_encoding::BASE64URL_NOPAD.decode(device.as_bytes()).is_ok_and(|d| d.len() == 32); - let id_ok = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'); - let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { return err("A malformed request.") }; + let id_ok = !id.is_empty() + && id.len() <= 64 + && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'); + let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { + return err("A malformed request."); + }; let label: String = label.trim().chars().filter(|c| !c.is_control()).take(40).collect(); let plain = json!({ "label": label, "device": device }).to_string(); match custos_seal::seal(&public, format!("domi-pair:{id}").as_bytes(), plain.as_bytes()) { @@ -473,6 +487,14 @@ mod abi { Ok(()) } + /// The same for getrandom 0.2, which rand_core 0.6 (custos-sign's RSA and X.509 crates) is built on. The + /// browser never makes signing keys, but the crates must link. + fn fill_v02(dest: &mut [u8]) -> Result<(), getrandom02::Error> { + unsafe { random_fill(dest.as_mut_ptr(), dest.len()) }; + Ok(()) + } + getrandom02::register_custom_getrandom!(fill_v02); + #[unsafe(no_mangle)] pub extern "C" fn alloc(len: usize) -> *mut u8 { if len == 0 { diff --git a/crates/custos-wasm/tests/factors.rs b/crates/custos-wasm/tests/factors.rs index cf583e6..ba0fd3e 100644 --- a/crates/custos-wasm/tests/factors.rs +++ b/crates/custos-wasm/tests/factors.rs @@ -17,8 +17,14 @@ fn call(v: Value) -> Value { /// A version-2 vault: the master password and a TOTP factor with `totp` as its material. fn vault(totp: &[u8]) -> Vault { let pw = SecretString::from(PASSWORD); - let mut v = Vault::create_with(Unlock::Password(&pw), "Master password", Unlock::Material(FactorKind::Totp, totp), "TOTP", FAST) - .unwrap(); + let mut v = Vault::create_with( + Unlock::Password(&pw), + "Master password", + Unlock::Material(FactorKind::Totp, totp), + "TOTP", + FAST, + ) + .unwrap(); let mut login = Item::new(ItemType::WebLogin, "GitHub", 0); login.set("password", SECRET, 0); v.add(login); @@ -53,7 +59,8 @@ fn open_with_password_and_a_sealed_totp_release() { assert_eq!(me["match"], custos_seal::match_code(&public)); // What the factor service sends back after a valid code. let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap()); - let sealed_in = |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx }); + let sealed_in = + |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx }); let password = json!({ "kind": "password", "password": PASSWORD }); // Only the right context opens it. @@ -91,7 +98,9 @@ fn a_phone_pairs_then_opens_and_approves() { // The PC waits with a one-time key; the phone seals its pairing to it. let pc = Recipient::generate(); let context = "pair:abc"; - let r = call(json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 })); + let r = call( + json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 }), + ); assert_eq!(r["ok"], true, "{r}"); let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap(); assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap(), "the PC checks the code the phone shows"); @@ -105,7 +114,8 @@ fn a_phone_pairs_then_opens_and_approves() { // The PC adds both factors. let passkey_id = v.add_factor(Unlock::Material(FactorKind::Passkey, &prf), "Phone passkey").unwrap(); - let approval_id = v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap(); + let approval_id = + v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap(); let file = b64(&v); // The phone opens it with its passkey and the master password. @@ -130,13 +140,18 @@ fn a_phone_pairs_then_opens_and_approves() { let req_pub = BASE64.encode(&requester.public()); assert_eq!(call(json!({ "op": "match_code", "pub": req_pub }))["match"], requester.match_code()); let ctx = format!("approval:{approval_id}:r1"); - let wrong_key = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx })); + let wrong_key = call( + json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx }), + ); assert_eq!(wrong_key["ok"], false); let r = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": prf64, "pub": req_pub, "context": ctx })); let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap(); let m = requester.open(&sealed, ctx.as_bytes()).unwrap(); let pw = SecretString::from(PASSWORD); - assert!(Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)).is_ok()); + assert!( + Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)) + .is_ok() + ); } #[test] @@ -144,7 +159,9 @@ fn a_phone_pairs_as_a_domi_device() { // The PC waits with a one-time key; the phone seals its device public key and label to it. let pc = Recipient::generate(); let device = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 32]); - let r = call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device })); + let r = call( + json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device }), + ); assert_eq!(r["ok"], true, "{r}"); let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap(); assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap()); @@ -153,6 +170,16 @@ fn a_phone_pairs_as_a_domi_device() { assert_eq!(plain, json!({ "label": "Pixel", "device": device })); // Malformed: a device key of the wrong length, an id that would change the context. let short = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 31]); - assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }))["ok"], false); - assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }))["ok"], false); + assert_eq!( + call( + json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }) + )["ok"], + false + ); + assert_eq!( + call( + json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }) + )["ok"], + false + ); } -- 2.53.0 From 510d5eecd14e69e625ea272ec6651292270cbd4a Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 00:27:37 +0100 Subject: [PATCH 6/6] [repo] Undo cargo fmt churn in files this branch does not change; CLAUDE.md: the trap --- CLAUDE.md | 4 +++ crates/custos-keys/src/lib.rs | 27 ++++----------- crates/custos-keys/tests/mandatory.rs | 3 +- crates/custos-seal/src/lib.rs | 4 +-- crates/custos-vault/tests/factors.rs | 38 ++++------------------ crates/custos-wasm/src/lib.rs | 24 +++----------- crates/custos-wasm/tests/factors.rs | 47 ++++++--------------------- 7 files changed, 34 insertions(+), 113 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 3eda70b..f34553a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,3 +51,7 @@ On the dev machine set `CARGO_HOME=F:\C-Drive-Migration\future-caches\cargo` (C: first, then a test, then the code. - Branch → PR on Gitea (token in `$GITEA_TOKEN`, never echoed) → self-review in the PR body → merge `--no-ff` → push → `git rev-parse HEAD origin/main` → tag `vX.Y.Z` (the private app pins tags). + +## Known traps +- `cargo fmt --all` reformats files that are not rustfmt-clean on `main` (custos-keys, custos-seal, custos-wasm and + some tests): run `rustfmt --edition 2024 ` on the files you changed, so a PR carries no unrelated churn. diff --git a/crates/custos-keys/src/lib.rs b/crates/custos-keys/src/lib.rs index 96eeab4..3dc5a7a 100644 --- a/crates/custos-keys/src/lib.rs +++ b/crates/custos-keys/src/lib.rs @@ -84,11 +84,9 @@ pub fn generate(alg: Algorithm, comment: &str) -> Result { /// An OpenSSH key keeps its own comment unless it has none. pub fn import(text: &str, comment: &str) -> Result { // Pasted or read from a Windows file: CRLF line ends. - let text = text.replace( - " + let text = text.replace(" ", " -", - ); +"); let text = text.trim(); let has = |label: &str| text.contains(&format!("-----BEGIN {label}-----")); if has("ENCRYPTED PRIVATE KEY") || text.contains("Proc-Type: 4,ENCRYPTED") { @@ -101,9 +99,7 @@ pub fn import(text: &str, comment: &str) -> Result { } let comment = if key.comment().is_empty() { comment.to_owned() } else { key.comment().to_owned() }; return match key.key_data() { - KeypairData::Ed25519(k) => { - from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment) - } + KeypairData::Ed25519(k) => from_ed25519(ed25519_dalek::SigningKey::from_bytes(&k.private.to_bytes()), &comment), KeypairData::Ecdsa(EcdsaKeypair::NistP256 { private, .. }) => { from_p256(p256::SecretKey::from_slice(private.as_slice()).map_err(|_| KeyError::Invalid)?, &comment) } @@ -139,13 +135,8 @@ pub fn import(text: &str, comment: &str) -> Result { /// rebuilt from its components here. fn rsa_from_openssh(k: &RsaKeypair) -> Result { let n = |m: &ssh_key::Mpint| rsa::BigUint::try_from(m).map_err(|_| KeyError::Invalid); - let sk = rsa::RsaPrivateKey::from_components( - n(&k.public.n)?, - n(&k.public.e)?, - n(&k.private.d)?, - vec![n(&k.private.p)?, n(&k.private.q)?], - ) - .map_err(|_| KeyError::Invalid)?; + let sk = rsa::RsaPrivateKey::from_components(n(&k.public.n)?, n(&k.public.e)?, n(&k.private.d)?, vec![n(&k.private.p)?, n(&k.private.q)?]) + .map_err(|_| KeyError::Invalid)?; sk.validate().map_err(|_| KeyError::Invalid)?; Ok(sk) } @@ -178,13 +169,7 @@ fn from_rsa(sk: rsa::RsaPrivateKey, comment: &str) -> Result assemble(&format!("rsa-{bits}"), KeypairData::Rsa(enc(RsaKeypair::try_from(sk))?), private_pem, public_pem, comment) } -fn assemble( - algorithm: &str, - data: KeypairData, - private_pem: String, - public_pem: String, - comment: &str, -) -> Result { +fn assemble(algorithm: &str, data: KeypairData, private_pem: String, public_pem: String, comment: &str) -> Result { let private = enc(PrivateKey::new(data, comment))?; let public = private.public_key(); Ok(KeyPair { diff --git a/crates/custos-keys/tests/mandatory.rs b/crates/custos-keys/tests/mandatory.rs index 415c3e9..caeed88 100644 --- a/crates/custos-keys/tests/mandatory.rs +++ b/crates/custos-keys/tests/mandatory.rs @@ -87,8 +87,7 @@ fn every_private_key_format_imports_to_the_same_key() { for text in inputs { // Surrounding whitespace (a paste, a file with CRLF line ends) does not matter. let pasted = format!("\r\n {}\r\n", text.replace('\n', "\r\n")); - let i = custos_keys::import(&pasted, "deploy") - .unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap())); + let i = custos_keys::import(&pasted, "deploy").unwrap_or_else(|e| panic!("{alg:?} {}: {e:?}", text.lines().next().unwrap())); assert_eq!((i.algorithm.as_str(), i.fingerprint.as_str()), (alg.name(), k.fingerprint.as_str()), "{alg:?}"); assert_eq!(i.public_pem, k.public_pem); } diff --git a/crates/custos-seal/src/lib.rs b/crates/custos-seal/src/lib.rs index b4a6a36..1bff122 100644 --- a/crates/custos-seal/src/lib.rs +++ b/crates/custos-seal/src/lib.rs @@ -52,9 +52,7 @@ fn random() -> Zeroizing<[u8; N]> { fn derive(ikm: &[u8], salt: &[u8], info: &[&[u8]]) -> Zeroizing<[u8; 32]> { let mut k = Zeroizing::new([0u8; 32]); - hkdf::Hkdf::::new(Some(salt), ikm) - .expand(&info.concat(), k.as_mut()) - .expect("32 bytes is a valid HKDF length"); + hkdf::Hkdf::::new(Some(salt), ikm).expand(&info.concat(), k.as_mut()).expect("32 bytes is a valid HKDF length"); k } diff --git a/crates/custos-vault/tests/factors.rs b/crates/custos-vault/tests/factors.rs index ab2530e..fcc7816 100644 --- a/crates/custos-vault/tests/factors.rs +++ b/crates/custos-vault/tests/factors.rs @@ -86,9 +86,7 @@ fn a_factor_is_added_and_removed_without_the_others() { // Only the new factor's material is needed: its pairs come from the factor keys in the body. let phone = v.add_factor(Unlock::Material(FactorKind::Approval, &PHONE), "Phone").unwrap(); let bytes = v.to_bytes().unwrap(); - let mut v = - open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)) - .unwrap(); + let mut v = open(&bytes, Unlock::Material(FactorKind::Approval, &PHONE), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); let kinds: Vec<_> = v.factors().iter().map(|f| f.kind).collect(); assert_eq!(kinds, [FactorKind::Password, FactorKind::Device, FactorKind::Approval]); // A lost device: drop its factor; the other two still open, the device no longer helps. @@ -110,8 +108,7 @@ fn a_forgotten_password_is_replaced_with_two_other_factors() { let mut v = two_factor_vault(); v.add_factor(Unlock::Material(FactorKind::Totp, &TOTP), "TOTP backup").unwrap(); let bytes = v.to_bytes().unwrap(); - let mut v = - open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap(); + let mut v = open(&bytes, Unlock::Material(FactorKind::Device, &DEVICE), Unlock::Material(FactorKind::Totp, &TOTP)).unwrap(); v.change_password(&pw("New9-Password4"), FAST).unwrap(); let bytes2 = v.to_bytes().unwrap(); let dev = || Unlock::Material(FactorKind::Device, &DEVICE); @@ -171,14 +168,7 @@ fn a_machine_store_opens_with_its_device_key_alone() { let user = two_factor_vault().to_bytes().unwrap(); assert!(!Vault::is_machine_store(&user).unwrap()); assert!(matches!(Vault::open_machine_store(&user, &DEVICE), Err(Error::NeedTwoFactors))); - assert!( - Vault::open_with( - &bytes, - Unlock::Material(FactorKind::Device, &STORE), - Unlock::Material(FactorKind::Device, &STORE) - ) - .is_err() - ); + assert!(Vault::open_with(&bytes, Unlock::Material(FactorKind::Device, &STORE), Unlock::Material(FactorKind::Device, &STORE)).is_err()); } #[test] @@ -188,20 +178,10 @@ fn limits_are_enforced() { v.add_factor(Unlock::Material(FactorKind::Device, &[100 + i; 32]), "extra").unwrap(); } assert_eq!(v.factors().len(), 8); - assert!(matches!( - v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), - Err(Error::TooManyFactors) - )); + assert!(matches!(v.add_factor(Unlock::Material(FactorKind::Device, &[1; 32]), "ninth"), Err(Error::TooManyFactors))); // Every pair still opens with 8 factors (8 factor slots + 28 pair slots). let bytes = v.to_bytes().unwrap(); - assert!( - open( - &bytes, - Unlock::Material(FactorKind::Device, &[100; 32]), - Unlock::Material(FactorKind::Device, &[105; 32]) - ) - .is_ok() - ); + assert!(open(&bytes, Unlock::Material(FactorKind::Device, &[100; 32]), Unlock::Material(FactorKind::Device, &[105; 32])).is_ok()); } #[test] @@ -210,10 +190,7 @@ fn no_factor_material_in_debug_output() { let u = Unlock::Material(FactorKind::Device, &secret); let p = pw("Orbit7-Fable3"); let printed = format!("{u:?} {:?}", Unlock::Password(&p)); - assert!( - !printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), - "{printed}" - ); + assert!(!printed.contains("171") && !printed.to_lowercase().contains("ab, ab") && !printed.contains("Orbit7"), "{printed}"); let v = two_factor_vault(); let printed = format!("{v:?} {:?}", v.factors()); for f in v.factors() { @@ -230,8 +207,7 @@ fn the_key_pair_item_type_round_trips() { k.set("private-key", "-----BEGIN PRIVATE KEY-----\n…", 5); v.add(k); let bytes = v.to_bytes().unwrap(); - let back = - open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); + let back = open(&bytes, Unlock::Password(&pw("Orbit7-Fable3")), Unlock::Material(FactorKind::Device, &DEVICE)).unwrap(); let item = back.items().iter().find(|i| i.kind == ItemType::KeyPair).unwrap(); assert!(item.fields.iter().any(|f| f.name == "private-key" && f.secret)); } diff --git a/crates/custos-wasm/src/lib.rs b/crates/custos-wasm/src/lib.rs index db1e966..1480b7e 100644 --- a/crates/custos-wasm/src/lib.rs +++ b/crates/custos-wasm/src/lib.rs @@ -48,21 +48,11 @@ const PHONE_APPROVAL: &[u8] = b"custos phone approval v1"; #[derive(Deserialize)] #[serde(tag = "kind", rename_all = "snake_case", rename_all_fields = "camelCase")] enum FactorIn { - Password { - password: SecretString, - }, + Password { password: SecretString }, /// A factor service's or a device's answer, sealed to a key from `recipient` (`pub`) for `context`. - Sealed { - factor: FactorKind, - r#pub: String, - sealed: String, - context: String, - }, + Sealed { factor: FactorKind, r#pub: String, sealed: String, context: String }, /// Material the page holds itself: a passkey's PRF output (base64). - Material { - factor: FactorKind, - material: SecretString, - }, + Material { factor: FactorKind, material: SecretString }, } #[derive(Deserialize)] @@ -436,12 +426,8 @@ pub fn handle(request: &[u8]) -> Value { } Request::DomiPair { r#pub, id, label, device } => { let device_ok = data_encoding::BASE64URL_NOPAD.decode(device.as_bytes()).is_ok_and(|d| d.len() == 32); - let id_ok = !id.is_empty() - && id.len() <= 64 - && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'); - let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { - return err("A malformed request."); - }; + let id_ok = !id.is_empty() && id.len() <= 64 && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'); + let (Some(public), true, true) = (b64(&r#pub), device_ok, id_ok) else { return err("A malformed request.") }; let label: String = label.trim().chars().filter(|c| !c.is_control()).take(40).collect(); let plain = json!({ "label": label, "device": device }).to_string(); match custos_seal::seal(&public, format!("domi-pair:{id}").as_bytes(), plain.as_bytes()) { diff --git a/crates/custos-wasm/tests/factors.rs b/crates/custos-wasm/tests/factors.rs index ba0fd3e..cf583e6 100644 --- a/crates/custos-wasm/tests/factors.rs +++ b/crates/custos-wasm/tests/factors.rs @@ -17,14 +17,8 @@ fn call(v: Value) -> Value { /// A version-2 vault: the master password and a TOTP factor with `totp` as its material. fn vault(totp: &[u8]) -> Vault { let pw = SecretString::from(PASSWORD); - let mut v = Vault::create_with( - Unlock::Password(&pw), - "Master password", - Unlock::Material(FactorKind::Totp, totp), - "TOTP", - FAST, - ) - .unwrap(); + let mut v = Vault::create_with(Unlock::Password(&pw), "Master password", Unlock::Material(FactorKind::Totp, totp), "TOTP", FAST) + .unwrap(); let mut login = Item::new(ItemType::WebLogin, "GitHub", 0); login.set("password", SECRET, 0); v.add(login); @@ -59,8 +53,7 @@ fn open_with_password_and_a_sealed_totp_release() { assert_eq!(me["match"], custos_seal::match_code(&public)); // What the factor service sends back after a valid code. let sealed = BASE64.encode(&custos_seal::seal(&public, context.as_bytes(), &material).unwrap()); - let sealed_in = - |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx }); + let sealed_in = |ctx: &str| json!({ "kind": "sealed", "factor": "totp", "pub": me["pub"], "sealed": sealed, "context": ctx }); let password = json!({ "kind": "password", "password": PASSWORD }); // Only the right context opens it. @@ -98,9 +91,7 @@ fn a_phone_pairs_then_opens_and_approves() { // The PC waits with a one-time key; the phone seals its pairing to it. let pc = Recipient::generate(); let context = "pair:abc"; - let r = call( - json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 }), - ); + let r = call(json!({ "op": "phone_enrol", "pub": BASE64.encode(&pc.public()), "context": context, "label": "Phone", "prf": prf64 })); assert_eq!(r["ok"], true, "{r}"); let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap(); assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap(), "the PC checks the code the phone shows"); @@ -114,8 +105,7 @@ fn a_phone_pairs_then_opens_and_approves() { // The PC adds both factors. let passkey_id = v.add_factor(Unlock::Material(FactorKind::Passkey, &prf), "Phone passkey").unwrap(); - let approval_id = - v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap(); + let approval_id = v.add_factor_apart(Unlock::Material(FactorKind::Approval, &approval), "Phone", &[&passkey_id]).unwrap(); let file = b64(&v); // The phone opens it with its passkey and the master password. @@ -140,18 +130,13 @@ fn a_phone_pairs_then_opens_and_approves() { let req_pub = BASE64.encode(&requester.public()); assert_eq!(call(json!({ "op": "match_code", "pub": req_pub }))["match"], requester.match_code()); let ctx = format!("approval:{approval_id}:r1"); - let wrong_key = call( - json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx }), - ); + let wrong_key = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": BASE64.encode(&[8u8; 32]), "pub": req_pub, "context": ctx })); assert_eq!(wrong_key["ok"], false); let r = call(json!({ "op": "phone_approve", "wrapped": wrapped, "prf": prf64, "pub": req_pub, "context": ctx })); let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap(); let m = requester.open(&sealed, ctx.as_bytes()).unwrap(); let pw = SecretString::from(PASSWORD); - assert!( - Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)) - .is_ok() - ); + assert!(Vault::open_with(&v.to_bytes().unwrap(), Unlock::Password(&pw), Unlock::Material(FactorKind::Approval, &m)).is_ok()); } #[test] @@ -159,9 +144,7 @@ fn a_phone_pairs_as_a_domi_device() { // The PC waits with a one-time key; the phone seals its device public key and label to it. let pc = Recipient::generate(); let device = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 32]); - let r = call( - json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device }), - ); + let r = call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc_-1", "label": " Pixel\n", "device": device })); assert_eq!(r["ok"], true, "{r}"); let sealed = BASE64.decode(r["sealed"].as_str().unwrap().as_bytes()).unwrap(); assert_eq!(r["code"], custos_seal::sender_code(&sealed).unwrap()); @@ -170,16 +153,6 @@ fn a_phone_pairs_as_a_domi_device() { assert_eq!(plain, json!({ "label": "Pixel", "device": device })); // Malformed: a device key of the wrong length, an id that would change the context. let short = data_encoding::BASE64URL_NOPAD.encode(&[5u8; 31]); - assert_eq!( - call( - json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }) - )["ok"], - false - ); - assert_eq!( - call( - json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }) - )["ok"], - false - ); + assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "abc", "label": "x", "device": short }))["ok"], false); + assert_eq!(call(json!({ "op": "domi_pair", "pub": BASE64.encode(&pc.public()), "id": "a:b", "label": "x", "device": device }))["ok"], false); } -- 2.53.0