alien-signing 3.3.71

Signed statements, signer lists, signing settings and the install ledger for installs that run only what the vendor signed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
//! The developer's signer list and its chain of versions.
//!
//! Version 1 is pinned by its fingerprint, the SHA-256 of its payload bytes,
//! which the customer's setup writes into the signing settings. Every later
//! version names the digest of the one before and is signed by
//! `adminThreshold` admin keys of the one before. Whoever carries the chain can
//! withhold a version, but can't change one or add one.
//!
//! A list never expires. An enforcer holds the highest version it accepted
//! (the install's ledger records it), so an older version can't come back.

use std::collections::{BTreeMap, BTreeSet};

use alien_error::AlienError;
use serde::{Deserialize, Serialize};

use crate::envelope::{Kind, Opened, Role, SignedStatement};
use crate::error::{ErrorData, Result};
use crate::key::PublicKey;

/// Most signers one list may hold.
pub const MAX_SIGNERS: usize = 256;

/// Where a signer's key lives. It is shown to admins and gives no authority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SignerKind {
    /// A CI key, in a CI secret or a cloud KMS.
    Ci,
    /// A key on a person's machine: in secure hardware or, when there is
    /// none, a software key in the signing home.
    Device,
    /// The key the recovery code derives.
    Recovery,
}

/// Where a device key is held. It is shown to admins and gives no authority.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum KeyBackend {
    /// Apple Secure Enclave.
    SecureEnclave,
    /// A TPM.
    Tpm,
    /// A YubiKey.
    Yubikey,
    /// A file: anyone who can read it can sign.
    Software,
}

impl KeyBackend {
    /// The name in JSON and on screen.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::SecureEnclave => "secure-enclave",
            Self::Tpm => "tpm",
            Self::Yubikey => "yubikey",
            Self::Software => "software",
        }
    }
}

/// One key on the list.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Signer {
    /// Unique id, such as `ci` or `alice-macbook`.
    pub id: String,
    /// `ecdsa-p256:<base64 SPKI>`.
    pub key: String,
    /// Where the key lives.
    pub kind: SignerKind,
    /// Where the key is held, when the signer who added it said.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backend: Option<KeyBackend>,
    /// What the key may sign.
    pub roles: Vec<Role>,
    /// Display label, such as the engineer's email.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

/// The deny-list entry that refuses every statement of the release signed
/// with `sequence`.
pub fn release_deny_entry(sequence: u64) -> String {
    format!("release:{sequence}")
}

/// What a kept statement is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum KeptKind {
    /// A `release/v2` statement.
    Release,
    /// A `config/v1` statement.
    Config,
}

impl KeptKind {
    /// The statement kind this names.
    pub fn kind(self) -> Kind {
        match self {
            Self::Release => Kind::Release,
            Self::Config => Kind::Config,
        }
    }

    /// The name in JSON and on screen.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Release => "release",
            Self::Config => "config",
        }
    }
}

/// Most statements one list may keep.
pub const MAX_KEEP: usize = 4096;

/// A statement the admins keep running although no signer on the list signed it
/// any more (its key was removed or rotated). The admin signs the entry with
/// the list, so enforcers need nothing else to accept the statement: a new
/// machine or a new Operator instance accepts it from the list alone.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Keep {
    /// `sha256:<hex>` of the statement's payload. This is what binds.
    pub digest: String,
    /// Whether it is a release or a config.
    pub kind: KeptKind,
    /// The release id the control plane gave the statement when the admin kept
    /// it. The admin saw it on screen; enforcers don't check it, because a
    /// statement can't name an id the control plane assigns after signing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub release_id: Option<String>,
    /// The statement's sequence.
    pub sequence: u64,
}

