Skip to main content

isothrum_machine/install/
root.rs

1//! The shell scripts run as root (Linux), and the pieces of those that download something and
2//! trust it only once it is checked: a fresh private work directory, gpg with a keyring of its own
3//! there, and the check of a downloaded signing key against the fingerprints pinned for it. The
4//! vendors' apt repositories an install sets up ([`super::linux`]) go through the same check, and so
5//! can an embedder's own root scripts.
6
7/// `PRIVATE_WORKDIR`'s text (a test constant), which [`PRELUDE`] starts with too.
8macro_rules! private_workdir {
9    () => {
10        r#"set -e; d="$(mktemp -d)"; trap 'rm -rf "$d"' EXIT; printf 'DPkg::Lock::Timeout "600";\n' >"$d/apt.conf"; export APT_CONFIG="$d/apt.conf""#
11    };
12}
13
14/// The start of every script run as root that downloads something: stop at the first failure,
15/// and work in a fresh private directory `$d` (`mktemp -d`, mode 0700, removed on exit). A fixed
16/// path such as `/tmp/aws` could be prepared by any local user beforehand and then run as root.
17/// apt waits up to ten minutes for the dpkg lock there (`APT_CONFIG`, a file in `$d`): a fresh
18/// Debian runs unattended-upgrades at boot, and the guided setup's Vagrant install met its lock
19/// ("Could not get lock /var/lib/dpkg/lock-frontend. It is held by process … (unattended-upgr)",
20/// exit 100) and failed instead of waiting. Every root script gets it through [`PRELUDE`]; on its
21/// own, only the tests below read it.
22#[cfg(test)]
23pub const PRIVATE_WORKDIR: &str = private_workdir!();
24
25/// A shell script run as root (through pkexec on Linux, or `sudo -n` unattended). The only way to make one is [`RootScript::new`],
26/// which starts it with [`PRELUDE`]: no root script can miss stopping at its first failure, its
27/// private work directory, apt's wait for the dpkg lock, or the C locale its output is read in.
28/// The step that runs a script as root takes this type, never a `String`.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct RootScript(String);
31
32/// What every [`RootScript`] starts with: the private work directory (`set -e`, `$d`, apt's lock wait),
33/// then the C locale, so a tool's output the script reads (`apt-cache policy`'s `Candidate:`) is
34/// the same words on every system: pkexec keeps the user's `LANG`, and apt translates its labels.
35pub const PRELUDE: &str = concat!(private_workdir!(), "; export LC_ALL=C");
36
37impl RootScript {
38    /// `body` after [`PRELUDE`]: its commands run in order, the first that fails stops the script
39    /// with its status (a command that may fail says so itself: `|| true`, `if`).
40    #[must_use]
41    pub fn new(body: impl AsRef<str>) -> Self {
42        Self(format!("{PRELUDE}; {}", body.as_ref()))
43    }
44
45    /// The script, as `sh -c` takes it.
46    #[must_use]
47    pub fn into_string(self) -> String {
48        self.0
49    }
50
51    /// The script, as `sh -c` takes it, with `first` run right after [`PRELUDE`], before its body
52    /// (a root step's proxy settings read from their file): still stopping at its first failure.
53    #[must_use]
54    pub fn with_after_prelude(self, first: &str) -> String {
55        let body = self.0.strip_prefix(PRELUDE).unwrap_or(&self.0);
56        format!("{PRELUDE}; {first}{body}")
57    }
58}
59
60impl std::ops::Deref for RootScript {
61    type Target = str;
62    fn deref(&self) -> &str {
63        &self.0
64    }
65}
66
67impl std::fmt::Display for RootScript {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        f.write_str(&self.0)
70    }
71}
72
73/// curl, installed first where a bare system has none (Debian's minimal image): every vendor
74/// install downloads with it, and without it the repository checks read as "no packages".
75/// Through apt where it is, else dnf (Fedora and the distributions built on it).
76pub const NEED_CURL: &str = r"command -v curl >/dev/null || { if command -v apt-get >/dev/null; then apt-get update; apt-get install -y curl ca-certificates; else dnf install -y curl ca-certificates; fi; }";
77
78/// unzip, for Amazon's AWS CLI bundle, through apt where it is, else dnf.
79pub const NEED_UNZIP: &str =
80    r"command -v unzip >/dev/null || { if command -v apt-get >/dev/null; then apt-get update; apt-get install -y unzip; else dnf install -y unzip; fi; }";
81
82/// gpg, for the vendors' signing keys (Debian's minimal installs have only gpgv), and a private
83/// keyring folder for it in the work directory, so root's own keyring is never read or changed.
84pub const NEED_GPG: &str = r#"command -v gpg >/dev/null || { if command -v apt-get >/dev/null; then apt-get update; apt-get install -y gnupg; else dnf install -y gnupg2; fi; }; mkdir -p -m 700 "$d/gnupg""#;
85
86/// Stops the script unless `"$d/key"`, a vendor's signing key (or keyring) just downloaded, holds
87/// exactly the keys pinned here (`fingerprints`, 40 hex digits each, their primary keys), no more
88/// and no fewer. TLS alone trusted whatever the vendor's server sent the first time; a swapped key
89/// would sign the packages apt then installs as root. Runs after [`NEED_GPG`].
90#[must_use]
91pub fn check_keys(fingerprints: &[&str], vendor: &str) -> String {
92    let want = expected(fingerprints);
93    format!(
94        r#"k="$(gpg --homedir "$d/gnupg" --batch --show-keys --with-colons "$d/key" | awk -F: '$1=="pub"{{p=1}} $1=="fpr"&&p{{print $10; p=0}}' | LC_ALL=C sort | paste -s -d ' ' -)"; [ "$k" = "{want}" ] || {{ echo "{vendor}'s signing key isn't the expected one (fingerprint {want}, got: $k). Nothing was installed." >&2; exit 1; }}"#
95    )
96}
97
98/// The primary keys' fingerprints [`check_keys`] reads from a key file, as it prints them: sorted,
99/// one space apart.
100fn expected(fingerprints: &[&str]) -> String {
101    let mut sorted = fingerprints.to_vec();
102    sorted.sort_unstable();
103    sorted.join(" ")
104}
105
106#[cfg(test)]
107mod tests {
108    #[test]
109    fn the_private_workdir_makes_apt_wait_for_the_dpkg_lock() {
110        // Regression: a fresh Debian's unattended-upgrades held the dpkg lock and the guided
111        // setup's apt-get failed with exit 100 instead of waiting.
112        assert!(
113            PRIVATE_WORKDIR.contains(r#"DPkg::Lock::Timeout "600";"#) && PRIVATE_WORKDIR.contains(r#"export APT_CONFIG="$d/apt.conf""#),
114            "{PRIVATE_WORKDIR}"
115        );
116        assert!(crate::testing::sh_parses(PRIVATE_WORKDIR), "not valid sh: {PRIVATE_WORKDIR}");
117        #[cfg(unix)]
118        {
119            let out = crate::testing::sh(&format!("{PRIVATE_WORKDIR}; cat \"$APT_CONFIG\""), &[]);
120            assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), r#"DPkg::Lock::Timeout "600";"#);
121        }
122    }
123
124    use super::*;
125
126    /// `script` run by `sh` with the user's French locale, as pkexec hands it on: its exit
127    /// code and what it printed.
128    #[cfg(unix)]
129    fn ran(script: &RootScript) -> (Option<i32>, String) {
130        let out = crate::testing::sh(script, &[("LANG", "fr_FR.UTF-8"), ("LC_ALL", "fr_FR.UTF-8")]);
131        (out.status.code, String::from_utf8_lossy(&out.stdout).into_owned())
132    }
133
134    #[test]
135    fn what_runs_after_the_prelude_comes_before_the_body() {
136        let script = RootScript::new("echo body").with_after_prelude("echo first");
137        assert_eq!(script, format!("{PRELUDE}; echo first; echo body"));
138    }
139
140    #[test]
141    fn a_root_script_is_its_body_after_the_prelude() {
142        let script = RootScript::new("apt-get install -y qemu-system");
143        assert_eq!(&*script, format!("{PRELUDE}; apt-get install -y qemu-system"));
144        assert!(PRELUDE.starts_with(PRIVATE_WORKDIR), "{PRELUDE}");
145        assert!(crate::testing::sh_parses(&script), "not valid sh: {script}");
146    }
147
148    #[cfg(unix)]
149    #[test]
150    fn a_root_script_stops_at_its_first_failing_command_with_its_status() {
151        // Regression: an install chain whose last command (a group change) succeeded made a failed
152        // `apt-get install` read as done.
153        let (code, said) = ran(&RootScript::new("echo before; sh -c 'exit 100'; echo after"));
154        assert_eq!(code, Some(100));
155        assert_eq!(said.trim(), "before");
156        // A command allowed to fail says so in the body.
157        assert_eq!(ran(&RootScript::new("false || true; echo after")), (Some(0), "after\n".to_owned()));
158    }
159
160    #[cfg(unix)]
161    #[test]
162    fn a_root_script_reads_tools_in_the_c_locale_whatever_the_users() {
163        // Regression: `apt-cache policy` printed `Candidat :` under a French LANG, and a grep for
164        // `Candidate:` never matched.
165        assert_eq!(ran(&RootScript::new(r#"echo "$LC_ALL""#)), (Some(0), "C\n".to_owned()));
166    }
167
168    #[test]
169    fn curl_and_gpg_come_through_apt_where_it_is_else_dnf() {
170        for need in [NEED_CURL, NEED_GPG, NEED_UNZIP] {
171            assert!(
172                need.contains("if command -v apt-get >/dev/null; then apt-get") && need.contains("else dnf install -y"),
173                "{need}"
174            );
175            assert!(crate::testing::sh_parses(need), "not valid sh: {need}");
176        }
177        assert!(NEED_GPG.contains("dnf install -y gnupg2"), "Fedora's package is gnupg2");
178    }
179
180    #[test]
181    fn a_keyring_is_checked_for_every_pinned_key_in_the_order_the_check_reads_them() {
182        assert_eq!(expected(&["827C", "44C6"]), "44C6 827C");
183        assert_eq!(expected(&["9DC8"]), "9DC8");
184        let check = check_keys(&["827C", "44C6"], "A vendor");
185        assert!(check.contains(r#"[ "$k" = "44C6 827C" ]"#), "{check}");
186        assert!(check.contains(r#"--homedir "$d/gnupg""#) && check.contains("LC_ALL=C sort"), "{check}");
187        assert!(
188            crate::testing::sh_parses(&format!("{PRIVATE_WORKDIR}; {NEED_GPG}; {check}")),
189            "not valid sh: {check}"
190        );
191    }
192
193    /// `check_keys(pinned)` run against a key file gpg lists as `listing` (gpg stood in for by a
194    /// shell function): whether the script went on, and what it said.
195    #[cfg(unix)]
196    fn checked(pinned: &[&str], listing: &str) -> (bool, String) {
197        let script = format!(
198            "d=/nonexistent; gpg() {{ printf '%s' '{listing}'; }}; {}; echo went on",
199            check_keys(pinned, "A vendor's archive")
200        );
201        let out = crate::testing::sh(&script, &[]);
202        (
203            String::from_utf8_lossy(&out.stdout).contains("went on"),
204            String::from_utf8_lossy(&out.stderr).into_owned(),
205        )
206    }
207
208    #[cfg(unix)]
209    #[test]
210    fn only_a_keyring_of_exactly_the_pinned_keys_goes_on() {
211        // gpg --show-keys --with-colons: each primary key's fingerprint follows its `pub` line, a
212        // subkey's its `sub` line (never counted).
213        let both = "pub:-:4096:1:ED65462EC8D5E4C5:::::\nfpr:::::::::827C:\nuid:-::::::::Vendor 2025:\npub:-:4096:1:ED444FF07D8D0BF6:::::\nfpr:::::::::44C6:\nsub:-:4096:1:A8373E18FC0D0DCB:::::\nfpr:::::::::0D76:\n";
214        assert!(checked(&["827C", "44C6"], both).0, "both pinned keys, in any order");
215        let (went_on, said) = checked(&["827C"], both);
216        assert!(!went_on && said.contains("isn't the expected one (fingerprint 827C, got: 44C6 827C)"), "{said}");
217        let (missing_went_on, missing_said) = checked(&["827C", "44C6"], "pub:-:4096:1:X:::::\nfpr:::::::::827C:\n");
218        assert!(!missing_went_on && missing_said.contains("got: 827C)"), "one missing: {missing_said}");
219        assert!(!checked(&["827C"], "<html>captive portal</html>").0);
220    }
221}