at master 2.6 kB view raw
1{ lib, pkgs, ... }: 2{ 3 name = "systemd-credentials-tpm2"; 4 5 meta = { 6 maintainers = with pkgs.lib.maintainers; [ tmarkus ]; 7 }; 8 9 nodes.machine = 10 { pkgs, ... }: 11 { 12 virtualisation.tpm.enable = true; 13 environment.systemPackages = with pkgs; [ diffutils ]; 14 }; 15 16 testScript = '' 17 CRED_NAME = "testkey" 18 CRED_RAW_FILE = f"/root/{CRED_NAME}" 19 CRED_FILE = f"/root/{CRED_NAME}.cred" 20 21 def systemd_run(machine, cmd): 22 machine.log(f"Executing command (via systemd-run): \"{cmd}\"") 23 24 (status, out) = machine.execute( " ".join([ 25 "systemd-run", 26 "--service-type=exec", 27 "--quiet", 28 "--wait", 29 "-E PATH=\"$PATH\"", 30 "-p StandardOutput=journal", 31 "-p StandardError=journal", 32 f"-p LoadCredentialEncrypted={CRED_NAME}:{CRED_FILE}", 33 f"$SHELL -c '{cmd}'" 34 ]) ) 35 36 if status != 0: 37 raise Exception(f"systemd_run failed (status {status})") 38 39 machine.log("systemd-run finished successfully") 40 41 machine.wait_for_unit("multi-user.target") 42 43 with subtest("Check whether TPM device exists"): 44 machine.succeed("test -e /dev/tpm0") 45 machine.succeed("test -e /dev/tpmrm0") 46 47 with subtest("Check whether systemd-creds detects TPM2 correctly"): 48 cmd = "systemd-creds has-tpm2" 49 machine.log(f"Running \"{cmd}\"") 50 (status, _) = machine.execute(cmd) 51 52 # Check exit code equals 0 or 1 (1 means firmware support is missing, which is OK here) 53 if status != 0 and status != 1: 54 raise Exception("systemd-creds failed to detect TPM2") 55 56 with subtest("Encrypt credential using systemd-creds"): 57 machine.succeed(f"dd if=/dev/urandom of={CRED_RAW_FILE} bs=1k count=16") 58 machine.succeed(f"systemd-creds --with-key=host+tpm2 encrypt --name=testkey {CRED_RAW_FILE} {CRED_FILE}") 59 60 with subtest("Write provided credential and check for equality"): 61 CRED_OUT_FILE = f"/root/{CRED_NAME}.out" 62 systemd_run(machine, f"systemd-creds cat testkey > {CRED_OUT_FILE}") 63 machine.succeed(f"cmp --silent -- {CRED_RAW_FILE} {CRED_OUT_FILE}") 64 65 with subtest("Check whether systemd service can see credential in systemd-creds list"): 66 systemd_run(machine, f"systemd-creds list | grep {CRED_NAME}") 67 68 with subtest("Check whether systemd service can access credential in $CREDENTIALS_DIRECTORY"): 69 systemd_run(machine, f"cmp --silent -- $CREDENTIALS_DIRECTORY/{CRED_NAME} {CRED_RAW_FILE}") 70 ''; 71}