331 lines
12 KiB
Rust
331 lines
12 KiB
Rust
//! 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<Vec<u8>>);
|
|
|
|
impl RsaSecret {
|
|
pub fn from_pkcs8_der(der: Vec<u8>) -> Result<Self, Error> {
|
|
let der = Zeroizing::new(der);
|
|
RsaPrivateKey::from_pkcs8_der(&der).map_err(|_| Error::BadKey)?;
|
|
Ok(RsaSecret(der))
|
|
}
|
|
|
|
/// The PKCS#8 DER, for storing in the vault body. Only the vault calls this.
|
|
pub fn expose(&self) -> &[u8] {
|
|
&self.0
|
|
}
|
|
|
|
fn key(&self) -> Result<RsaPrivateKey, Error> {
|
|
RsaPrivateKey::from_pkcs8_der(&self.0).map_err(|_| Error::BadKey)
|
|
}
|
|
}
|
|
|
|
impl fmt::Debug for RsaSecret {
|
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str("[redacted]")
|
|
}
|
|
}
|
|
|
|
// ---- 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:<unix seconds>\tfile:<file>\thashed`, as minisign writes it.
|
|
pub fn minisign(
|
|
secret: &Ed25519Secret,
|
|
key_id: &[u8; 8],
|
|
digest: &[u8],
|
|
file: &str,
|
|
timestamp: u64,
|
|
) -> Result<String, Error> {
|
|
let digest: &[u8; 64] = digest.try_into().map_err(|_| Error::DigestLength(64))?;
|
|
check_file_name(file)?;
|
|
let key = SigningKey::from_bytes(&secret.0);
|
|
let signature = key.sign(digest).to_bytes();
|
|
let trusted = format!("timestamp:{timestamp}\tfile:{file}\thashed");
|
|
let mut global_msg = Vec::with_capacity(64 + trusted.len());
|
|
global_msg.extend_from_slice(&signature);
|
|
global_msg.extend_from_slice(trusted.as_bytes());
|
|
let global = key.sign(&global_msg).to_bytes();
|
|
let mut line = Vec::with_capacity(74);
|
|
line.extend_from_slice(b"ED");
|
|
line.extend_from_slice(key_id);
|
|
line.extend_from_slice(&signature);
|
|
Ok(format!(
|
|
"untrusted comment: signature from Custos key {}\n{}\ntrusted comment: {trusted}\n{}\n",
|
|
key_id_hex(key_id),
|
|
BASE64.encode(&line),
|
|
BASE64.encode(&global)
|
|
))
|
|
}
|
|
|
|
fn check_file_name(file: &str) -> Result<(), Error> {
|
|
if file.is_empty() {
|
|
return Err(Error::FileName("empty"));
|
|
}
|
|
if file.len() > 255 {
|
|
return Err(Error::FileName("longer than 255 bytes"));
|
|
}
|
|
if file.chars().any(char::is_control) {
|
|
return Err(Error::FileName("control characters"));
|
|
}
|
|
if file.contains(['/', '\\']) {
|
|
return Err(Error::FileName("a path, not a file name"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
// ---- the SHA256SUMS manifest ----
|
|
|
|
/// Checks that `text` is a canonical `SHA256SUMS` (docs/SIGNING.md): `<64 lower hex> <name>\n` lines, names
|
|
/// without `/`, `\`, control characters or a leading `-`, unique, sorted by bytes, at least one line.
|
|
pub fn manifest_check(text: &str) -> Result<(), Error> {
|
|
let err = |line: usize, why: &'static str| Err(Error::Manifest { line, why });
|
|
if text.len() > MAX_MANIFEST {
|
|
return err(0, "larger than 32 KiB");
|
|
}
|
|
if text.is_empty() {
|
|
return err(0, "empty");
|
|
}
|
|
if !text.ends_with('\n') {
|
|
return err(text.lines().count(), "the last line has no newline");
|
|
}
|
|
let mut prev: Option<&str> = None;
|
|
for (i, line) in text.split_terminator('\n').enumerate() {
|
|
let n = i + 1;
|
|
if line.ends_with('\r') {
|
|
return err(n, "CRLF line ending");
|
|
}
|
|
let Some((hash, name)) = line.split_once(" ") else {
|
|
return err(n, "not `<sha256> <name>`");
|
|
};
|
|
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) {
|
|
return err(n, "the hash is not 64 lower-case hex digits");
|
|
}
|
|
if name.is_empty()
|
|
|| name.starts_with(['-', ' ', '*'])
|
|
|| name.contains(['/', '\\'])
|
|
|| name.chars().any(char::is_control)
|
|
{
|
|
return err(n, "not a plain file name");
|
|
}
|
|
if prev.is_some_and(|p| p.as_bytes() >= name.as_bytes()) {
|
|
return err(n, "names are not sorted and unique");
|
|
}
|
|
prev = Some(name);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Signs a canonical manifest as minisign (file name `SHA256SUMS`).
|
|
pub fn manifest(secret: &Ed25519Secret, key_id: &[u8; 8], text: &str, timestamp: u64) -> Result<String, Error> {
|
|
manifest_check(text)?;
|
|
minisign(secret, key_id, &blake2b512(text.as_bytes()), "SHA256SUMS", timestamp)
|
|
}
|
|
|
|
// ---- Authenticode ----
|
|
|
|
/// RSA PKCS#1 v1.5 with the SHA-256 DigestInfo over the 32 bytes of signtool's `.dig` (384 bytes for RSA-3072):
|
|
/// what goes, base64-encoded, into `.dig.signed`.
|
|
pub fn authenticode(secret: &RsaSecret, digest: &[u8]) -> Result<Vec<u8>, Error> {
|
|
if digest.len() != 32 {
|
|
return Err(Error::DigestLength(32));
|
|
}
|
|
let key = pkcs1v15::SigningKey::<Sha256>::new(secret.key()?);
|
|
let sig: pkcs1v15::Signature = key.sign_prehash(digest).map_err(|_| Error::BadKey)?;
|
|
Ok(Box::<[u8]>::from(sig).into_vec())
|
|
}
|
|
|
|
// ---- the household CA ----
|
|
|
|
/// A new RSA-3072 key and its certificate.
|
|
pub struct NewCert {
|
|
pub secret: RsaSecret,
|
|
pub cert_der: Vec<u8>,
|
|
}
|
|
|
|
fn new_rsa() -> Result<(RsaPrivateKey, RsaSecret), Error> {
|
|
let key = RsaPrivateKey::new(&mut 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<SerialNumber, Error> {
|
|
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<Name, Error> {
|
|
if cn.is_empty() || cn.len() > 64 || cn.contains([',', '+', '=', '"', '\\', '<', '>', ';', '#']) {
|
|
return Err(Error::Certificate);
|
|
}
|
|
Name::from_str(&format!("CN={cn},O=Domi")).map_err(|_| Error::Certificate)
|
|
}
|
|
|
|
fn spki(key: &RsaPrivateKey) -> Result<SubjectPublicKeyInfoOwned, Error> {
|
|
let der = key.to_public_key().to_public_key_der().map_err(|_| Error::Certificate)?;
|
|
SubjectPublicKeyInfoOwned::from_der(der.as_bytes()).map_err(|_| Error::Certificate)
|
|
}
|
|
|
|
/// A self-signed root CA, valid for `years` years from now.
|
|
pub fn new_root(cn: &str, years: u64) -> Result<NewCert, Error> {
|
|
let (key, secret) = new_rsa()?;
|
|
let spki = spki(&key)?;
|
|
let signer = pkcs1v15::SigningKey::<Sha256>::new(key);
|
|
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
|
|
let builder = CertificateBuilder::new(Profile::Root, serial()?, validity, name(cn)?, spki, &signer)
|
|
.map_err(|_| Error::Certificate)?;
|
|
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
|
|
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
|
|
}
|
|
|
|
/// A code-signing leaf issued by `issuer`, valid for `years` years from now.
|
|
pub fn new_code_signing(cn: &str, years: u64, issuer: &RsaSecret, issuer_cert: &[u8]) -> Result<NewCert, Error> {
|
|
let issuer_cert = Certificate::from_der(issuer_cert).map_err(|_| Error::Certificate)?;
|
|
let (key, secret) = new_rsa()?;
|
|
let signer = pkcs1v15::SigningKey::<Sha256>::new(issuer.key()?);
|
|
let validity = Validity::from_now(Duration::from_secs(years * 365 * DAY)).map_err(|_| Error::Certificate)?;
|
|
let profile = Profile::Leaf {
|
|
issuer: issuer_cert.tbs_certificate.subject.clone(),
|
|
enable_key_agreement: false,
|
|
enable_key_encipherment: false,
|
|
};
|
|
let mut builder = CertificateBuilder::new(profile, serial()?, validity, name(cn)?, spki(&key)?, &signer)
|
|
.map_err(|_| Error::Certificate)?;
|
|
builder.add_extension(&ExtendedKeyUsage(vec![CODE_SIGNING])).map_err(|_| Error::Certificate)?;
|
|
let cert = builder.build::<pkcs1v15::Signature>().map_err(|_| Error::Certificate)?;
|
|
Ok(NewCert { secret, cert_der: cert.to_der().map_err(|_| Error::Certificate)? })
|
|
}
|
|
|
|
/// A certificate as PEM, for tools that want text.
|
|
pub fn cert_pem(der: &[u8]) -> String {
|
|
let b64 = BASE64.encode(der);
|
|
let mut out = String::from("-----BEGIN CERTIFICATE-----\n");
|
|
for chunk in b64.as_bytes().chunks(64) {
|
|
out.push_str(std::str::from_utf8(chunk).expect("base64 is ASCII"));
|
|
out.push('\n');
|
|
}
|
|
out.push_str("-----END CERTIFICATE-----\n");
|
|
out
|
|
}
|
|
|
|
/// The SHA-256 (hex) of `bytes`, for the audit log.
|
|
pub fn sha256_hex(bytes: &[u8]) -> String {
|
|
Sha256::digest(bytes).iter().map(|b| format!("{b:02x}")).collect()
|
|
}
|