/// The body of a `signer-list/v1` statement.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SignerListBody {
    /// Digest of the previous version's payload; absent on version 1.
    pub previous: Option<String>,
    /// How many admin keys of this version must sign the next one.
    pub admin_threshold: u32,
    /// The keys.
    pub signers: Vec<Signer>,
    /// Statements that must be refused even though they verify: a digest
    /// (`sha256:<hex>`), or `release:<sequence>` for a whole release (every
    /// platform's statement of one release carries the same sequence).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub deny: Vec<String>,
    /// Statements signed by a key that is no longer on the list, which still
    /// run. Without an entry here everything a removed key signed is refused.
    /// Later versions carry the entries until an admin drops them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keep: Vec<Keep>,
    /// Set on a version the recovery key signed, so whoever verifies the
    /// install sees that signing was restored with the recovery code.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub recovered: bool,
}

impl SignerListBody {
    /// Whether the list refuses this statement: its digest is denied, or it is
    /// a release whose release is. The one rule every enforcer applies.
    pub fn refuses(&self, opened: &crate::envelope::Opened) -> bool {
        self.deny.contains(&opened.digest)
            || (opened.kind == crate::envelope::Kind::Release
                && self.deny.contains(&release_deny_entry(opened.sequence)))
    }

    /// Whether the list keeps this statement: an entry names its digest, kind
    /// and sequence.
    pub fn keeps(&self, opened: &crate::envelope::Opened) -> bool {
        self.keep.iter().any(|kept| {
            kept.digest == opened.digest
                && kept.kind.kind() == opened.kind
                && kept.sequence == opened.sequence
        })
    }
}

/// One trusted version, with its keys parsed.
#[derive(Debug, Clone)]
pub struct TrustedList {
    /// Version.
    pub version: u64,
    /// Digest of the version's payload.
    pub digest: String,
    /// The body.
    pub body: SignerListBody,
    keys: BTreeMap<String, (PublicKey, BTreeSet<Role>)>,
}

impl TrustedList {
    /// The key and roles of signer `id`.
    pub fn signer(&self, id: &str) -> Option<(&PublicKey, &BTreeSet<Role>)> {
        self.keys.get(id).map(|(key, roles)| (key, roles))
    }

    /// Kind of signer `id`.
    pub fn signer_kind(&self, id: &str) -> Option<SignerKind> {
        self.body
            .signers
            .iter()
            .find(|signer| signer.id == id)
            .map(|signer| signer.kind)
    }

    /// Whether a statement digest is denied.
    pub fn denies(&self, digest: &str) -> bool {
        self.body.deny.iter().any(|denied| denied == digest)
    }

    /// Whether the list keeps this statement. See [`SignerListBody::keeps`].
    pub fn keeps(&self, opened: &crate::envelope::Opened) -> bool {
        self.body.keeps(opened)
    }

    /// Whether the list refuses this statement. See [`SignerListBody::refuses`].
    pub fn refuses(&self, opened: &crate::envelope::Opened) -> bool {
        self.body.refuses(opened)
    }

    /// Check every signature on `opened` against this list. Each must be by a
    /// signer on the list holding `role`; returns the distinct signer ids.
    /// Any signature that doesn't count refuses the whole statement, so a
    /// statement never passes on a signature nobody could check.
    pub fn check_signatures(&self, opened: &Opened, role: Role) -> Result<BTreeSet<String>> {
        let mut signers = BTreeSet::new();
        for signature in &opened.signatures {
            let (key, roles) = self.signer(&signature.signer).ok_or_else(|| {
                refused_signature(
                    &signature.signer,
                    format!("not on signer list version {}", self.version),
                )
            })?;
            if !roles.contains(&role) {
                return Err(refused_signature(
                    &signature.signer,
                    format!("does not hold the '{}' role", role.as_str()),
                ));
            }
            key.verify(&opened.bytes, &signature.sig)
                .map_err(|error| refused_signature(&signature.signer, error.message))?;
            if !signers.insert(signature.signer.clone()) {
                return Err(refused_signature(
                    &signature.signer,
                    "signed twice".to_string(),
                ));
            }
        }
        if signers.is_empty() {
            return Err(AlienError::new(ErrorData::Unsigned {
                role: role.as_str().to_string(),
            }));
        }
        Ok(signers)
    }

