From 59fdfa26ef4226d535f44310012179b444454b2b Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 4 Nov 2026 00:15:33 +0100 Subject: [PATCH] [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" }