//! 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); //! - Android APKs: an RSA-4096 key with a self-signed certificate, signing the SHA-512 digests of the APK //! Signature Scheme v2/v3 signed data with RSA PKCS#1 v1.5 (apksig does the APK itself, on the build's side). //! //! Secret keys are [`Ed25519Secret`] and [`RsaSecret`]: zeroized on drop, printed as `[redacted]`. use std::fmt; use std::str::FromStr; use std::time::Duration; use blake2::{Blake2b512, Digest}; use data_encoding::BASE64; use ed25519_dalek::{Signer as _, SigningKey}; use rand::rand_core::UnwrapErr; use rand::rngs::SysRng; use rsa::RsaPrivateKey; use rsa::pkcs1v15; use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey}; use rsa::signature::hazmat::PrehashSigner; use sha2_010::{Sha256, Sha512}; 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; /// An Android app's signing key: RSA-4096. apksig signs with SHA512withRSA for any RSA key over 3072 bits. pub const ANDROID_RSA_BITS: usize = 4096; /// An Android app's certificate is valid this long: the key can never change for the app's whole life. pub const ANDROID_YEARS: u64 = 100; /// One `apk` request carries 1 to this many SHA-512 digests (v2 and v3 are two). pub const MAX_APK_DIGESTS: usize = 4; const DAY: u64 = 24 * 60 * 60; /// The largest manifest Custos signs (docs/SIGNING.md). pub const MAX_MANIFEST: usize = 32 * 1024; #[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, #[error("the approval cannot be signed: {0}")] Approval(&'static str), #[error("an APK request is 1 to 4 SHA-512 digests of 64 bytes each")] ApkDigests, } /// An Ed25519 seed. Wiped on drop; never printed. 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]") } } /// Fills `buf` from the OS CSPRNG through `rand`'s `SysRng`, as the rest of the workspace does (the browser build /// routes it to `crypto.getRandomValues`). fn fill(buf: &mut [u8]) { rand::Rng::fill_bytes(&mut UnwrapErr(SysRng), buf); } /// rand_core 0.6's interface, which `rsa` 0.9 generates keys with, over [`fill`]. struct OsRng06; impl rand_core::RngCore for OsRng06 { fn next_u32(&mut self) -> u32 { let mut b = [0u8; 4]; fill(&mut b); u32::from_le_bytes(b) } fn next_u64(&mut self) -> u64 { let mut b = [0u8; 8]; fill(&mut b); u64::from_le_bytes(b) } fn fill_bytes(&mut self, dest: &mut [u8]) { fill(dest); } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> { fill(dest); Ok(()) } } impl rand_core::CryptoRng for OsRng06 {} // ---- minisign ---- /// A new Ed25519 key with a random minisign key id. pub struct NewEd25519 { pub secret: Ed25519Secret, pub public: [u8; 32], pub key_id: [u8; 8], } pub fn new_ed25519() -> NewEd25519 { let mut seed = Zeroizing::new([0u8; 32]); fill(&mut *seed); let mut key_id = [0u8; 8]; fill(&mut key_id); let secret = Ed25519Secret(seed); let public = secret.public(); NewEd25519 { secret, public, key_id } } /// minisign prints a key id as one little-endian u64 in upper-case hex. pub fn key_id_hex(key_id: &[u8; 8]) -> String { format!("{:016X}", u64::from_le_bytes(*key_id)) } /// The BLAKE2b-512 of `data`: what a prehashed minisign signature signs. pub fn blake2b512(data: &[u8]) -> [u8; 64] { Blake2b512::digest(data).into() } /// `minisign.pub`: the public key file minisign `-V -p` and Tauri (base64 of it) read. pub fn minisign_public(public: &[u8; 32], key_id: &[u8; 8]) -> String { let mut raw = Vec::with_capacity(42); raw.extend_from_slice(b"Ed"); raw.extend_from_slice(key_id); raw.extend_from_slice(public); format!("untrusted comment: minisign public key {}\n{}\n", key_id_hex(key_id), BASE64.encode(&raw)) } /// A prehashed minisign signature file over a file whose BLAKE2b-512 is `digest`. /// The trusted comment is `timestamp:\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(bits: usize) -> Result<(RsaPrivateKey, RsaSecret), Error> { let key = RsaPrivateKey::new(&mut OsRng06, bits).map_err(|_| Error::BadKey)?; let der = key.to_pkcs8_der().map_err(|_| Error::BadKey)?.as_bytes().to_vec(); Ok((key, RsaSecret(Zeroizing::new(der)))) } fn serial() -> Result { let mut bytes = [0u8; 16]; fill(&mut bytes); bytes[0] &= 0x7f; // positive bytes[0] |= 0x01; // and without a leading zero byte SerialNumber::new(&bytes).map_err(|_| Error::Certificate) } fn name(cn: &str) -> Result { 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(RSA_BITS)?; 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(RSA_BITS)?; 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)? }) } // ---- Android APKs ---- /// One attribute value of an Android certificate's subject: 1 to 64 bytes, no characters RFC 4514 would have to /// escape, no control characters, no space at either end. fn subject_part(s: &str) -> Result<&str, Error> { let bad = s.is_empty() || s.len() > 64 || s.trim() != s || s.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#']) || s.chars().any(char::is_control); if bad { Err(Error::Certificate) } else { Ok(s) } } /// A new Android app signing key: RSA-4096 and a self-signed X.509 v3 certificate `CN=, O=, C=` valid /// [`ANDROID_YEARS`] years from now, an end-entity certificate (not a CA, key usage digitalSignature + /// nonRepudiation, no extended key usage). `c` is a two-letter country code. Slow: one RSA-4096 key. pub fn new_android(cn: &str, o: &str, c: &str) -> Result { let (cn, o) = (subject_part(cn)?, subject_part(o)?); if c.len() != 2 || !c.bytes().all(|b| b.is_ascii_uppercase()) { return Err(Error::Certificate); } // RFC 4514 order: the string names the most specific part first, the certificate encodes C, O, CN. let subject = Name::from_str(&format!("CN={cn},O={o},C={c}")).map_err(|_| Error::Certificate)?; let (key, secret) = new_rsa(ANDROID_RSA_BITS)?; let spki = spki(&key)?; let signer = pkcs1v15::SigningKey::::new(key); let validity = Validity::from_now(Duration::from_secs(ANDROID_YEARS * 365 * DAY)).map_err(|_| Error::Certificate)?; // A leaf issued by itself: self-signed, but without the CA extensions of a root. let profile = Profile::Leaf { issuer: subject.clone(), enable_key_agreement: false, enable_key_encipherment: false }; let builder = CertificateBuilder::new(profile, serial()?, validity, subject, spki, &signer) .map_err(|_| Error::Certificate)?; let cert = builder.build::().map_err(|_| Error::Certificate)?; Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? }) } /// RSA PKCS#1 v1.5 with the SHA-512 DigestInfo over each 64-byte digest in `digests` (1 to [`MAX_APK_DIGESTS`], /// concatenated): the signatures, concatenated in the same order, for APK Signature Scheme v2 and v3 /// (`RSA_PKCS1_V1_5_WITH_SHA512`, what apksig picks for an RSA key over 3072 bits). pub fn apk(secret: &RsaSecret, digests: &[u8]) -> Result, Error> { if digests.is_empty() || digests.len() % 64 != 0 || digests.len() > 64 * MAX_APK_DIGESTS { return Err(Error::ApkDigests); } let key = pkcs1v15::SigningKey::::new(secret.key()?); let mut out = Vec::new(); for digest in digests.chunks(64) { let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?; out.extend_from_slice(&Box::<[u8]>::from(sig)); } Ok(out) } /// A certificate as PEM, for tools that want text. pub fn cert_pem(der: &[u8]) -> String { let b64 = BASE64.encode(der); 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() } // ---- deploy approvals ---- /// The largest approval text Custos reads (docs/SIGNING.md). pub const MAX_APPROVAL: usize = 8 * 1024; /// An approval expires at most this many seconds after it is checked. pub const APPROVAL_MAX_AHEAD: u64 = 3600; /// A deploy approval, read from its canonical JSON (docs/SIGNING.md, "approval"). Nothing in it is secret. #[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct Approval { pub run: String, pub repo: String, pub commit: String, pub pipeline: String, pub version: String, pub targets: Vec, /// Unix seconds. pub expires: u64, } /// The JSON as it is parsed: `v` first, the rest as [`Approval`]. #[derive(serde::Deserialize)] #[serde(deny_unknown_fields)] struct ApprovalJson { v: u64, run: String, repo: String, commit: String, pipeline: String, version: String, targets: Vec, expires: u64, } impl Approval { /// The canonical text (docs/SIGNING.md): one line, no spaces, keys in the fixed order, `"` and `\` escaped, /// nothing else. Meaningful for an approval that passed [`approval_check`]. pub fn canonical(&self) -> String { fn string(out: &mut String, s: &str) { out.push('"'); for c in s.chars() { match c { '"' => out.push_str("\\\""), '\\' => out.push_str("\\\\"), c => out.push(c), } } out.push('"'); } let mut out = String::with_capacity(256); out.push_str("{\"v\":1,\"run\":"); string(&mut out, &self.run); out.push_str(",\"repo\":"); string(&mut out, &self.repo); out.push_str(",\"commit\":"); string(&mut out, &self.commit); out.push_str(",\"pipeline\":"); string(&mut out, &self.pipeline); out.push_str(",\"version\":"); string(&mut out, &self.version); out.push_str(",\"targets\":["); for (i, t) in self.targets.iter().enumerate() { if i > 0 { out.push(','); } string(&mut out, t); } out.push_str("],\"expires\":"); out.push_str(&self.expires.to_string()); out.push('}'); out } } /// A run id: `[A-Za-z0-9._-]{1,64}`. pub fn run_id_ok(run: &str) -> bool { (1..=64).contains(&run.len()) && run.bytes().all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c)) } /// `[A-Za-z0-9._+-]{1,64}`: an approval's repo, pipeline and version. fn name_ok(s: &str) -> bool { (1..=64).contains(&s.len()) && s.bytes().all(|c| c.is_ascii_alphanumeric() || b"._+-".contains(&c)) } /// Characters a target may not hold: control characters, and the invisible ones that change how the rest of the /// line is shown on the card (bidi overrides and isolates, zero-width characters, line separators, soft hyphen). fn unprintable(c: char) -> bool { c.is_control() || matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}') || matches!(c, '\u{2060}'..='\u{2069}' | '\u{FEFF}') } /// Checks that `text` is a deploy approval in canonical form that has not expired at `now_secs` and expires at most /// an hour later (docs/SIGNING.md). It is parsed, written again in canonical form and compared byte for byte, so /// any other spelling of the same values (key order, spaces, escapes, a trailing newline) is refused. pub fn approval_check(text: &str, now_secs: u64) -> Result { let a = approval_parse(text)?; if a.expires <= now_secs { return Err(Error::Approval("it has expired")); } if a.expires > now_secs.saturating_add(APPROVAL_MAX_AHEAD) { return Err(Error::Approval("it expires more than an hour from now")); } Ok(a) } /// [`approval_check`] without the clock: the canonical form and every member's rule, not the expiry. For reading /// what a refused or expired request said; never enough to sign. pub fn approval_parse(text: &str) -> Result { let err = |why: &'static str| Err(Error::Approval(why)); if text.len() > MAX_APPROVAL { return err("larger than 8 KiB"); } let Ok(j) = serde_json::from_str::(text) else { return err("not an approval in canonical form"); }; if j.v != 1 { return err("v is not 1"); } let a = Approval { run: j.run, repo: j.repo, commit: j.commit, pipeline: j.pipeline, version: j.version, targets: j.targets, expires: j.expires, }; if !run_id_ok(&a.run) { return err("the run is not a run id ([A-Za-z0-9._-], 1 to 64)"); } if !name_ok(&a.repo) { return err("the repo is not 1 to 64 of [A-Za-z0-9._+-]"); } if a.commit.len() != 40 || !a.commit.bytes().all(|c| c.is_ascii_digit() || (b'a'..=b'f').contains(&c)) { return err("the commit is not 40 lower-case hex digits"); } if !name_ok(&a.pipeline) { return err("the pipeline is not 1 to 64 of [A-Za-z0-9._+-]"); } if !name_ok(&a.version) { return err("the version is not 1 to 64 of [A-Za-z0-9._+-]"); } if !(1..=16).contains(&a.targets.len()) { return err("there must be 1 to 16 targets"); } for t in &a.targets { if !(1..=80).contains(&t.chars().count()) { return err("a target is not 1 to 80 characters"); } if t.chars().any(unprintable) { return err("a target has control or invisible characters"); } } if a.canonical() != text { return err("not in canonical form (key order, spaces or escaping)"); } Ok(a) } /// Signs a deploy approval for `run` as prehashed minisign over the text's bytes, file name `approval-.json`. /// The text is checked with [`approval_check`] at `timestamp` (Unix seconds) and must name `run`. pub fn approval( secret: &Ed25519Secret, key_id: &[u8; 8], text: &str, timestamp: u64, run: &str, ) -> Result { let a = approval_check(text, timestamp)?; if a.run != run { return Err(Error::Approval("the approval's run is not the request's")); } minisign(secret, key_id, &blake2b512(text.as_bytes()), &format!("approval-{run}.json"), timestamp) }