    fn admin_count(&self) -> usize {
        self.keys
            .values()
            .filter(|(_, roles)| roles.contains(&Role::Admin))
            .count()
    }
}

/// The chain of signer lists an enforcer trusts, from the pinned version 1
/// to the highest version it has accepted.
#[derive(Debug, Clone)]
pub struct SignerChain {
    project: String,
    statements: Vec<SignedStatement>,
    digests: Vec<String>,
    /// Every trusted version, oldest first; the last is the current one.
    lists: Vec<TrustedList>,
}

impl SignerChain {
    /// Trust version 1, which must hash to `fingerprint` (`SHA256:<hex>`).
    /// The project is the one version 1 names.
    pub fn genesis(fingerprint: &str, statement: &SignedStatement) -> Result<Self> {
        let opened = statement.open()?;
        let version = opened.sequence;
        let expected = fingerprint_digest(fingerprint)?;
        let project = opened.project.clone();
        if opened.digest != expected {
            return Err(list_refused(
                version,
                format!(
                    "its digest {} does not match the pinned fingerprint {fingerprint}",
                    opened.digest
                ),
            ));
        }
        let list = parse_list(&project, &opened, 1)?;
        if list.body.previous.is_some() {
            return Err(list_refused(1, "version 1 names a previous version"));
        }
        if list.body.recovered {
            return Err(list_refused(1, "version 1 can't be a recovery"));
        }
        let signers = list.check_signatures(&opened, Role::Admin)?;
        if signers.len() < list.body.admin_threshold as usize {
            return Err(list_refused(
                1,
                format!(
                    "signed by {} of its own admins, below its threshold of {}",
                    signers.len(),
                    list.body.admin_threshold
                ),
            ));
        }
        Ok(Self {
            project,
            statements: vec![statement.clone()],
            digests: vec![opened.digest],
            lists: vec![list],
        })
    }

    /// Build a chain from version 1 on, verifying every link.
    pub fn from_statements(fingerprint: &str, statements: &[SignedStatement]) -> Result<Self> {
        let mut opened = statements
            .iter()
            .map(|statement| statement.open().map(|opened| (opened.sequence, statement)))
            .collect::<Result<Vec<_>>>()?;
        opened.sort_by_key(|(sequence, _)| *sequence);
        let ((_, first), rest) = opened
            .split_first()
            .ok_or_else(|| list_refused(1, "the chain is empty"))?;
        let mut chain = Self::genesis(fingerprint, first)?;
        let rest: Vec<SignedStatement> = rest
            .iter()
            .map(|(_, statement)| (*statement).clone())
            .collect();
        chain.extend(&rest)?;
        Ok(chain)
    }

    /// The digest of version `version`, if the chain holds it.
    pub fn digest_of(&self, version: u64) -> Option<&str> {
        version
            .checked_sub(1)
            .and_then(|index| self.digests.get(index as usize))
            .map(String::as_str)
    }

    /// The highest trusted version.
    pub fn current(&self) -> &TrustedList {
        self.lists.last().expect("a chain holds version 1")
    }

    /// Trusted version `version`, if the chain holds it.
    pub fn version(&self, version: u64) -> Option<&TrustedList> {
        version
            .checked_sub(1)
            .and_then(|index| self.lists.get(index as usize))
    }

    /// The project the chain belongs to.
    pub fn project(&self) -> &str {
        &self.project
    }

    /// Every trusted version's statement, oldest first, for storage.
    pub fn statements(&self) -> &[SignedStatement] {
        &self.statements
    }

