Blob Blame History Raw
#!/usr/bin/python3
"""
Verify, and install RPM packages

Verify, and install RPM packages.

`gpgkeys` should be an array of strings containing each GPG key to be used
to verify the packages.

`packages` is an array of objects representing RPMs. Each RPM is identified by
its checksums. Specifically, the content hash of the rpm, not the checksums
found in the rpm header. The `check_gpg` property indicates that the RPM's
must be signed by one of the given GPG keys, and that the transaction should
fail otherwise.

This stage will fail if any of the packages can't be found, or if any
RPM fails signature verification.

Uses the following binaries from the host:
    * `rpmkeys` to import keys and to verify signatures for each package
    * `sh`, `mkdir`, `mount`, `chmod` to prepare the target tree for `rpm`
    * `rpm` to install packages into the target tree
"""


import contextlib
import json
import os
import pathlib
import subprocess
import sys
import tempfile

import osbuild.sources

SCHEMA = """
"additionalProperties": false,
"properties": {
  "gpgkeys": {
    "description": "Array of GPG key contents to import",
    "type": "array",
    "items": { "type": "string" }
  },
  "packages": {
    "description": "Array of RPM content hashes",
    "type": "array",
    "items": {
      "oneOf": [
        {
          "type": "string",
          "description": ".rpm file checksum, prefixed with 'md5:', 'sha1:', 'sha256:', 'sha384:', or 'sha512:', indicating the algorithm used."
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": ["checksum"],
          "properties": {
            "checksum": {
              "type": "string",
              "description": ".rpm file checksum, prefixed with 'md5:', 'sha1:', 'sha256:', 'sha384:', or 'sha512:', indicating the algorithm used."
            },
            "check_gpg": {
              "type": "boolean",
              "description": "Whether the GPG signatures of the RPM should be verified.",
              "default": false
            }
          }
        }
      ]
    }
  }
}
"""


def packages_from_legacy(legacy):
    packages = []
    for package in legacy:
        if isinstance(package, dict):
            packages.append(package)
        else:
            packages.append({"checksum": package, "check_gpg": False})
    return packages


def main(tree, sources, options):
    packages = packages_from_legacy(options.get("packages", []))
    checksums = [p["checksum"] for p in packages]
    for key in options.get("gpgkeys", []):
        with tempfile.NamedTemporaryFile(prefix="gpgkey.", mode="w") as keyfile:
            keyfile.write(key)
            keyfile.flush()
            subprocess.run([
                "rpmkeys",
                "--root", tree,
                "--import", keyfile.name
            ], check=True)
        print("imported gpg key")

    print("fetching sources")
    osbuild.sources.get("org.osbuild.files", checksums)

    for pkg in packages:
        if pkg.get("check_gpg"):
            subprocess.run([
                "rpmkeys",
                "--root", tree,
                "--checksig",
                pkg["checksum"]
            ], cwd=f"{sources}/org.osbuild.files", stdout=subprocess.DEVNULL, check=True)

    script = f"""
        set -e
        mkdir -p {tree}/dev {tree}/sys {tree}/proc
        mount -o bind /dev {tree}/dev
        mount -o bind /sys {tree}/sys
        mount -o bind /proc {tree}/proc
    """

    machine_id_set_previously = os.path.exists(f"{tree}/etc/machine-id")
    if not machine_id_set_previously:
        # create a fake machine ID to improve reproducibility
        print("creating a fake machine id")
        script += f"""
            mkdir -p {tree}/etc
            echo "ffffffffffffffffffffffffffffffff" > {tree}/etc/machine-id
            chmod 0444 {tree}/etc/machine-id
        """

    subprocess.run(["/bin/sh", "-c", script], check=True)

    with tempfile.NamedTemporaryFile(prefix="manifest.", mode='w') as manifest:
        manifest.writelines(c+'\n' for c in checksums)
        manifest.flush()
        subprocess.run([
            "rpm",
            "--verbose",
            "--root", tree,
            # The content hash of the rpms has been verified, default to not
            # verifying again (see /usr/lib/rpm/macros for more info)
            "--define", "_pkgverify_level none",
            "--install", manifest.name
        ], cwd=f"{sources}/org.osbuild.files", check=True)

    # remove temporary machine ID if it was created by us
    if not machine_id_set_previously:
        print("deleting the fake machine id")
        machine_id_file = pathlib.Path(f"{tree}/etc/machine-id")
        machine_id_file.unlink()
        machine_id_file.touch()

    # remove random seed from the tree if exists
    with contextlib.suppress(FileNotFoundError):
        os.unlink(f"{tree}/var/lib/systemd/random-seed")

    return 0


if __name__ == '__main__':
    args = json.load(sys.stdin)
    r = main(args["tree"], args["sources"], args["options"])
    sys.exit(r)