Skip to content

Instantly share code, notes, and snippets.

@jordiclariana
Created July 24, 2024 10:10
Show Gist options
  • Save jordiclariana/76113b22d42d45fa643257165d41fc5e to your computer and use it in GitHub Desktop.
Save jordiclariana/76113b22d42d45fa643257165d41fc5e to your computer and use it in GitHub Desktop.
TPM2 Seal Secret
#!/usr/bin/env bash
set -e
TMPDIR=$(mktemp -d)
PCRS=0,2,3,7
# Chosen randomly, can be 0x81000000, or 0x81000001, etc
PERSISTENT_HANDLE=0x81010020
cleanup() {
cd "$PWD"
if [ -d "$TMPDIR" ]; then
rm -fr "$TMPDIR"
fi
}
trap cleanup EXIT
if [ "$#" -ne 1 ]; then
echo "ERROR: This command accepts just 1 argument: the file where the secret to seal is"
exit 1
fi
if [ ! -f "$1" ]; then
echo "ERROR: '$1' is not a file or does not exist"
exit 1
fi
PLAIN_SECRET_FILE="${1}"
OLDCD="$PWD"
cd "$TMPDIR"
echo "Read PCRs values and save them to pcrs.bin"
tpm2_pcrread -Q -o pcrs.bin sha256:"$PCRS"
echo "Create PCR policy with given PCRs"
tpm2_createpolicy -Q -f pcrs.bin -l sha256:"$PCRS" --policy-pcr -L policy.digest
echo "Create primary"
tpm2_createprimary -Q -c primary.ctx
echo "Create encrypted object (seal.*) locally"
tpm2_create -Q -C primary.ctx -L policy.digest -i "$PLAIN_SECRET_FILE" -u seal.pub -r seal.priv -c seal.ctx
echo "Load encrypted object to TPM2 chip"
tpm2_load -Q -C primary.ctx -u seal.pub -r seal.priv -c seal.ctx
if tpm2_getcap handles-persistent | grep -q "$PERSISTENT_HANDLE"; then
echo "Remove old sealed secret"
tpm2_evictcontrol -Q -C o -c "$PERSISTENT_HANDLE"
fi
echo "Remove original primary and give full controll to TPM2 chip"
tpm2_evictcontrol -Q -c seal.ctx "$PERSISTENT_HANDLE"
echo "Check secret from TPM2"
RETRIEVED_SECRET=$(tpm2_unseal -c "$PERSISTENT_HANDLE" -p pcr:sha256:"$PCRS")
ORIGINAL_SECRET=$(cat "$PLAIN_SECRET_FILE")
if [ "$RETRIEVED_SECRET" != "$ORIGINAL_SECRET" ]; then
echo "\n\tSomething went wrong, retrieved secret from TPM2 chip seems different from original secret (taken from '$PLAIN_SECRET_FILE')\n"
else
echo -e "\n\tTPM2 unsealed secret and original secret are the same\n"
fi
echo "Clean up everything with:"
echo " tpm2_clear"
echo "or just the sealed secret with"
echo " tpm2_evictcontrol -C o -c $PERSISTENT_HANDLE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment