alien-signing 3.3.69

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
//! What setup pins for a protected install, how an enforcer finds it, and
//! the install id every enforcer derives from its own identity.
//!
//! Setup writes three values: the signer list fingerprint, the install's
//! prefix and the release channel it follows. The project is the one signer
//! list version 1 names. Nothing else comes from setup, and nothing at all
//! from the control plane.

use std::fmt;

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

use crate::error::{ErrorData, Result};
use crate::signer_list::is_fingerprint;

/// The signing settings of one install.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SigningSettings {
    /// `SHA256:<hex>` fingerprint of the project's signer list version 1.
    pub fingerprint: String,
    /// The install's resource prefix. It must equal the place the settings
    /// were found, so a value copied from a neighbor is refused.
    pub prefix: String,
    /// Release channel the install follows. A release for another channel is
    /// refused.
    pub channel: String,
}

impl SigningSettings {
    /// Parse settings found at `prefix` and check each field.
    pub fn parse(bytes: &[u8], prefix: &str) -> Result<Self> {
        let settings: SigningSettings =
            serde_json::from_slice(bytes).map_err(|error| invalid(format!("{error}")))?;
        settings.validate()?;
        if settings.prefix != prefix {
            return Err(invalid(format!(
                "the settings found for '{prefix}' name prefix '{}'",
                settings.prefix
            )));
        }
        Ok(settings)
    }

    /// Check each field.
    pub fn validate(&self) -> Result<()> {
        if !is_fingerprint(&self.fingerprint) {
            return Err(invalid(format!(
                "fingerprint '{}' is not SHA256:<64 lowercase hex>",
                self.fingerprint
            )));
        }
        if !is_prefix(&self.prefix) {
            return Err(invalid(format!(
                "prefix '{}' is not 1 to 63 of [A-Za-z0-9-] starting with a letter",
                self.prefix
            )));
        }
        if !is_name(&self.channel, 63) {
            return Err(invalid(format!(
                "channel '{}' is not 1 to 63 of [a-z0-9-]",
                self.channel
            )));
        }
        Ok(())
    }

    /// The JSON setup writes.
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).expect("settings always serialize")
    }
}

/// The install id. Enforcers derive it from their own identity and never
/// read it from anywhere the control plane writes, so a statement signed for
/// one customer's install is refused by another's.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InstallId {
    /// `aws:<account>:<region>:<prefix>`.
    Aws {
        /// 12-digit account id.
        account: String,
        /// Region.
        region: String,
        /// Stack prefix.
        prefix: String,
    },
    /// `gcp:<project>:<prefix>`.
    Gcp {
        /// Project id.
        project: String,
        /// Resource prefix.
        prefix: String,
    },
    /// `azure:<subscription>:<resource-group>`.
    Azure {
        /// Subscription id.
        subscription: String,
        /// Resource group.
        resource_group: String,
    },
    /// `k8s:<kube-system namespace uid>:<namespace>/<release>`.
    Kubernetes {
        /// UID of the cluster's `kube-system` namespace.
        cluster: String,
        /// Install namespace.
        namespace: String,
        /// Helm release name.
        release: String,
    },
    /// `machine:<uuid>`, generated by `join` on the machine itself.
    Machine {
        /// UUID.
        id: String,
    },
}

impl fmt::Display for InstallId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Aws {
                account,
                region,
                prefix,
            } => write!(f, "aws:{account}:{region}:{prefix}"),
            Self::Gcp { project, prefix } => write!(f, "gcp:{project}:{prefix}"),
            Self::Azure {
                subscription,
                resource_group,
            } => write!(f, "azure:{subscription}:{resource_group}"),
            Self::Kubernetes {
                cluster,
                namespace,
                release,
            } => write!(f, "k8s:{cluster}:{namespace}/{release}"),
            Self::Machine { id } => write!(f, "machine:{id}"),
        }
    }
}

impl InstallId {
    /// Parse the printed form, checking each part, so an id the CLI shows an
    /// admin is the one an enforcer would derive.
    pub fn parse(text: &str) -> Result<Self> {
        let bad = || invalid_install(text);
        let (kind, rest) = text.split_once(':').ok_or_else(bad)?;
        let parts: Vec<&str> = rest.split(':').collect();
        let id = match (kind, parts.as_slice()) {
            ("aws", [account, region, prefix]) => Self::Aws {
                account: account.to_string(),
                region: region.to_string(),
                prefix: prefix.to_string(),
            },
            ("gcp", [project, prefix]) => Self::Gcp {
                project: project.to_string(),
                prefix: prefix.to_string(),
            },
            ("azure", [subscription, resource_group]) => Self::Azure {
                subscription: subscription.to_string(),
                resource_group: resource_group.to_string(),
            },
            ("k8s", [cluster, scoped]) => {
                let (namespace, release) = scoped.split_once('/').ok_or_else(bad)?;
                Self::Kubernetes {
                    cluster: cluster.to_string(),
                    namespace: namespace.to_string(),
                    release: release.to_string(),
                }
            }
            ("machine", [id]) => Self::Machine { id: id.to_string() },
            _ => return Err(bad()),
        };
        id.validate()?;
        Ok(id)
    }

    /// Check each part.
    pub fn validate(&self) -> Result<()> {
        let ok = match self {
            Self::Aws {
                account,
                region,
                prefix,
            } => {
                account.len() == 12
                    && account.bytes().all(|byte| byte.is_ascii_digit())
                    && is_name(region, 32)
                    && is_prefix(prefix)
            }
            Self::Gcp { project, prefix } => is_name(project, 30) && is_prefix(prefix),
            Self::Azure {
                subscription,
                resource_group,
            } => {
                is_uuid(subscription)
                    && !resource_group.is_empty()
                    && resource_group.len() <= 90
                    && resource_group.bytes().all(|byte| {
                        byte.is_ascii_alphanumeric()
                            || matches!(byte, b'-' | b'_' | b'.' | b'(' | b')')
                    })
            }
            Self::Kubernetes {
                cluster,
                namespace,
                release,
            } => is_uuid(cluster) && is_name(namespace, 63) && is_name(release, 53),
            Self::Machine { id } => is_uuid(id),
        };
        if ok {
            Ok(())
        } else {
            Err(invalid_install(&self.to_string()))
        }
    }
}

/// What an enforcer got when it read one place the settings could be.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Lookup {
    /// The value was there.
    Found(Vec<u8>),
    /// The place is empty.
    Absent,
    /// The enforcer may not read it.
    Denied,
}

/// Decide whether an install is protected from every place its settings
/// could be, keyed by the prefix each place belongs to.
///
/// Every candidate must be read; this never stops at the first answer. The
/// install is protected if exactly one place holds settings and they name
/// that place's prefix. Two or more, or settings that don't parse, are an
/// error. It is unprotected only if every place is absent or denied and at
/// least one is absent: when every place is denied, nothing was learned.
pub fn discover(candidates: &[(String, Lookup)]) -> Result<Option<SigningSettings>> {
    if candidates.is_empty() {
        return Err(undecided("there was no place to look for the settings"));
    }
    let mut found = Vec::new();
    let mut any_absent = false;
    for (prefix, lookup) in candidates {
        match lookup {
            Lookup::Found(bytes) => found.push(SigningSettings::parse(bytes, prefix)?),
            Lookup::Absent => any_absent = true,
            Lookup::Denied => {}
        }
    }
    match found.len() {
        0 if any_absent => Ok(None),
        0 => Err(undecided(
            "every place the settings could be refused the read",
        )),
        1 => Ok(found.pop()),
        count => Err(undecided(format!(
            "{count} places hold signing settings: {}",
            found
                .iter()
                .map(|settings| settings.prefix.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        ))),
    }
}

/// The prefixes a resource name could belong to, longest first: the name
/// itself, then every part of it ending before a `-`. An enforcer whose role
/// is `acme-prod-verifier` looks for settings of `acme-prod-verifier`,
/// `acme-prod` and `acme`.
pub fn candidate_prefixes(name: &str) -> Vec<String> {
    let mut prefixes = vec![name.to_string()];
    let mut rest = name;
    while let Some((head, _)) = rest.rsplit_once('-') {
        if !head.is_empty() {
            prefixes.push(head.to_string());
        }
        rest = head;
    }
    prefixes
}

fn is_name(text: &str, max: usize) -> bool {
    (1..=max).contains(&text.len())
        && text
            .bytes()
            .all(|byte| matches!(byte, b'a'..=b'z' | b'0'..=b'9' | b'-'))
        && !text.starts_with('-')
}

/// Resource prefixes: CloudFormation stack names allow upper case.
fn is_prefix(text: &str) -> bool {
    (1..=63).contains(&text.len())
        && text.as_bytes()[0].is_ascii_alphabetic()
        && text
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
}

fn is_uuid(text: &str) -> bool {
    text.len() == 36
        && text.bytes().enumerate().all(|(index, byte)| match index {
            8 | 13 | 18 | 23 => byte == b'-',
            _ => byte.is_ascii_hexdigit() && !byte.is_ascii_uppercase(),
        })
}

fn invalid(reason: impl Into<String>) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::SettingsInvalid {
        reason: reason.into(),
    })
}

fn invalid_install(text: &str) -> AlienError<ErrorData> {
    invalid(format!("'{text}' is not an install id"))
}

fn undecided(reason: impl Into<String>) -> AlienError<ErrorData> {
    AlienError::new(ErrorData::SettingsUndecided {
        reason: reason.into(),
    })
}

/// Where setup writes the signing settings, the ledger and deployer inputs.
///
/// Every name sits under a root no management grant reaches: grants are on
/// `<prefix>-*`, and these start with `/signed/` or `signed-`, so a neighbor
/// install whose prefix overlaps this one's can't write them.
pub mod names {
    /// AWS SSM parameter holding the signing settings.
    pub fn aws_settings(prefix: &str) -> String {
        format!("/signed/{prefix}/fingerprint")
    }

    /// AWS SSM parameter holding the ledger.
    pub fn aws_ledger(prefix: &str) -> String {
        format!("/signed/{prefix}/state")
    }

    /// AWS SSM path under which each deployer input is one parameter.
    pub fn aws_inputs(prefix: &str) -> String {
        format!("/signed/{prefix}/inputs/")
    }

    /// GCP Parameter Manager parameter holding the signing settings.
    pub fn gcp_settings(prefix: &str) -> String {
        format!("signed-{prefix}-fingerprint")
    }

    /// GCP Secret Manager secret holding the ledger.
    pub fn gcp_ledger(prefix: &str) -> String {
        format!("signed-{prefix}-state")
    }

    /// GCP Secret Manager secret holding deployer input `name`.
    pub fn gcp_input(prefix: &str, name: &str) -> String {
        format!("signed-{prefix}-input-{name}")
    }

    /// Azure resource-group tag holding the signing settings.
    pub const AZURE_SETTINGS_TAG: &str = "signing-fingerprint";

    /// Azure resource group holding the install's signing vault: `<install group>-signing`.
    ///
    /// The vault is not in the install's own group. Management holds role-assignment rights in
    /// that group, so a vault there could be opened to an identity the vendor holds; this group
    /// is setup's alone.
    pub fn azure_signing_resource_group(install_group: &str) -> String {
        format!("{install_group}-signing")
    }

    /// Azure Key Vault secret, in the install's signing vault, holding the ledger.
    pub const AZURE_LEDGER_SECRET: &str = "signing-state";

    /// IAM path of the instance profiles setup creates for machines the verifier launches.
    pub const AWS_SIGNED_PROFILE_PATH: &str = "/alien-signed/";

    /// Name of the marked instance profile for capacity group profile `base`
    /// (`<prefix>-<cluster>-<group>`). The name differs from the unmarked profile because IAM
    /// instance profile names are unique per account whatever the path.
    pub fn aws_signed_profile_name(base: &str) -> String {
        format!("{base}-signed")
    }

