diff --git a/docs/user/images.md b/docs/user/images.md index 079133ab..8a53b821 100644 --- a/docs/user/images.md +++ b/docs/user/images.md @@ -535,6 +535,12 @@ hash. A host validates the signature against the certificates in its `/usr/lib/v only where its image policy says so (see "Example targets" below). The DDI contains no os-release and no package database. +When the host and the extension come from different projects, sign the extension with +`image.derived_signing_key()`. It derives an ECDSA P-256 pair from the target name, so every project that +declares a key with the same name gets the same pair, and the host installs the certificate from its own +declaration. Anyone who knows the name can compute the private key: use it for test images only. UEFI +firmware only enrolls RSA certificates, so the key can't sign for Secure Boot. + The rule writes one extension-release file per class: `/usr/lib/extension-release.d/extension-release.` for a sysext and `/etc/extension-release.d/extension-release.` for a confext. Each file contains: @@ -1301,7 +1307,7 @@ A host that merges a confext or attaches a portable image needs two things, whic `systemd-container`. The signed variant lives in `//examples/image-secureboot`: its `demo-ext` signs the verity root hash with a -generated key, the image ships that key's certificate in `/usr/lib/verity.d/` and a +derived key, the image ships that key's certificate in `/usr/lib/verity.d/` and a `/usr/lib/systemd/sysext.conf` whose `ImagePolicy` grants `signed` only, and its `vm-smoke` proves both directions — the signed extension merges, and the unsigned `demo-ext-unsigned` DDI is refused. Without such a policy the signature is decorative: systemd-sysext's default policy merges unsigned images, and falls back diff --git a/examples/image-secureboot/BUCK b/examples/image-secureboot/BUCK index a36ea053..c85dba58 100644 --- a/examples/image-secureboot/BUCK +++ b/examples/image-secureboot/BUCK @@ -10,7 +10,8 @@ serves both, and nothing downstream of the keys knows which it got, since every certificate whether it is held in the graph or by a token. The signed demo-ext system extension shows verity signing for a sysext DDI, with the image -enforcing the signature through its sysext.conf image policy. +enforcing the signature through its sysext.conf image policy. demo-ext signs with a key derived from +its name, as an extension from another project would, so it uses the derived key with or without tokens. Every image here is built for each release in `catalog//:releases.bzl`, so a build names one of the per-distribution aliases, such as `:image.fedora`. @@ -47,8 +48,13 @@ image.generate_signing_key(name = "signing") image.generate_signing_key(name = "pcr-signing") -# The two certificates this image reads back must say which key they belong to, and neither may fall -# back to ukify's own name for a Secure Boot key. +# demo-ext stands in for an extension that another project builds. Every project that declares a derived +# key with this name gets the same pair, so the image trusts the extension without a copy of the other +# project's certificate. +image.derived_signing_key(name = "extension-signing") + +# Each certificate must say which key it belongs to. A generated certificate must not fall back to +# ukify's own name for a Secure Boot key. [ box.sh_test( name = "generated-key-name-test." + name, @@ -63,7 +69,7 @@ if ! echo "$subject" | grep -qF "CN=$2"; then fi """, ) - for name in ["signing", "pcr-signing"] + for name in ["signing", "pcr-signing", "extension-signing"] ] _SIGNING = ":signing.token" if SIGN_WITH_TOKEN else ":signing" @@ -92,7 +98,7 @@ image.disk( image.ops.copy(_PCR_SIGNING + "[cert]", "/usr/share/tine-example/expected-pcr.crt"), # demo-ext's signature verifies against this certificate; the sysext.conf policy next to # it makes that verification a requirement rather than opportunistic. - image.ops.copy(_SIGNING + "[cert]", "/usr/lib/verity.d/demo-ext.crt"), + image.ops.copy(":extension-signing[cert]", "/usr/lib/verity.d/demo-ext.crt"), image.ops.copy("sysext.conf", "/usr/lib/systemd/sysext.conf"), # Plain data for the boot smoke's negative proof: a DDI the policy must refuse. image.ops.copy(":demo-ext-unsigned", "/usr/share/tine-example/demo-ext-unsigned.raw"), @@ -143,13 +149,13 @@ for name in ("PK", "KEK", "db"): ) # System-extension DDI extending :image, signed so the strict policy in sysext.conf accepts the -# merge. The image's own key, whose certificate it carries in /usr/lib/verity.d. +# merge. The image carries the certificate of the derived key in /usr/lib/verity.d. image.sysext( name = "demo-ext", parent = ":image", packages = ["zsh"], install_docs = False, - verity_key = _SIGNING, + verity_key = ":extension-signing", ) # The sysupdate definitions of the release, which its test compares with what the targets inline. diff --git a/image/BUCK b/image/BUCK index b3a285f6..8285731b 100644 --- a/image/BUCK +++ b/image/BUCK @@ -100,6 +100,13 @@ python.binary( visibility = ["PUBLIC"], ) +python.binary( + name = "signing-key", + main = "signing_key.py", + boxes = ["tine//distribution:tools.box"], + visibility = ["PUBLIC"], +) + python.library( name = "version", srcs = ["version.py"], @@ -126,6 +133,8 @@ python.test( "layer_test.py", "preload.py", "preload_test.py", + "signing_key.py", + "signing_key_test.py", "substitute.py", "substitute_test.py", "uki.py", diff --git a/image/defs.bzl b/image/defs.bzl index 931b57a1..444823e1 100644 --- a/image/defs.bzl +++ b/image/defs.bzl @@ -53,6 +53,7 @@ load(":publish.bzl", "PublishedFile", "PublishedInfo", "image_artifacts") load( ":sign.bzl", "SigningKeyInfo", + "derived_signing_key", "generate_signing_key", "pem_signing_key", "pkcs11_signing_key", @@ -73,6 +74,7 @@ image = struct( bootable = bootable, partition = partition, vm = image_vm, + derived_signing_key = derived_signing_key, generate_signing_key = generate_signing_key, install = image_install, substitute = substitute, diff --git a/image/sign.bzl b/image/sign.bzl index b1edc842..8d4a3a83 100644 --- a/image/sign.bzl +++ b/image/sign.bzl @@ -193,6 +193,65 @@ generate_signing_key = rule( """, ) +def _derived_signing_key_impl(ctx: AnalysisContext) -> list[Provider]: + common_name = _GENERATED_CN_PREFIX + ctx.label.name + # x509 limits a common name to 64 characters. Without the check, a long target name fails in the + # action with a Python traceback. + if len(common_name) > 64: + fail( + "derived_signing_key: the name {!r} is too long, the certificate's common name {!r} must have at most 64 characters".format( + ctx.label.name, common_name + ) + ) + key = ctx.actions.declare_output("signing.key") + certificate = ctx.actions.declare_output("signing.crt") + ctx.actions.run( + cmd_args( + box.run(box = ctx.attrs._box[box.Info], exe = ctx.attrs._derive), + common_name, + key.as_output(), + certificate.as_output(), + ), + category = "signing_key", + # Anyone who knows the name can compute the pair, so a shared cache may hold it. + allow_cache_upload = True, + ) + return [ + DefaultInfo( + sub_targets = { + "cert": [DefaultInfo(default_output = certificate)], + "key": [DefaultInfo(default_output = key)], + } + ), + SigningKeyInfo(certificate = certificate, private_key = key), + ] + +derived_signing_key = rule( + impl = _derived_signing_key_impl, + attrs = { + "_box": attrs.exec_dep(providers = [box.Info], default = "tine//distribution:tools.box"), + "_derive": attrs.exec_dep(default = "tine//image:signing-key"), + }, + doc = """Derive a development ECDSA P-256 signing key pair from the target name. + + The pair is a function of the name alone, so every build, workspace and project that uses the + same name gets the same pair. Images from different projects can then trust each other's + signatures without copying a certificate between them. Anyone who knows the name can compute + the private key, so never enroll the certificate on real hardware. `:[cert]` and + `:[key]` are the PEM artifacts. + + UEFI firmware only enrolls certificates with RSA keys, so a P-256 key can't sign for Secure + Boot. Use `generate_signing_key` for that role. The kernel and systemd accept P-256 for + dm-verity signatures. + + The pair is derived in the tools box of the default release. The certificate's signature needs + python-cryptography 45 or newer in that box. + + The certificate is named `tine.generated.`, to signify that it is not an official + production key. + """, +) + def _pem_signing_key_impl(ctx: AnalysisContext) -> list[Provider]: return [ DefaultInfo(sub_targets = {"cert": [DefaultInfo(default_output = ctx.attrs.certificate)]}), diff --git a/image/signing_key.py b/image/signing_key.py new file mode 100755 index 00000000..cfe642e4 --- /dev/null +++ b/image/signing_key.py @@ -0,0 +1,75 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Amutable GmbH +# SPDX-License-Identifier: MPL-2.0 + +"""Derive a development signing key pair from its certificate's common name. + +Everything in the pair is a function of the common name, so every build, workspace and project that +uses the same name gets the same pair. Anyone who knows the name can compute the private key. + +Projects that pin different tine revisions must derive the same pair from the same name, or their +images stop trusting each other's signatures. Never change how the key, the issuer or the serial number +are derived. signing_key_test.py pins them. +""" + +import datetime +import hashlib +import sys +from pathlib import Path + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec + +# RFC 5280 reserves 99991231235959Z for a certificate without an expiration date. +_NOT_VALID_BEFORE = datetime.datetime(2000, 1, 1, tzinfo=datetime.UTC) +_NOT_VALID_AFTER = datetime.datetime(9999, 12, 31, 23, 59, 59, tzinfo=datetime.UTC) + + +def _derive_bytes(common_name: str, purpose: str, size: int) -> bytes: + return hashlib.shake_256(b"\0".join([common_name.encode(), purpose.encode()])).digest(size) + + +def derive(common_name: str) -> tuple[bytes, bytes]: + """Return the PEM private key and PEM certificate for the common name.""" + # The kernel can't verify a certificate with an Ed25519 key, so dm-verity signatures need ECDSA or + # RSA. A P-256 private key must be below the order of the curve, and every 31-byte value is. + key = ec.derive_private_key(int.from_bytes(_derive_bytes(common_name, "key", 31)), ec.SECP256R1()) + + # systemd-repart identifies the signer of a verity signature by the issuer and serial number of its + # certificate. The kernel and the userspace check against /usr/lib/verity.d look up the certificate by + # both, so both must be derived from the name for a certificate from another build to match. + name = x509.Name([x509.NameAttribute(x509.oid.NameOID.COMMON_NAME, common_name)]) + # RFC 5280 limits the serial number to 20 bytes. DER adds a zero byte to a value whose top bit is set. + serial = int.from_bytes(_derive_bytes(common_name, "serial", 19)) + certificate = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .not_valid_before(_NOT_VALID_BEFORE) + .not_valid_after(_NOT_VALID_AFTER) + .serial_number(serial) + .public_key(key.public_key()) + .add_extension(x509.BasicConstraints(ca=False, path_length=None), critical=True) + # An ECDSA signature contains a random nonce by default. RFC 6979 derives the nonce from the key + # and the message instead, so the certificate is the same on every run. + .sign(private_key=key, algorithm=hashes.SHA256(), ecdsa_deterministic=True) + ) + + key_pem = key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ) + return key_pem, certificate.public_bytes(serialization.Encoding.PEM) + + +def main() -> None: + common_name, key_path, certificate_path = sys.argv[1:] + key_pem, certificate_pem = derive(common_name) + Path(key_path).write_bytes(key_pem) + Path(certificate_path).write_bytes(certificate_pem) + + +if __name__ == "__main__": + main() diff --git a/image/signing_key_test.py b/image/signing_key_test.py new file mode 100644 index 00000000..3ed774ed --- /dev/null +++ b/image/signing_key_test.py @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: Amutable GmbH +# SPDX-License-Identifier: MPL-2.0 + +"""Tests for deriving a development signing key pair from its common name. + +buck test tine//image:test +""" + +import unittest + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec + +import signing_key + + +class DeriveTest(unittest.TestCase): + def test_same_name_same_pair(self) -> None: + # Builds in different workspaces must derive the same pair. Derive the pair twice from the same + # name and check that the key and the certificate are byte-identical. + self.assertEqual( + signing_key.derive("tine.generated.verity"), signing_key.derive("tine.generated.verity") + ) + + def test_known_answer(self) -> None: + # Projects that pin different tine revisions must derive the same pair from the same name. + # Derive the pair for a fixed name and compare the public key, the issuer and the serial number + # with the values that earlier revisions derived. A signature matches a certificate by those + # three, so the rest of the certificate may change. + _, certificate_pem = signing_key.derive("tine.generated.verity") + certificate = x509.load_pem_x509_certificate(certificate_pem) + self.assertEqual( + certificate.public_key() + .public_bytes(serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo) + .hex(), + "3059301306072a8648ce3d020106082a8648ce3d030107034200046de4e9d1f314dd10fdbe68ad79ba9c42a10b15dc" + "74082ccf2b45885a4af2e6988072bc9b100468e7829fbd016463b07ce95110c69e2c14b008efe2163c29768c", + ) + self.assertEqual(certificate.issuer.rfc4514_string(), "CN=tine.generated.verity") + self.assertEqual(certificate.serial_number, 0x5F2C5133861D5C56A4B6A91C03692FBBA03AFB) + + def test_other_name_other_pair(self) -> None: + # Two names must not share a key. Derive pairs for two names and check that the keys and the + # serial numbers differ. + key_a, certificate_a = signing_key.derive("tine.generated.verity") + key_b, certificate_b = signing_key.derive("tine.generated.secureboot") + self.assertNotEqual(key_a, key_b) + self.assertNotEqual( + x509.load_pem_x509_certificate(certificate_a).serial_number, + x509.load_pem_x509_certificate(certificate_b).serial_number, + ) + + def test_certificate_matches_key(self) -> None: + # The kernel rejects a self-signed certificate whose signature doesn't verify. Derive a pair and + # check that the key is P-256, that the certificate has the common name, and that the key signed + # the certificate. The signature only verifies if the certificate contains the key's public key. + key_pem, certificate_pem = signing_key.derive("tine.generated.verity") + key = serialization.load_pem_private_key(key_pem, password=None) + assert isinstance(key, ec.EllipticCurvePrivateKey) + self.assertIsInstance(key.curve, ec.SECP256R1) + + certificate = x509.load_pem_x509_certificate(certificate_pem) + self.assertEqual(certificate.subject.rfc4514_string(), "CN=tine.generated.verity") + certificate.verify_directly_issued_by(certificate) + + +if __name__ == "__main__": + unittest.main()