    /// Accept whatever `statements` adds beyond the current version.
    ///
    /// Versions already trusted are skipped when their bytes match and refused
    /// when they don't, so a second, different version N is reported as a
    /// fork rather than ignored. The rest must follow on in order. Returns
    /// whether the chain grew.
    pub fn extend(&mut self, statements: &[SignedStatement]) -> Result<bool> {
        let mut opened = statements
            .iter()
            .map(|statement| statement.open().map(|opened| (opened, statement)))
            .collect::<Result<Vec<_>>>()?;
        opened.sort_by_key(|(opened, _)| opened.sequence);
        let before = self.current().version;
        for (opened, statement) in opened {
            if opened.kind != Kind::SignerList {
                return Err(list_refused(
                    opened.sequence,
                    format!("it is a '{}' statement", opened.kind),
                ));
            }
            let version = opened.sequence;
            if version <= self.current().version {
                if self.digest_of(version) != Some(opened.digest.as_str()) {
                    return Err(list_refused(
                        version,
                        "a different list with this version is already trusted",
                    ));
                }
                continue;
            }
            self.advance(&opened, statement)?;
        }
        Ok(self.current().version > before)
    }

    fn advance(&mut self, opened: &Opened, statement: &SignedStatement) -> Result<()> {
        let version = opened.sequence;
        if version != self.current().version + 1 {
            return Err(list_refused(
                version,
                format!(
                    "version {} is missing; the chain is at version {}",
                    self.current().version + 1,
                    self.current().version
                ),
            ));
        }
        let next = parse_list(&self.project, opened, self.current().version)?;
        if next.body.previous.as_deref() != Some(self.current().digest.as_str()) {
            return Err(list_refused(
                version,
                format!(
                    "it does not name version {}'s digest",
                    self.current().version
                ),
            ));
        }
        let signers = self.current().check_signatures(opened, Role::Admin)?;
        let threshold = self.current().body.admin_threshold as usize;
        if signers.len() < threshold {
            return Err(list_refused(
                version,
                format!(
                    "signed by {} admins of version {}, below its threshold of {threshold}",
                    signers.len(),
                    self.current().version
                ),
            ));
        }
        let by_recovery = signers
            .iter()
            .any(|signer| self.current().signer_kind(signer) == Some(SignerKind::Recovery));
        if by_recovery != next.body.recovered {
            return Err(list_refused(
                version,
                if by_recovery {
                    "the recovery key signed it, but it isn't marked recovered"
                } else {
                    "it is marked recovered, but the recovery key didn't sign it"
                },
            ));
        }
        self.statements.push(statement.clone());
        self.digests.push(opened.digest.clone());
        self.lists.push(next);
        Ok(())
    }
}

/// The fingerprint that pins a version 1, from its digest.
pub fn fingerprint(digest: &str) -> String {
    format!(
        "SHA256:{}",
        digest.strip_prefix("sha256:").unwrap_or(digest)
    )
}

