1 import ./make-test-python.nix ({ lib, pkgs, ... }:
3 name = "systemd-credentials-tpm2";
6 maintainers = with pkgs.lib.maintainers; [ tmarkus ];
9 nodes.machine = { pkgs, ... }: {
10 virtualisation.tpm.enable = true;
11 environment.systemPackages = with pkgs; [ diffutils ];
16 CRED_RAW_FILE = f"/root/{CRED_NAME}"
17 CRED_FILE = f"/root/{CRED_NAME}.cred"
19 def systemd_run(machine, cmd):
20 machine.log(f"Executing command (via systemd-run): \"{cmd}\"")
22 (status, out) = machine.execute( " ".join([
24 "--service-type=exec",
28 "-p StandardOutput=journal",
29 "-p StandardError=journal",
30 f"-p LoadCredentialEncrypted={CRED_NAME}:{CRED_FILE}",
35 raise Exception(f"systemd_run failed (status {status})")
37 machine.log("systemd-run finished successfully")
39 machine.wait_for_unit("multi-user.target")
41 with subtest("Check whether TPM device exists"):
42 machine.succeed("test -e /dev/tpm0")
43 machine.succeed("test -e /dev/tpmrm0")
45 with subtest("Check whether systemd-creds detects TPM2 correctly"):
46 cmd = "systemd-creds has-tpm2"
47 machine.log(f"Running \"{cmd}\"")
48 (status, _) = machine.execute(cmd)
50 # Check exit code equals 0 or 1 (1 means firmware support is missing, which is OK here)
51 if status != 0 and status != 1:
52 raise Exception("systemd-creds failed to detect TPM2")
54 with subtest("Encrypt credential using systemd-creds"):
55 machine.succeed(f"dd if=/dev/urandom of={CRED_RAW_FILE} bs=1k count=16")
56 machine.succeed(f"systemd-creds --with-key=host+tpm2 encrypt --name=testkey {CRED_RAW_FILE} {CRED_FILE}")
58 with subtest("Write provided credential and check for equality"):
59 CRED_OUT_FILE = f"/root/{CRED_NAME}.out"
60 systemd_run(machine, f"systemd-creds cat testkey > {CRED_OUT_FILE}")
61 machine.succeed(f"cmp --silent -- {CRED_RAW_FILE} {CRED_OUT_FILE}")
63 with subtest("Check whether systemd service can see credential in systemd-creds list"):
64 systemd_run(machine, f"systemd-creds list | grep {CRED_NAME}")
66 with subtest("Check whether systemd service can access credential in $CREDENTIALS_DIRECTORY"):
67 systemd_run(machine, f"cmp --silent -- $CREDENTIALS_DIRECTORY/{CRED_NAME} {CRED_RAW_FILE}")