#!/bin/bash -e
# vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80:
#
# Copyright (c) 2017 Red Hat, Inc.
# Author: Nathaniel McCallum <npmccallum@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/>.
#

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

if [ -t 0 ]; then
    exec >&2
    echo
    echo "Usage: clevis decrypt tang < JWE > PLAINTEXT"
    echo
    exit 2
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")" != "tang" ]; then
    echo "JWE pin mismatch!" >&2
    exit 1
fi

if ! clt="$(jose fmt -j- -Og epk -Oo- <<< "$jhd")"; then
    echo "JWE missing required 'epk' header parameter!" >&2
    exit 1
fi

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

CLEVIS_DEFAULT_THP_ALG=S256       # SHA-256.
CLEVIS_DEFAULT_THP_LEN=43         # Length of SHA-256 thumbprint.
CLEVIS_ALTERNATIVE_THP_ALGS=S1    # SHA-1.

# The adv field is optional when the server provides tang_pub in recovery.
# However, if adv IS present, the kid must match — a mismatch indicates
# a corrupted or tampered header and must fail immediately.
srv=
if keys="$(jose fmt -j- -Og clevis -g tang -g adv -Oo- <<< "${jhd}" 2>/dev/null)"; then
    if [ "${#kid}" -lt "${CLEVIS_DEFAULT_THP_LEN}" ]; then
        echo "WARNING: tang using a deprecated hash for the JWK thumbprints" >&2
    fi

    if ! srv="$(jose jwk thp -i- -f "${kid}" -a "${CLEVIS_DEFAULT_THP_ALG}" \
                <<< "${keys}")"; then
        for alg in ${CLEVIS_ALTERNATIVE_THP_ALGS}; do
            srv="$(jose jwk thp -i- -f "$kid" -a "${alg}" <<< "${keys}")" \
                && break
        done
        if [ -z "${srv}" ]; then
            echo "JWE header validation of 'clevis.tang.adv' failed: key thumbprint does not match" >&2
            exit 1
        fi
    fi
fi

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

# Optional (m)TLS parameters. Absent for JWEs created without mTLS, in which
# case curl behaves exactly as before.
cacert="$(jose fmt -j- -Og clevis -g tang -g cacert -Su- <<< "$jhd")" || true
cert="$(jose fmt -j- -Og clevis -g tang -g cert -Su- <<< "$jhd")" || true
key="$(jose fmt -j- -Og clevis -g tang -g key -Su- <<< "$jhd")" || true

# Fail with a targeted diagnostic if a referenced (m)TLS file is missing.
# Otherwise curl -sfg fails silently below and the generic "Error
# communicating with server" sends the operator chasing network issues,
# when the real cause is a rotated cert or a file left out of the initramfs.
[ -n "$cacert" ] && [ ! -f "$cacert" ] && { echo "mTLS CA cert '$cacert' not found (is it in the initramfs?)" >&2; exit 1; }
[ -n "$cert" ]   && [ ! -f "$cert" ]   && { echo "mTLS client cert '$cert' not found (is it in the initramfs?)" >&2; exit 1; }
[ -n "$key" ]    && [ ! -f "$key" ]    && { echo "mTLS client key '$key' not found (is it in the initramfs?)" >&2; exit 1; }

curl_opts=()
[ -n "$cacert" ] && curl_opts+=(--cacert "$cacert")
[ -n "$cert" ]   && curl_opts+=(--cert "$cert")
[ -n "$key" ]    && curl_opts+=(--key "$key")

if ! crv="$(jose fmt -j- -Og crv -Su- <<< "$clt")"; then
    echo "Unable to determine EPK's curve!" >&2
    exit 1
fi

if ! eph="$(jose jwk gen -i "{\"alg\":\"ECMR\",\"crv\":\"$crv\"}")"; then
    echo "Error generating ephemeral key!" >&2
    exit 1
fi

xfr="$(jose jwk exc -i '{"alg":"ECMR"}' -l- -r- <<< "$clt$eph")"

rec_url="$url/rec/$kid"
ct="Content-Type: application/jwk+json"
if ! full_rep="$(curl -sfg "${curl_opts[@]}" -X POST -H "$ct" --data-binary @- "$rec_url" <<< "$xfr")"; then
    echo "Error communicating with server $url" >&2
    exit 1
fi

# Use tang_pub from recovery response when available.
if tang_pub="$(jose fmt -j- -Og tang_pub -Oo- <<< "$full_rep" 2>/dev/null)"; then
    if tang_pub_key="$(jose jwk thp -i- -f "${kid}" -a "${CLEVIS_DEFAULT_THP_ALG}" \
                       <<< "$tang_pub" 2>/dev/null)"; then
        srv="$tang_pub_key"
    else
        for alg in ${CLEVIS_ALTERNATIVE_THP_ALGS}; do
            tang_pub_key="$(jose jwk thp -i- -f "$kid" -a "${alg}" \
                           <<< "$tang_pub" 2>/dev/null)" \
                && srv="$tang_pub_key" && break
        done
    fi
fi

# Fallback: fetch /adv and look up the exchange key by kid thumbprint.
# This handles the case where adv was not stored (tang_pub mode) but
# the server did not return tang_pub in the /rec response (downgrade,
# mixed-version pool, or proxy stripping the field).
if [ -z "$srv" ]; then
    if adv_jws="$(curl -sfg "${curl_opts[@]}" "${url}/adv" 2>/dev/null)"; then
        if adv_keys="$(jose fmt -j- -Og payload -Su- <<< "$adv_jws" \
                       | jose b64 dec -i- \
                       | jose fmt -j- -Og keys -AUo- 2>/dev/null)"; then
            srv="$(jose jwk thp -i- -f "${kid}" -a "${CLEVIS_DEFAULT_THP_ALG}" \
                   <<< "$adv_keys" 2>/dev/null)" || true
            if [ -z "$srv" ]; then
                for alg in ${CLEVIS_ALTERNATIVE_THP_ALGS}; do
                    srv="$(jose jwk thp -i- -f "$kid" -a "${alg}" \
                           <<< "$adv_keys" 2>/dev/null)" \
                        && break
                done
            fi
        fi
    fi
fi

if [ -z "$srv" ]; then
    echo "Unable to determine server exchange key" >&2
    exit 1
fi

rep="$(jose fmt -j- -Od tang_pub -o- <<< "$full_rep" 2>/dev/null)" || rep="$full_rep"

if ! rep="$(jose fmt -j- -Og kty -q EC -EUUg crv -q "$crv" -EUUo- <<< "$rep")"; then
    echo "Received invalid server reply!" >&2
    exit 1
fi

tmp="$(jose jwk exc -i '{"alg":"ECMR"}' -l- -r- <<< "$eph$srv")"
rep="$(jose jwk pub -i- <<< "$rep")"
jwk="$(jose jwk exc -l- -r- <<< "$rep$tmp")"
(echo -n "$jwk$hdr."; /bin/cat) | jose jwe dec -k- -i-
exit $?
