at 23.11-beta 2.6 kB view raw
1import ./make-test-python.nix ({ lib, pkgs, ... }: 2{ 3 name = "systemd-credentials-tpm2"; 4 5 meta = { 6 maintainers = with pkgs.lib.maintainers; [ tmarkus ]; 7 }; 8 9 nodes.machine = { pkgs, ... }: { 10 virtualisation.tpm.enable = true; 11 environment.systemPackages = with pkgs; [ diffutils ]; 12 }; 13 14 testScript = '' 15 CRED_NAME = "testkey" 16 CRED_RAW_FILE = f"/root/{CRED_NAME}" 17 CRED_FILE = f"/root/{CRED_NAME}.cred" 18 19 def systemd_run(machine, cmd): 20 machine.log(f"Executing command (via systemd-run): \"{cmd}\"") 21 22 (status, out) = machine.execute( " ".join([ 23 "systemd-run", 24 "--service-type=exec", 25 "--quiet", 26 "--wait", 27 "-E PATH=\"$PATH\"", 28 "-p StandardOutput=journal", 29 "-p StandardError=journal", 30 f"-p LoadCredentialEncrypted={CRED_NAME}:{CRED_FILE}", 31 f"$SHELL -c '{cmd}'" 32 ]) ) 33 34 if status != 0: 35 raise Exception(f"systemd_run failed (status {status})") 36 37 machine.log("systemd-run finished successfully") 38 39 machine.wait_for_unit("multi-user.target") 40 41 with subtest("Check whether TPM device exists"): 42 machine.succeed("test -e /dev/tpm0") 43 machine.succeed("test -e /dev/tpmrm0") 44 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) 49 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") 53 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}") 57 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}") 62 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}") 65 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}") 68 ''; 69})