HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/ukify/test/test_ukify.py
Git blob: 01c173e107fcb673ccaeb72d31085976af789338
Lines 1001–1636 of 1,636
assert len(result[name]) == 2, name
assert all('sha256' in d for d in result[name]), name
assert result[name][0]['sha256'] != result[name][1]['sha256'], name
# A single entry is still reported as a (one-element) list, not a bare object.
single = f'{tmp_path}/single.efi'
build_inspect_uki(f'--devicetree-auto={dtbs[0]}', f'--efifw={efifws[0]}', f'--output={single}')
result = inspect(single)
assert isinstance(result['.dtbauto'], list) and len(result['.dtbauto']) == 1
assert isinstance(result['.efifw'], list) and len(result['.efifw']) == 1
shutil.rmtree(tmp_path)
@pytest.mark.skipif(not slow_tests, reason='slow')
def test_pcr_signing(kernel_initrd, tmp_path):
if kernel_initrd is None:
pytest.skip('linux+initrd not found')
try:
systemd_measure()
except ValueError:
pytest.skip('systemd-measure not found')
ourdir = pathlib.Path(__file__).parent
pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
priv = unbase64(ourdir / 'example.tpm2-pcr-private.pem.base64')
output = f'{tmp_path}/signed.efi'
args = [
'build',
*kernel_initrd,
f'--output={output}',
'--uname=1.2.3',
'--cmdline=ARG1 ARG2 ARG3',
'--os-release=ID=foobar\n',
'--pcr-banks=sha384', # sha1 might not be allowed, use something else
f'--pcr-private-key={priv.name}',
] + arg_tools
# If the public key is not explicitly specified, it is derived
# automatically. Let's make sure everything works as expected both when the
# public keys is specified explicitly and when it is derived from the
# private key.
for extra in ([f'--pcrpkey={pub.name}', f'--pcr-public-key={pub.name}'], []):
opts = ukify.parse_args(args + extra)
try:
ukify.check_inputs(opts)
except OSError as e:
pytest.skip(str(e))
ukify.make_uki(opts)
# let's check that objdump likes the resulting file
dump = subprocess.check_output(['objdump', '-h', output], text=True)
for sect in 'text osrel cmdline linux initrd uname pcrsig'.split():
assert re.search(rf'^\s*\d+\s+\.{sect}\s+[0-9a-f]+', dump, re.MULTILINE)
# objcopy fails when called without an output argument (EPERM).
# It also fails when called with /dev/null (file truncated).
# It also fails when called with /dev/zero (because it reads the
# output file, infinitely in this case.)
# So let's just call it with a dummy output argument.
subprocess.check_call(
[
'objcopy',
*(
f'--dump-section=.{n}={tmp_path}/out.{n}'
for n in ('pcrpkey', 'pcrsig', 'osrel', 'uname', 'cmdline')
),
output,
tmp_path / 'dummy',
],
text=True,
)
assert open(tmp_path / 'out.pcrpkey').read() == open(pub.name).read()
assert open(tmp_path / 'out.osrel').read() == 'ID=foobar\n'
assert open(tmp_path / 'out.uname').read() == '1.2.3'
assert open(tmp_path / 'out.cmdline').read() == 'ARG1 ARG2 ARG3'
sig = open(tmp_path / 'out.pcrsig').read()
sig = json.loads(sig)
assert list(sig.keys()) == ['sha384']
assert len(sig['sha384']) == 4 # four items for four phases
shutil.rmtree(tmp_path)
@pytest.mark.skipif(not slow_tests, reason='slow')
def test_pcr_signing2(kernel_initrd, tmp_path):
if kernel_initrd is None:
pytest.skip('linux+initrd not found')
try:
systemd_measure()
except ValueError:
pytest.skip('systemd-measure not found')
ourdir = pathlib.Path(__file__).parent
pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
priv = unbase64(ourdir / 'example.tpm2-pcr-private.pem.base64')
pub2 = unbase64(ourdir / 'example.tpm2-pcr-public2.pem.base64')
priv2 = unbase64(ourdir / 'example.tpm2-pcr-private2.pem.base64')
# simulate a microcode file
with open(f'{tmp_path}/microcode', 'wb') as microcode:
microcode.write(b'1234567890')
output = f'{tmp_path}/signed.efi'
assert kernel_initrd[0] == '--linux'
opts = ukify.parse_args(
[
'build',
*kernel_initrd[:2],
f'--initrd={microcode.name}',
*kernel_initrd[2:],
f'--output={output}',
'--uname=1.2.3',
'--cmdline=ARG1 ARG2 ARG3',
'--os-release=ID=foobar\n',
'--pcr-banks=sha384',
f'--pcrpkey={pub2.name}',
f'--pcr-public-key={pub.name}',
f'--pcr-private-key={priv.name}',
'--phases=enter-initrd enter-initrd:leave-initrd',
f'--pcr-public-key={pub2.name}',
f'--pcr-private-key={priv2.name}',
'--phases=sysinit ready shutdown final', # yes, those phase paths are not reachable
]
+ arg_tools
)
try:
ukify.check_inputs(opts)
except OSError as e:
pytest.skip(str(e))
ukify.make_uki(opts)
# let's check that objdump likes the resulting file
dump = subprocess.check_output(['objdump', '-h', output], text=True)
for sect in 'text osrel cmdline linux initrd uname pcrsig'.split():
assert re.search(rf'^\s*\d+\s+\.{sect}\s+[0-9a-f]+', dump, re.MULTILINE)
subprocess.check_call(
[
'objcopy',
*(
f'--dump-section=.{n}={tmp_path}/out.{n}'
for n in ('pcrpkey', 'pcrsig', 'osrel', 'uname', 'cmdline', 'initrd')
),
output,
tmp_path / 'dummy',
],
text=True,
)
assert open(tmp_path / 'out.pcrpkey').read() == open(pub2.name).read()
assert open(tmp_path / 'out.osrel').read() == 'ID=foobar\n'
assert open(tmp_path / 'out.uname').read() == '1.2.3'
assert open(tmp_path / 'out.cmdline').read() == 'ARG1 ARG2 ARG3'
assert open(tmp_path / 'out.initrd', 'rb').read(10) == b'1234567890'
sig = open(tmp_path / 'out.pcrsig').read()
sig = json.loads(sig)
assert list(sig.keys()) == ['sha384']
assert len(sig['sha384']) == 6 # six items for six phases paths
shutil.rmtree(tmp_path)
@pytest.mark.skipif(not slow_tests, reason='slow')
def test_pcr_signing3(kernel_initrd, tmp_path):
if kernel_initrd is None:
pytest.skip('linux+initrd not found')
try:
systemd_measure()
except ValueError:
pytest.skip('systemd-measure not found')
ourdir = pathlib.Path(__file__).parent
pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
priv = unbase64(ourdir / 'example.tpm2-pcr-private.pem.base64')
# simulate a microcode file
with open(f'{tmp_path}/microcode', 'wb') as microcode:
microcode.write(b'1234567890')
output = f'{tmp_path}/signed.efi'
assert kernel_initrd[0] == '--linux'
opts = ukify.parse_args(
[
'build',
*kernel_initrd[:2],
f'--initrd={microcode.name}',
*kernel_initrd[2:],
f'--output={output}',
'--uname=1.2.3',
'--cmdline=ARG1 ARG2 ARG3',
'--os-release=ID=foobar\n',
'--pcr-banks=sha384',
f'--pcrpkey={pub.name}',
f'--pcr-private-key={priv.name}',
'--phases=enter-initrd enter-initrd:leave-initrd enter-initrd:leave-initrd:sysinit enter-initrd:leave-initrd:sysinit:ready',
'--policyref=',
f'--pcr-private-key={priv.name}',
'--phases=enter-initrd',
'--policyref=initrd',
]
+ arg_tools
)
try:
ukify.check_inputs(opts)
except OSError as e:
pytest.skip(str(e))
ukify.make_uki(opts)
# let's check that objdump likes the resulting file
dump = subprocess.check_output(['objdump', '-h', output], text=True)
for sect in 'text osrel cmdline linux initrd uname pcrsig'.split():
assert re.search(rf'^\s*\d+\s+\.{sect}\s+[0-9a-f]+', dump, re.MULTILINE)
subprocess.check_call(
[
'objcopy',
*(
f'--dump-section=.{n}={tmp_path}/out.{n}'
for n in ('pcrpkey', 'pcrsig', 'osrel', 'uname', 'cmdline', 'initrd')
),
output,
tmp_path / 'dummy',
],
text=True,
)
assert open(tmp_path / 'out.pcrpkey').read() == open(pub.name).read()
assert open(tmp_path / 'out.osrel').read() == 'ID=foobar\n'
assert open(tmp_path / 'out.uname').read() == '1.2.3'
assert open(tmp_path / 'out.cmdline').read() == 'ARG1 ARG2 ARG3'
assert open(tmp_path / 'out.initrd', 'rb').read(10) == b'1234567890'
sig = open(tmp_path / 'out.pcrsig').read()
sig = json.loads(sig)
assert list(sig.keys()) == ['sha384']
assert len(sig['sha384']) == 5 # five items for five phases paths
assert 'ref' not in sig['sha384'][0]
assert 'ref' not in sig['sha384'][1]
assert 'ref' not in sig['sha384'][2]
assert 'ref' not in sig['sha384'][3]
assert 'ref' in sig['sha384'][4]
assert sig['sha384'][4]['ref'] == 'initrd'
shutil.rmtree(tmp_path)
@pytest.mark.skipif(not slow_tests, reason='slow')
@pytest.mark.parametrize('policy_digest', (False, True), ids=('sign', 'policy-digest'))
def test_pcr_signing_initrd_pcrs(kernel_initrd, tmp_path, policy_digest):
if kernel_initrd is None:
pytest.skip('linux+initrd not found')
try:
systemd_measure()
except ValueError:
pytest.skip('systemd-measure not found')
ourdir = pathlib.Path(__file__).parent
pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
priv = unbase64(ourdir / 'example.tpm2-pcr-private.pem.base64')
output = f'{tmp_path}/signed.efi'
args = [
'build',
*kernel_initrd,
f'--output={output}',
'--uname=1.2.3',
'--cmdline=ARG1 ARG2 ARG3',
'--os-release=ID=foobar\n',
'--pcr-banks=sha384', # sha1 might not be allowed, use something else
*(['--policy-digest'] if policy_digest else [f'--pcr-private-key={priv.name}']),
f'--pcr-public-key={pub.name}',
'--sign-initrd-pcrs',
] + arg_tools
opts = ukify.parse_args(args)
try:
ukify.check_inputs(opts)
except OSError as e:
pytest.skip(str(e))
ukify.make_uki(opts)
subprocess.check_call(
['objcopy', f'--dump-section=.pcrsig={tmp_path}/out.pcrsig', output, tmp_path / 'dummy'],
text=True,
)
sig = json.loads(open(tmp_path / 'out.pcrsig').read())
assert list(sig.keys()) == ['sha384']
policies = sig['sha384']
assert len(policies) == 5 # five items for five phase paths
assert policies[0]['pol'] == policies[4]['pol']
assert all('ref' not in policy for policy in policies[:4])
assert policies[4]['ref'] == 'initrd'
if policy_digest:
assert all('pkfp' in policy and 'sig' not in policy for policy in policies)
else:
assert all('sig' in policy for policy in policies)
shutil.rmtree(tmp_path)
@pytest.mark.parametrize(
'options',
[
['--pcr-private-key=shared', '--pcr-public-key=shared'],
['--pcr-private-key=shared', '--pcr-public-key=sub/../shared'],
['--secureboot-private-key=shared', '--secureboot-certificate=shared'],
[
'--pcr-private-key=shared',
'--pcr-private-key=shared',
'--pcr-public-key=first',
'--pcr-public-key=second',
],
[
'--pcr-private-key=first',
'--pcr-private-key=second',
'--pcr-public-key=shared',
'--pcr-public-key=shared',
],
[
'--pcr-private-key=first',
'--pcr-private-key=shared',
'--pcr-public-key=shared',
'--pcr-public-key=second',
],
[
'--secureboot-private-key=shared',
'--secureboot-certificate=cert',
'--pcr-private-key=shared',
'--pcr-public-key=public',
],
[
'--secureboot-private-key=private',
'--secureboot-certificate=shared',
'--pcr-private-key=pcr',
'--pcr-public-key=shared',
],
[
'--secureboot-private-key=private',
'--secureboot-certificate=public',
'--pcr-private-key=private',
'--pcr-public-key=public',
],
],
)
def test_genkey_conflicting_outputs(tmp_path, monkeypatch, options):
(tmp_path / 'sub').mkdir()
args = ['ukify', 'genkey', '--config=/dev/null']
for option in options:
key, path = option.split('=')
args.append(f'{key}={tmp_path / path}')
monkeypatch.setattr(sys, 'argv', args)
with pytest.raises(ValueError, match='Conflicting key output path'):
ukify.main()
assert list(tmp_path.rglob('*')) == [tmp_path / 'sub']
@pytest.mark.parametrize('alias', ['', 'sub/..'])
def test_genkey_repeated_pair(tmp_path, monkeypatch, alias):
serialization = pytest.importorskip('cryptography.hazmat.primitives.serialization')
(tmp_path / 'sub').mkdir()
private, public = tmp_path / 'private.pem', tmp_path / 'public.pem'
opts = ukify.parse_args(
[
'genkey',
'--config=/dev/null',
f'--pcr-private-key={private}',
f'--pcr-public-key={public}',
f'--pcr-private-key={tmp_path / alias / "private.pem"}',
f'--pcr-public-key={tmp_path / alias / "public.pem"}',
'--sign-initrd-pcrs',
]
)
ukify.check_cert_and_keys_nonexistent(opts)
generate = ukify.generate_priv_pub_key_pair
calls = []
def generate_once():
calls.append(True)
return generate()
monkeypatch.setattr(ukify, 'generate_priv_pub_key_pair', generate_once)
ukify.generate_keys(opts)
assert len(calls) == 1
priv = serialization.load_pem_private_key(private.read_bytes(), password=None)
pub = serialization.load_pem_public_key(public.read_bytes())
assert priv.public_key().public_numbers() == pub.public_numbers()
def test_key_cert_generation(tmp_path):
opts = ukify.parse_args(
[
'genkey',
f'--pcr-public-key={tmp_path / "pcr1.pub.pem"}',
f'--pcr-private-key={tmp_path / "pcr1.priv.pem"}',
'--phases=enter-initrd enter-initrd:leave-initrd',
f'--pcr-public-key={tmp_path / "pcr2.pub.pem"}',
f'--pcr-private-key={tmp_path / "pcr2.priv.pem"}',
'--phases=sysinit ready',
f'--secureboot-private-key={tmp_path / "sb.priv.pem"}',
f'--secureboot-certificate={tmp_path / "sb.cert.pem"}',
]
)
assert opts.verb == 'genkey'
ukify.check_cert_and_keys_nonexistent(opts)
pytest.importorskip('cryptography')
ukify.generate_keys(opts)
if not shutil.which('openssl'):
return
for key in (tmp_path / 'pcr1.priv.pem', tmp_path / 'pcr2.priv.pem', tmp_path / 'sb.priv.pem'):
out = subprocess.check_output(
[
'openssl', 'rsa',
'-in', key,
'-text',
'-noout',
],
text=True,
) # fmt: skip
assert 'Private-Key' in out
assert '2048 bit' in out
for pub in (tmp_path / 'pcr1.pub.pem', tmp_path / 'pcr2.pub.pem'):
out = subprocess.check_output(
[
'openssl', 'rsa',
'-pubin',
'-in', pub,
'-text',
'-noout',
],
text=True,
) # fmt: skip
assert 'Public-Key' in out
assert '2048 bit' in out
out = subprocess.check_output(
[
'openssl', 'x509',
'-in', tmp_path / 'sb.cert.pem',
'-text',
'-noout',
],
text=True,
) # fmt: skip
assert 'Certificate' in out
assert re.search(r'Issuer: CN\s?=\s?SecureBoot signing key on host', out)
def test_key_cert_generation_common_name(tmp_path):
opts = ukify.parse_args(
[
'genkey',
f'--secureboot-private-key={tmp_path / "sb.priv.pem"}',
f'--secureboot-certificate={tmp_path / "sb.cert.pem"}',
'--secureboot-certificate-common-name=ukify test key',
]
)
assert opts.verb == 'genkey'
pytest.importorskip('cryptography')
ukify.generate_keys(opts)
if not shutil.which('openssl'):
return
out = subprocess.check_output(
[
'openssl', 'x509',
'-in', tmp_path / 'sb.cert.pem',
'-text',
'-noout',
],
text=True,
) # fmt: skip
assert re.search(r'Subject: CN\s?=\s?ukify test key', out)
assert re.search(r'Issuer: CN\s?=\s?ukify test key', out)
def test_key_cert_generation_empty_common_name(tmp_path):
opts = ukify.parse_args(
[
'genkey',
f'--secureboot-private-key={tmp_path / "sb.priv.pem"}',
f'--secureboot-certificate={tmp_path / "sb.cert.pem"}',
'--secureboot-certificate-common-name=',
]
)
with pytest.raises(ValueError, match='--secureboot-certificate-common-name= must not be empty'):
ukify.generate_keys(opts)
def test_key_cert_generation_common_name_too_long(tmp_path):
opts = ukify.parse_args(
[
'genkey',
f'--secureboot-private-key={tmp_path / "sb.priv.pem"}',
f'--secureboot-certificate={tmp_path / "sb.cert.pem"}',
f'--secureboot-certificate-common-name={"x" * 65}',
]
)
with pytest.raises(ValueError, match='is longer than 64 bytes'):
ukify.generate_keys(opts)
def test_apply_pcr_signatures() -> None:
pcrsig = {
'sha256': [
{'pol': 'same', 'tbs': 'first'},
{'pol': 'same', 'tbs': 'second'},
{'pol': 'legacy', 'ref': 'first'},
{'pol': 'legacy', 'ref': 'second'},
]
}
signatures = {
'sha256': [
{'pol': 'same', 'tbs': 'second', 'sig': 'second-signature'},
{'pol': 'same', 'tbs': 'first', 'sig': 'first-signature'},
{'pol': 'legacy', 'ref': 'second', 'sig': 'legacy-second-signature'},
{'pol': 'legacy', 'ref': 'first', 'sig': 'legacy-first-signature'},
]
}
ukify.apply_pcr_signatures(pcrsig, signatures)
assert [policy['sig'] for policy in pcrsig['sha256']] == [
'first-signature',
'second-signature',
'legacy-first-signature',
'legacy-second-signature',
]
@pytest.mark.skipif(not slow_tests, reason='slow')
def test_join_pcrsig(capsys, kernel_initrd, tmp_path):
if kernel_initrd is None:
pytest.skip('linux+initrd not found')
try:
systemd_measure()
except ValueError:
pytest.skip('systemd-measure not found')
ourdir = pathlib.Path(__file__).parent
pub = unbase64(ourdir / 'example.tpm2-pcr-public.pem.base64')
output = tmp_path / 'basic.efi'
args = [
'build',
*kernel_initrd,
f'--output={output}',
f'--pcr-public-key={pub.name}',
'--json=short',
'--policy-digest',
'--sign-initrd-pcrs',
] + arg_tools
opts = ukify.parse_args(args)
try:
ukify.check_inputs(opts)
except OSError as e:
pytest.skip(str(e))
ukify.make_uki(opts)
pcrs = json.loads(capsys.readouterr().out)
for bank, sigs in pcrs.items():
for sig in sigs:
sig['sig'] = ('b' if sig.get('ref') else 'a') * int(bank[3:])
opts = ukify.parse_args(['inspect', str(output)])
ukify.inspect_sections(opts)
text = capsys.readouterr().out
assert re.search(r'\.pcrpkey', text, re.MULTILINE)
assert re.search(r'\.pcrsig', text, re.MULTILINE)
assert not re.search(r'"sig":', text, re.MULTILINE)
output_sig = tmp_path / 'pcrsig.efi'
args = [
'build',
f'--output={output_sig}',
f'--join-pcrsig={output}',
f'--pcrsig={json.dumps(pcrs)}',
'--json=short',
] + arg_tools
opts = ukify.parse_args(args)
try:
ukify.check_inputs(opts)
except OSError as e:
pytest.skip(str(e))
ukify.make_uki(opts)
pcrsig = tmp_path / 'out.pcrsig'
subprocess.check_call(
['objcopy', f'--dump-section=.pcrsig={pcrsig}', output_sig, tmp_path / 'dummy'],
text=True,
)
attached = json.loads(pcrsig.read_text())
for bank, sigs in attached.items():
for sig in sigs:
assert sig['sig'] == ('b' if sig.get('ref') else 'a') * int(bank[3:])
opts = ukify.parse_args(['inspect', str(output_sig)])
ukify.inspect_sections(opts)
text = capsys.readouterr().out
assert re.search(r'\.pcrpkey', text, re.MULTILINE)
assert re.search(r'\.pcrsig', text, re.MULTILINE)
assert re.search(r'"sig":', text, re.MULTILINE)
shutil.rmtree(tmp_path)
if __name__ == '__main__':
sys.exit(pytest.main(sys.argv))