    /// ARN of the marked instance profile for `base` in `account`.
    pub fn aws_signed_profile_arn(account: &str, base: &str) -> String {
        format!(
            "arn:aws:iam::{account}:instance-profile{AWS_SIGNED_PROFILE_PATH}{}",
            aws_signed_profile_name(base)
        )
    }

    /// Whether an instance profile ARN names a profile under the reserved path. The check is
    /// case-sensitive and covers the whole `instance-profile/alien-signed/` prefix, so
    /// `/alien-signed-x/` and `/x/alien-signed/` are not marked.
    pub fn aws_profile_is_signed(arn: &str) -> bool {
        arn.split_once(":instance-profile")
            .is_some_and(|(head, tail)| {
                head.starts_with("arn:")
                    && tail.starts_with(AWS_SIGNED_PROFILE_PATH)
                    && tail.len() > AWS_SIGNED_PROFILE_PATH.len()
            })
    }

    /// Kubernetes ConfigMap holding the signing settings of Helm release `release`.
    pub fn kubernetes_settings(release: &str) -> String {
        format!("{release}-signing")
    }

    /// IAM role names setup may give the cloud identity of permission
    /// profile `profile`. Setup at runtime names it `<prefix>-<profile>-sa`;
    /// Terraform keeps that while it fits IAM's 64 characters and otherwise
    /// cuts it to 55 and appends 8 hex of its SHA-1.
    pub fn aws_workload_roles(prefix: &str, profile: &str) -> Vec<String> {
        const MAX: usize = 64;
        let full = format!("{prefix}-{profile}-sa");
        if full.chars().count() <= MAX {
            return vec![full];
        }
        let readable: String = full.chars().take(MAX - 9).collect();
        vec![format!("{readable}-{}", &sha1_hex(&full)[..8])]
    }

    /// GCP service account ids setup may give the cloud identity of
    /// permission profile `profile`: `<prefix>-<profile>-sa` at runtime, and
    /// Terraform's id (lowercase, `_` as `-`, `a-` in front, cut to 21 and
    /// trimmed of `-`, then 8 hex of the SHA-1 of the full name).
    pub fn gcp_workload_service_accounts(prefix: &str, profile: &str) -> Vec<String> {
        let runtime = format!("{prefix}-{profile}-sa");
        let normalized = runtime.to_lowercase().replace('_', "-");
        let readable: String = format!("a-{normalized}").chars().take(21).collect();
        let terraform = format!(
            "{}-{}",
            readable.trim_matches('-'),
            &sha1_hex(&normalized)[..8]
        );
        if terraform == runtime {
            vec![runtime]
        } else {
            vec![runtime, terraform]
        }
    }

    fn sha1_hex(text: &str) -> String {
        use sha1::{Digest, Sha1};
        hex::encode(Sha1::digest(text.as_bytes()))
    }
}

#[cfg(test)]
mod signed_profile_tests {
    use super::names::{aws_profile_is_signed, aws_signed_profile_arn};

    #[test]
    fn only_the_reserved_path_marks_a_profile() {
        let own = aws_signed_profile_arn("111122223333", "acme-prod-compute-general");
        assert_eq!(
            own,
            "arn:aws:iam::111122223333:instance-profile/alien-signed/acme-prod-compute-general-signed"
        );
        assert!(aws_profile_is_signed(&own));
        for unmarked in [
            "arn:aws:iam::111122223333:instance-profile/acme-prod-compute-general",
            "arn:aws:iam::111122223333:instance-profile/alien-signed-x/p",
            "arn:aws:iam::111122223333:instance-profile/x/alien-signed/p",
            "arn:aws:iam::111122223333:instance-profile/Alien-Signed/p",
            "arn:aws:iam::111122223333:instance-profile/alien-signed/",
            "arn:aws:iam::111122223333:role/alien-signed/p",
            "instance-profile/alien-signed/p",
            "",
        ] {
            assert!(!aws_profile_is_signed(unmarked), "{unmarked}");
        }
    }
}