1004 lines
39 KiB
Rust
1004 lines
39 KiB
Rust
//! 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,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The key that signs deploy approvals, and nothing else (docs/SIGNING.md, "approval").
|
|
pub const APPROVE_KEY: &str = "domi-approve";
|
|
|
|
#[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,
|
|
/// 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)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum SignKind {
|
|
Minisign,
|
|
Manifest,
|
|
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)]
|
|
#[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,
|
|
/// The version being built (core 0.12.0); absent when empty, so older readers see the entry they knew.
|
|
#[serde(skip_serializing_if = "String::is_empty")]
|
|
pub version: 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), 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<u8>,
|
|
/// The `SHA256SUMS` text, for a manifest.
|
|
pub manifest: Option<String>,
|
|
/// The deploy approval's canonical JSON, for `SignKind::Approval` (core 0.12.0).
|
|
pub approval: Option<String>,
|
|
/// The build's run id, `[A-Za-z0-9._-]{1,64}` (core 0.12.0). Required for an approval, and equal to its `run`.
|
|
pub run: 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>,
|
|
/// The request's run id (core 0.12.0), when it had a well-formed one.
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub run: Option<String>,
|
|
}
|
|
|
|
/// A signature handed back to the build.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Signed {
|
|
/// 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<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, code-signing and Android 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 | KeyKind::Android => {
|
|
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,
|
|
};
|
|
// 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,
|
|
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)
|
|
}
|
|
}
|
|
|
|
/// Unix seconds from the vault's milliseconds, as minisign and approvals count them.
|
|
fn seconds(now_ms: i64) -> u64 {
|
|
(now_ms.max(0) / 1000) as u64
|
|
}
|
|
|
|
/// A new `domi-approve`: Ed25519, a release key with the given scope.
|
|
fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key {
|
|
let ed = custos_sign::new_ed25519();
|
|
Key {
|
|
id: APPROVE_KEY.into(),
|
|
kind: KeyKind::Ed25519,
|
|
role: Role::Release,
|
|
name: "Domi deploy approval".into(),
|
|
secret: Secret::Ed25519(ed.secret),
|
|
public: Some(ed.public),
|
|
key_id: Some(ed.key_id),
|
|
cert: None,
|
|
issuer: None,
|
|
created: now,
|
|
pipelines: pipelines.to_vec(),
|
|
repos: repos.to_vec(),
|
|
}
|
|
}
|
|
|
|
/// 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<String>,
|
|
pub repos: Vec<String>,
|
|
}
|
|
|
|
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> {
|
|
// An Android key (core 0.14.0) is a key of its own, not part of a set: it never counts as the set.
|
|
if self.signing.keys.iter().any(|k| k.role == role && k.kind != KeyKind::Android) {
|
|
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]);
|
|
let mut ids = vec![ed_id.to_string(), root_id.into(), leaf_id.into()];
|
|
if role == Role::Release {
|
|
self.signing.keys.push(approve_key(&pipelines, &repos, now));
|
|
ids.push(APPROVE_KEY.into());
|
|
}
|
|
Ok(ids)
|
|
}
|
|
|
|
/// Adds `domi-approve` to a vault whose release keys an older core made, with `domi-release`'s scope (else the
|
|
/// first release key's). Refused without release keys, or when the key is there already. The caller saves.
|
|
pub fn signing_add_approve(&mut self, now: i64) -> Result<String, Error> {
|
|
if self.signing.get(APPROVE_KEY).is_some() {
|
|
return Err(Error::SigningExists("approval"));
|
|
}
|
|
let release = self
|
|
.signing
|
|
.keys
|
|
.iter()
|
|
.filter(|k| k.role == Role::Release && !matches!(k.kind, KeyKind::RootCa | KeyKind::Android));
|
|
let model = self
|
|
.signing
|
|
.get("domi-release")
|
|
.filter(|k| k.role == Role::Release)
|
|
.or_else(|| release.clone().next())
|
|
.ok_or_else(|| Error::Signing("there are no release keys to add an approval key to".into()))?;
|
|
let key = approve_key(&model.pipelines, &model.repos, now);
|
|
self.signing.keys.push(key);
|
|
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<String, Error> {
|
|
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<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.
|
|
/// An approval's expiry is checked against the system clock; [`Vault::signing_check_at`] takes the time.
|
|
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
|
|
self.signing_check_at(req, crate::now_ms())
|
|
}
|
|
|
|
/// [`Vault::signing_check`] at `now` (Unix milliseconds): an approval must not have expired then, and must
|
|
/// expire at most an hour later.
|
|
pub fn signing_check_at(&self, req: &Request, now: i64) -> Result<KeyView, Refusal> {
|
|
self.check(req, now).map(|(view, _)| view)
|
|
}
|
|
|
|
/// The check, and the approval it read (for an approval request).
|
|
fn check(&self, req: &Request, now: i64) -> Result<(KeyView, Option<custos_sign::Approval>), Refusal> {
|
|
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
|
|
let approver = k.id == APPROVE_KEY && k.kind == KeyKind::Ed25519 && k.role == Role::Release;
|
|
let fits = match (k.kind, req.kind) {
|
|
(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 {
|
|
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
|
|
}
|
|
if !fits {
|
|
return Err(Refusal::Invalid(if k.id == APPROVE_KEY || req.kind == SignKind::Approval {
|
|
format!("`{APPROVE_KEY}` signs deploy approvals only, and only it signs them (asked: `{}`)", k.id)
|
|
} else {
|
|
format!("`{}` cannot make {:?} signatures", k.id, req.kind)
|
|
}));
|
|
}
|
|
if req.run.as_deref().is_some_and(|r| !custos_sign::run_id_ok(r)) {
|
|
return Err(Refusal::Invalid("the run is not a run id ([A-Za-z0-9._-], 1 to 64)".into()));
|
|
}
|
|
if req.kind != SignKind::Approval && req.approval.is_some() {
|
|
return Err(Refusal::Invalid("approval text comes only with an approval request".into()));
|
|
}
|
|
let mut approval = None;
|
|
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::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()))?;
|
|
}
|
|
SignKind::Approval => {
|
|
let text = req.approval.as_deref().ok_or_else(|| Refusal::Invalid("no approval text".into()))?;
|
|
let a = custos_sign::approval_check(text, seconds(now)).map_err(|e| Refusal::Invalid(e.to_string()))?;
|
|
if req.run.as_deref() != Some(a.run.as_str()) {
|
|
return Err(Refusal::Invalid("the approval's run is not the request's run".into()));
|
|
}
|
|
let c = &req.context;
|
|
for (member, ours, theirs) in [
|
|
("repo", &c.repo, &a.repo),
|
|
("pipeline", &c.pipeline, &a.pipeline),
|
|
("commit", &c.commit, &a.commit),
|
|
("version", &c.version, &a.version),
|
|
] {
|
|
if !ours.is_empty() && ours != theirs {
|
|
return Err(Refusal::Invalid(format!("the request's {member} is not the approval's")));
|
|
}
|
|
}
|
|
approval = Some(a);
|
|
}
|
|
_ => {}
|
|
}
|
|
let file = &req.context.file;
|
|
if !matches!(req.kind, SignKind::Manifest | SignKind::Approval)
|
|
&& (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()));
|
|
}
|
|
// An approval is scoped by what it approves.
|
|
let (pipeline, repo) = match &approval {
|
|
Some(a) => (a.pipeline.as_str(), a.repo.as_str()),
|
|
None => (req.context.pipeline.as_str(), req.context.repo.as_str()),
|
|
};
|
|
if !in_scope(&k.pipelines, pipeline) {
|
|
return Err(Refusal::OutOfScope(format!("pipeline `{pipeline}` may not use `{}`", k.id)));
|
|
}
|
|
if !in_scope(&k.repos, repo) {
|
|
return Err(Refusal::OutOfScope(format!("repo `{repo}` may not use `{}`", 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)));
|
|
}
|
|
let view = self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists");
|
|
Ok((view, approval))
|
|
}
|
|
|
|
/// 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.check(req, now) {
|
|
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 = seconds(now);
|
|
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::Ed25519(s), SignKind::Approval) => custos_sign::approval(
|
|
s,
|
|
&k.key_id.expect("ed25519 keys have an id"),
|
|
req.approval.as_deref().unwrap_or_default(),
|
|
seconds,
|
|
req.run.as_deref().unwrap_or_default(),
|
|
)
|
|
.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 {
|
|
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();
|
|
let run = req.run.clone().filter(|r| custos_sign::run_id_ok(r));
|
|
match req.kind {
|
|
SignKind::Manifest => context.file = "SHA256SUMS".into(),
|
|
SignKind::Approval => {
|
|
context.file = match &run {
|
|
Some(r) => format!("approval-{r}.json"),
|
|
None => "approval.json".into(),
|
|
};
|
|
// What the approval says, where the request left the context empty: read without the clock, so a
|
|
// refused or expired request is filled in too. A text that does not read leaves the context as is.
|
|
let read = custos_sign::approval_parse(req.approval.as_deref().unwrap_or_default()).ok();
|
|
if let Some(a) = read {
|
|
for (ours, theirs) in [
|
|
(&mut context.repo, a.repo),
|
|
(&mut context.pipeline, a.pipeline),
|
|
(&mut context.commit, a.commit),
|
|
(&mut context.version, a.version),
|
|
] {
|
|
if ours.is_empty() {
|
|
*ours = theirs;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
self.signing.audit.push(AuditEntry {
|
|
at: now,
|
|
key: req.key.clone(),
|
|
kind: req.kind,
|
|
outcome,
|
|
via: req.via,
|
|
context,
|
|
signature,
|
|
reason,
|
|
run,
|
|
});
|
|
}
|
|
|
|
/// Every request any key was named in, oldest first.
|
|
pub fn signing_audit(&self) -> &[AuditEntry] {
|
|
&self.signing.audit
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
//! Mandatory test 2 for the core: no API path returns a private key. It lives here because only this module can
|
|
//! see the secrets to look for.
|
|
use super::*;
|
|
use crate::{KdfParams, SecretString};
|
|
|
|
fn s(v: &[&str]) -> Vec<String> {
|
|
v.iter().map(|x| x.to_string()).collect()
|
|
}
|
|
|
|
fn req(key: &str, kind: SignKind, digest: usize) -> Request {
|
|
Request {
|
|
key: key.into(),
|
|
kind,
|
|
digest: vec![5; digest],
|
|
manifest: None,
|
|
approval: None,
|
|
run: None,
|
|
context: Context {
|
|
repo: "Arca".into(),
|
|
pipeline: "release".into(),
|
|
trigger: "tag".into(),
|
|
file: "a.exe".into(),
|
|
..Default::default()
|
|
},
|
|
via: Via::Local,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_vault_with_release_keys_from_an_older_core_gets_its_approval_key() {
|
|
let mut v =
|
|
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
|
|
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), 1).unwrap();
|
|
// What core 0.11.0 made: the release set without `domi-approve`.
|
|
v.signing.keys.retain(|k| k.id != "domi-approve");
|
|
assert_eq!(v.signing.keys.len(), 3);
|
|
assert_eq!(v.signing_add_approve(7).unwrap(), "domi-approve");
|
|
let views = v.signing_keys();
|
|
let a = views.iter().find(|k| k.id == "domi-approve").unwrap();
|
|
assert_eq!((a.kind, a.role, a.created), (KeyKind::Ed25519, Role::Release, 7));
|
|
assert_eq!((a.pipelines.clone(), a.repos.clone()), (s(&["release"]), s(&["Arca"])));
|
|
assert!(a.minisign_public.is_some());
|
|
assert!(matches!(v.signing_add_approve(8), Err(Error::SigningExists("approval"))));
|
|
// It survives a save and a reopen.
|
|
let back = Vault::open(&v.to_bytes().unwrap(), &SecretString::from("pw")).unwrap();
|
|
assert_eq!(back.signing_keys(), views);
|
|
}
|
|
|
|
#[test]
|
|
fn no_api_path_returns_a_private_key() {
|
|
let mut v =
|
|
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<Vec<u8>> = v
|
|
.signing
|
|
.keys
|
|
.iter()
|
|
.map(|k| match &k.secret {
|
|
Secret::Ed25519(s) => s.expose().to_vec(),
|
|
Secret::Rsa(s) => s.expose().to_vec(),
|
|
})
|
|
.collect();
|
|
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.
|
|
let mut out = String::new();
|
|
let views = v.signing_keys();
|
|
out += &serde_json::to_string(&views).unwrap();
|
|
out += &format!("{views:?}{:?}", v.signing);
|
|
for k in &views {
|
|
if let Ok(c) = v.signing_export_cert(&k.id) {
|
|
out += &data_encoding::HEXLOWER.encode(&c);
|
|
}
|
|
}
|
|
let mut reqs =
|
|
vec![req("domi-release", SignKind::Minisign, 64), req("domi-code-signing", SignKind::Authenticode, 32)];
|
|
reqs.push(req("domi-root", SignKind::Authenticode, 32));
|
|
reqs.push(req("domi-test", SignKind::Minisign, 64));
|
|
let mut approve = req("domi-approve", SignKind::Approval, 0);
|
|
approve.run = Some("r-1".into());
|
|
approve.approval = Some(format!(
|
|
r#"{{"v":1,"run":"r-1","repo":"Arca","commit":"{}","pipeline":"release","version":"1.0.0","targets":["deploy"],"expires":600}}"#,
|
|
"a".repeat(40)
|
|
));
|
|
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] {
|
|
match v.signing_sign(r, approval, 2) {
|
|
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
|
|
Err(e) => out += &format!("{e:?}{e}"),
|
|
}
|
|
}
|
|
}
|
|
assert!(
|
|
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));
|
|
|
|
for secret in &secrets {
|
|
for enc in [
|
|
data_encoding::HEXLOWER.encode(secret),
|
|
data_encoding::HEXUPPER.encode(secret),
|
|
data_encoding::BASE64.encode(secret),
|
|
data_encoding::BASE64URL_NOPAD.encode(secret),
|
|
] {
|
|
assert!(!out.contains(&enc), "a secret appears in an output");
|
|
}
|
|
}
|
|
// Partial copies too: every 16-byte window of the numbers that are actually private. (A PKCS#8 RSA key
|
|
// also holds the public modulus and DER headers, which the certificate rightly shows.)
|
|
for private in private_parts(&secrets) {
|
|
for w in private.windows(16).step_by(8) {
|
|
assert!(!out.contains(&data_encoding::HEXLOWER.encode(w)), "part of a secret appears in an output");
|
|
assert!(!out.contains(&data_encoding::BASE64.encode(w)[..20]), "part of a secret appears in an output");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Ed25519 seeds as they are; for RSA the private exponent and the primes.
|
|
fn private_parts(secrets: &[Vec<u8>]) -> Vec<Vec<u8>> {
|
|
use rsa::pkcs8::DecodePrivateKey;
|
|
use rsa::traits::PrivateKeyParts;
|
|
let mut out = Vec::new();
|
|
for s in secrets {
|
|
if s.len() == 32 {
|
|
out.push(s.clone());
|
|
} else {
|
|
let k = rsa::RsaPrivateKey::from_pkcs8_der(s).unwrap();
|
|
out.push(k.d().to_bytes_be());
|
|
out.extend(k.primes().iter().map(|p| p.to_bytes_be()));
|
|
}
|
|
}
|
|
assert!(out.len() >= 2 + 4 * 3, "seeds, exponents and primes");
|
|
out
|
|
}
|
|
}
|