summaryrefslogtreecommitdiffstatshomepage
path: root/tests/test_nvpcr.py
blob: 48464a75096cfbc1efacddd5e96c4b4550ca1198 (plain) (blame)
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
import base64
import hashlib
import json
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest import mock

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

from scripts import tpm_negative_uki, tpm_nvpcr, tpm_nvpcr_unmask, tpm_unlock

ROOT = Path(__file__).resolve().parents[1]


class NvPCRConfigTests(unittest.TestCase):
    def test_check_recipe_accepts_no_images_or_one_image(self):
        for images in ((), ("candidate.efi",)):
            output = subprocess.check_output(
                ["just", "--dry-run", "tpm-nvpcr-check", *images],
                cwd=ROOT,
                stderr=subprocess.STDOUT,
                text=True,
            )
            self.assertIn("scripts/tpm_nvpcr.py", output)

    def test_hook_adds_required_initrd_services(self):
        hook = ROOT / "etc/initcpio/install/nvpcr"
        output = subprocess.check_output(
            [
                "bash",
                "-c",
                'map() { "$@"; }; add_systemd_unit() { printf "%s\\n" "$@"; }; source "$1"; build',
                "bash",
                str(hook),
            ],
            text=True,
        ).splitlines()
        self.assertEqual(
            set(output),
            {
                "systemd-tpm2-setup-early.service",
                "systemd-pcrnvdone.service",
                "systemd-pcrextend.socket",
                "systemd-pcrextend@.service",
            },
        )
        self.assertIn(
            "etc/initcpio/install/*)",
            (ROOT / "run_onchange_after_deploy-etc.sh.tmpl").read_text(),
        )

    def test_deploy_requires_a_signed_main_image_and_backup(self):
        script = (ROOT / "run_onchange_after_deploy-etc.sh.tmpl").read_text()
        self.assertIn("backup/etc.tar", script)
        self.assertIn("backup/arch-linux-lts-fallback.efi", script)
        self.assertIn("sudo sbverify --cert", script)
        self.assertNotIn("arch-linux-hardened-nvpcr-recovery.efi", script)

    def test_pcr7_policy_is_unchanged(self):
        policy = (
            ROOT / "etc/systemd/system/systemd-pcrlock-make-policy.service.d/pcr7.conf"
        )
        self.assertIn("--pcr=7 --location=770", policy.read_text())
        for name in ("systemd-tpm2-setup.service", "systemd-tpm2-setup-early.service"):
            self.assertFalse((ROOT / "etc/systemd/system" / name).exists())

    def test_uki_signs_initrd_and_root_policies(self):
        config = (ROOT / "etc/kernel/uki.conf").read_text()
        self.assertIn("PolicyRef=initrd", config)
        self.assertIn("PolicyRef=luks-root", config)
        self.assertIn("Phases=enter-initrd", config)
        self.assertNotIn("SignInitrdPCRs=", config)

    def test_old_masks_are_not_in_source(self):
        for name in ("cryptsetup", "hardware", "login", "verity"):
            self.assertFalse((ROOT / f"etc/nvpcr/{name}.nvpcr").exists())
        self.assertFalse((ROOT / "etc/mkinitcpio.conf.d/60-no-nvpcr.conf").exists())
        for name in ("systemd-pcrlogin@.service", "systemd-pcrproduct.service"):
            self.assertFalse((ROOT / "etc/systemd/system" / name).exists())


def sections(public_key, *, policies=None, options=None):
    if policies is None:
        policies = {
            "sha256": [
                {"pcrs": [11], "ref": ref, "sig": "signature"}
                for ref in tpm_nvpcr.POLICY_REFS
            ]
        }
    if options is None:
        options = (
            "tpm2-device=auto,tpm2-measure-pcr=15,tpm2-measure-keyslot-nvpcr=cryptsetup"
        )
    return {
        ".pcrpkey": {"sha256": hashlib.sha256(public_key).hexdigest()},
        ".pcrsig": {"text": json.dumps(policies)},
        ".cmdline": {
            "text": f"rd.luks.name={tpm_nvpcr.ROOT_UUID}=root rd.luks.options={tpm_nvpcr.ROOT_UUID}={options} root=/dev/mapper/root"
        },
    }


