Removed unnecessary code and added comments to zlevis-encrypt.

This commit is contained in:
Luc Bijl 2024-11-14 21:58:38 +01:00
parent fa928de63c
commit f830d0f5ab

View file

@ -1,230 +1,242 @@
#!/bin/sh #!/bin/sh
# Exit immediately if a command exits with a non-zero status
set -e set -e
SUMMARY="Encrypts using a TPM2.0 chip binding policy" # Summary of the script's functionality
summary="Encrypts using a TPM2.0 chip binding policy."
# TPM2.0 owner hierarchy to be used by the Operating System
auth="o" auth="o"
# Algorithm type for the TPM2 object with user-provided sensitive data
alg_create_key="keyedhash" alg_create_key="keyedhash"
# Policy options for the TPM2 object
policy_options=""
# Attributes for the created TPM2 object with the JWK as sensitive data
obj_attr="fixedtpm|fixedparent|noda|adminwithpolicy" obj_attr="fixedtpm|fixedparent|noda|adminwithpolicy"
on_exit() { # Display summary if requested
if [ ! -d "$TMP" ] || ! rm -rf "$TMP"; then
echo "Delete temporary files failed!" >&2
echo "You need to clean up: $TMP" >&2
exit 1
fi
}
if [ "$1" = "--summary" ]; then if [ "$1" = "--summary" ]; then
echo "$SUMMARY" echo "$summary"
exit 0 exit 0
fi fi
# Display usage information if input is from a terminal
if [ -t 0 ]; then if [ -t 0 ]; then
exec >&2 exec >&2
echo "Usage: zlevis-encrypt '{\"property\":\"value\"}' < tank.key > tank.jwe"
echo echo
echo "Usage: zlevis-encrypt tpm2 CONFIG < PLAINTEXT > JWE" echo "$summary"
echo
echo "$SUMMARY"
echo echo
echo "This command uses the following configuration properties:" echo "This command uses the following configuration properties:"
echo " hash: <string>; Hash algorithm used in the computation of the object name (default: sha256)." echo " hash: <string> -> Hash algorithm used in the computation of the object name (default: sha256)."
echo " key: <string>; Algorithm type for the generated key (default: ecc)." echo " key: <string> -> Algorithm type for the generated key (default: ecc)."
echo " pcr_bank: <string>; PCR algorithm bank to use for policy (default: first supported by TPM)." echo " pcr_bank: <string> -> PCR algorithm bank to use for policy (default: first supported by TPM)."
echo " pcr_ids: <string>; PCR list used for policy. If not present, no policy is used." echo " pcr_ids: <string> -> PCR list used for policy. If not present, no policy is used."
echo " pcr_digest: <string>; Binary PCR hashes encoded in base64. If not present, the hash values are looked up." echo " pcr_digest: <string> -> Binary PCR hashes encoded in base64. If not present, the hash values are looked up."
exit 2 exit 2
fi fi
# Function to validate PCRs
validate_pcrs() { validate_pcrs() {
_tpm2_tools_v="${1}" _tpm2_tools_v="${1}"
_pcr_bank="${2}" _pcr_bank="${2}"
_pcrs="${3}" _pcrs="${3}"
# Return if PCR bank is not provided
[ -z "${_pcr_bank}" ] && return 1 [ -z "${_pcr_bank}" ] && return 1
[ -z "${_pcrs}" ] && return 0 [ -z "${_pcrs}" ] && return 0
_fail=""
_pcrs_r="" _pcrs_r=""
case "${_tpm2_tools_v}" in case "${_tpm2_tools_v}" in
3) _pcrs_r="$(tpm2_pcrlist -L "${_pcr_bank}":"${_pcrs}" | grep -v "^${_pcr_bank}")" || _fail=$?;;
4|5) _pcrs_r=$(tpm2_pcrread "${_pcr_bank}":"${_pcrs}" | grep -v " ${_pcr_bank}") || _fail=$?;; 4|5) _pcrs_r=$(tpm2_pcrread "${_pcr_bank}":"${_pcrs}" | grep -v " ${_pcr_bank}") || _fail=$?;;
*) _fail=1 *) _fail=1
esac esac
# Check for errors in PCR validation
if [ -n "${_fail}" ] || [ -z "${_pcrs_r}" ]; then if [ -n "${_fail}" ] || [ -z "${_pcrs_r}" ]; then
return 1 return 1
fi fi
return 0 return 0
} }
TPM2TOOLS_VERSION=$(tpm2_createprimary -v | awk -F'version="' '{print $2}' | awk -F'.' '{print $1}') # Function to clean up temporary files on exit
on_exit() {
if [ ! -d "$tmp" ] || ! rm -rf "$tmp"; then
echo "Delete temporary files failed" >&2
echo "You need to clean up: $tmp" >&2
exit 1
fi
}
if [ -z "$TPM2TOOLS_VERSION" ] || [ $TPM2TOOLS_VERSION -lt 3 ] || [ $TPM2TOOLS_VERSION -gt 5 ]; then # Get the version of tpm2-tools
echo "The tpm2 pin requires a tpm2-tools version between 3 and 5" tpm2tools_version=$(tpm2_createprimary -v | awk -F'version="' '{print $2}' | awk -F'.' '{print $1}')
# Check if the tpm2-tools version is supported
if [ -z "$tpm2tools_version" ] || [ $tpm2tools_version -lt 4 ] || [ $tpm2tools_version -gt 5 ]; then
echo "The tpm2 pin requires a tpm2-tools version between 4 and 5"
exit 1 exit 1
fi fi
if [ -z "$TPM2TOOLS_TCTI" ]; then # Create a temporary directory for TPM files
export TPM2TOOLS_TCTI_NAME=device mkdir -p "${tmpdir:-/tmp}"
export TPM2TOOLS_DEVICE_FILE= if ! tmp="$(mktemp -d)"; then
for dev in /dev/tpmrm?; do echo "Creating a temporary dir for TPM files failed" >&2
[ -e "$dev" ] || continue exit 1
TPM2TOOLS_DEVICE_FILE="$dev"
break
done
export TPM2TOOLS_TCTI="$TPM2TOOLS_TCTI_NAME:$TPM2TOOLS_DEVICE_FILE"
if [ -z "$TPM2TOOLS_DEVICE_FILE" ]; then
echo "A TPM2 device with the in-kernel resource manager is needed!" >&2
exit 1
fi
if [ ! -r "$TPM2TOOLS_DEVICE_FILE" ] || [ ! -w "$TPM2TOOLS_DEVICE_FILE" ]; then
echo "The $TPM2TOOLS_DEVICE_FILE device must be readable and writable!" >&2
exit 1
fi
fi fi
# Set up cleanup on exit
trap 'on_exit' EXIT
# Validate the configuration input
if ! cfg="$(jose fmt -j "$1" -Oo- 2>/dev/null)"; then if ! cfg="$(jose fmt -j "$1" -Oo- 2>/dev/null)"; then
echo "Configuration is malformed!" >&2 echo "Configuration is malformed" >&2
exit 1 exit 1
fi fi
mkdir -p "${TMPDIR:-/tmp}" # Store the configuration in a temporary file
if ! TMP="$(mktemp -d)"; then echo "$cfg" > "$tmp"/cfg
echo "Creating a temporary dir for TPM files failed!" >&2
exit 1
fi
echo $cfg > "$TMP"/cfg # Extract hash and key from the configuration, defaulting if not present
hash="$(jose fmt -j- -Og hash -u- < "$TMP"/cfg)" || hash="sha256" hash="$(jose fmt -j- -Og hash -u- < "$tmp"/cfg)" || hash="sha256"
key="$(jose fmt -j- -Og key -u- < "$TMP"/cfg)" || key="ecc" key="$(jose fmt -j- -Og key -u- < "$tmp"/cfg)" || key="ecc"
pcr_bank="$(jose fmt -j- -Og pcr_bank -u- < "$TMP"/cfg)" || { # Determine the PCR bank to use for policy
if ! pcr_bank=$(tpm2_getcap pcrs | pcr_bank="$(jose fmt -j- -Og pcr_bank -u- < "$tmp"/cfg)" || {
awk '/^[[:space:]]*-[[:space:]]*([^:]+):[[:space:]]*\[[[:space:]]*[^][:space:]]/ \ # If not specified, find a non-empty PCR algorithm bank
{found=1; split($0, m, /[-:[:space:]]+/); print m[2]; exit} if ! pcr_bank=$(tpm2_getcap pcrs | awk '/^[[:space:]]*-[[:space:]]*([^:]+):[[:space:]]*\[[[:space:]]*[^][:space:]]/ {found=1; split($0, m, /[-:[:space:]]+/); print m[2]; exit} END {exit !found}'); then
END {exit !found}'); then
echo "Unable to find non-empty PCR algorithm bank, please check output of tpm2_getcap pcrs" >&2 echo "Unable to find non-empty PCR algorithm bank, please check output of tpm2_getcap pcrs" >&2
exit 1 exit 1
fi fi
} }
pcr_cfg=$(tr -d '[:space:]' < "$TMP"/cfg) # Trim spaces from the configuration for parsing PCR IDs
echo $pcr_cfg > "$TMP"/pcr_cfg pcr_cfg=$(tr -d '[:space:]' < "$tmp"/cfg)
echo "$pcr_cfg" > "$tmp"/pcr_cfg
if jose fmt -j- -Og pcr_ids 2>/dev/null < "$TMP"/pcr_cfg && ! pcr_ids="$(jose fmt -j- -Og pcr_ids -u- 2>/dev/null < "$TMP"/pcr_cfg)"; then # Handle both string and JSON array formats for pcr_ids
if jose fmt -j- -Og pcr_ids 2>/dev/null < "$tmp"/pcr_cfg && ! pcr_ids="$(jose fmt -j- -Og pcr_ids -u- 2>/dev/null < "$tmp"/pcr_cfg)"; then
if jose fmt -j- -Og pcr_ids -A 2>/dev/null < "$TMP"/pcr_cfg; then # Attempt to parse as a JSON array if string parsing fails
pcr_ids= if jose fmt -j- -Og pcr_ids -A 2>/dev/null < "$tmp"/pcr_cfg; then
for pcr in $(jose fmt -j- -Og pcr_ids -Af- < "$TMP"/pcr_cfg | tr -d '"'); do # Construct a comma-separated string from the array
for pcr in $(jose fmt -j- -Og pcr_ids -Af- < "$tmp"/pcr_cfg | tr -d '"'); do
pcr_ids=$(printf '%s,%s' "${pcr_ids}" "${pcr}") pcr_ids=$(printf '%s,%s' "${pcr_ids}" "${pcr}")
done done
# Remove leading comma
pcr_ids=${pcr_ids#,} pcr_ids=${pcr_ids#,}
else else
echo "Parsing the requested policy failed!" >&2 echo "Parsing the requested policy failed" >&2
exit 1 exit 1
fi fi
fi fi
if ! validate_pcrs "${TPM2TOOLS_VERSION}" "${pcr_bank}" "${pcr_ids}"; then # Validate the combination of PCR bank and PCR IDs
echo "Unable to validate combination of PCR bank '${pcr_bank}' and PCR IDs '${pcr_ids}'." >&2 if ! validate_pcrs "${tpm2tools_version}" "${pcr_bank}" "${pcr_ids}"; then
echo "Unable to validate combination of PCR bank '${pcr_bank}' and PCR IDs '${pcr_ids}'" >&2
exit 1 exit 1
fi fi
pcr_digest="$(jose fmt -j- -Og pcr_digest -u- < "$TMP"/cfg)" || true # Get the PCR digest from the configuration or read it if not provided
echo $pcr_digest > "$TMP"/pcr_digest pcr_digest="$(jose fmt -j- -Og pcr_digest -u- < "$tmp"/cfg)" || true
echo "$pcr_digest" > "$tmp"/pcr_digest
# Generate a JSON Web Key (JWK)
if ! jwk="$(jose jwk gen -i '{"alg":"A256GCM"}')"; then if ! jwk="$(jose jwk gen -i '{"alg":"A256GCM"}')"; then
echo "Generating a jwk failed!" >&2 echo "Generating a jwk failed" >&2
exit 1 exit 1
fi fi
echo $jwk > "$TMP"/jwk echo "$jwk" > "$tmp"/jwk
trap 'on_exit' EXIT # Create the primary key in the TPM
case "$tpm2tools_version" in
case "$TPM2TOOLS_VERSION" in 4|5) tpm2_createprimary -Q -C "$auth" -g "$hash" -G "$key" -c "$tmp"/primary.context || fail=$?;;
3) tpm2_createprimary -Q -H "$auth" -g "$hash" -G "$key" -C "$TMP"/primary.context || fail=$?;;
4|5) tpm2_createprimary -Q -C "$auth" -g "$hash" -G "$key" -c "$TMP"/primary.context || fail=$?;;
*) fail=1;; *) fail=1;;
esac esac
if [ -n "$fail" ]; then if [ -n "$fail" ]; then
echo "Creating TPM2 primary key failed!" >&2 echo "Creating TPM2 primary key failed" >&2
exit 1 exit 1
fi fi
tpm2_flushcontext -t tpm2_flushcontext -t
policy_options="" # Handle PCRs and policy creation if PCR IDs are provided
if [ -n "$pcr_ids" ]; then if [ -n "$pcr_ids" ]; then
if [ -z "$pcr_digest" ]; then if [ -z "$pcr_digest" ]; then
case "$TPM2TOOLS_VERSION" in case "$tpm2tools_version" in
3) tpm2_pcrlist -Q -L "$pcr_bank":"$pcr_ids" -o "$TMP"/pcr.digest || fail=$?;; 4|5) tpm2_pcrread -Q "$pcr_bank":"$pcr_ids" -o "$tmp"/pcr.digest || fail=$?;;
4|5) tpm2_pcrread -Q "$pcr_bank":"$pcr_ids" -o "$TMP"/pcr.digest || fail=$?;;
*) fail=1;; *) fail=1;;
esac esac
if [ -n "$fail" ]; then if [ -n "$fail" ]; then
echo "Creating PCR hashes file failed!" >&2 echo "Creating PCR hashes file failed" >&2
exit 1 exit 1
fi fi
tpm2_flushcontext -t tpm2_flushcontext -t
else else
if ! jose b64 dec -i- -O "$TMP"/pcr.digest < "$TMP"/pcr_digest; then if ! jose b64 dec -i- -O "$tmp"/pcr.digest < "$tmp"/pcr_digest; then
echo "Error decoding PCR digest!" >&2 echo "Error decoding PCR digest" >&2
exit 1 exit 1
fi fi
fi fi
case "$TPM2TOOLS_VERSION" in # Create the policy based on PCRs
3) tpm2_createpolicy -Q -g "$hash" -P -L "$pcr_bank":"$pcr_ids" -F "$TMP"/pcr.digest -f "$TMP"/pcr.policy || fail=$?;; case "$tpm2tools_version" in
4|5) tpm2_createpolicy -Q -g "$hash" --policy-pcr -l "$pcr_bank":"$pcr_ids" -f "$TMP"/pcr.digest -L "$TMP"/pcr.policy || fail=$?;; 4|5) tpm2_createpolicy -Q -g "$hash" --policy-pcr -l "$pcr_bank":"$pcr_ids" -f "$tmp"/pcr.digest -L "$tmp"/pcr.policy || fail=$?;;
*) fail=1;; *) fail=1;;
esac esac
if [ -n "$fail" ]; then if [ -n "$fail" ]; then
echo "create policy fail, please check the environment or parameters!" echo "create policy fail, please check the environment or parameters"
exit 1 exit 1
fi fi
tpm2_flushcontext -t tpm2_flushcontext -t
tpm2_flushcontext -l tpm2_flushcontext -l
policy_options="$TMP/pcr.policy" # Set the policy options to the created policy file
policy_options="$tmp/pcr.policy"
else else
# If no PCR IDs are provided, add user authentication to the object attributes
obj_attr="$obj_attr|userwithauth" obj_attr="$obj_attr|userwithauth"
fi fi
case "$TPM2TOOLS_VERSION" in # Create the TPM2 object for the JWK
3) tpm2_create -Q -g "$hash" -G "$alg_create_key" -c "$TMP"/primary.context -u "$TMP"/jwk.pub -r "$TMP"/jwk.priv -A "$obj_attr" -L "$policy_options" -I- < "$TMP"/jwk || fail=$?;; case "$tpm2tools_version" in
4|5) tpm2_create -Q -g "$hash" -C "$TMP"/primary.context -u "$TMP"/jwk.pub -r "$TMP"/jwk.priv -a "$obj_attr" -L "$policy_options" -i- < "$TMP"/jwk || fail=$?;; 4|5) tpm2_create -Q -g "$hash" -C "$tmp"/primary.context -u "$tmp"/jwk.pub -r "$tmp"/jwk.priv -a "$obj_attr" -L "$policy_options" -i- < "$tmp"/jwk || fail=$?;;
*) fail=1;; *) fail=1;;
esac esac
if [ -n "$fail" ]; then if [ -n "$fail" ]; then
echo "Creating TPM2 object for jwk failed!" >&2 echo "Creating TPM2 object for jwk failed" >&2
exit 1 exit 1
fi fi
tpm2_flushcontext -t tpm2_flushcontext -t
if ! jwk_pub="$(jose b64 enc -I "$TMP"/jwk.pub)"; then # Encode the JWK public and private keys in Base64
echo "Encoding jwk.pub in Base64 failed!" >&2 if ! jwk_pub="$(jose b64 enc -I "$tmp"/jwk.pub)"; then
exit 1 echo "Encoding jwk.pub in Base64 failed" >&2
fi exit 1
fi
if ! jwk_priv="$(jose b64 enc -I "$TMP"/jwk.priv)"; then if ! jwk_priv="$(jose b64 enc -I "$tmp"/jwk.priv)"; then
echo "Encoding jwk.priv in Base64 failed!" >&2 echo "Encoding jwk.priv in Base64 failed" >&2
exit 1 exit 1
fi fi
# Construct the JWE (JSON Web Encryption) structure
jwe='{"protected":{"clevis":{"pin":"tpm2","tpm2":{}}}}' jwe='{"protected":{"clevis":{"pin":"tpm2","tpm2":{}}}}'
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$hash" -s hash -UUUUo-)" jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$hash" -s hash -UUUUo-)"
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$key" -s key -UUUUo-)" jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$key" -s key -UUUUo-)"
# Include PCR bank and IDs in the JWE if they are provided
if [ -n "$pcr_ids" ]; then if [ -n "$pcr_ids" ]; then
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$pcr_bank" -s pcr_bank -UUUUo-)" jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$pcr_bank" -s pcr_bank -UUUUo-)"
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$pcr_ids" -s pcr_ids -UUUUo-)" jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$pcr_ids" -s pcr_ids -UUUUo-)"
fi fi
# Add the Base64 encoded JWK public and private keys to the JWE
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$jwk_pub" -s jwk_pub -UUUUo-)" jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$jwk_pub" -s jwk_pub -UUUUo-)"
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$jwk_priv" -s jwk_priv -UUUUo-)" jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tpm2 -q "$jwk_priv" -s jwk_priv -UUUUo-)"
[ -d "${TMP}" ] && rm -rf "${TMP}" # Clean up the temporary directory at the end of the script
[ -d "${tmp}" ] && rm -rf "${tmp}"
# Output the final JWE
exec jose jwe enc -i- -k- -I- -c < <(echo -n "$jwe$jwk"; /bin/cat) exec jose jwe enc -i- -k- -I- -c < <(echo -n "$jwe$jwk"; /bin/cat)