#!/bin/bash -e
# vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80:
#
# Copyright (c) 2017 Red Hat, Inc.
# Author: Javier Martinez Canillas <javierm@redhat.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# First try to use the new version of the PIN implementation
if command -v clevis-pin-tpm2 >/dev/null;
then
    exec clevis-pin-tpm2 decrypt $@
fi

# The owner hierarchy is the one that should be used by the Operating System.
auth="o"

function 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
}

[ $# -eq 1 ] && [ "$1" == "--summary" ] && exit 2

if [ -t 0 ]; then
    exec >&2
    echo
    echo "Usage: clevis decrypt tpm2 < JWE > PLAINTEXT"
    echo
    exit 2
fi

TPM2TOOLS_INFO="$(tpm2_createprimary -v)"

match='version="(.)\.'
[[ $TPM2TOOLS_INFO =~ $match ]] && TPM2TOOLS_VERSION="${BASH_REMATCH[1]}"
if [[ $TPM2TOOLS_VERSION -lt 3 ]] || [[ $TPM2TOOLS_VERSION -gt 5 ]]; then
    echo "The tpm2 pin requires a tpm2-tools version between 3 and 5" >&2
    exit 1
fi

if [ -z "$TPM2TOOLS_TCTI" ]; then
    # Old environment variables for tpm2-tools 3.0
    export TPM2TOOLS_TCTI_NAME=device
    export TPM2TOOLS_DEVICE_FILE=
    for dev in /dev/tpmrm?; do
        [ -e "$dev" ] || continue
        TPM2TOOLS_DEVICE_FILE="$dev"
        break
    done

    # New environment variable for tpm2-tools >= 3.1
    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

read -r -d . hdr

if ! jhd="$(jose b64 dec -i- <<< "$hdr")"; then
    echo "Error decoding JWE protected header!" >&2
    exit 1
fi

if [ "$(jose fmt -j- -Og clevis -g pin -u- <<< "$jhd")" != "tpm2" ]; then
    echo "JWE pin mismatch!" >&2
    exit 1
fi

if ! hash="$(jose fmt -j- -Og clevis -g tpm2 -g hash -Su- <<< "$jhd")"; then
    echo "JWE missing required 'hash' header parameter!" >&2
    exit 1
fi

if ! key="$(jose fmt -j- -Og clevis -g tpm2 -g key -Su- <<< "$jhd")"; then
    echo "JWE missing required 'key' header parameter!" >&2
    exit 1
fi

if ! jwk_pub="$(jose fmt -j- -Og clevis -g tpm2 -g jwk_pub -Su- <<< "$jhd")"; then
    echo "JWE missing required 'jwk_pub' header parameter!" >&2
    exit 1
fi

if ! jwk_priv="$(jose fmt -j- -Og clevis -g tpm2 -g jwk_priv -Su- <<< "$jhd")"; then
    echo "JWE missing required 'jwk_priv' header parameter!" >&2
    exit 1
fi

mkdir -p "${TMPDIR:-/tmp}"
if ! TMP="$(mktemp -d)"; then
    echo "Creating a temporary dir for TPM files failed!" >&2
    exit 1
fi

trap 'on_exit' EXIT

pcr_ids="$(jose fmt -j- -Og clevis -g tpm2 -g pcr_ids -Su- <<< "$jhd")" || true

pcr_spec=''
if [ -n "$pcr_ids" ]; then
    pcr_bank="$(jose fmt -j- -Og clevis -g tpm2 -g pcr_bank -Su- <<< "$jhd")"
    pcr_spec="$pcr_bank:$pcr_ids"
fi

if ! jose b64 dec -i- -O "$TMP"/jwk.pub <<< "$jwk_pub"; then
    echo "Decoding jwk.pub from Base64 failed!" >&2
    exit 1
fi

if ! jose b64 dec -i- -O "$TMP"/jwk.priv <<< "$jwk_priv"; then
    echo "Decoding jwk.priv from Base64 failed!" >&2
    exit 1
fi

case "$TPM2TOOLS_VERSION" in
    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;;
esac
if [ -n "$fail" ]; then
    echo "Creating TPM2 primary key failed!" >&2
    exit 1
fi
tpm2_flushcontext -t

case "$TPM2TOOLS_VERSION" in
    3) tpm2_load -Q -c "$TMP"/primary.context -u "$TMP"/jwk.pub -r "$TMP"/jwk.priv \
                 -C "$TMP"/load.context || fail=$?;;
    4|5) tpm2_load -Q -C "$TMP"/primary.context -u "$TMP"/jwk.pub -r "$TMP"/jwk.priv \
                   -c "$TMP"/load.context || fail=$?;;
    *) fail=1;;
esac
if [ -n "$fail" ]; then
    echo "Loading jwk to TPM2 failed!" >&2
    exit 1
fi
tpm2_flushcontext -t

case "$TPM2TOOLS_VERSION" in
    3) jwk="$(tpm2_unseal -c "$TMP"/load.context ${pcr_spec:+-L $pcr_spec})" || fail=$?;;
    4|5) jwk="$(tpm2_unseal -c "$TMP"/load.context ${pcr_spec:+-p pcr:$pcr_spec})" || fail=$?;;
    *) fail=1;;
esac
if [ -n "$fail" ]; then
    echo "Unsealing jwk from TPM failed!" >&2
    exit 1
fi
tpm2_flushcontext -t

(echo -n "$jwk$hdr."; /bin/cat) | jose jwe dec -k- -i-
exit $?