class NvPCRImageTests(unittest.TestCase):
    def test_command_failure_reports_stderr(self):
        error = subprocess.CalledProcessError(1, ["ukify"], stderr="file not found")
        with (
            mock.patch.object(tpm_nvpcr.subprocess, "run", side_effect=error),
            self.assertRaisesRegex(RuntimeError, "ukify exited 1: file not found"),
        ):
            tpm_nvpcr.run("ukify", "inspect", "missing.efi")

    def test_initrd_has_required_units(self):
        listing = "\n".join(
            f"usr/lib/systemd/system/{unit}" for unit in tpm_nvpcr.INITRD_UNITS
        )
        tpm_nvpcr.check_initrd_listing(listing)

    def test_rejects_missing_initrd_service(self):
        listing = "\n".join(
            f"usr/lib/systemd/system/{unit}"
            for unit in tpm_nvpcr.INITRD_UNITS
            if unit != "systemd-pcrnvdone.service"
        )
        with self.assertRaisesRegex(ValueError, "systemd-pcrnvdone.service"):
            tpm_nvpcr.check_initrd_listing(listing)

    def test_valid_initrd_signature_and_root_options(self):
        tpm_nvpcr.check_sections(sections(b"public key"), b"public key")

    def test_rejects_wrong_public_key(self):
        with self.assertRaisesRegex(ValueError, "public key"):
            tpm_nvpcr.check_sections(sections(b"one"), b"two")

    def test_rejects_policy_without_initrd_reference(self):
        bad = {"sha256": [{"pcrs": [11], "ref": "system", "sig": "signature"}]}
        with self.assertRaisesRegex(ValueError, "initrd PCR 11"):
            tpm_nvpcr.check_sections(sections(b"key", policies=bad), b"key")

    def test_rejects_unsigned_initrd_policy(self):
        bad = {"sha256": [{"pcrs": [11], "ref": "initrd"}]}
        with self.assertRaisesRegex(ValueError, "initrd PCR 11"):
            tpm_nvpcr.check_sections(sections(b"key", policies=bad), b"key")

    def test_rejects_missing_root_policy(self):
        bad = {"sha256": [{"pcrs": [11], "ref": "initrd", "sig": "signature"}]}
        with self.assertRaisesRegex(ValueError, "luks-root PCR 11"):
            tpm_nvpcr.check_sections(sections(b"key", policies=bad), b"key")

    def test_pcr_signatures_match_measured_sections(self):
        key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
        private = key.private_bytes(
            serialization.Encoding.PEM,
            serialization.PrivateFormat.PKCS8,
            serialization.NoEncryption(),
        )
        public = key.public_key().public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo,
        )
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            private_path = root / "private.pem"
            public_path = root / "public.pem"
            private_path.write_bytes(private)
            private_path.chmod(0o600)
            public_path.write_bytes(public)
            image = {
                ".linux": b"kernel",
                ".initrd": b"initrd",
                ".pcrpkey": public,
                ".cmdline": b"root=/dev/mapper/root",
            }
            args = []
            for name, content in image.items():
                path = root / name.removeprefix(".")
                path.write_bytes(content)
                args.append(f"--{name.removeprefix('.')}={path}")
            signatures = []
            for ref in tpm_nvpcr.POLICY_REFS:
                result = subprocess.check_output(
                    [
                        "/usr/lib/systemd/systemd-measure",
                        "sign",
                        "--bank=sha256",
                        "--phase=enter-initrd",
                        f"--policyref={ref}",
                        f"--private-key={private_path}",
                        f"--public-key={public_path}",
                        *args,
                    ],
                    text=True,
                )
                signatures.extend(json.loads(result)["sha256"])
            image[".pcrsig"] = json.dumps({"sha256": signatures}).encode()
            with mock.patch.object(tpm_nvpcr, "PUBLIC_KEY", public_path):
                tpm_nvpcr.verify_pcr_signatures(image, public)
                changed = dict(image, **{".initrd": b"changed"})
                with self.assertRaisesRegex(ValueError, "does not match UKI contents"):
                    tpm_nvpcr.verify_pcr_signatures(changed, public)
                changed = json.loads(image[".pcrsig"])
                changed["sha256"][1]["sig"] = base64.b64encode(b"wrong").decode()
                image[".pcrsig"] = json.dumps(changed).encode()
                with self.assertRaisesRegex(
                    ValueError, "Invalid luks-root PCR 11 signature"
                ):
                    tpm_nvpcr.verify_pcr_signatures(image, public)

    def test_ukify_image_signatures_match_its_sections(self):
        key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            private = root / "private.pem"
            public = root / "public.pem"
            private.write_bytes(
                key.private_bytes(
                    serialization.Encoding.PEM,
                    serialization.PrivateFormat.PKCS8,
                    serialization.NoEncryption(),
                )
            )
            private.chmod(0o600)
            public.write_bytes(
                key.public_key().public_bytes(
                    serialization.Encoding.PEM,
                    serialization.PublicFormat.SubjectPublicKeyInfo,
                )
            )
            initrd = root / "initrd"
            initrd.write_bytes(b"test initrd")
            config = root / "uki.conf"
            config.write_text(
                f"[UKI]\nPCRPKey={public}\nPCRBanks=sha256\n\n"
                + "".join(
                    f"[PCRSignature:{ref}]\nPCRPrivateKey={private}\n"
                    f"PCRPublicKey={public}\nPhases=enter-initrd\nPolicyRef={ref}\n\n"
                    for ref in tpm_nvpcr.POLICY_REFS
                )
            )
            output = root / "test.efi"
            subprocess.run(
                [
                    "ukify",
                    "build",
                    "--config",
                    str(config),
                    "--linux=/usr/bin/true",
                    f"--initrd={initrd}",
                    f"--output={output}",
                ],
                check=True,
                capture_output=True,
            )
            sb_key = root / "secureboot.key"
            sb_cert = root / "secureboot.pem"
            subprocess.run(
                [
                    "openssl",
                    "req",
                    "-x509",
                    "-newkey",
                    "rsa:2048",
                    "-nodes",
                    "-keyout",
                    str(sb_key),
                    "-out",
                    str(sb_cert),
                    "-days",
                    "1",
                    "-subj",
                    "/CN=UKI test",
                ],
                check=True,
                capture_output=True,
            )
            signed = root / "signed.efi"
            subprocess.run(
                [
                    "sbsign",
                    "--key",
                    str(sb_key),
                    "--cert",
                    str(sb_cert),
                    "--output",
                    str(signed),
                    str(output),
                ],
                check=True,
                capture_output=True,
            )
            with mock.patch.object(tpm_nvpcr, "PUBLIC_KEY", public):
                tpm_nvpcr.verify_pcr_signatures(
                    tpm_nvpcr.read_pe_sections(signed), public.read_bytes()
                )
                negative = root / "negative.efi"
                tpm_negative_uki.remove_root_approval(
                    signed, negative, public.read_bytes()
                )
                changed = tpm_nvpcr.read_pe_sections(negative)
                tpm_nvpcr.verify_pcr_signatures(
                    changed, public.read_bytes(), refs=("initrd",)
                )
                with self.assertRaisesRegex(ValueError, "luks-root"):
                    tpm_nvpcr.verify_pcr_signatures(changed, public.read_bytes())
                resigned = root / "resigned.efi"
                subprocess.run(
                    [
                        "sbsign",
                        "--key",
                        str(sb_key),
                        "--cert",
                        str(sb_cert),
                        "--output",
                        str(resigned),
                        str(negative),
                    ],
                    check=True,
                    capture_output=True,
                )
                subprocess.run(
                    ["sbverify", "--cert", str(sb_cert), str(resigned)],
                    check=True,
                )

    def test_rejects_missing_tpm_selection(self):
        with self.assertRaisesRegex(ValueError, "option is missing"):
            tpm_nvpcr.check_sections(
                sections(
                    b"key",
                    options="tpm2-measure-pcr=15,tpm2-measure-keyslot-nvpcr=cryptsetup",
                ),
                b"key",
            )

    def test_rejects_wrong_root_uuid(self):
        image = sections(b"key")
        image[".cmdline"]["text"] = image[".cmdline"]["text"].replace(
            f"rd.luks.options={tpm_nvpcr.ROOT_UUID}=", "rd.luks.options=other="
        )
        with self.assertRaisesRegex(ValueError, "wrong LUKS UUID"):
            tpm_nvpcr.check_sections(image, b"key")


