Debian Codegraph @

src/ukify/test/test_ukify.py

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 # The tests can be called via pytest:
5 # PATH=build/:$PATH pytest -v src/ukify/test/test_ukify.py
6 # or directly:
7 # PATH=build/:$PATH src/ukify/test/test_ukify.py
8 # or via the meson test machinery output:
9 # meson test -C build test-ukify -v
10 # or without verbose output:
11 # meson test -C build test-ukify
12
13 # pylint: disable=unused-import,import-outside-toplevel,useless-else-on-loop
14 # pylint: disable=consider-using-with,wrong-import-position,unspecified-encoding
15 # pylint: disable=protected-access,redefined-outer-name
16
17 import base64
18 import glob
19 import json
20 import os
21 import pathlib
22 import re
23 import shutil
24 import subprocess
25 import sys
26 import tempfile
27 import textwrap
28
29 try:
30 import pytest
31 except ImportError as e:
32 print(str(e), file=sys.stderr)
33 sys.exit(77)
34
35 try:
36 import pefile
37 except ImportError as e:
38 print(str(e), file=sys.stderr)
39 sys.exit(77)
40
41 # We import ukify.py, which is a template file. But only __version__ is
42 # substituted, which we don't care about here. Having the .py suffix makes it
43 # easier to import the file.
44 sys.path.append(os.path.dirname(__file__) + '/..')
45 import ukify
46
47 # Skip if we're running on an architecture that does not use UEFI.
48 try:
49 ukify.guess_efi_arch()
50 except ValueError as e:
51 print(str(e), file=sys.stderr)
52 sys.exit(77)
53
54 build_root = os.getenv('PROJECT_BUILD_ROOT')
55 try:
56 slow_tests = bool(int(os.getenv('SYSTEMD_SLOW_TESTS', '1')))
57 except ValueError:
58 slow_tests = True
59
60 arg_tools = ['--tools', build_root] if build_root else []
61 if (
62 build_root
63 and (p := pathlib.Path(f'{build_root}/linux{ukify.guess_efi_arch()}.efi.stub')).exists()
64 ): # fmt: skip
65 arg_tools += ['--stub', p]
66
67
68 def systemd_measure():
69 opts = ukify.create_parser().parse_args(arg_tools)
70 return ukify.find_tool('systemd-measure', opts=opts)
71
72
73 def test_guess_efi_arch():
74 arch = ukify.guess_efi_arch()
75 assert arch in ukify.EFI_ARCHES
76
77
78 def test_shell_join():
79 assert ukify.shell_join(['a', 'b', ' ']) == "a b ' '"
80
81
82 def test_round_up():
83 assert ukify.round_up(0) == 0
84 assert ukify.round_up(4095) == 4096
85 assert ukify.round_up(4096) == 4096
86 assert ukify.round_up(4097) == 8192
87
88
89 def test_namespace_creation():
90 ns = ukify.create_parser().parse_args(())
91 assert ns.linux is None
92 assert ns.initrd is None
93
94
95 def test_config_example():
96 ex = ukify.config_example()
97 assert '[UKI]' in ex
98 assert 'Splash = BMP' in ex
99
100
101 def test_apply_config(tmp_path):
102 config = tmp_path / 'config1.conf'
103 config.write_text(
104 textwrap.dedent(
105 f'''
106 [UKI]
107 Linux = LINUX
108 Initrd = initrd1 initrd2
109 initrd3
110 Cmdline = 1 2 3 4 5
111 6 7 8
112 OSRelease = @some/path1
113 DeviceTree = some/path2
114 Splash = some/path3
115 Uname = 1.2.3
116 EFIArch=arm
117 Stub = some/path4
118 PCRBanks = sha512,sha1
119 SigningEngine = engine1
120 SecureBootPrivateKey = some/path5
121 SecureBootCertificate = some/path6
122 SignKernel = no
123
124 [PCRSignature:NAME]
125 PCRPrivateKey = some/path7
126 PCRPublicKey = some/path8
127 Phases = {':'.join(ukify.KNOWN_PHASES)}
128 '''
129 )
130 )
131
132 ns = ukify.create_parser().parse_args(['build'])
133 ns.linux = None
134 ns.initrd = []
135 ukify.apply_config(ns, config)
136
137 assert ns.linux == pathlib.Path('LINUX')
138 assert ns.initrd == [
139 pathlib.Path('initrd1'),
140 pathlib.Path('initrd2'),
141 pathlib.Path('initrd3'),
142 ]
143 assert ns.cmdline == '1 2 3 4 5\n6 7 8'
144 assert ns.os_release == '@some/path1'
145 assert ns.devicetree == pathlib.Path('some/path2')
146 assert ns.splash == pathlib.Path('some/path3')
147 assert ns.efi_arch == 'arm'
148 assert ns.stub == pathlib.Path('some/path4')
149 assert ns.pcr_banks == ['sha512', 'sha1']
150 assert ns.signing_engine == 'engine1'
151 assert ns.sb_key == 'some/path5'
152 assert ns.sb_cert == 'some/path6'
153 assert ns.sign_kernel is False
154
155 assert ns._groups == ['NAME']
156 assert ns.pcr_private_keys == ['some/path7']
157 assert ns.pcr_public_keys == ['some/path8']
158 assert ns.phase_path_groups == [['enter-initrd:leave-initrd:sysinit:ready:shutdown:final']]
159
160 ukify.finalize_options(ns)
161
162 assert ns.linux == pathlib.Path('LINUX')
163 assert ns.initrd == [
164 pathlib.Path('initrd1'),
165 pathlib.Path('initrd2'),
166 pathlib.Path('initrd3'),
167 ]
168 assert ns.cmdline == '1 2 3 4 5 6 7 8'
169 assert ns.os_release == pathlib.Path('some/path1')
170 assert ns.devicetree == pathlib.Path('some/path2')
171 assert ns.splash == pathlib.Path('some/path3')
172 assert ns.efi_arch == 'arm'
173 assert ns.stub == pathlib.Path('some/path4')
174 assert ns.pcr_banks == ['sha512', 'sha1']
175 assert ns.signing_engine == 'engine1'
176 assert ns.sb_key == 'some/path5'
177 assert ns.sb_cert == pathlib.Path('some/path6')
178 assert ns.sign_kernel is False
179
180 assert ns._groups == ['NAME']
181 assert ns.pcr_private_keys == ['some/path7']
182 assert ns.pcr_public_keys == ['some/path8']
183 assert ns.phase_path_groups == [['enter-initrd:leave-initrd:sysinit:ready:shutdown:final']]
184
185
186 def test_parse_args_minimal():
187 with pytest.raises(ValueError):
188 ukify.parse_args([])
189
190 opts = ukify.parse_args('arg1 arg2'.split())
191 assert opts.linux == pathlib.Path('arg1')
192 assert opts.initrd == [pathlib.Path('arg2')]
193 assert opts.os_release in (
194 pathlib.Path('/etc/os-release'),
195 pathlib.Path('/usr/lib/os-release'),
196 )
197
198
199 def test_parse_args_many_deprecated():
200 opts = ukify.parse_args(
201 [
202 '/ARG1',
203 '///ARG2',
204 '/ARG3 WITH SPACE',
205 '--cmdline=a b c',
206 '--os-release=K1=V1\nK2=V2',
207 '--devicetree=DDDDTTTT',
208 '--splash=splash',
209 '--pcrpkey=PATH',
210 '--uname=1.2.3',
211 '--stub=STUBPATH',
212 '--pcr-private-key=PKEY1',
213 '--pcr-public-key=PKEY2',
214 '--pcr-banks=SHA1,SHA256',
215 '--signing-engine=ENGINE',
216 '--secureboot-private-key=SBKEY',
217 '--secureboot-certificate=SBCERT',
218 '--sign-kernel',
219 '--no-sign-kernel',
220 '--tools=TOOLZ///',
221 '--output=OUTPUT',
222 '--measure',
223 '--no-measure',
224 ]
225 )
226 assert opts.linux == pathlib.Path('/ARG1')
227 assert opts.initrd == [pathlib.Path('/ARG2'), pathlib.Path('/ARG3 WITH SPACE')]
228 assert opts.cmdline == 'a b c'
229 assert opts.os_release == 'K1=V1\nK2=V2'
230 assert opts.devicetree == pathlib.Path('DDDDTTTT')
231 assert opts.splash == pathlib.Path('splash')
232 assert opts.pcrpkey == pathlib.Path('PATH')
233 assert opts.uname == '1.2.3'
234 assert opts.stub == pathlib.Path('STUBPATH')
235 assert opts.pcr_private_keys == ['PKEY1']
236 assert opts.pcr_public_keys == ['PKEY2']
237 assert opts.pcr_banks == ['SHA1', 'SHA256']
238 assert opts.signing_engine == 'ENGINE'
239 assert opts.sb_key == 'SBKEY'
240 assert opts.sb_cert == pathlib.Path('SBCERT')
241 assert opts.sign_kernel is False
242 assert opts.tools == [pathlib.Path('TOOLZ/')]
243 assert opts.output == pathlib.Path('OUTPUT')
244 assert opts.measure is False
245
246
247 def test_parse_args_many():
248 opts = ukify.parse_args(
249 [
250 'build',
251 '--linux=/ARG1',
252 '--initrd=///ARG2',
253 '--initrd=/ARG3 WITH SPACE',
254 '--cmdline=a b c',
255 '--os-release=K1=V1\nK2=V2',
256 '--devicetree=DDDDTTTT',
257 '--splash=splash',
258 '--pcrpkey=PATH',
259 '--uname=1.2.3',
260 '--stub=STUBPATH',
261 '--pcr-private-key=PKEY1',
262 '--pcr-public-key=PKEY2',
263 '--pcr-banks=SHA1,SHA256',
264 '--signing-engine=ENGINE',
265 '--secureboot-private-key=SBKEY',
266 '--secureboot-certificate=SBCERT',
267 '--sign-kernel',
268 '--no-sign-kernel',
269 '--tools=TOOLZ///',
270 '--output=OUTPUT',
271 '--measure',
272 '--no-measure',
273 '--policy-digest',
274 '--no-policy-digest',
275 ]
276 )
277 assert opts.linux == pathlib.Path('/ARG1')
278 assert opts.initrd == [pathlib.Path('/ARG2'), pathlib.Path('/ARG3 WITH SPACE')]
279 assert opts.cmdline == 'a b c'
280 assert opts.os_release == 'K1=V1\nK2=V2'
281 assert opts.devicetree == pathlib.Path('DDDDTTTT')
282 assert opts.splash == pathlib.Path('splash')
283 assert opts.pcrpkey == pathlib.Path('PATH')
284 assert opts.uname == '1.2.3'
285 assert opts.stub == pathlib.Path('STUBPATH')
286 assert opts.pcr_private_keys == ['PKEY1']
287 assert opts.pcr_public_keys == ['PKEY2']
288 assert opts.pcr_banks == ['SHA1', 'SHA256']
289 assert opts.signing_engine == 'ENGINE'
290 assert opts.sb_key == 'SBKEY'
291 assert opts.sb_cert == pathlib.Path('SBCERT')
292 assert opts.sign_kernel is False
293 assert opts.tools == [pathlib.Path('TOOLZ/')]
294 assert opts.output == pathlib.Path('OUTPUT')
295 assert opts.measure is False
296 assert opts.policy_digest is False
297
298
299 def test_parse_sections():
300 opts = ukify.parse_args(
301 [
302 'build',
303 '--linux=/ARG1',
304 '--initrd=/ARG2',
305 '--section=test:TESTTESTTEST',
306 '--section=test2:@FILE',
307 ]
308 )
309
310 assert opts.linux == pathlib.Path('/ARG1')
311 assert opts.initrd == [pathlib.Path('/ARG2')]
312 assert len(opts.sections) == 2
313
314 assert opts.sections[0].name == 'test'
315 assert isinstance(opts.sections[0].content, pathlib.Path)
316 assert opts.sections[0].tmpfile
317 assert opts.sections[0].measure is False
318
319 assert opts.sections[1].name == 'test2'
320 assert opts.sections[1].content == pathlib.Path('FILE')
321 assert opts.sections[1].tmpfile is None
322 assert opts.sections[1].measure is False
323
324
325 def test_config_priority(tmp_path):
326 config = tmp_path / 'config1.conf'
327 # config: use pesign and give certdir + certname
328 config.write_text(
329 textwrap.dedent(
330 f'''
331 [UKI]
332 Linux = LINUX
333 Initrd = initrd1 initrd2
334 initrd3
335 Cmdline = 1 2 3 4 5
336 6 7 8
337 OSRelease = @some/path1
338 DeviceTree = some/path2
339 Splash = some/path3
340 Uname = 1.2.3
341 EFIArch = arm
342 Stub = some/path4
343 PCRBanks = sha512,sha1
344 SigningEngine = engine1
345 SecureBootSigningTool = pesign
346 SecureBootCertificateDir = some/path5
347 SecureBootCertificateName = some/name1
348 SignKernel = no
349
350 [PCRSignature:NAME]
351 PCRPrivateKey = some/path7
352 PCRPublicKey = some/path8
353 Phases = {':'.join(ukify.KNOWN_PHASES)}
354 '''
355 )
356 )
357
358 # args: use sbsign and give key + cert, should override pesign
359 opts = ukify.parse_args(
360 [
361 'build',
362 '--linux=/ARG1',
363 '--initrd=///ARG2',
364 '--initrd=/ARG3 WITH SPACE',
365 '--cmdline= a b c ',
366 '--os-release=K1=V1\nK2=V2',
367 '--devicetree=DDDDTTTT',
368 '--splash=splash',
369 '--pcrpkey=PATH',
370 '--uname=1.2.3',
371 '--stub=STUBPATH',
372 '--pcr-private-key=PKEY1',
373 '--pcr-public-key=PKEY2',
374 '--pcr-banks=SHA1,SHA256',
375 '--signing-engine=ENGINE',
376 '--signtool=sbsign',
377 '--secureboot-private-key=SBKEY',
378 '--secureboot-certificate=SBCERT',
379 '--sign-kernel',
380 '--no-sign-kernel',
381 '--tools=TOOLZ///',
382 '--output=OUTPUT',
383 '--measure',
384 ]
385 )
386
387 ukify.apply_config(opts, config)
388 ukify.finalize_options(opts)
389
390 assert opts.linux == pathlib.Path('/ARG1')
391 assert opts.initrd == [
392 pathlib.Path('initrd1'),
393 pathlib.Path('initrd2'),
394 pathlib.Path('initrd3'),
395 pathlib.Path('/ARG2'),
396 pathlib.Path('/ARG3 WITH SPACE'),
397 ]
398 assert opts.cmdline == 'a b c'
399 assert opts.os_release == 'K1=V1\nK2=V2'
400 assert opts.devicetree == pathlib.Path('DDDDTTTT')
401 assert opts.splash == pathlib.Path('splash')
402 assert opts.pcrpkey == pathlib.Path('PATH')
403 assert opts.uname == '1.2.3'
404 assert opts.stub == pathlib.Path('STUBPATH')
405 assert opts.pcr_private_keys == ['PKEY1', 'some/path7']
406 assert opts.pcr_public_keys == ['PKEY2', 'some/path8']
407 assert opts.pcr_banks == ['SHA1', 'SHA256']
408 assert opts.signing_engine == 'ENGINE'
409 assert opts.signtool == 'sbsign' # from args
410 assert opts.sb_key == 'SBKEY' # from args
411 assert opts.sb_cert == pathlib.Path('SBCERT') # from args
412 assert opts.sb_certdir == 'some/path5' # from config
413 assert opts.sb_cert_name == 'some/name1' # from config
414 assert opts.sign_kernel is False
415 assert opts.tools == [pathlib.Path('TOOLZ/')]
416 assert opts.output == pathlib.Path('OUTPUT')
417 assert opts.measure is True
418
419
420 def test_help(capsys):
421 with pytest.raises(SystemExit):
422 ukify.parse_args(['--help'])
423 out = capsys.readouterr()
424 assert '--section' in out.out
425 assert not out.err
426
427
428 def test_help_display(capsys):
429 with pytest.raises(SystemExit):
430 ukify.parse_args(['inspect', '--help'])
431 out = capsys.readouterr()
432 assert '--section' in out.out
433 assert not out.err
434
435
436 def test_help_error_deprecated(capsys):
437 with pytest.raises(SystemExit):
438 ukify.parse_args(['a', 'b', '--no-such-option'])
439 out = capsys.readouterr()
440 assert not out.out
441 assert '--no-such-option' in out.err
442 assert len(out.err.splitlines()) == 1
443
444
445 def test_help_error(capsys):
446 with pytest.raises(SystemExit):
447 ukify.parse_args(['build', '--no-such-option'])
448 out = capsys.readouterr()
449 assert not out.out
450 assert '--no-such-option' in out.err
451 assert len(out.err.splitlines()) == 1
452
453
454 @pytest.fixture(scope='session')
455 def kernel_initrd():
456 items = sorted(glob.glob('/lib/modules/*/vmlinuz'))
457 if not items:
458 items = sorted(glob.glob('/boot/vmlinuz*'))
459 # Drop entries we cannot read (e.g. /boot/vmlinuz.old with mode 0600 on
460 # GitHub-hosted runners), the test opens the file later and would fail.
461 items = [p for p in items if os.access(p, os.R_OK)]
462 if not items:
463 return None
464
465 # This doesn't necessarily give us the latest version, since we're just
466 # using alphanumeric ordering. But this is fine, a predictable result is
467 # enough.
468 linux = items[-1]
469
470 # We don't look _into_ the initrd. Any file is OK.
471 return ['--linux', linux, '--initrd', ukify.__file__]
472
473
474 def test_check_splash():
475 try:
476 # pyflakes: noqa
477 import PIL # noqa
478 except ImportError:
479 pytest.skip('PIL not available')
480
481 with pytest.raises(OSError):
482 ukify.check_splash(os.devnull)
483
484
485 def test_basic_operation(kernel_initrd, tmp_path):
486 if kernel_initrd is None:
487 pytest.skip('linux+initrd not found')
488
489 output = f'{tmp_path}/basic.efi'
490 opts = ukify.parse_args(
491 [
492 'build',
493 *kernel_initrd,
494 f'--output={output}',
495 ]
496 )
497 try:
498 ukify.check_inputs(opts)
499 except OSError as e:
500 pytest.skip(str(e))
501
502 ukify.make_uki(opts)
503
504 # let's check that objdump likes the resulting file
505 subprocess.check_output(['objdump', '-h', output])
506
507 shutil.rmtree(tmp_path)
508
509
510 def test_sections(kernel_initrd, tmp_path):
511 if kernel_initrd is None:
512 pytest.skip('linux+initrd not found')
513
514 output = f'{tmp_path}/basic.efi'
515 opts = ukify.parse_args(
516 [
517 'build',
518 *kernel_initrd,
519 f'--output={output}',
520 '--uname=1.2.3',
521 '--cmdline=ARG1 ARG2 ARG3',
522 '--os-release=K1=V1\nK2=V2\n',
523 '--section=.test:CONTENTZ',
524 ]
525 )
526
527 try:
528 ukify.check_inputs(opts)
529 except OSError as e:
530 pytest.skip(str(e))
531
532 ukify.make_uki(opts)
533
534 # let's check that objdump likes the resulting file
535 dump = subprocess.check_output(['objdump', '-h', output], text=True)
536
537 for sect in 'text osrel cmdline linux initrd uname test'.split():
538 assert re.search(rf'^\s*\d+\s+\.{sect}\s+[0-9a-f]+', dump, re.MULTILINE)
539
540 shutil.rmtree(tmp_path)
541
542
543 def test_addon(tmp_path):
544 output = f'{tmp_path}/addon.efi'
545 args = [
546 'build',
547 f'--output={output}',
548 '--cmdline=ARG1 ARG2 ARG3',
549 '''--sbat=sbat,1,foo
550 foo,1
551 bar,2
552 ''',
553 '--section=.test:CONTENTZ',
554 '''--sbat=sbat,1,foo
555 baz,3
556 ''',
557 ]
558 if stub := os.getenv('EFI_ADDON'):
559 args += [f'--stub={stub}']
560 expected_exceptions = ()
561 else:
562 expected_exceptions = (FileNotFoundError,)
563
564 opts = ukify.parse_args(args)
565 try:
566 ukify.check_inputs(opts)
567 except expected_exceptions as e:
568 pytest.skip(str(e))
569
570 ukify.make_uki(opts)
571
572 # let's check that objdump likes the resulting file
573 dump = subprocess.check_output(['objdump', '-h', output], text=True)
574
575 for sect in 'text cmdline test sbat'.split():
576 assert re.search(rf'^\s*\d+\s+\.{sect}\s+[0-9a-f]+', dump, re.MULTILINE)
577
578 pe = pefile.PE(output, fast_load=True)
579 found = False
580
581 for section in pe.sections:
582 if section.Name.rstrip(b'\x00').decode() == '.sbat':
583 assert found is False
584 split = section.get_data().rstrip(b'\x00').decode().splitlines()
585 assert split == [
586 'sbat,1,SBAT Version,sbat,1,https://github.com/rhboot/shim/blob/main/SBAT.md',
587 'foo,1',
588 'bar,2',
589 'baz,3',
590 ]
591 found = True
592
593 assert found is True
594
595
596 def unbase64(filename):
597 tmp = tempfile.NamedTemporaryFile()
598 base64.decode(filename.open('rb'), tmp)
599 tmp.flush()
600 return tmp
601
602
603 def test_uname_scraping(kernel_initrd):
604 if kernel_initrd is None:
605 pytest.skip('linux+initrd not found')
606
607 assert kernel_initrd[0] == '--linux'
608 uname = ukify.Uname.scrape(kernel_initrd[1])
609 assert re.match(r'\d+\.\d+\.\d+', uname)
610
611
612 @pytest.mark.skipif(not slow_tests, reason='slow')
613 @pytest.mark.parametrize('days', [365 * 10, None])
614 def test_efi_signing_sbsign(days, kernel_initrd, tmp_path):
615 if kernel_initrd is None:
616 pytest.skip('linux+initrd not found')
617 if not shutil.which('sbsign'):
618 pytest.skip('sbsign not found')
619
620 ourdir = pathlib.Path(__file__).parent
621 cert = unbase64(ourdir / 'example.signing.crt.base64')
622 key = unbase64(ourdir / 'example.signing.key.base64')
623
624 output = f'{tmp_path}/signed.efi'
625 args = [
626 'build',
627 *kernel_initrd,
628 f'--output={output}',
629 '--uname=1.2.3',
630 '--cmdline=ARG1 ARG2 ARG3',
631 f'--secureboot-certificate={cert.name}',
632 f'--secureboot-private-key={key.name}',
633 ]
634 if days is not None:
635 args += [f'--secureboot-certificate-validity={days}']
636
637 opts = ukify.parse_args(args)
638
639 try:
640 ukify.check_inputs(opts)
641 except OSError as e:
642 pytest.skip(str(e))
643
644 ukify.make_uki(opts)
645
646 if shutil.which('sbverify'):
647 # let's check that sbverify likes the resulting file
648 dump = subprocess.check_output(
649 [
650 'sbverify',
651 '--cert', cert.name,
652 output,
653 ],
654 text=True,
655 ) # fmt: skip
656
657 assert 'Signature verification OK' in dump
658
659 shutil.rmtree(tmp_path)
660
661
662 @pytest.mark.skipif(not slow_tests, reason='slow')
663 def test_efi_signing_pesign(kernel_initrd, tmp_path):
664 if kernel_initrd is None:
665 pytest.skip('linux+initrd not found')
666 if not shutil.which('pesign'):
667 pytest.skip('pesign not found')
668
669 nss_db = f'{tmp_path}/nss_db'
670 name = 'Test_Secureboot'
671 author = 'systemd'
672
673 subprocess.check_call(['mkdir', '-p', nss_db])
674 cmd = f'certutil -N --empty-password -d {nss_db}'.split(' ')
675 subprocess.check_call(cmd)
676 cmd = f'efikeygen -d {nss_db} -S -k -c CN={author} -n {name}'.split(' ')
677 subprocess.check_call(cmd)
678
679 output = f'{tmp_path}/signed.efi'
680 opts = ukify.parse_args(
681 [
682 'build',
683 *kernel_initrd,
684 f'--output={output}',
685 '--uname=1.2.3',
686 '--signtool=pesign',
687 '--cmdline=ARG1 ARG2 ARG3',
688 f'--secureboot-certificate-name={name}',
689 f'--secureboot-certificate-dir={nss_db}',
690 ]
691 )
692
693 try:
694 ukify.check_inputs(opts)
695 except OSError as e:
696 pytest.skip(str(e))
697
698 ukify.make_uki(opts)
699
700 # let's check that pesign likes the resulting file
701 dump = subprocess.check_output(
702 [
703 'pesign',
704 '-S',
705 '-i', output,
706 ],
707 text=True,
708 ) # fmt: skip
709
710 assert f"The signer's common name is {author}" in dump
711
712 shutil.rmtree(tmp_path)
713
714
715 def test_inspect(kernel_initrd, tmp_path, capsys, osrel=True):
716 if kernel_initrd is None:
717 pytest.skip('linux+initrd not found')
718 if not shutil.which('sbsign'):
719 pytest.skip('sbsign not found')
720
721 ourdir = pathlib.Path(__file__).parent
722 cert = unbase64(ourdir / 'example.signing.crt.base64')
723 key = unbase64(ourdir / 'example.signing.key.base64')
724
725 output = f'{tmp_path}/signed2.efi'
726 uname_arg = '1.2.3'
727 osrel_arg = 'Linux' if osrel else ''
728 cmdline_arg = 'ARG1 ARG2 ARG3'
729
730 args = [
731 'build',
732 *kernel_initrd,
733 f'--cmdline={cmdline_arg}',
734 f'--os-release={osrel_arg}',
735 f'--uname={uname_arg}',
736 f'--output={output}',
737 ] + arg_tools
738 if slow_tests:
739 args += [
740 f'--secureboot-certificate={cert.name}',
741 f'--secureboot-private-key={key.name}',
742 ]
743
744 opts = ukify.parse_args(args)
745
746 ukify.check_inputs(opts)
747 ukify.make_uki(opts)
748
749 opts = ukify.parse_args(['inspect', output])
750 ukify.inspect_sections(opts)
751
752 text = capsys.readouterr().out
753
754 if osrel:
755 expected_osrel = f'.osrel:\n size: {len(osrel_arg)}'
756 assert expected_osrel in text
757 else:
758 assert '.osrel:' not in text
759
760 expected_cmdline = f'.cmdline:\n size: {len(cmdline_arg)}'
761 assert expected_cmdline in text
762 expected_uname = f'.uname:\n size: {len(uname_arg)}'
763 assert expected_uname in text
764
765 expected_initrd = '.initrd:\n size:'
766 assert expected_initrd in text
767 expected_linux = '.linux:\n size:'
768 assert expected_linux in text
769
770 shutil.rmtree(tmp_path)
771
772
773 def test_inspect_no_osrel(kernel_initrd, tmp_path, capsys):
774 test_inspect(kernel_initrd, tmp_path, capsys, osrel=False)
775
776
777 @pytest.mark.skipif(not slow_tests, reason='slow')
778 def test_pcr_signing(kernel_initrd, tmp_path):
779 if kernel_initrd is None:
780 pytest.skip('linux+initrd not found')
781 try:
782 systemd_measure()
783 except ValueError:
784 pytest.skip('systemd-measure not found')
785
786 ourdir = pathlib.Path(__file__).parent
787 pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
788 priv = unbase64(ourdir / 'example.tpm2-pcr-private.pem.base64')
789
790 output = f'{tmp_path}/signed.efi'
791 args = [
792 'build',
793 *kernel_initrd,
794 f'--output={output}',
795 '--uname=1.2.3',
796 '--cmdline=ARG1 ARG2 ARG3',
797 '--os-release=ID=foobar\n',
798 '--pcr-banks=sha384', # sha1 might not be allowed, use something else
799 f'--pcr-private-key={priv.name}',
800 ] + arg_tools
801
802 # If the public key is not explicitly specified, it is derived
803 # automatically. Let's make sure everything works as expected both when the
804 # public keys is specified explicitly and when it is derived from the
805 # private key.
806 for extra in ([f'--pcrpkey={pub.name}', f'--pcr-public-key={pub.name}'], []):
807 opts = ukify.parse_args(args + extra)
808 try:
809 ukify.check_inputs(opts)
810 except OSError as e:
811 pytest.skip(str(e))
812
813 ukify.make_uki(opts)
814
815 # let's check that objdump likes the resulting file
816 dump = subprocess.check_output(['objdump', '-h', output], text=True)
817
818 for sect in 'text osrel cmdline linux initrd uname pcrsig'.split():
819 assert re.search(rf'^\s*\d+\s+\.{sect}\s+[0-9a-f]+', dump, re.MULTILINE)
820
821 # objcopy fails when called without an output argument (EPERM).
822 # It also fails when called with /dev/null (file truncated).
823 # It also fails when called with /dev/zero (because it reads the
824 # output file, infinitely in this case.)
825 # So let's just call it with a dummy output argument.
826 subprocess.check_call(
827 [
828 'objcopy',
829 *(
830 f'--dump-section=.{n}={tmp_path}/out.{n}'
831 for n in ('pcrpkey', 'pcrsig', 'osrel', 'uname', 'cmdline')
832 ),
833 output,
834 tmp_path / 'dummy',
835 ],
836 text=True,
837 )
838
839 assert open(tmp_path / 'out.pcrpkey').read() == open(pub.name).read()
840 assert open(tmp_path / 'out.osrel').read() == 'ID=foobar\n'
841 assert open(tmp_path / 'out.uname').read() == '1.2.3'
842 assert open(tmp_path / 'out.cmdline').read() == 'ARG1 ARG2 ARG3'
843 sig = open(tmp_path / 'out.pcrsig').read()
844 sig = json.loads(sig)
845 assert list(sig.keys()) == ['sha384']
846 assert len(sig['sha384']) == 4 # four items for four phases
847
848 shutil.rmtree(tmp_path)
849
850
851 @pytest.mark.skipif(not slow_tests, reason='slow')
852 def test_pcr_signing2(kernel_initrd, tmp_path):
853 if kernel_initrd is None:
854 pytest.skip('linux+initrd not found')
855 try:
856 systemd_measure()
857 except ValueError:
858 pytest.skip('systemd-measure not found')
859
860 ourdir = pathlib.Path(__file__).parent
861 pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
862 priv = unbase64(ourdir / 'example.tpm2-pcr-private.pem.base64')
863 pub2 = unbase64(ourdir / 'example.tpm2-pcr-public2.pem.base64')
864 priv2 = unbase64(ourdir / 'example.tpm2-pcr-private2.pem.base64')
865
866 # simulate a microcode file
867 with open(f'{tmp_path}/microcode', 'wb') as microcode:
868 microcode.write(b'1234567890')
869
870 output = f'{tmp_path}/signed.efi'
871 assert kernel_initrd[0] == '--linux'
872 opts = ukify.parse_args(
873 [
874 'build',
875 *kernel_initrd[:2],
876 f'--initrd={microcode.name}',
877 *kernel_initrd[2:],
878 f'--output={output}',
879 '--uname=1.2.3',
880 '--cmdline=ARG1 ARG2 ARG3',
881 '--os-release=ID=foobar\n',
882 '--pcr-banks=sha384',
883 f'--pcrpkey={pub2.name}',
884 f'--pcr-public-key={pub.name}',
885 f'--pcr-private-key={priv.name}',
886 '--phases=enter-initrd enter-initrd:leave-initrd',
887 f'--pcr-public-key={pub2.name}',
888 f'--pcr-private-key={priv2.name}',
889 '--phases=sysinit ready shutdown final', # yes, those phase paths are not reachable
890 ]
891 + arg_tools
892 )
893
894 try:
895 ukify.check_inputs(opts)
896 except OSError as e:
897 pytest.skip(str(e))
898
899 ukify.make_uki(opts)
900
901 # let's check that objdump likes the resulting file
902 dump = subprocess.check_output(['objdump', '-h', output], text=True)
903
904 for sect in 'text osrel cmdline linux initrd uname pcrsig'.split():
905 assert re.search(rf'^\s*\d+\s+\.{sect}\s+[0-9a-f]+', dump, re.MULTILINE)
906
907 subprocess.check_call(
908 [
909 'objcopy',
910 *(
911 f'--dump-section=.{n}={tmp_path}/out.{n}'
912 for n in ('pcrpkey', 'pcrsig', 'osrel', 'uname', 'cmdline', 'initrd')
913 ),
914 output,
915 tmp_path / 'dummy',
916 ],
917 text=True,
918 )
919
920 assert open(tmp_path / 'out.pcrpkey').read() == open(pub2.name).read()
921 assert open(tmp_path / 'out.osrel').read() == 'ID=foobar\n'
922 assert open(tmp_path / 'out.uname').read() == '1.2.3'
923 assert open(tmp_path / 'out.cmdline').read() == 'ARG1 ARG2 ARG3'
924 assert open(tmp_path / 'out.initrd', 'rb').read(10) == b'1234567890'
925
926 sig = open(tmp_path / 'out.pcrsig').read()
927 sig = json.loads(sig)
928 assert list(sig.keys()) == ['sha384']
929 assert len(sig['sha384']) == 6 # six items for six phases paths
930
931 shutil.rmtree(tmp_path)
932
933
934 def test_key_cert_generation(tmp_path):
935 opts = ukify.parse_args(
936 [
937 'genkey',
938 f'--pcr-public-key={tmp_path / "pcr1.pub.pem"}',
939 f'--pcr-private-key={tmp_path / "pcr1.priv.pem"}',
940 '--phases=enter-initrd enter-initrd:leave-initrd',
941 f'--pcr-public-key={tmp_path / "pcr2.pub.pem"}',
942 f'--pcr-private-key={tmp_path / "pcr2.priv.pem"}',
943 '--phases=sysinit ready',
944 f'--secureboot-private-key={tmp_path / "sb.priv.pem"}',
945 f'--secureboot-certificate={tmp_path / "sb.cert.pem"}',
946 ]
947 )
948 assert opts.verb == 'genkey'
949 ukify.check_cert_and_keys_nonexistent(opts)
950
951 pytest.importorskip('cryptography')
952
953 ukify.generate_keys(opts)
954
955 if not shutil.which('openssl'):
956 return
957
958 for key in (tmp_path / 'pcr1.priv.pem', tmp_path / 'pcr2.priv.pem', tmp_path / 'sb.priv.pem'):
959 out = subprocess.check_output(
960 [
961 'openssl', 'rsa',
962 '-in', key,
963 '-text',
964 '-noout',
965 ],
966 text=True,
967 ) # fmt: skip
968 assert 'Private-Key' in out
969 assert '2048 bit' in out
970
971 for pub in (tmp_path / 'pcr1.pub.pem', tmp_path / 'pcr2.pub.pem'):
972 out = subprocess.check_output(
973 [
974 'openssl', 'rsa',
975 '-pubin',
976 '-in', pub,
977 '-text',
978 '-noout',
979 ],
980 text=True,
981 ) # fmt: skip
982 assert 'Public-Key' in out
983 assert '2048 bit' in out
984
985 out = subprocess.check_output(
986 [
987 'openssl', 'x509',
988 '-in', tmp_path / 'sb.cert.pem',
989 '-text',
990 '-noout',
991 ],
992 text=True,
993 ) # fmt: skip
994 assert 'Certificate' in out
995 assert re.search(r'Issuer: CN\s?=\s?SecureBoot signing key on host', out)
996
997
998 @pytest.mark.skipif(not slow_tests, reason='slow')
999 def test_join_pcrsig(capsys, kernel_initrd, tmp_path):
1000 if kernel_initrd is None:
1001 pytest.skip('linux+initrd not found')
1002 try:
1003 systemd_measure()
1004 except ValueError:
1005 pytest.skip('systemd-measure not found')
1006
1007 ourdir = pathlib.Path(__file__).parent
1008 pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
1009
1010 output = tmp_path / 'basic.efi'
1011 args = [
1012 'build',
1013 *kernel_initrd,
1014 f'--output={output}',
1015 f'--pcr-public-key={pub.name}',
1016 '--json=short',
1017 '--policy-digest',
1018 ] + arg_tools
1019 opts = ukify.parse_args(args)
1020 try:
1021 ukify.check_inputs(opts)
1022 except OSError as e:
1023 pytest.skip(str(e))
1024
1025 ukify.make_uki(opts)
1026 pcrs = json.loads(capsys.readouterr().out)
1027 for bank, sigs in pcrs.items():
1028 for sig in sigs:
1029 sig['sig'] = 'a' * int(bank[3:])
1030
1031 opts = ukify.parse_args(['inspect', str(output)])
1032 ukify.inspect_sections(opts)
1033 text = capsys.readouterr().out
1034 assert re.search(r'\.pcrpkey', text, re.MULTILINE)
1035 assert re.search(r'\.pcrsig', text, re.MULTILINE)
1036 assert not re.search(r'"sig":', text, re.MULTILINE)
1037
1038 output_sig = tmp_path / 'pcrsig.efi'
1039 args = [
1040 'build',
1041 f'--output={output_sig}',
1042 f'--join-pcrsig={output}',
1043 f'--pcrsig={json.dumps(pcrs)}',
1044 '--json=short',
1045 ] + arg_tools
1046 opts = ukify.parse_args(args)
1047 try:
1048 ukify.check_inputs(opts)
1049 except OSError as e:
1050 pytest.skip(str(e))
1051
1052 ukify.make_uki(opts)
1053
1054 opts = ukify.parse_args(['inspect', str(output_sig)])
1055 ukify.inspect_sections(opts)
1056 text = capsys.readouterr().out
1057 assert re.search(r'\.pcrpkey', text, re.MULTILINE)
1058 assert re.search(r'\.pcrsig', text, re.MULTILINE)
1059 assert re.search(r'"sig":', text, re.MULTILINE)
1060
1061 shutil.rmtree(tmp_path)
1062
1063
1064 if __name__ == '__main__':
1065 sys.exit(pytest.main(sys.argv))