Skip to main content

alien_signing/
signer_list.rs

1//! The developer's signer list and its chain of versions.
2//!
3//! Version 1 is pinned by its fingerprint, the SHA-256 of its payload bytes,
4//! which the customer's setup writes into the signing settings. Every later
5//! version names the digest of the one before and is signed by
6//! `adminThreshold` admin keys of the one before. Whoever carries the chain can
7//! withhold a version, but can't change one or add one.
8//!
9//! A list never expires. An enforcer holds the highest version it accepted
10//! (the install's ledger records it), so an older version can't come back.
11
12use std::collections::{BTreeMap, BTreeSet};
13
14use alien_error::AlienError;
15use serde::{Deserialize, Serialize};
16
17use crate::envelope::{Kind, Opened, Role, SignedStatement};
18use crate::error::{ErrorData, Result};
19use crate::key::PublicKey;
20
21/// Most signers one list may hold.
22pub const MAX_SIGNERS: usize = 256;
23
24/// Where a signer's key lives. It is shown to admins and gives no authority.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
26#[serde(rename_all = "camelCase")]
27pub enum SignerKind {
28    /// A CI key, in a CI secret or a cloud KMS.
29    Ci,
30    /// A key on a person's machine: in secure hardware or, when there is
31    /// none, a software key in the signing home.
32    Device,
33    /// The key the recovery code derives.
34    Recovery,
35}
36
37/// Where a device key is held. It is shown to admins and gives no authority.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "kebab-case")]
40pub enum KeyBackend {
41    /// Apple Secure Enclave.
42    SecureEnclave,
43    /// A TPM.
44    Tpm,
45    /// A YubiKey.
46    Yubikey,
47    /// A file: anyone who can read it can sign.
48    Software,
49}
50
51impl KeyBackend {
52    /// The name in JSON and on screen.
53    pub fn as_str(self) -> &'static str {
54        match self {
55            Self::SecureEnclave => "secure-enclave",
56            Self::Tpm => "tpm",
57            Self::Yubikey => "yubikey",
58            Self::Software => "software",
59        }
60    }
61}
62
63/// One key on the list.
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase", deny_unknown_fields)]
66pub struct Signer {
67    /// Unique id, such as `ci` or `alice-macbook`.
68    pub id: String,
69    /// `ecdsa-p256:<base64 SPKI>`.
70    pub key: String,
71    /// Where the key lives.
72    pub kind: SignerKind,
73    /// Where the key is held, when the signer who added it said.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub backend: Option<KeyBackend>,
76    /// What the key may sign.
77    pub roles: Vec<Role>,
78    /// Display label, such as the engineer's email.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub label: Option<String>,
81}
82
83/// The deny-list entry that refuses every statement of the release signed
84/// with `sequence`.
85pub fn release_deny_entry(sequence: u64) -> String {
86    format!("release:{sequence}")
87}
88
89/// What a kept statement is.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
91#[serde(rename_all = "camelCase")]
92pub enum KeptKind {
93    /// A `release/v2` statement.
94    Release,
95    /// A `config/v1` statement.
96    Config,
97}
98
99impl KeptKind {
100    /// The statement kind this names.
101    pub fn kind(self) -> Kind {
102        match self {
103            Self::Release => Kind::Release,
104            Self::Config => Kind::Config,
105        }
106    }
107
108    /// The name in JSON and on screen.
109    pub fn as_str(self) -> &'static str {
110        match self {
111            Self::Release => "release",
112            Self::Config => "config",
113        }
114    }
115}
116
117/// Most statements one list may keep.
118pub const MAX_KEEP: usize = 4096;
119
120/// A statement the admins keep running although no signer on the list signed it
121/// any more (its key was removed or rotated). The admin signs the entry with
122/// the list, so enforcers need nothing else to accept the statement: a new
123/// machine or a new Operator instance accepts it from the list alone.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125#[serde(rename_all = "camelCase", deny_unknown_fields)]
126pub struct Keep {
127    /// `sha256:<hex>` of the statement's payload. This is what binds.
128    pub digest: String,
129    /// Whether it is a release or a config.
130    pub kind: KeptKind,
131    /// The release id the control plane gave the statement when the admin kept
132    /// it. The admin saw it on screen; enforcers don't check it, because a
133    /// statement can't name an id the control plane assigns after signing.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub release_id: Option<String>,
136    /// The statement's sequence.
137    pub sequence: u64,
138}
139
140/// The body of a `signer-list/v1` statement.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "camelCase", deny_unknown_fields)]
143pub struct SignerListBody {
144    /// Digest of the previous version's payload; absent on version 1.
145    pub previous: Option<String>,
146    /// How many admin keys of this version must sign the next one.
147    pub admin_threshold: u32,
148    /// The keys.
149    pub signers: Vec<Signer>,
150    /// Statements that must be refused even though they verify: a digest
151    /// (`sha256:<hex>`), or `release:<sequence>` for a whole release (every
152    /// platform's statement of one release carries the same sequence).
153    #[serde(default, skip_serializing_if = "Vec::is_empty")]
154    pub deny: Vec<String>,
155    /// Statements signed by a key that is no longer on the list, which still
156    /// run. Without an entry here everything a removed key signed is refused.
157    /// Later versions carry the entries until an admin drops them.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub keep: Vec<Keep>,
160    /// Set on a version the recovery key signed, so whoever verifies the
161    /// install sees that signing was restored with the recovery code.
162    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
163    pub recovered: bool,
164}
165
166impl SignerListBody {
167    /// Whether the list refuses this statement: its digest is denied, or it is
168    /// a release whose release is. The one rule every enforcer applies.
169    pub fn refuses(&self, opened: &crate::envelope::Opened) -> bool {
170        self.deny.contains(&opened.digest)
171            || (opened.kind == crate::envelope::Kind::Release
172                && self.deny.contains(&release_deny_entry(opened.sequence)))
173    }
174
175    /// Whether the list keeps this statement: an entry names its digest, kind
176    /// and sequence.
177    pub fn keeps(&self, opened: &crate::envelope::Opened) -> bool {
178        self.keep.iter().any(|kept| {
179            kept.digest == opened.digest
180                && kept.kind.kind() == opened.kind
181                && kept.sequence == opened.sequence
182        })
183    }
184}
185
186/// One trusted version, with its keys parsed.
187#[derive(Debug, Clone)]
188pub struct TrustedList {
189    /// Version.
190    pub version: u64,
191    /// Digest of the version's payload.
192    pub digest: String,
193    /// The body.
194    pub body: SignerListBody,
195    keys: BTreeMap<String, (PublicKey, BTreeSet<Role>)>,
196}
197
198impl TrustedList {
199    /// The key and roles of signer `id`.
200    pub fn signer(&self, id: &str) -> Option<(&PublicKey, &BTreeSet<Role>)> {
201        self.keys.get(id).map(|(key, roles)| (key, roles))
202    }
203
204    /// Kind of signer `id`.
205    pub fn signer_kind(&self, id: &str) -> Option<SignerKind> {
206        self.body
207            .signers
208            .iter()
209            .find(|signer| signer.id == id)
210            .map(|signer| signer.kind)
211    }
212
213    /// Whether a statement digest is denied.
214    pub fn denies(&self, digest: &str) -> bool {
215        self.body.deny.iter().any(|denied| denied == digest)
216    }
217
218    /// Whether the list keeps this statement. See [`SignerListBody::keeps`].
219    pub fn keeps(&self, opened: &crate::envelope::Opened) -> bool {
220        self.body.keeps(opened)
221    }
222
223    /// Whether the list refuses this statement. See [`SignerListBody::refuses`].
224    pub fn refuses(&self, opened: &crate::envelope::Opened) -> bool {
225        self.body.refuses(opened)
226    }
227
228    /// Check every signature on `opened` against this list. Each must be by a
229    /// signer on the list holding `role`; returns the distinct signer ids.
230    /// Any signature that doesn't count refuses the whole statement, so a
231    /// statement never passes on a signature nobody could check.
232    pub fn check_signatures(&self, opened: &Opened, role: Role) -> Result<BTreeSet<String>> {
233        let mut signers = BTreeSet::new();
234        for signature in &opened.signatures {
235            let (key, roles) = self.signer(&signature.signer).ok_or_else(|| {
236                refused_signature(
237                    &signature.signer,
238                    format!("not on signer list version {}", self.version),
239                )
240            })?;
241            if !roles.contains(&role) {
242                return Err(refused_signature(
243                    &signature.signer,
244                    format!("does not hold the '{}' role", role.as_str()),
245                ));
246            }
247            key.verify(&opened.bytes, &signature.sig)
248                .map_err(|error| refused_signature(&signature.signer, error.message))?;
249            if !signers.insert(signature.signer.clone()) {
250                return Err(refused_signature(
251                    &signature.signer,
252                    "signed twice".to_string(),
253                ));
254            }
255        }
256        if signers.is_empty() {
257            return Err(AlienError::new(ErrorData::Unsigned {
258                role: role.as_str().to_string(),
259            }));
260        }
261        Ok(signers)
262    }
263
264    fn admin_count(&self) -> usize {
265        self.keys
266            .values()
267            .filter(|(_, roles)| roles.contains(&Role::Admin))
268            .count()
269    }
270}
271
272/// The chain of signer lists an enforcer trusts, from the pinned version 1
273/// to the highest version it has accepted.
274#[derive(Debug, Clone)]
275pub struct SignerChain {
276    project: String,
277    statements: Vec<SignedStatement>,
278    digests: Vec<String>,
279    /// Every trusted version, oldest first; the last is the current one.
280    lists: Vec<TrustedList>,
281}
282
283impl SignerChain {
284    /// Trust version 1, which must hash to `fingerprint` (`SHA256:<hex>`).
285    /// The project is the one version 1 names.
286    pub fn genesis(fingerprint: &str, statement: &SignedStatement) -> Result<Self> {
287        let opened = statement.open()?;
288        let version = opened.sequence;
289        let expected = fingerprint_digest(fingerprint)?;
290        let project = opened.project.clone();
291        if opened.digest != expected {
292            return Err(list_refused(
293                version,
294                format!(
295                    "its digest {} does not match the pinned fingerprint {fingerprint}",
296                    opened.digest
297                ),
298            ));
299        }
300        let list = parse_list(&project, &opened, 1)?;
301        if list.body.previous.is_some() {
302            return Err(list_refused(1, "version 1 names a previous version"));
303        }
304        if list.body.recovered {
305            return Err(list_refused(1, "version 1 can't be a recovery"));
306        }
307        let signers = list.check_signatures(&opened, Role::Admin)?;
308        if signers.len() < list.body.admin_threshold as usize {
309            return Err(list_refused(
310                1,
311                format!(
312                    "signed by {} of its own admins, below its threshold of {}",
313                    signers.len(),
314                    list.body.admin_threshold
315                ),
316            ));
317        }
318        Ok(Self {
319            project,
320            statements: vec![statement.clone()],
321            digests: vec![opened.digest],
322            lists: vec![list],
323        })
324    }
325
326    /// Build a chain from version 1 on, verifying every link.
327    pub fn from_statements(fingerprint: &str, statements: &[SignedStatement]) -> Result<Self> {
328        let mut opened = statements
329            .iter()
330            .map(|statement| statement.open().map(|opened| (opened.sequence, statement)))
331            .collect::<Result<Vec<_>>>()?;
332        opened.sort_by_key(|(sequence, _)| *sequence);
333        let ((_, first), rest) = opened
334            .split_first()
335            .ok_or_else(|| list_refused(1, "the chain is empty"))?;
336        let mut chain = Self::genesis(fingerprint, first)?;
337        let rest: Vec<SignedStatement> = rest
338            .iter()
339            .map(|(_, statement)| (*statement).clone())
340            .collect();
341        chain.extend(&rest)?;
342        Ok(chain)
343    }
344
345    /// The digest of version `version`, if the chain holds it.
346    pub fn digest_of(&self, version: u64) -> Option<&str> {
347        version
348            .checked_sub(1)
349            .and_then(|index| self.digests.get(index as usize))
350            .map(String::as_str)
351    }
352
353    /// The highest trusted version.
354    pub fn current(&self) -> &TrustedList {
355        self.lists.last().expect("a chain holds version 1")
356    }
357
358    /// Trusted version `version`, if the chain holds it.
359    pub fn version(&self, version: u64) -> Option<&TrustedList> {
360        version
361            .checked_sub(1)
362            .and_then(|index| self.lists.get(index as usize))
363    }
364
365    /// The project the chain belongs to.
366    pub fn project(&self) -> &str {
367        &self.project
368    }
369
370    /// Every trusted version's statement, oldest first, for storage.
371    pub fn statements(&self) -> &[SignedStatement] {
372        &self.statements
373    }
374
375    /// Accept whatever `statements` adds beyond the current version.
376    ///
377    /// Versions already trusted are skipped when their bytes match and refused
378    /// when they don't, so a second, different version N is reported as a
379    /// fork rather than ignored. The rest must follow on in order. Returns
380    /// whether the chain grew.
381    pub fn extend(&mut self, statements: &[SignedStatement]) -> Result<bool> {
382        let mut opened = statements
383            .iter()
384            .map(|statement| statement.open().map(|opened| (opened, statement)))
385            .collect::<Result<Vec<_>>>()?;
386        opened.sort_by_key(|(opened, _)| opened.sequence);
387        let before = self.current().version;
388        for (opened, statement) in opened {
389            if opened.kind != Kind::SignerList {
390                return Err(list_refused(
391                    opened.sequence,
392                    format!("it is a '{}' statement", opened.kind),
393                ));
394            }
395            let version = opened.sequence;
396            if version <= self.current().version {
397                if self.digest_of(version) != Some(opened.digest.as_str()) {
398                    return Err(list_refused(
399                        version,
400                        "a different list with this version is already trusted",
401                    ));
402                }
403                continue;
404            }
405            self.advance(&opened, statement)?;
406        }
407        Ok(self.current().version > before)
408    }
409
410    fn advance(&mut self, opened: &Opened, statement: &SignedStatement) -> Result<()> {
411        let version = opened.sequence;
412        if version != self.current().version + 1 {
413            return Err(list_refused(
414                version,
415                format!(
416                    "version {} is missing; the chain is at version {}",
417                    self.current().version + 1,
418                    self.current().version
419                ),
420            ));
421        }
422        let next = parse_list(&self.project, opened, self.current().version)?;
423        if next.body.previous.as_deref() != Some(self.current().digest.as_str()) {
424            return Err(list_refused(
425                version,
426                format!(
427                    "it does not name version {}'s digest",
428                    self.current().version
429                ),
430            ));
431        }
432        let signers = self.current().check_signatures(opened, Role::Admin)?;
433        let threshold = self.current().body.admin_threshold as usize;
434        if signers.len() < threshold {
435            return Err(list_refused(
436                version,
437                format!(
438                    "signed by {} admins of version {}, below its threshold of {threshold}",
439                    signers.len(),
440                    self.current().version
441                ),
442            ));
443        }
444        let by_recovery = signers
445            .iter()
446            .any(|signer| self.current().signer_kind(signer) == Some(SignerKind::Recovery));
447        if by_recovery != next.body.recovered {
448            return Err(list_refused(
449                version,
450                if by_recovery {
451                    "the recovery key signed it, but it isn't marked recovered"
452                } else {
453                    "it is marked recovered, but the recovery key didn't sign it"
454                },
455            ));
456        }
457        self.statements.push(statement.clone());
458        self.digests.push(opened.digest.clone());
459        self.lists.push(next);
460        Ok(())
461    }
462}
463
464/// The fingerprint that pins a version 1, from its digest.
465pub fn fingerprint(digest: &str) -> String {
466    format!(
467        "SHA256:{}",
468        digest.strip_prefix("sha256:").unwrap_or(digest)
469    )
470}
471
472/// A fingerprint as people compare it: the first 128 bits as eight groups of
473/// four upper-case hex digits.
474pub fn display_fingerprint(fingerprint: &str) -> String {
475    let hex_part = fingerprint.strip_prefix("SHA256:").unwrap_or(fingerprint);
476    hex_part
477        .as_bytes()
478        .chunks(4)
479        .take(8)
480        .map(|chunk| String::from_utf8_lossy(chunk).to_uppercase())
481        .collect::<Vec<_>>()
482        .join(" ")
483}
484
485/// Whether `fingerprint` is `SHA256:<64 lowercase hex>`.
486pub fn is_fingerprint(fingerprint: &str) -> bool {
487    fingerprint_digest(fingerprint).is_ok()
488}
489
490fn fingerprint_digest(fingerprint: &str) -> Result<String> {
491    let hex_part = fingerprint
492        .strip_prefix("SHA256:")
493        .filter(|hex_part| {
494            hex_part.len() == 64
495                && hex_part
496                    .bytes()
497                    .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
498        })
499        .ok_or_else(|| {
500            AlienError::new(ErrorData::SettingsInvalid {
501                reason: format!("fingerprint '{fingerprint}' is not SHA256:<64 lowercase hex>"),
502            })
503        })?;
504    Ok(format!("sha256:{hex_part}"))
505}
506
507fn parse_list(project: &str, opened: &Opened, authorizing_version: u64) -> Result<TrustedList> {
508    let version = opened.sequence;
509    if opened.kind != Kind::SignerList {
510        return Err(list_refused(
511            version,
512            format!("it is a '{}' statement", opened.kind),
513        ));
514    }
515    if opened.project != project || project.is_empty() {
516        return Err(AlienError::new(ErrorData::WrongProject {
517            expected: project.to_string(),
518            actual: opened.project.clone(),
519        }));
520    }
521    if opened.install.is_some() {
522        return Err(list_refused(version, "a signer list names no install"));
523    }
524    if opened.not_after.is_some() {
525        // Lists published by CLIs before 3.3.69 carried an expiry. They can't be
526        // read now, so say how to start over instead of just naming the field.
527        return Err(list_refused(
528            version,
529            "it has an expiry date, so an Alien CLI older than 3.3.69 published it. \
530             Signer lists no longer expire. Run `alien devices init` to start signing \
531             again, then re-run the protected setup with the new fingerprint",
532        ));
533    }
534    if version == 0 {
535        return Err(list_refused(version, "versions start at 1"));
536    }
537    if opened.signer_list_version != authorizing_version {
538        return Err(list_refused(
539            version,
540            format!(
541                "it says it is authorized by version {}, not {authorizing_version}",
542                opened.signer_list_version
543            ),
544        ));
545    }
546    let body: SignerListBody = opened.body()?;
547    if body.signers.len() > MAX_SIGNERS {
548        return Err(list_refused(
549            version,
550            format!("more than {MAX_SIGNERS} signers"),
551        ));
552    }
553    if body.keep.len() > MAX_KEEP {
554        return Err(list_refused(
555            version,
556            format!("more than {MAX_KEEP} kept statements"),
557        ));
558    }
559    let mut kept_digests = BTreeSet::new();
560    for kept in &body.keep {
561        if !crate::release::is_sha256_digest(&kept.digest) {
562            return Err(list_refused(
563                version,
564                format!("kept '{}' is not a digest", kept.digest),
565            ));
566        }
567        if !kept_digests.insert(kept.digest.as_str()) {
568            return Err(list_refused(
569                version,
570                format!("{} is kept twice", kept.digest),
571            ));
572        }
573    }
574    let mut keys = BTreeMap::new();
575    let mut key_texts = BTreeSet::new();
576    for signer in &body.signers {
577        if !valid_signer_id(&signer.id) {
578            return Err(list_refused(
579                version,
580                format!("signer id '{}' is not 1-64 of [a-z0-9-]", signer.id),
581            ));
582        }
583        let key = PublicKey::parse(&signer.key).map_err(|error| {
584            list_refused(
585                version,
586                format!("signer '{}': {}", signer.id, error.message),
587            )
588        })?;
589        if !key_texts.insert(key.as_str().to_string()) {
590            return Err(list_refused(
591                version,
592                format!("signer '{}' reuses a key already on the list", signer.id),
593            ));
594        }
595        let roles: BTreeSet<Role> = signer.roles.iter().copied().collect();
596        if roles.is_empty() || roles.len() != signer.roles.len() {
597            return Err(list_refused(
598                version,
599                format!("signer '{}' has no roles or repeats one", signer.id),
600            ));
601        }
602        if keys.insert(signer.id.clone(), (key, roles)).is_some() {
603            return Err(list_refused(
604                version,
605                format!("signer id '{}' appears twice", signer.id),
606            ));
607        }
608    }
609    let list = TrustedList {
610        version,
611        digest: opened.digest.clone(),
612        body,
613        keys,
614    };
615    let admins = list.admin_count();
616    let threshold = list.body.admin_threshold as usize;
617    if threshold == 0 || threshold > admins {
618        return Err(list_refused(
619            version,
620            format!("admin threshold {threshold} must be between 1 and its {admins} admins"),
621        ));
622    }
623    Ok(list)
624}
625
626fn valid_signer_id(id: &str) -> bool {
627    (1..=64).contains(&id.len())
628        && id
629            .bytes()
630            .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
631}
632
633fn list_refused(version: u64, reason: impl Into<String>) -> AlienError<ErrorData> {
634    AlienError::new(ErrorData::SignerListRefused {
635        version,
636        reason: reason.into(),
637    })
638}
639
640fn refused_signature(signer: &str, reason: String) -> AlienError<ErrorData> {
641    AlienError::new(ErrorData::SignatureRefused {
642        signer: signer.to_string(),
643        reason,
644    })
645}