class NvPCRUnmaskTests(unittest.TestCase):
    def test_refuses_any_modified_file_before_deleting_masks(self):
        with tempfile.TemporaryDirectory() as directory:
            root = Path(directory)
            first = root / "first.nvpcr"
            changed = root / "second.nvpcr"
            first.touch()
            changed.write_text("owned by user")
            with self.assertRaisesRegex(ValueError, "not empty"):
                tpm_nvpcr_unmask.validate([first, changed])
            self.assertTrue(first.exists())

    def test_accepts_only_expected_dropin_contents(self):
        with tempfile.TemporaryDirectory() as directory:
            dropin = Path(directory) / "dropin.conf"
            dropin.write_text("changed")
            with (
                mock.patch.object(tpm_nvpcr_unmask, "DROPIN", dropin),
                self.assertRaisesRegex(ValueError, "was changed"),
            ):
                tpm_nvpcr_unmask.validate([dropin])


class TPMUnlockTests(unittest.TestCase):
    def test_combined_token_and_trial_slot(self):
        key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
        public = key.public_key().public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo,
        )
        token = {
            "type": "systemd-tpm2",
            "keyslots": ["2"],
            "tpm2-pcrs": [],
            "tpm2-pcr-bank": "sha256",
            "tpm2_pcrlock": True,
            "tpm2_pcrlock_nv": base64.b64encode(b"nv").decode(),
            "tpm2_pubkey_pcrs": [11],
            "tpm2_pubkey_ref": "luks-root",
            "tpm2_pubkey": base64.b64encode(public).decode(),
            "tpm2-blob": [base64.b64encode(b"blob").decode()] * 2,
            "tpm2-policy-hash": ["a0" * 32] * 2,
        }
        header = {"tokens": {"1": token}, "keyslots": {"0": {}, "1": {}, "2": {}}}
        self.assertEqual(
            tpm_unlock.check_header(header, public, trial=True), ("1", "2")
        )
        with self.assertRaisesRegex(ValueError, "extra keyslot"):
            tpm_unlock.check_header(header, public)
        del header["keyslots"]["1"]
        self.assertEqual(tpm_unlock.check_header(header, public), ("1", "2"))
        token["tpm2_pubkey_ref"] = "initrd"
        with self.assertRaisesRegex(ValueError, "luks-root"):
            tpm_unlock.check_header(header, public)
        token["tpm2_pubkey_ref"] = "luks-root"
        token["tpm2_pcrlock"] = False
        with self.assertRaisesRegex(ValueError, "pcrlock"):
            tpm_unlock.check_header(header, public)
        token["tpm2_pcrlock"] = True
        token["tpm2-blob"] = token["tpm2-blob"][:1]
        with self.assertRaisesRegex(ValueError, "two sealed blobs"):
            tpm_unlock.check_header(header, public)


if __name__ == "__main__":
    unittest.main()