From 045f1f5d00ad675834dac562a9c0a8feefc274d5 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sun, 8 Nov 2026 00:27:47 +0100 Subject: [PATCH] [vault] Android: the android key kind (RSA-4096, self-signed, 100 years) and the apk sign kind (1-4 SHA-512 digests, PKCS#1 v1.5), never unattended; v0.14.0 --- Cargo.lock | 20 +- Cargo.toml | 2 +- crates/custos-sign/src/lib.rs | 75 +++++- crates/custos-sign/tests/fixtures/README.md | 2 + .../custos-sign/tests/fixtures/digest512.bin | Bin 0 -> 64 bytes .../tests/fixtures/digest512.openssl.sig | Bin 0 -> 384 bytes crates/custos-sign/tests/kat.rs | 77 +++++- crates/custos-vault/src/signing.rs | 112 +++++++- crates/custos-vault/tests/android.rs | 248 ++++++++++++++++++ docs/FORMAT.md | 6 +- docs/SIGNING.md | 45 +++- docs/THREAT_MODEL.md | 4 + 12 files changed, 564 insertions(+), 27 deletions(-) create mode 100644 crates/custos-sign/tests/fixtures/digest512.bin create mode 100644 crates/custos-sign/tests/fixtures/digest512.openssl.sig create mode 100644 crates/custos-vault/tests/android.rs diff --git a/Cargo.lock b/Cargo.lock index ead1fc3..d930cd7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,7 +329,7 @@ dependencies = [ [[package]] name = "custos-gen" -version = "0.13.0" +version = "0.14.0" dependencies = [ "custos-vault", "data-encoding", @@ -341,7 +341,7 @@ dependencies = [ [[package]] name = "custos-kdbx" -version = "0.13.0" +version = "0.14.0" dependencies = [ "aes", "argon2", @@ -362,7 +362,7 @@ dependencies = [ [[package]] name = "custos-keys" -version = "0.13.0" +version = "0.14.0" dependencies = [ "custos-vault", "ed25519-dalek", @@ -375,11 +375,11 @@ dependencies = [ [[package]] name = "custos-qr" -version = "0.13.0" +version = "0.14.0" [[package]] name = "custos-seal" -version = "0.13.0" +version = "0.14.0" dependencies = [ "chacha20poly1305", "hkdf", @@ -392,7 +392,7 @@ dependencies = [ [[package]] name = "custos-share" -version = "0.13.0" +version = "0.14.0" dependencies = [ "argon2", "chacha20poly1305", @@ -409,7 +409,7 @@ dependencies = [ [[package]] name = "custos-sign" -version = "0.13.0" +version = "0.14.0" dependencies = [ "blake2 0.10.6", "data-encoding", @@ -428,7 +428,7 @@ dependencies = [ [[package]] name = "custos-totp" -version = "0.13.0" +version = "0.14.0" dependencies = [ "custos-vault", "data-encoding", @@ -441,7 +441,7 @@ dependencies = [ [[package]] name = "custos-vault" -version = "0.13.0" +version = "0.14.0" dependencies = [ "argon2", "bip39", @@ -465,7 +465,7 @@ dependencies = [ [[package]] name = "custos-wasm" -version = "0.13.0" +version = "0.14.0" dependencies = [ "custos-qr", "custos-seal", diff --git a/Cargo.toml b/Cargo.toml index 7e91a5d..1c52387 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.13.0" +version = "0.14.0" edition = "2024" license = "MPL-2.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-sign/src/lib.rs b/crates/custos-sign/src/lib.rs index a2e06cf..9fa63e0 100644 --- a/crates/custos-sign/src/lib.rs +++ b/crates/custos-sign/src/lib.rs @@ -4,7 +4,9 @@ //! - 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). +//! - 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]`. @@ -21,7 +23,7 @@ use rsa::RsaPrivateKey; use rsa::pkcs1v15; use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey, EncodePublicKey}; use rsa::signature::hazmat::PrehashSigner; -use sha2_010::Sha256; +use sha2_010::{Sha256, Sha512}; use x509_cert::Certificate; use x509_cert::builder::{Builder, CertificateBuilder, Profile}; use x509_cert::der::{Decode, Encode}; @@ -36,6 +38,12 @@ use zeroize::Zeroizing; 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; @@ -54,6 +62,8 @@ pub enum Error { 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. @@ -290,8 +300,8 @@ pub struct NewCert { pub cert_der: Vec, } -fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> { - let key = RsaPrivateKey::new(&mut OsRng06, RSA_BITS).map_err(|_| Error::BadKey)?; +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)))) } @@ -318,7 +328,7 @@ fn spki(key: &RsaPrivateKey) -> Result { /// 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 (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)?; @@ -331,7 +341,7 @@ pub fn new_root(cn: &str, years: u64) -> Result { /// 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 (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 { @@ -346,6 +356,59 @@ pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: & 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); diff --git a/crates/custos-sign/tests/fixtures/README.md b/crates/custos-sign/tests/fixtures/README.md index fbdba73..9b7151e 100644 --- a/crates/custos-sign/tests/fixtures/README.md +++ b/crates/custos-sign/tests/fixtures/README.md @@ -4,3 +4,5 @@ Throwaway **test keys** for the known-answer tests in `../kat.rs`. They sign not `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). +- `digest512.bin` (64 random bytes) and `digest512.openssl.sig`: `openssl pkeyutl -sign -inkey rsa3072.pk8.der -keyform DER + -in digest512.bin -pkeyopt digest:sha512` (PKCS#1 v1.5 with the SHA-512 DigestInfo: the `apk` kind). diff --git a/crates/custos-sign/tests/fixtures/digest512.bin b/crates/custos-sign/tests/fixtures/digest512.bin new file mode 100644 index 0000000000000000000000000000000000000000..5a18714dc97f6b6397bc9bf74a2571f98a0bdb79 GIT binary patch literal 64 zcmezH>8WD9(3=Wn#`uX#FU2t*WZ28PYVx_)mnS8+r}|s{JtJQwb#UdJ*1mbAbK67t W<}ca6VeH6mWu)7Z%G{ZBdJ+H)y&duZ literal 0 HcmV?d00001 diff --git a/crates/custos-sign/tests/fixtures/digest512.openssl.sig b/crates/custos-sign/tests/fixtures/digest512.openssl.sig new file mode 100644 index 0000000000000000000000000000000000000000..0b2b084ee429538af4bba7c18e3d72c81255dea7 GIT binary patch literal 384 zcmb1I==ym^^ahXDFMc&hpFbPw*H-zP=URBf;s4KXmCa!M{OtW=0gY*uHP?UMT>kIv z_nS!h@$<3D%~>lx^}kN5{IoP< zp7{~GX^r_D6OEmp*ss`X$8t{X#qIt@p&Z9A7H|9a_(r(tGfS6Ev7vYR*78|IZ0Y^5?TBPHR4|)TM8-L&1?@wfiLJsnbuqtf z-x&VoTbrI__C8x1A$g-u)?s6HM_-P^0B?_pzh zW3HaW?vuJYzgzw=+;ZRNAC%|6@q$a$0ohePCmxG^eCW{_CG^GF{?VfYH3`?Xq9%x} zfBIH%s=LyRMFKLSF$(V=o99H%x^`_vSQWeH1RR literal 0 HcmV?d00001 diff --git a/crates/custos-sign/tests/kat.rs b/crates/custos-sign/tests/kat.rs index a23f945..c7b0ad8 100644 --- a/crates/custos-sign/tests/kat.rs +++ b/crates/custos-sign/tests/kat.rs @@ -1,6 +1,7 @@ //! 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`. +//! `payload.bin.minisig` signed by it; `rsa3072.pk8.der`, `digest.openssl.sig` and `digest512.openssl.sig` by +//! `openssl pkeyutl`. //! tools/signing/interop.ps1 checks the other direction with the real minisign, signtool and osslsigncode. use std::fs; @@ -108,6 +109,80 @@ fn authenticode_signature_equals_openssls() { assert_eq!(authenticode(&key, &[0u8; 64]).unwrap_err(), Error::DigestLength(32)); } +#[test] +fn apk_signatures_equal_openssls_sha512_pkcs1() { + // The PKCS#1 v1.5 SHA-512 DigestInfo does not depend on the key size: the 3072-bit fixture checks it. + let key = RsaSecret::from_pkcs8_der(fixture("rsa3072.pk8.der")).unwrap(); + let digest = fixture("digest512.bin"); + let expected = fixture("digest512.openssl.sig"); + assert_eq!(apk(&key, &digest).unwrap(), expected); + // Two digests (v2 and v3): two signatures, in order. + let mut two = digest.clone(); + two.extend(custos_sign::sha256_hex(&digest).as_bytes()); // any other 64 bytes + let both = apk(&key, &two).unwrap(); + assert_eq!(both.len(), 2 * 384); + assert_eq!(&both[..384], expected.as_slice()); + assert_eq!(both[384..].to_vec(), apk(&key, &two[64..]).unwrap()); + for bad in [0usize, 32, 63, 65, 64 * 5] { + assert_eq!(apk(&key, &vec![1u8; bad]).unwrap_err(), Error::ApkDigests, "{bad}"); + } +} + +#[test] +fn an_android_key_is_rsa_4096_with_a_self_signed_end_entity_certificate_for_100_years() { + use rsa::RsaPublicKey; + use rsa::pkcs1v15::{Signature, VerifyingKey}; + use rsa::pkcs8::DecodePublicKey; + use rsa::signature::Verifier; + use rsa::signature::hazmat::PrehashVerifier; + use rsa::traits::PublicKeyParts; + use x509_cert::ext::pkix::{BasicConstraints, ExtendedKeyUsage, KeyUsage}; + + let made = new_android("Postea", "Marek Novak", "CZ").unwrap(); + let c = Certificate::from_der(&made.cert_der).unwrap(); + assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ"); + assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject, "self-signed"); + let v = &c.tbs_certificate.validity; + let days = (v.not_after.to_unix_duration().as_secs() - v.not_before.to_unix_duration().as_secs()) / 86_400; + assert_eq!(days, 100 * 365); + let (_, bc) = c.tbs_certificate.get::().unwrap().unwrap(); + assert!(!bc.ca, "not a CA"); + assert!(c.tbs_certificate.get::().unwrap().is_some()); + assert!(c.tbs_certificate.get::().unwrap().is_none(), "no extended key usage"); + + let spki = c.tbs_certificate.subject_public_key_info.to_der().unwrap(); + assert_eq!(RsaPublicKey::from_public_key_der(&spki).unwrap().n().bits(), 4096); + // Signed by its own key, and that key makes the APK signatures. + let sha256 = VerifyingKey::::from_public_key_der(&spki).unwrap(); + sha256 + .verify(&c.tbs_certificate.to_der().unwrap(), &Signature::try_from(c.signature.raw_bytes()).unwrap()) + .unwrap(); + let digests = [3u8; 128]; + let sigs = apk(&made.secret, &digests).unwrap(); + assert_eq!(sigs.len(), 2 * 512); + let sha512 = VerifyingKey::::from_public_key_der(&spki).unwrap(); + for (d, s) in digests.chunks(64).zip(sigs.chunks(512)) { + sha512.verify_prehash(d, &Signature::try_from(s).unwrap()).unwrap(); + } + // An Android key is not an Authenticode key, but the function cannot tell: the vault keeps them apart. + assert_eq!(format!("{:?}", made.secret), "[redacted]"); + + for (cn, o, c) in [ + ("", "O", "CZ"), + ("A,B", "O", "CZ"), + (" Postea", "O", "CZ"), + ("Postea", "O=x", "CZ"), + ("Postea", "O", "cz"), + ("Postea", "O", "CZE"), + ( + "Postea", "O +", "CZ", + ), + ] { + assert!(matches!(new_android(cn, o, c), Err(Error::Certificate)), "{cn:?} {o:?} {c:?}"); + } +} + #[test] fn digests_and_file_names_are_checked() { let (secret, key_id) = minisign_key(); diff --git a/crates/custos-vault/src/signing.rs b/crates/custos-vault/src/signing.rs index 746c4db..2ab8d43 100644 --- a/crates/custos-vault/src/signing.rs +++ b/crates/custos-vault/src/signing.rs @@ -49,6 +49,8 @@ pub enum KeyKind { Ed25519, RootCa, CodeSigning, + /// An Android app's signing key (core 0.14.0): RSA-4096 and a self-signed certificate; signs `apk` only. + Android, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -59,6 +61,9 @@ pub enum SignKind { Authenticode, /// A deploy approval's canonical JSON, signed as minisign by `domi-approve` only (core 0.12.0). Approval, + /// APK Signature Scheme v2/v3: 1 to 4 SHA-512 digests, signed with RSA PKCS#1 v1.5, by an Android key only + /// (core 0.14.0). + Apk, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -92,7 +97,8 @@ pub struct Context { 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. + /// BLAKE2b-512 of the file (minisign), signtool's 32-byte digest (authenticode), or 1 to 4 SHA-512 digests of + /// an APK's signed data, concatenated (apk). Empty for a manifest or an approval. pub digest: Vec, /// The `SHA256SUMS` text, for a manifest. pub manifest: Option, @@ -148,7 +154,8 @@ pub struct AuditEntry { /// 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). + /// The `.minisig` text (minisign, manifest, approval), the raw RSA signature (authenticode) or the raw RSA + /// signatures, concatenated in the order of the digests (apk). pub bytes: Vec, pub sha256: String, } @@ -170,7 +177,7 @@ pub struct KeyView { pub key_id: Option, /// The `minisign.pub` text, for Ed25519 keys. pub minisign_public: Option, - /// The certificate (DER), for root and code-signing keys. + /// The certificate (DER), for root, code-signing and Android keys. pub cert: Option>, pub issuer: Option, } @@ -275,7 +282,7 @@ impl Store { let seed: [u8; 32] = k.secret.expose().try_into().ok()?; Secret::Ed25519(Ed25519Secret::from_bytes(seed)) } - KeyKind::RootCa | KeyKind::CodeSigning => { + KeyKind::RootCa | KeyKind::CodeSigning | KeyKind::Android => { Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?) } }; @@ -297,6 +304,10 @@ impl Store { Some(c) => Some(unb64(c)?), None => None, }; + // An Android key is nothing without its certificate: the app is identified by it forever. + if k.kind == KeyKind::Android && cert.is_none() { + return None; + } keys.push(Key { id: k.id, kind: k.kind, @@ -372,6 +383,22 @@ fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key { } } +/// What [`Vault::signing_create_android`] makes: the key's id and name, the certificate's subject, its role and +/// who may ask. The key is RSA-4096 and the certificate is valid [`custos_sign::ANDROID_YEARS`] years. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AndroidKey { + /// `[a-z0-9-]{1,64}`, e.g. `postea-android`; not the id of a key the vault has. + pub id: String, + pub name: String, + /// The certificate's subject: common name, organisation, two-letter country code. + pub cn: String, + pub o: String, + pub c: String, + pub role: Role, + pub pipelines: Vec, + pub repos: Vec, +} + fn in_scope(list: &[String], what: &str) -> bool { list.iter().any(|x| x == "*" || x == what) } @@ -484,6 +511,49 @@ impl Vault { Ok(APPROVE_KEY.into()) } + /// Creates an Android app signing key (core 0.14.0): RSA-4096 and a self-signed certificate. A release key + /// always asks; a test key signs without asking, never for a `tag`. The caller saves. Slow: one RSA-4096 key. + pub fn signing_create_android(&mut self, spec: &AndroidKey, now: i64) -> Result { + let id = spec.id.as_str(); + if id.is_empty() + || id.len() > 64 + || !id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + { + return Err(Error::Signing("a key id is 1 to 64 of a-z, 0-9 and -".into())); + } + if self.signing.get(id).is_some() { + return Err(Error::Signing(format!("there is a key `{id}` already"))); + } + let name = spec.name.trim(); + if name.is_empty() || name.len() > 100 || name.chars().any(char::is_control) { + return Err(Error::Signing("the key's name is not usable".into())); + } + let (pipelines, repos) = (clean_list(&spec.pipelines)?, clean_list(&spec.repos)?); + let made = custos_sign::new_android(&spec.cn, &spec.o, &spec.c).map_err(|e| match e { + custos_sign::Error::Certificate => Error::Signing( + "the certificate's name is not usable (1-64 characters without , + = \" \\ < > ; # and no space at \ + either end, and a two-letter country code)" + .into(), + ), + e => Error::Signing(e.to_string()), + })?; + self.signing.keys.push(Key { + id: id.into(), + kind: KeyKind::Android, + role: spec.role, + name: name.into(), + secret: Secret::Rsa(made.secret), + public: None, + key_id: None, + cert: Some(made.cert_der), + issuer: None, + created: now, + pipelines, + repos, + }); + Ok(id.into()) + } + /// Every signing key, public parts only. pub fn signing_keys(&self) -> Vec { self.signing @@ -553,6 +623,7 @@ impl Vault { (KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY, (KeyKind::Ed25519, SignKind::Approval) => approver, (KeyKind::CodeSigning, SignKind::Authenticode) => true, + (KeyKind::Android, SignKind::Apk) => true, _ => false, }; if k.kind == KeyKind::RootCa { @@ -579,6 +650,13 @@ impl Vault { SignKind::Authenticode if req.digest.len() != 32 => { return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into())); } + SignKind::Apk + if req.digest.is_empty() + || req.digest.len() % 64 != 0 + || req.digest.len() > 64 * custos_sign::MAX_APK_DIGESTS => + { + return Err(Refusal::Invalid("an APK request is 1 to 4 SHA-512 digests: 64 bytes each".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()))?; @@ -670,6 +748,7 @@ impl Vault { ) .map(String::into_bytes), (Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest), + (Secret::Rsa(s), SignKind::Apk) => custos_sign::apk(s, &req.digest), _ => unreachable!("signing_check matched the key to the kind"), }; let bytes = match bytes { @@ -805,6 +884,19 @@ mod tests { 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(); + for (id, role) in [("postea-android", Role::Release), ("domi-test-android", Role::Test)] { + let spec = AndroidKey { + id: id.into(), + name: id.into(), + cn: "Postea".into(), + o: "Marek Novak".into(), + c: "CZ".into(), + role, + pipelines: s(&["*"]), + repos: s(&["*"]), + }; + v.signing_create_android(&spec, 1).unwrap(); + } let secrets: Vec> = v .signing .keys @@ -814,7 +906,7 @@ mod tests { Secret::Rsa(s) => s.expose().to_vec(), }) .collect(); - assert_eq!(secrets.len(), 7, "the release set with domi-approve, and the test set"); + assert_eq!(secrets.len(), 9, "the release set with domi-approve, the test set, two Android keys"); // 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. @@ -839,6 +931,10 @@ mod tests { )); reqs.push(approve); reqs.push(req("domi-approve", SignKind::Minisign, 64)); + reqs.push(req("postea-android", SignKind::Apk, 128)); + reqs.push(req("domi-test-android", SignKind::Apk, 64)); + reqs.push(req("postea-android", SignKind::Authenticode, 32)); + reqs.push(req("domi-code-signing", SignKind::Apk, 64)); for r in &reqs { out += &format!("{:?}", v.signing_check(r)); for approval in [Approval::Mark, Approval::Auto] { @@ -852,6 +948,12 @@ mod tests { v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved), "an approval was signed too" ); + assert!( + v.signing_audit() + .iter() + .any(|e| e.kind == SignKind::Apk && e.key == "postea-android" && e.outcome == Outcome::Approved), + "and an APK" + ); out += &serde_json::to_string(v.signing_audit()).unwrap(); out += &format!("{:?}", v.signing_audit()); out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3)); diff --git a/crates/custos-vault/tests/android.rs b/crates/custos-vault/tests/android.rs new file mode 100644 index 0000000..7d2bfab --- /dev/null +++ b/crates/custos-vault/tests/android.rs @@ -0,0 +1,248 @@ +//! Android APK signing keys (core 0.14.0, docs/SIGNING.md "apk"): the key and its certificate, the `apk` kind and +//! nothing else, scope, the test-key rules, malformed requests, the audit through a reopen, and never unattended. +//! That no API path returns an Android key's private half is part of the unit test in src/signing.rs. + +use std::collections::BTreeSet; +use std::sync::OnceLock; + +use custos_vault::security::{self, Level}; +use custos_vault::signing::{AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via}; +use custos_vault::{Error, KdfParams, SecretString, Vault}; +use rsa::pkcs1v15::{Signature, VerifyingKey}; +use rsa::pkcs8::DecodePublicKey; +use rsa::signature::hazmat::PrehashVerifier; +use x509_cert::der::{Decode, Encode}; + +const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }; +const NOW: i64 = 1_793_750_000_000; +const REPO: &str = "mnovak/Postea"; + +fn s(v: &[&str]) -> Vec { + v.iter().map(|x| x.to_string()).collect() +} + +fn spec(id: &str, role: Role, pipelines: &[&str], repos: &[&str]) -> AndroidKey { + AndroidKey { + id: id.into(), + name: if role == Role::Release { "Postea Android".into() } else { "Domi test Android".into() }, + cn: if role == Role::Release { "Postea".into() } else { "Domi Test Android".into() }, + o: if role == Role::Release { "Marek Novak".into() } else { "Domi".into() }, + c: "CZ".into(), + role, + pipelines: s(pipelines), + repos: s(repos), + } +} + +/// A vault with the release and test sets, `postea-android` (release, `mnovak/Postea`) and `domi-test-android` +/// (test, any). Two RSA-4096 keys are made once and the vault reopened from its bytes for each test. +fn vault() -> Vault { + static BYTES: OnceLock> = OnceLock::new(); + let bytes = BYTES.get_or_init(|| { + let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap(); + v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap(); + v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap(); + v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW).unwrap(); + v.signing_create_android(&spec("domi-test-android", Role::Test, &["*"], &["*"]), NOW).unwrap(); + v.to_bytes().unwrap() + }); + Vault::open(bytes, &SecretString::from("pw")).unwrap() +} + +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: "Postea-1.0.0.apk".into(), + size: 9_876_543, + sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(), + version: "1.0.0".into(), + } +} + +fn apk_req(key: &str, digests: usize, c: Context) -> Request { + Request { + key: key.into(), + kind: SignKind::Apk, + digest: (0..digests * 64).map(|i| (i % 251) as u8).collect(), + manifest: None, + approval: None, + run: Some("r-7".into()), + context: c, + via: Via::Local, + } +} + +fn release() -> Context { + ctx("release", REPO, "tag") +} + +#[test] +fn an_android_key_has_its_certificate_and_no_secret_in_its_view() { + let v = vault(); + let keys = v.signing_keys(); + let k = keys.iter().find(|k| k.id == "postea-android").unwrap(); + assert_eq!((k.kind, k.role, k.auto_approve), (KeyKind::Android, Role::Release, false)); + assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&[REPO]))); + assert_eq!((k.issuer.clone(), k.key_id.clone(), k.minisign_public.clone()), (None, None, None)); + let cert = v.signing_export_cert("postea-android").unwrap(); + assert_eq!(k.cert.as_deref(), Some(cert.as_slice())); + let c = x509_cert::Certificate::from_der(&cert).unwrap(); + assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ"); + assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject); + let t = keys.iter().find(|k| k.id == "domi-test-android").unwrap(); + assert_eq!((t.kind, t.role, t.auto_approve), (KeyKind::Android, Role::Test, true)); + // Both serialise as the closed value `android`. + assert!(serde_json::to_string(k).unwrap().contains(r#""kind":"android""#)); +} + +#[test] +fn ids_and_names_are_checked_and_an_id_is_made_once() { + let mut v = vault(); + let again = v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW); + assert!(matches!(again, Err(Error::Signing(m)) if m.contains("already"))); + let taken = v.signing_create_android(&spec("domi-release", Role::Release, &["release"], &[REPO]), NOW); + assert!(matches!(taken, Err(Error::Signing(_))), "an id of another kind"); + for bad in ["", "Postea", "postea android", "postea/android", &"x".repeat(65)] { + let r = v.signing_create_android(&spec(bad, Role::Release, &["release"], &[REPO]), NOW); + assert!(matches!(r, Err(Error::Signing(_))), "{bad:?}"); + } + let mut odd = spec("odd-android", Role::Release, &["release"], &[REPO]); + odd.c = "Czechia".into(); + assert!(matches!(v.signing_create_android(&odd, NOW), Err(Error::Signing(m)) if m.contains("country"))); + assert_eq!(v.signing_keys().len(), 9, "nothing was added"); +} + +#[test] +fn an_apk_request_signs_every_digest_with_sha512_pkcs1_and_the_certificates_key() { + let mut v = vault(); + let req = apk_req("postea-android", 2, release()); + assert!(v.signing_check(&req).is_ok()); + let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap(); + assert_eq!(signed.bytes.len(), 2 * 512, "two RSA-4096 signatures"); + assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes)); + let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("postea-android").unwrap()).unwrap(); + let spki = cert.tbs_certificate.subject_public_key_info.to_der().unwrap(); + let key = VerifyingKey::::from_public_key_der(&spki).unwrap(); + for (d, sig) in req.digest.chunks(64).zip(signed.bytes.chunks(512)) { + key.verify_prehash(d, &Signature::try_from(sig).unwrap()).unwrap(); + } + // One request, one audit entry, whatever the number of digests. + let a = v.signing_audit().last().unwrap(); + assert_eq!((a.key.as_str(), a.kind, a.outcome), ("postea-android", SignKind::Apk, Outcome::Approved)); + assert_eq!((a.context.file.as_str(), a.run.as_deref()), ("Postea-1.0.0.apk", Some("r-7"))); +} + +#[test] +fn an_android_key_signs_only_apks_and_only_android_keys_sign_apks() { + let mut v = vault(); + let mut exe = apk_req("postea-android", 0, release()); + exe.kind = SignKind::Authenticode; + exe.digest = vec![9; 32]; + let mut minisign = exe.clone(); + minisign.kind = SignKind::Minisign; + minisign.digest = vec![9; 64]; + let leaf = Request { + key: "domi-code-signing".into(), + context: ctx("release", "Arca", "tag"), + ..apk_req("", 1, release()) + }; + let ed = + Request { key: "domi-release".into(), context: ctx("release", "Arca", "tag"), ..apk_req("", 1, release()) }; + let root = Request { key: "domi-root".into(), ..apk_req("", 1, release()) }; + let test_leaf = Request { key: "domi-test-code-signing".into(), ..apk_req("", 1, ctx("ci", REPO, "push")) }; + for r in [&exe, &minisign, &leaf, &ed, &root, &test_leaf] { + assert!(matches!(v.signing_check(r), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind); + assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind); + } + assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none())); +} + +#[test] +fn another_repo_or_pipeline_is_out_of_scope_even_when_approved() { + let mut v = vault(); + for c in [ctx("release", "mnovak/Arca", "tag"), ctx("release", "Postea", "tag"), ctx("nightly", REPO, "tag")] { + let r = apk_req("postea-android", 2, c); + assert!(matches!(v.signing_check(&r), Err(Refusal::OutOfScope(_)))); + assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_)))); + } + assert_eq!(v.signing_audit().iter().filter(|e| e.outcome == Outcome::OutOfScope).count(), 3); +} + +#[test] +fn the_release_key_always_needs_mark_and_the_test_twin_signs_alone_but_never_a_tag() { + let mut v = vault(); + let r = v.signing_sign(&apk_req("postea-android", 2, release()), Approval::Auto, NOW); + assert!(matches!(r, Err(Refusal::NeedsApproval(_)))); + assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused); + let t = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "manual")), Approval::Auto, NOW).unwrap(); + assert_eq!(t.bytes.len(), 1024); + assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Auto); + let tag = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "tag")), Approval::Auto, NOW); + assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag"))); +} + +#[test] +fn malformed_apk_requests_are_refused() { + let mut v = vault(); + let mut cases = Vec::new(); + for n in [0usize, 1, 32, 63, 65, 64 * 5] { + let mut r = apk_req("postea-android", 0, release()); + r.digest = vec![1; n]; + if n != 1 { + cases.push(r); + } + } + let mut no_file = apk_req("postea-android", 2, release()); + no_file.context.file = String::new(); + let mut path = apk_req("postea-android", 2, release()); + path.context.file = "out\\Postea.apk".into(); + let mut stray = apk_req("postea-android", 2, release()); + stray.approval = Some("{}".into()); + let mut bad_run = apk_req("postea-android", 2, release()); + bad_run.run = Some("r 7".into()); + cases.extend([no_file, path, stray, bad_run]); + for r in &cases { + assert!( + matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), + "{} bytes {:?}", + r.digest.len(), + r.context.file + ); + } + assert_eq!(v.signing_audit().len(), cases.len()); + assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none())); +} + +#[test] +fn refused_and_expired_apk_requests_are_recorded_and_everything_survives_a_reopen() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("v.custos"); + let mut v = vault(); + let req = apk_req("postea-android", 2, release()); + v.signing_refuse(&req, Outcome::Refused, Some("Mark refused this signature".into()), NOW); + v.signing_refuse(&req, Outcome::Expired, None, NOW + 1); + let signed = v.signing_sign(&req, Approval::Mark, NOW + 2).unwrap(); + v.save(&path).unwrap(); + + let mut back = Vault::open_file(&path, &SecretString::from("pw")).unwrap(); + assert_eq!(back.signing_audit(), v.signing_audit()); + let outcomes: Vec = back.signing_audit().iter().map(|e| e.outcome).collect(); + assert_eq!(outcomes, [Outcome::Refused, Outcome::Expired, Outcome::Approved]); + assert_eq!(back.signing_audit()[2].signature.as_deref(), Some(signed.sha256.as_str())); + assert_eq!(back.signing_keys(), v.signing_keys()); + // The same key: a reopened vault makes the same (deterministic PKCS#1 v1.5) signatures. + assert_eq!(back.signing_sign(&req, Approval::Mark, NOW + 3).unwrap().bytes, signed.bytes); +} + +#[test] +fn apk_requests_are_never_signed_unattended_even_on_the_hands_off_vault() { + // `unattended_sign` is a closed list of kinds: `apk` is not on it, so an APK always shows the card. + for level in [Level::Setup, Level::Standard] { + assert!(!security::unattended_sign(level, &BTreeSet::new(), true, "apk", true)); + assert!(security::unattended_sign(level, &BTreeSet::new(), true, "authenticode", true)); + } +} diff --git a/docs/FORMAT.md b/docs/FORMAT.md index f8feb51..c47baec 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -140,7 +140,9 @@ UTF-8 JSON, held in zeroizing buffers while being encrypted or parsed: **Values older cores refuse.** A reader refuses a file whose closed lists hold a value it does not know (see each member), so these values, new in core 0.12.0, make a vault unreadable for a core before 0.12.0 once they are written: a `signing` audit entry of kind `approval` (docs/SIGNING.md), a `provision` entry with store `display` or -outcome `confirmed`. A vault without them still opens in core 0.11.0. +outcome `confirmed`. A vault without them still opens in core 0.11.0. Core 0.14.0 adds two more: a `signing` key +of kind `android` and an audit entry of kind `apk` (docs/SIGNING.md); a vault that holds either does not open in a +core before 0.14.0. ### The provision audit (core 0.11.0) @@ -226,7 +228,7 @@ the first change after it, not by reading. existing item: an `ask --generate` or an `offer` into `arca/`, `custos/`, `fabrica/`, `aula/`, `gitea/`, an offer into the Claude Code store, a TOTP offer unless `totp-on-phone`; never `display`) and `unattended_sign` (a machine-key vault, a request with a run, not Hardened, `card-signing` not ticked, the kinds `minisign`, - `manifest`, `authenticode`, `approval`). The app enforces them; the server never decides. + `manifest`, `authenticode`, `approval`; never `apk`, core 0.14.0). The app enforces them; the server never decides. - Readers ignore members they do not know. A file whose `security` has an item, action or auth this core does not know, a window whose `until` is not after `started`, `finished` without `setup`, or a kept scope that breaks the rules above does not open (`Corrupted`). diff --git a/docs/SIGNING.md b/docs/SIGNING.md index 71981f8..c0ba71a 100644 --- a/docs/SIGNING.md +++ b/docs/SIGNING.md @@ -1,4 +1,4 @@ -# Signing keys (core 0.9.0; deploy approvals 0.12.0) +# Signing keys (core 0.9.0; deploy approvals 0.12.0; Android APKs 0.14.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 @@ -46,6 +46,7 @@ vault must be 0.9.0 or later. There is no mnemonic for these keys: back the vaul | `ed25519` | Ed25519; `secret` is the 32-byte seed, `public` the 32-byte key, `keyId` minisign's 8-byte key id | `minisign`, `manifest`; `domi-approve` only `approval` | 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 | +| `android` (core 0.14.0) | RSA-4096; `secret` PKCS#8 DER; `cert` a self-signed X.509 v3 certificate, valid 100 years, no EKU, under no root | only `apk` | random | `role` is `release` or `test`. *Create release keys* makes `domi-release`, `domi-root`, `domi-code-signing` and (since core 0.12.0) `domi-approve` ("Domi deploy approval"), the Ed25519 key that signs deploy approvals, with the @@ -55,6 +56,15 @@ release keys' scope. A vault whose release keys were made by an older core gets `domi-test-root`: a test certificate never chains to the household root, so an automatically approved signature is never trusted by Mark's PCs. +*Create Android key* (`signing_create_android`, core 0.14.0) makes one Android app signing key at a time, with the +id, name, certificate subject (`CN`, `O`, a two-letter `C`), role and scope the app gives it; an id is used once. +The app makes `postea-android` (`CN=Postea, O=Marek Novak, C=CZ`, release, pipeline `release`, repo +`mnovak/Postea`) and its test twin `domi-test-android` (`CN=Domi Test Android, O=Domi, C=CZ`, test). An Android +key's certificate *is* the app's identity: Android accepts an update only when it is signed by the same certificate, +for the app's whole life. Its loss ends the app's updates for good, and there is no phrase to recover it from (the +vault has none), so **the vault must have two backups off the PC before the first real signature**. Its public +half is the certificate (`signing_export_cert`). + `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). @@ -66,6 +76,9 @@ Certificates: `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. +- android: subject and issuer `CN=, O=, C=` (encoded C, O, CN; `C` a PrintableString), validity 100 × 365 + days, `basicConstraints` not a CA, `keyUsage` digitalSignature + nonRepudiation, subject and authority key + identifiers (both of its own key), no `extKeyUsage`; sha256WithRSAEncryption by its own key. ## Signature kinds @@ -77,6 +90,7 @@ A request names a key, a kind and what to sign. Custos never receives the file. | `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` | | `approval` | `approval`: a deploy approval's canonical JSON (at most 8 KiB, see below), and `run` | a `.minisig` file over it | +| `apk` (core 0.14.0) | `digest`: 1 to 4 SHA-512 digests of APK Signature Scheme signed data, concatenated (64·n bytes) | the n RSA PKCS#1 v1.5 signatures (512 bytes each), concatenated in the same order | Any request may carry a `run` (`[A-Za-z0-9._-]{1,64}`, core 0.12.0): the build's run id, so the app can show every request of one run on one card. It is kept in the audit entry. A malformed `run` is `invalid`; `approval` text on a @@ -158,6 +172,28 @@ Checked on 2026-11-04 with signtool 10.0.26100 and a throwaway RSA-3072 key: the 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. +### apk (core 0.14.0) + +An APK is signed by Google's apksig (`apksigner.jar` from the Android SDK build-tools) on the build's side; Custos +signs only what apksig's signer would sign. APK Signature Scheme v2 and v3 each sign one *signed data* block (the +APK's content digests, the certificate, attributes; v3 adds the SDK range), so a v2+v3 APK needs two signatures. +apksig picks `RSA_PKCS1_V1_5_WITH_SHA512` (`SHA512withRSA`) for every RSA key over 3072 bits and has no way to +choose otherwise, so the kind takes **SHA-512** digests and signs each with the SHA-512 DigestInfo: + +- `digest` is 64·n bytes, n from 1 to 4: the SHA-512 of each signed data block, in the order the build wants the + signatures back. Anything else is `invalid`. The context's `file` (the APK's name) is required, as for minisign. +- The answer is the n signatures concatenated, 512 bytes each for RSA-4096. One request, one card line, one audit + entry (its `signature` is the SHA-256 of all of them), so a release run raises **one** card for its APK. +- `apk` is signed only by an `android` key, and an `android` key signs nothing else: an Authenticode key cannot sign + an APK and an Android key cannot sign an exe (`invalid`). +- `apk` is not one of the kinds the hands-off vault may sign without a card (FORMAT.md, `unattended_sign`): an + Android key cannot be revoked or replaced, so its signatures always ask. + +The client (`custos-sign apk`, in the app's repository) runs apksig twice: once with a stand-in signer that records +the digests and answers with placeholder signatures (the signed data does not depend on the signatures), then, with +Custos's answer, again with a signer that hands each recorded digest its signature, and refuses any digest it did +not record. It verifies the result with apksig's verifier before it writes the APK. + ## 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 @@ -177,7 +213,11 @@ one entry, whatever happened: (core 0.12.0) is the context's version, absent when empty. The entry is part of the vault, so it survives a reopen and travels with it. -**Compatibility.** Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind +**Compatibility.** A key of kind `android` and an audit entry of kind `apk` (core 0.14.0) are values a core +before 0.14.0 does not know: once the vault holds an Android key, every Custos that opens it must be on core 0.14.0 +or later (an older one refuses the vault as `Corrupted`; the web vault, which never reads `signing`, is unaffected). + +Older cores ignore `run`, `version` and the `domi-approve` key. An audit entry of kind `approval` is a value they do not know, so a core before 0.12.0 refuses a vault that holds one (`Corrupted`): once a vault has recorded an approval request, every Custos that opens it must be on core 0.12.0 or later. @@ -186,6 +226,7 @@ vault has recorded an approval request, every Custos that opens it must be on co ``` Vault::signing_create(role, pipelines, repos, now) -> ids // release (with domi-approve) or test set Vault::signing_add_approve(now) -> "domi-approve" // for release keys made before 0.12.0 +Vault::signing_create_android(&AndroidKey, now) -> id // one Android key (core 0.14.0) 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 diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index b8b7e45..3ea5253 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -69,6 +69,10 @@ just as plainly, what it does not. password, the TOTP code or a PC. - **An approval is only as careful as the person approving.** Compare the six-digit match code on both screens; a request you did not start is someone else's. +- **Losing the vault loses its signing keys.** They never leave it, so no backup holds them but a backup of the + vault itself, and there is no phrase to rebuild them from. Most can be replaced with new keys; an Android app's + key (docs/SIGNING.md, `android`) cannot: Android accepts updates only from the same certificate, so its loss ends + that app's updates for good. Keep two copies of the vault off the PC before the first real signature. ## Design rules that follow from this