/// A fingerprint as people compare it: the first 128 bits as eight groups of
/// four upper-case hex digits.
pub fn display_fingerprint(fingerprint: &str) -> String {
    let hex_part = fingerprint.strip_prefix("SHA256:").unwrap_or(fingerprint);
    hex_part
        .as_bytes()
        .chunks(4)
        .take(8)
        .map(|chunk| String::from_utf8_lossy(chunk).to_uppercase())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Whether `fingerprint` is `SHA256:<64 lowercase hex>`.
pub fn is_fingerprint(fingerprint: &str) -> bool {
    fingerprint_digest(fingerprint).is_ok()
}

fn fingerprint_digest(fingerprint: &str) -> Result<String> {
    let hex_part = fingerprint
        .strip_prefix("SHA256:")
        .filter(|hex_part| {
            hex_part.len() == 64
                && hex_part
                    .bytes()
                    .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
        })
        .ok_or_else(|| {
            AlienError::new(ErrorData::SettingsInvalid {
                reason: format!("fingerprint '{fingerprint}' is not SHA256:<64 lowercase hex>"),
            })
        })?;
    Ok(format!("sha256:{hex_part}"))
}

fn parse_list(project: &str, opened: &Opened, authorizing_version: u64) -> Result<TrustedList> {
    let version = opened.sequence;
    if opened.kind != Kind::SignerList {
        return Err(list_refused(
            version,
            format!("it is a '{}' statement", opened.kind),
        ));
    }
    if opened.project != project || project.is_empty() {
        return Err(AlienError::new(ErrorData::WrongProject {
            expected: project.to_string(),
            actual: opened.project.clone(),
        }));
    }
    if opened.install.is_some() {
        return Err(list_refused(version, "a signer list names no install"));
    }
    if opened.not_after.is_some() {
        // Lists published by CLIs before 3.3.69 carried an expiry. They can't be
        // read now, so say how to start over instead of just naming the field.
        return Err(list_refused(
            version,
            "it has an expiry date, so an Alien CLI older than 3.3.69 published it. \
             Signer lists no longer expire. Run `alien devices init` to start signing \
             again, then re-run the protected setup with the new fingerprint",
        ));
    }
    if version == 0 {
        return Err(list_refused(version, "versions start at 1"));
    }
    if opened.signer_list_version != authorizing_version {
        return Err(list_refused(
            version,
            format!(
                "it says it is authorized by version {}, not {authorizing_version}",
                opened.signer_list_version
            ),
        ));
    }
    let body: SignerListBody = opened.body()?;
    if body.signers.len() > MAX_SIGNERS {
        return Err(list_refused(
            version,
            format!("more than {MAX_SIGNERS} signers"),
        ));
    }
    if body.keep.len() > MAX_KEEP {
        return Err(list_refused(
            version,
            format!("more than {MAX_KEEP} kept statements"),
        ));
    }
    let mut kept_digests = BTreeSet::new();
    for kept in &body.keep {
        if !crate::release::is_sha256_digest(&kept.digest) {
            return Err(list_refused(
                version,
                format!("kept '{}' is not a digest", kept.digest),
            ));
        }
        if !kept_digests.insert(kept.digest.as_str()) {
            return Err(list_refused(
                version,
                format!("{} is kept twice", kept.digest),
            ));
        }
    }
    let mut keys = BTreeMap::new();
    let mut key_texts = BTreeSet::new();
    for signer in &body.signers {
        if !valid_signer_id(&signer.id) {
            return Err(list_refused(
                version,
                format!("signer id '{}' is not 1-64 of [a-z0-9-]", signer.id),
            ));
        }
        let key = PublicKey::parse(&signer.key).map_err(|error| {
            list_refused(
                version,
                format!("signer '{}': {}", signer.id, error.message),
            )
        })?;
        if !key_texts.insert(key.as_str().to_string()) {
            return Err(list_refused(
                version,
                format!("signer '{}' reuses a key already on the list", signer.id),
            ));
        }
        let roles: BTreeSet<Role> = signer.roles.iter().copied().collect();
        if roles.is_empty() || roles.len() != signer.roles.len() {
            return Err(list_refused(
                version,
                format!("signer '{}' has no roles or repeats one", signer.id),
            ));
        }
        if keys.insert(signer.id.clone(), (key, roles)).is_some() {
            return Err(list_refused(
                version,
                format!("signer id '{}' appears twice", signer.id),
            ));
        }
    }
    let list = TrustedList {
        version,
        digest: opened.digest.clone(),
        body,
        keys,
    };
    let admins = list.admin_count();
    let threshold = list.body.admin_threshold as usize;
    if threshold == 0 || threshold > admins {
        return Err(list_refused(
            version,
            format!("admin threshold {threshold} must be between 1 and its {admins} admins"),
        ));
    }
    Ok(list)
}

fn valid_signer_id(id: &str) -> bool {
    (1..=64).contains(&id.len())
        && id
            .bytes()
            .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
}

fn list_refused(version: u64, reason: impl Into<String>) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::SignerListRefused {
        version,
        reason: reason.into(),
    })
}

fn refused_signature(signer: &str, reason: String) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::SignatureRefused {
        signer: signer.to_string(),
        reason,
    })
}