[vault] Signing: mandatory tests for scope, refusals and the audit log through a reopen
This commit is contained in:
@@ -20,6 +20,12 @@ data-encoding.workspace = true
|
||||
# The Domi identity (docs/IDENTITY.md): the mnemonic and the root key.
|
||||
bip39 = { version = "2", default-features = false, features = ["std", "zeroize"] }
|
||||
ed25519-dalek = { version = "2", default-features = false, features = ["std", "zeroize"] }
|
||||
# Signing keys for releases (docs/SIGNING.md).
|
||||
custos-sign = { path = "../custos-sign" }
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
minisign-verify = "0.3"
|
||||
rsa = { version = "0.9", features = ["sha2"] }
|
||||
sha2-010 = { package = "sha2", version = "0.10", features = ["oid"] }
|
||||
x509-cert = "0.2.5"
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
//! Signing keys for releases and the audit log of every request (docs/SIGNING.md): the vault body member
|
||||
//! `signing`. A key's secret is used inside this module and never handed out: the public API returns
|
||||
//! public keys, certificates, signatures and audit entries only.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use custos_sign::{Ed25519Secret, RsaSecret};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{Error, SecretBytes, Vault};
|
||||
|
||||
/// What a request may be refused with. Every refusal names why, and none carries key material.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Refusal {
|
||||
#[error("there is no signing key `{0}`")]
|
||||
NoKey(String),
|
||||
#[error("{0}")]
|
||||
OutOfScope(String),
|
||||
#[error("{0}")]
|
||||
Invalid(String),
|
||||
#[error("`{0}` is a release key: it signs only after Mark approves")]
|
||||
NeedsApproval(String),
|
||||
}
|
||||
|
||||
impl Refusal {
|
||||
/// The audit outcome this refusal is recorded as.
|
||||
pub fn outcome(&self) -> Outcome {
|
||||
match self {
|
||||
Refusal::OutOfScope(_) => Outcome::OutOfScope,
|
||||
Refusal::NeedsApproval(_) => Outcome::Refused,
|
||||
Refusal::NoKey(_) | Refusal::Invalid(_) => Outcome::Invalid,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Role {
|
||||
Release,
|
||||
Test,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum KeyKind {
|
||||
Ed25519,
|
||||
RootCa,
|
||||
CodeSigning,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum SignKind {
|
||||
Minisign,
|
||||
Manifest,
|
||||
Authenticode,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum Via {
|
||||
Local,
|
||||
Remote,
|
||||
}
|
||||
|
||||
/// What the build says it is signing. Shown on the card and kept in the audit log; Custos cannot check it
|
||||
/// against the file (docs/SIGNING.md, the wrong-file risk).
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Context {
|
||||
pub repo: String,
|
||||
pub commit: String,
|
||||
pub pipeline: String,
|
||||
pub step: String,
|
||||
/// `manual`, `push` or `tag`. A test key never signs for `tag`.
|
||||
pub trigger: String,
|
||||
pub file: String,
|
||||
pub size: u64,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
/// A signing request, from the Domi pipe or the factor service's mailbox.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Request {
|
||||
pub key: String,
|
||||
pub kind: SignKind,
|
||||
/// BLAKE2b-512 of the file (minisign) or signtool's 32-byte digest (authenticode). Empty for a manifest.
|
||||
pub digest: Vec<u8>,
|
||||
/// The `SHA256SUMS` text, for a manifest.
|
||||
pub manifest: Option<String>,
|
||||
pub context: Context,
|
||||
pub via: Via,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Approval {
|
||||
/// Mark approved this request on the card.
|
||||
Mark,
|
||||
/// Nobody was asked: allowed for test keys only.
|
||||
Auto,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Outcome {
|
||||
Approved,
|
||||
Auto,
|
||||
Refused,
|
||||
Expired,
|
||||
OutOfScope,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
/// One audit entry. Append-only: nothing edits or removes one.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AuditEntry {
|
||||
pub at: i64,
|
||||
pub key: String,
|
||||
pub kind: SignKind,
|
||||
pub outcome: Outcome,
|
||||
pub via: Via,
|
||||
#[serde(flatten)]
|
||||
pub context: Context,
|
||||
/// SHA-256 (hex) of what was returned, for signed outcomes.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub signature: Option<String>,
|
||||
/// Why, for refusals the vault decided.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
/// A signature handed back to the build.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Signed {
|
||||
/// The `.minisig` text (minisign, manifest) or the raw RSA signature (authenticode).
|
||||
pub bytes: Vec<u8>,
|
||||
pub sha256: String,
|
||||
}
|
||||
|
||||
/// A key as the app may see it: public parts only.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct KeyView {
|
||||
pub id: String,
|
||||
pub kind: KeyKind,
|
||||
pub role: Role,
|
||||
pub name: String,
|
||||
pub created: i64,
|
||||
pub pipelines: Vec<String>,
|
||||
pub repos: Vec<String>,
|
||||
/// Test keys are approved automatically (within scope, never for a `tag` trigger).
|
||||
pub auto_approve: bool,
|
||||
/// minisign's key id (hex, as minisign prints it), for Ed25519 keys.
|
||||
pub key_id: Option<String>,
|
||||
/// The `minisign.pub` text, for Ed25519 keys.
|
||||
pub minisign_public: Option<String>,
|
||||
/// The certificate (DER), for root and code-signing keys.
|
||||
pub cert: Option<Vec<u8>>,
|
||||
pub issuer: Option<String>,
|
||||
}
|
||||
|
||||
enum Secret {
|
||||
Ed25519(Ed25519Secret),
|
||||
Rsa(RsaSecret),
|
||||
}
|
||||
|
||||
struct Key {
|
||||
id: String,
|
||||
kind: KeyKind,
|
||||
role: Role,
|
||||
name: String,
|
||||
secret: Secret,
|
||||
public: Option<[u8; 32]>,
|
||||
key_id: Option<[u8; 8]>,
|
||||
cert: Option<Vec<u8>>,
|
||||
issuer: Option<String>,
|
||||
created: i64,
|
||||
pipelines: Vec<String>,
|
||||
repos: Vec<String>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for Key {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Key").field("id", &self.id).field("kind", &self.kind).field("secret", &"[redacted]").finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The keys and the log, in the vault.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Store {
|
||||
keys: Vec<Key>,
|
||||
audit: Vec<AuditEntry>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct KeyJson {
|
||||
id: String,
|
||||
kind: KeyKind,
|
||||
role: Role,
|
||||
name: String,
|
||||
secret: SecretBytes,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
public: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
key_id: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cert: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
issuer: Option<String>,
|
||||
created: i64,
|
||||
#[serde(default)]
|
||||
pipelines: Vec<String>,
|
||||
#[serde(default)]
|
||||
repos: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(crate) struct StoreJson {
|
||||
#[serde(default)]
|
||||
keys: Vec<KeyJson>,
|
||||
#[serde(default)]
|
||||
audit: Vec<AuditEntry>,
|
||||
}
|
||||
|
||||
fn b64(bytes: &[u8]) -> String {
|
||||
data_encoding::BASE64.encode(bytes)
|
||||
}
|
||||
|
||||
fn unb64(s: &str) -> Option<Vec<u8>> {
|
||||
data_encoding::BASE64.decode(s.as_bytes()).ok()
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
bytes.iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn unhex8(s: &str) -> Option<[u8; 8]> {
|
||||
if s.len() != 16 {
|
||||
return None;
|
||||
}
|
||||
let mut out = [0u8; 8];
|
||||
for (i, o) in out.iter_mut().enumerate() {
|
||||
*o = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?;
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
impl Store {
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.keys.is_empty() && self.audit.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
|
||||
let mut keys = Vec::new();
|
||||
for k in j.keys {
|
||||
let secret = match k.kind {
|
||||
KeyKind::Ed25519 => {
|
||||
let seed: [u8; 32] = k.secret.expose().try_into().ok()?;
|
||||
Secret::Ed25519(Ed25519Secret::from_bytes(seed))
|
||||
}
|
||||
KeyKind::RootCa | KeyKind::CodeSigning => {
|
||||
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
|
||||
}
|
||||
};
|
||||
let public = match &k.public {
|
||||
Some(p) => Some(unb64(p)?.try_into().ok()?),
|
||||
None => None,
|
||||
};
|
||||
// The stored public key must be the secret's, as for the identity root.
|
||||
if let (Secret::Ed25519(s), Some(p)) = (&secret, public) {
|
||||
if s.public() != p {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let key_id = match &k.key_id {
|
||||
Some(h) => Some(unhex8(h)?),
|
||||
None => None,
|
||||
};
|
||||
let cert = match &k.cert {
|
||||
Some(c) => Some(unb64(c)?),
|
||||
None => None,
|
||||
};
|
||||
keys.push(Key {
|
||||
id: k.id,
|
||||
kind: k.kind,
|
||||
role: k.role,
|
||||
name: k.name,
|
||||
secret,
|
||||
public,
|
||||
key_id,
|
||||
cert,
|
||||
issuer: k.issuer,
|
||||
created: k.created,
|
||||
pipelines: k.pipelines,
|
||||
repos: k.repos,
|
||||
});
|
||||
}
|
||||
Some(Store { keys, audit: j.audit })
|
||||
}
|
||||
|
||||
pub(crate) fn json(&self) -> Option<StoreJson> {
|
||||
if self.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let keys = self
|
||||
.keys
|
||||
.iter()
|
||||
.map(|k| KeyJson {
|
||||
id: k.id.clone(),
|
||||
kind: k.kind,
|
||||
role: k.role,
|
||||
name: k.name.clone(),
|
||||
secret: SecretBytes::new(match &k.secret {
|
||||
Secret::Ed25519(s) => s.expose().to_vec(),
|
||||
Secret::Rsa(s) => s.expose().to_vec(),
|
||||
}),
|
||||
public: k.public.map(|p| b64(&p)),
|
||||
key_id: k.key_id.map(|i| hex(&i)),
|
||||
cert: k.cert.as_ref().map(|c| b64(c)),
|
||||
issuer: k.issuer.clone(),
|
||||
created: k.created,
|
||||
pipelines: k.pipelines.clone(),
|
||||
repos: k.repos.clone(),
|
||||
})
|
||||
.collect();
|
||||
Some(StoreJson { keys, audit: self.audit.clone() })
|
||||
}
|
||||
|
||||
fn get(&self, id: &str) -> Option<&Key> {
|
||||
self.keys.iter().find(|k| k.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
fn in_scope(list: &[String], what: &str) -> bool {
|
||||
list.iter().any(|x| x == "*" || x == what)
|
||||
}
|
||||
|
||||
fn clean_list(list: &[String]) -> Result<Vec<String>, Error> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for x in list.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) {
|
||||
if x.len() > 100 || x.chars().any(char::is_control) {
|
||||
return Err(Error::Signing("a pipeline or repo name is not usable".into()));
|
||||
}
|
||||
if !out.iter().any(|o| o == x) {
|
||||
out.push(x.to_string());
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
/// Creates the release set (`domi-release`, `domi-root`, `domi-code-signing`) or the test set (`domi-test`,
|
||||
/// `domi-test-root`, `domi-test-code-signing`). The caller saves. Slow: two RSA-3072 keys.
|
||||
pub fn signing_create(&mut self, role: Role, pipelines: &[String], repos: &[String], now: i64) -> Result<Vec<String>, Error> {
|
||||
if self.signing.keys.iter().any(|k| k.role == role) {
|
||||
return Err(Error::SigningExists(match role {
|
||||
Role::Release => "release",
|
||||
Role::Test => "test",
|
||||
}));
|
||||
}
|
||||
let pipelines = clean_list(pipelines)?;
|
||||
let repos = clean_list(repos)?;
|
||||
let (ed_id, root_id, leaf_id, ed_name, root_name, leaf_name) = match role {
|
||||
Role::Release => ("domi-release", "domi-root", "domi-code-signing", "Domi release", "Domi Household Root CA", "Domi Code Signing"),
|
||||
Role::Test => ("domi-test", "domi-test-root", "domi-test-code-signing", "Domi test", "Domi Test Root (never trusted)", "Domi Test Code Signing"),
|
||||
};
|
||||
let ed = custos_sign::new_ed25519();
|
||||
let root = custos_sign::new_root(root_name, 10).map_err(|e| Error::Signing(e.to_string()))?;
|
||||
let leaf = custos_sign::new_code_signing(leaf_name, 2, &root.secret, &root.cert_der)
|
||||
.map_err(|e| Error::Signing(e.to_string()))?;
|
||||
let key = |id: &str, kind, name: &str, secret, cert, issuer: Option<&str>, scoped: bool| Key {
|
||||
id: id.into(),
|
||||
kind,
|
||||
role,
|
||||
name: name.into(),
|
||||
secret,
|
||||
public: None,
|
||||
key_id: None,
|
||||
cert,
|
||||
issuer: issuer.map(String::from),
|
||||
created: now,
|
||||
pipelines: if scoped { pipelines.clone() } else { Vec::new() },
|
||||
repos: if scoped { repos.clone() } else { Vec::new() },
|
||||
};
|
||||
let mut ed_key = key(ed_id, KeyKind::Ed25519, ed_name, Secret::Ed25519(ed.secret), None, None, true);
|
||||
ed_key.public = Some(ed.public);
|
||||
ed_key.key_id = Some(ed.key_id);
|
||||
let root_key = key(root_id, KeyKind::RootCa, root_name, Secret::Rsa(root.secret), Some(root.cert_der), None, false);
|
||||
let leaf_key = key(leaf_id, KeyKind::CodeSigning, leaf_name, Secret::Rsa(leaf.secret), Some(leaf.cert_der), Some(root_id), true);
|
||||
self.signing.keys.extend([ed_key, root_key, leaf_key]);
|
||||
Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()])
|
||||
}
|
||||
|
||||
/// Every signing key, public parts only.
|
||||
pub fn signing_keys(&self) -> Vec<KeyView> {
|
||||
self.signing
|
||||
.keys
|
||||
.iter()
|
||||
.map(|k| KeyView {
|
||||
id: k.id.clone(),
|
||||
kind: k.kind,
|
||||
role: k.role,
|
||||
name: k.name.clone(),
|
||||
created: k.created,
|
||||
pipelines: k.pipelines.clone(),
|
||||
repos: k.repos.clone(),
|
||||
auto_approve: k.role == Role::Test && k.kind != KeyKind::RootCa,
|
||||
key_id: k.key_id.map(|i| custos_sign::key_id_hex(&i)),
|
||||
minisign_public: match (k.public, k.key_id) {
|
||||
(Some(p), Some(i)) => Some(custos_sign::minisign_public(&p, &i)),
|
||||
_ => None,
|
||||
},
|
||||
cert: k.cert.clone(),
|
||||
issuer: k.issuer.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Changes who may ask for a key. The caller saves.
|
||||
pub fn signing_set_scope(&mut self, id: &str, pipelines: &[String], repos: &[String]) -> Result<(), Error> {
|
||||
let (pipelines, repos) = (clean_list(pipelines)?, clean_list(repos)?);
|
||||
let k = self.signing.keys.iter_mut().find(|k| k.id == id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
|
||||
if k.kind == KeyKind::RootCa {
|
||||
return Err(Error::Signing("a root CA signs no requests, so it has no scope".into()));
|
||||
}
|
||||
k.pipelines = pipelines;
|
||||
k.repos = repos;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A key's certificate (DER): public, for installing the root or giving signtool the leaf.
|
||||
pub fn signing_export_cert(&self, id: &str) -> Result<Vec<u8>, Error> {
|
||||
let k = self.signing.get(id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
|
||||
k.cert.clone().ok_or_else(|| Error::Signing(format!("`{id}` has no certificate")))
|
||||
}
|
||||
|
||||
/// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline
|
||||
/// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card.
|
||||
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
|
||||
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
|
||||
let fits = matches!(
|
||||
(k.kind, req.kind),
|
||||
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) | (KeyKind::CodeSigning, SignKind::Authenticode)
|
||||
);
|
||||
if k.kind == KeyKind::RootCa {
|
||||
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
|
||||
}
|
||||
if !fits {
|
||||
return Err(Refusal::Invalid(format!("`{}` cannot make {:?} signatures", k.id, req.kind)));
|
||||
}
|
||||
match req.kind {
|
||||
SignKind::Minisign if req.digest.len() != 64 => {
|
||||
return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into()));
|
||||
}
|
||||
SignKind::Authenticode if req.digest.len() != 32 => {
|
||||
return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into()));
|
||||
}
|
||||
SignKind::Manifest => {
|
||||
let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?;
|
||||
custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let file = &req.context.file;
|
||||
if req.kind != SignKind::Manifest
|
||||
&& (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control))
|
||||
{
|
||||
return Err(Refusal::Invalid("the file name is missing or not a plain name".into()));
|
||||
}
|
||||
if !in_scope(&k.pipelines, &req.context.pipeline) {
|
||||
return Err(Refusal::OutOfScope(format!("pipeline `{}` may not use `{}`", req.context.pipeline, k.id)));
|
||||
}
|
||||
if !in_scope(&k.repos, &req.context.repo) {
|
||||
return Err(Refusal::OutOfScope(format!("repo `{}` may not use `{}`", req.context.repo, k.id)));
|
||||
}
|
||||
if k.role == Role::Test && req.context.trigger == "tag" {
|
||||
return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id)));
|
||||
}
|
||||
Ok(self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists"))
|
||||
}
|
||||
|
||||
/// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only.
|
||||
/// A refusal is recorded too. The caller saves.
|
||||
pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result<Signed, Refusal> {
|
||||
let view = match self.signing_check(req) {
|
||||
Ok(v) => v,
|
||||
Err(r) => {
|
||||
self.signing_record(req, r.outcome(), Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
}
|
||||
};
|
||||
if approval == Approval::Auto && !view.auto_approve {
|
||||
let r = Refusal::NeedsApproval(req.key.clone());
|
||||
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
}
|
||||
let k = self.signing.get(&req.key).expect("checked");
|
||||
let seconds = (now.max(0) / 1000) as u64;
|
||||
let bytes = match (&k.secret, req.kind) {
|
||||
(Secret::Ed25519(s), SignKind::Minisign) => {
|
||||
custos_sign::minisign(s, &k.key_id.expect("ed25519 keys have an id"), &req.digest, &req.context.file, seconds)
|
||||
.map(String::into_bytes)
|
||||
}
|
||||
(Secret::Ed25519(s), SignKind::Manifest) => custos_sign::manifest(
|
||||
s,
|
||||
&k.key_id.expect("ed25519 keys have an id"),
|
||||
req.manifest.as_deref().unwrap_or_default(),
|
||||
seconds,
|
||||
)
|
||||
.map(String::into_bytes),
|
||||
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
|
||||
_ => unreachable!("signing_check matched the key to the kind"),
|
||||
};
|
||||
let bytes = match bytes {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
let r = Refusal::Invalid(e.to_string());
|
||||
self.signing_record(req, Outcome::Invalid, Some(r.to_string()), None, now);
|
||||
return Err(r);
|
||||
}
|
||||
};
|
||||
let sha256 = custos_sign::sha256_hex(&bytes);
|
||||
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
|
||||
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
|
||||
Ok(Signed { bytes, sha256 })
|
||||
}
|
||||
|
||||
/// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves.
|
||||
pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, now: i64) {
|
||||
let outcome = match outcome {
|
||||
Outcome::Approved | Outcome::Auto => Outcome::Refused,
|
||||
o => o,
|
||||
};
|
||||
self.signing_record(req, outcome, reason, None, now);
|
||||
}
|
||||
|
||||
fn signing_record(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, signature: Option<String>, now: i64) {
|
||||
let mut context = req.context.clone();
|
||||
if req.kind == SignKind::Manifest {
|
||||
context.file = "SHA256SUMS".into();
|
||||
}
|
||||
self.signing.audit.push(AuditEntry {
|
||||
at: now,
|
||||
key: req.key.clone(),
|
||||
kind: req.kind,
|
||||
outcome,
|
||||
via: req.via,
|
||||
context,
|
||||
signature,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
/// Every request any key was named in, oldest first.
|
||||
pub fn signing_audit(&self) -> &[AuditEntry] {
|
||||
&self.signing.audit
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! Mandatory tests for signing keys (docs/SIGNING.md): scope (4) and the audit log through a reopen (6). That no API
|
||||
//! path returns a private key (2) is a unit test in src/signing.rs, which can see the stored secrets; the app tests
|
||||
//! it again over its pipe ops and mailbox messages.
|
||||
|
||||
use custos_vault::signing::{Approval, AuditEntry, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
|
||||
use custos_vault::{Error, KdfParams, SecretString, Vault};
|
||||
|
||||
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
|
||||
const NOW: i64 = 1_793_750_000_000;
|
||||
|
||||
fn s(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
fn vault_with_keys() -> Vault {
|
||||
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
|
||||
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca", "Fabrica"]), NOW).unwrap();
|
||||
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
|
||||
v
|
||||
}
|
||||
|
||||
fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
|
||||
Context {
|
||||
repo: repo.into(),
|
||||
commit: "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1".into(),
|
||||
pipeline: pipeline.into(),
|
||||
step: "sign".into(),
|
||||
trigger: trigger.into(),
|
||||
file: "Arca_0.2.0_x64-setup.exe".into(),
|
||||
size: 25_145_977,
|
||||
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn minisign_req(key: &str, c: Context) -> Request {
|
||||
Request {
|
||||
key: key.into(),
|
||||
kind: SignKind::Minisign,
|
||||
digest: vec![7; 64],
|
||||
manifest: None,
|
||||
context: c,
|
||||
via: Via::Local,
|
||||
}
|
||||
}
|
||||
|
||||
fn authenticode_req(key: &str, c: Context) -> Request {
|
||||
Request {
|
||||
key: key.into(),
|
||||
kind: SignKind::Authenticode,
|
||||
digest: vec![9; 32],
|
||||
manifest: None,
|
||||
context: c,
|
||||
via: Via::Remote,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_release_and_test_sets_are_made_once_each() {
|
||||
let mut v = vault_with_keys();
|
||||
let keys = v.signing_keys();
|
||||
let ids: Vec<&str> = keys.iter().map(|k| k.id.as_str()).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
["domi-release", "domi-root", "domi-code-signing", "domi-test", "domi-test-root", "domi-test-code-signing"]
|
||||
);
|
||||
assert_eq!(keys[1].kind, KeyKind::RootCa);
|
||||
assert_eq!(keys[2].issuer.as_deref(), Some("domi-root"));
|
||||
assert_eq!(keys[5].issuer.as_deref(), Some("domi-test-root"));
|
||||
assert!(!keys[0].auto_approve && !keys[2].auto_approve);
|
||||
assert!(keys[3].auto_approve && keys[5].auto_approve && !keys[4].auto_approve);
|
||||
assert!(keys[0].minisign_public.as_deref().unwrap().starts_with("untrusted comment: minisign public key "));
|
||||
assert!(matches!(v.signing_create(Role::Release, &[], &[], NOW), Err(Error::SigningExists("release"))));
|
||||
// The root's certificate is exported; a key without one is not.
|
||||
assert_eq!(v.signing_export_cert("domi-root").unwrap(), keys[1].cert.clone().unwrap());
|
||||
assert!(v.signing_export_cert("domi-release").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_kind_signs_and_verifies() {
|
||||
use rsa::pkcs1v15::{Signature, VerifyingKey};
|
||||
use rsa::pkcs8::DecodePublicKey;
|
||||
use rsa::signature::hazmat::PrehashVerifier;
|
||||
use x509_cert::der::{Decode, Encode};
|
||||
|
||||
let mut v = vault_with_keys();
|
||||
let data = b"the installer";
|
||||
let mut req = minisign_req("domi-release", ctx("release", "Arca", "tag"));
|
||||
req.digest = custos_sign::blake2b512(data).to_vec();
|
||||
let sig = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
|
||||
let public = minisign_verify::PublicKey::decode(v.signing_keys()[0].minisign_public.as_deref().unwrap()).unwrap();
|
||||
let text = String::from_utf8(sig.bytes.clone()).unwrap();
|
||||
public.verify(data, &minisign_verify::Signature::decode(&text).unwrap(), false).unwrap();
|
||||
assert_eq!(sig.sha256, custos_sign::sha256_hex(&sig.bytes));
|
||||
|
||||
let sums = format!("{} Arca_0.2.0_x64-setup.exe\n", "c".repeat(64));
|
||||
let man = Request { kind: SignKind::Manifest, digest: vec![], manifest: Some(sums.clone()), ..req.clone() };
|
||||
let msig = v.signing_sign(&man, Approval::Mark, NOW).unwrap();
|
||||
public
|
||||
.verify(
|
||||
sums.as_bytes(),
|
||||
&minisign_verify::Signature::decode(std::str::from_utf8(&msig.bytes).unwrap()).unwrap(),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let auth = authenticode_req("domi-code-signing", ctx("release", "Arca", "tag"));
|
||||
let asig = v.signing_sign(&auth, Approval::Mark, NOW).unwrap();
|
||||
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("domi-code-signing").unwrap()).unwrap();
|
||||
let key = VerifyingKey::<sha2_010::Sha256>::from_public_key_der(
|
||||
&cert.tbs_certificate.subject_public_key_info.to_der().unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
key.verify_prehash(&auth.digest, &Signature::try_from(asig.bytes.as_slice()).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pipeline_or_repo_off_the_list_is_refused_even_when_approved() {
|
||||
let mut v = vault_with_keys();
|
||||
for c in [ctx("nightly", "Arca", "tag"), ctx("release", "Custos", "tag")] {
|
||||
let req = minisign_req("domi-release", c);
|
||||
assert!(matches!(v.signing_check(&req), Err(Refusal::OutOfScope(_))));
|
||||
assert!(matches!(v.signing_sign(&req, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
|
||||
}
|
||||
let leaf = authenticode_req("domi-code-signing", ctx("release", "Custos", "tag"));
|
||||
assert!(
|
||||
matches!(v.signing_sign(&leaf, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))),
|
||||
"the leaf has the same scope"
|
||||
);
|
||||
// Widening the scope takes an explicit change.
|
||||
v.signing_set_scope("domi-release", &s(&["release", "nightly"]), &s(&["Arca"])).unwrap();
|
||||
assert!(v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW).is_ok());
|
||||
assert!(v.signing_set_scope("domi-root", &s(&["*"]), &s(&["*"])).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn release_keys_never_sign_without_mark_and_test_keys_never_sign_a_tag() {
|
||||
let mut v = vault_with_keys();
|
||||
let r = v.signing_sign(&minisign_req("domi-release", ctx("release", "Arca", "tag")), Approval::Auto, NOW);
|
||||
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
|
||||
let t = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW);
|
||||
assert!(t.is_ok());
|
||||
let tag = v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "tag")), Approval::Auto, NOW);
|
||||
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
|
||||
let leaf =
|
||||
v.signing_sign(&authenticode_req("domi-test-code-signing", ctx("ci", "Arca", "push")), Approval::Auto, NOW);
|
||||
assert!(leaf.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_requests_and_the_root_are_refused() {
|
||||
let mut v = vault_with_keys();
|
||||
let mut short = minisign_req("domi-release", ctx("release", "Arca", "tag"));
|
||||
short.digest = vec![0; 32];
|
||||
let wrong_key = authenticode_req("domi-release", ctx("release", "Arca", "tag"));
|
||||
let root = authenticode_req("domi-root", ctx("release", "Arca", "tag"));
|
||||
let mut path = minisign_req("domi-release", ctx("release", "Arca", "tag"));
|
||||
path.context.file = "..\\evil.exe".into();
|
||||
let man =
|
||||
Request { kind: SignKind::Manifest, manifest: Some("not sums\n".into()), digest: vec![], ..short.clone() };
|
||||
let none = minisign_req("nope", ctx("release", "Arca", "tag"));
|
||||
for r in [&short, &wrong_key, &root, &path, &man] {
|
||||
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{r:?}");
|
||||
}
|
||||
assert!(matches!(v.signing_sign(&none, Approval::Mark, NOW), Err(Refusal::NoKey(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_audit_log_records_every_outcome_and_survives_a_reopen() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("v.custos");
|
||||
let mut v = vault_with_keys();
|
||||
let rel = minisign_req("domi-release", ctx("release", "Arca", "tag"));
|
||||
let signed = v.signing_sign(&rel, Approval::Mark, NOW).unwrap();
|
||||
v.signing_sign(&minisign_req("domi-test", ctx("ci", "Arca", "manual")), Approval::Auto, NOW + 1).unwrap();
|
||||
v.signing_refuse(&rel, Outcome::Refused, None, NOW + 2);
|
||||
v.signing_refuse(&rel, Outcome::Expired, Some("no answer in 5 minutes".into()), NOW + 3);
|
||||
let _ = v.signing_sign(&minisign_req("domi-release", ctx("nightly", "Arca", "tag")), Approval::Mark, NOW + 4);
|
||||
let _ = v.signing_sign(&minisign_req("nope", ctx("release", "Arca", "tag")), Approval::Mark, NOW + 5);
|
||||
// A refusal can never be recorded as a signature.
|
||||
v.signing_refuse(&rel, Outcome::Approved, None, NOW + 6);
|
||||
v.save(&path).unwrap();
|
||||
|
||||
let reopened = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
|
||||
let audit: &[AuditEntry] = reopened.signing_audit();
|
||||
let outcomes: Vec<Outcome> = audit.iter().map(|e| e.outcome).collect();
|
||||
assert_eq!(
|
||||
outcomes,
|
||||
[
|
||||
Outcome::Approved,
|
||||
Outcome::Auto,
|
||||
Outcome::Refused,
|
||||
Outcome::Expired,
|
||||
Outcome::OutOfScope,
|
||||
Outcome::Invalid,
|
||||
Outcome::Refused
|
||||
]
|
||||
);
|
||||
assert_eq!(audit[0].signature.as_deref(), Some(signed.sha256.as_str()));
|
||||
assert!(audit[2..].iter().all(|e| e.signature.is_none()));
|
||||
assert_eq!(audit[0].context, ctx("release", "Arca", "tag"));
|
||||
assert_eq!(audit[0].via, Via::Local);
|
||||
assert_eq!(audit[3].reason.as_deref(), Some("no answer in 5 minutes"));
|
||||
assert_eq!(reopened.signing_audit(), v.signing_audit());
|
||||
// The keys came back too, and still sign.
|
||||
let mut reopened = reopened;
|
||||
assert!(reopened.signing_sign(&rel, Approval::Mark, NOW + 7).is_ok());
|
||||
}
|
||||
Reference in New Issue
Block a user