#!/usr/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/>.
#

SUMMARY="Encrypts using a Tang binding server policy"

if [ "$1" == "--summary" ]; then
    echo "$SUMMARY"
    exit 0
fi

if [ -t 0 ]; then
    exec >&2
    echo
    echo "Usage: clevis encrypt tang CONFIG [-y] < PLAINTEXT > JWE"
    echo
    echo "$SUMMARY"
    echo
    echo "  -y              Use this option for skipping the advertisement"
    echo "                  trust check. This can be useful in automated"
    echo "                  deployments"
    echo
    echo "This command uses the following configuration properties:"
    echo
    echo "  url: <string>   The base URL of the Tang server (REQUIRED)"
    echo
    echo "  thp: <string>   The thumbprint of a trusted signing key"
    echo
    echo "  adv: <string>   A filename containing a trusted advertisement"
    echo "  adv: <object>   A trusted advertisement (raw JSON)"
    echo
    echo "  cacert: <string>  Path to a CA bundle used to verify the Tang"
    echo "                    server's TLS certificate (curl --cacert)"
    echo
    echo "  cert: <string>    Path to the client TLS certificate for mutual"
    echo "                    TLS authentication (curl --cert)"
    echo
    echo "  key: <string>     Path to the private key for the client TLS"
    echo "                    certificate (curl --key). May be omitted if the"
    echo "                    key is bundled in the 'cert' file"
    echo
    echo "Obtaining the thumbprint of a trusted signing key is easy. If you"
    echo "have access to the Tang server's database directory, simply do:"
    echo
    echo "    $ jose jwk thp -i \$DBDIR/\$SIG.jwk "
    echo
    echo "Alternatively, if you have certainty that your network connection"
    echo "is not compromised (not likely), you can download the advertisement"
    echo "yourself using:"
    echo
    echo "    $ curl -f \$URL/adv > adv.jws"
    echo
    exit 2
fi

if ! cfg="$(jose fmt -j- -Oo- <<< "$1" 2>/dev/null)"; then
    echo "Configuration is malformed!" >&2
    exit 1
fi

CLEVIS_DEFAULT_THP_ALG=S256       # SHA-256.
CLEVIS_ALTERNATIVE_THP_ALGS=S1    # SHA-1.

trust=
[ -n "${2}" ] && [ "${2}" == "-y" ] && trust=yes

if ! url="$(jose fmt -j- -Og url -u- <<< "$cfg")"; then
    echo "Missing the required 'url' property!" >&2
    exit 1
fi

thp="$(jose fmt -j- -Og thp -Su- <<< "$cfg")" || true

# Optional (m)TLS parameters. If none are set, curl behaves exactly as before
# (plain HTTP/TLS, no client certificate and default CA verification).
cacert="$(jose fmt -j- -Og cacert -Su- <<< "$cfg")" || true
cert="$(jose fmt -j- -Og cert -Su- <<< "$cfg")" || true
key="$(jose fmt -j- -Og key -Su- <<< "$cfg")" || true

# Validate the (m)TLS file paths up front, matching the 'adv' check below.
# Otherwise a typo'd path either surfaces as a misleading "Unable to fetch
# advertisement" error, or (when 'adv' is inline and curl is never called)
# gets baked into the JWE header and only fails later at decrypt time.
[ -n "$cacert" ] && [ ! -f "$cacert" ] && { echo "CA cert file '$cacert' not found!" >&2; exit 1; }
[ -n "$cert" ]   && [ ! -f "$cert" ]   && { echo "Client cert file '$cert' not found!" >&2; exit 1; }
[ -n "$key" ]    && [ ! -f "$key" ]    && { echo "Client key file '$key' not found!" >&2; exit 1; }

# 'key' on its own is a no-op: curl ignores --key unless --cert is also given.
[ -n "$key" ] && [ -z "$cert" ] && { echo "'key' requires 'cert' to also be set!" >&2; exit 1; }

# Reject http:// when cacert or cert is set: curl would silently ignore them.
if [ -n "$cacert" ] || [ -n "$cert" ]; then
    case "$url" in
        https://*) ;;
        *) echo "TLS options (cacert/cert/key) require an https:// URL!" >&2
           exit 1 ;;
    esac
fi

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

### Get the advertisement
if jws="$(jose fmt -j- -g adv -Oo- <<< "$cfg")"; then
    thp="${thp:-any}"
elif jws="$(jose fmt -j- -g adv -Su- <<< "$cfg")"; then
    if ! [ -f "$jws" ]; then
        echo "Advertisement file '$jws' not found!" >&2
        exit 1
    fi

    if ! jws="$(jose fmt --json="${jws}" -Oo- 2>/dev/null)"; then
        echo "Advertisement file '$jws' is malformed!" >&2
        exit 1
    fi

    thp="${thp:-any}"
elif ! jws="$(curl -sfg "${curl_opts[@]}" "$url/adv/$thp")"; then
    echo "Unable to fetch advertisement: '$url/adv/$thp'!" >&2
    exit 1
fi

if ! jwks="$(jose fmt --json="${jws}" -Og payload -SyOg keys \
             -AUo- 2>/dev/null)"; then
    echo "Advertisement is malformed!" >&2
    exit 1
fi

### Check advertisement validity
ver="$(jose jwk use -i- -r -u verify -o- <<< "$jwks")"
if ! jose jws ver -i "$jws" -k- -a <<< "$ver"; then
    echo "Advertisement is missing signatures!" >&2
    exit 1
fi

### Check advertisement trust
if [ -z "${trust}" ]; then
    if [ -z "$thp" ]; then
        echo "The advertisement contains the following signing keys:" >&2
        echo >&2
        jose jwk thp -i- -a "${CLEVIS_DEFAULT_THP_ALG}" <<< "$ver" >&2
        echo >&2
        read -r -p "Do you wish to trust these keys? [ynYN] " ans < /dev/tty
        [[ "$ans" =~ ^[yY]$ ]] || exit 1

    elif [ "$thp" != "any" ] && \
        ! jose jwk thp -i- -f "${thp}" -a "${CLEVIS_DEFAULT_THP_ALG}" \
          -o /dev/null <<< "$ver"; then
        # Thumbprint of trusted JWK did not match the signature. Let's check
        # alternative thumbprints generated with clevis supported hash
        # algorithms to be sure.
        for alg in ${CLEVIS_ALTERNATIVE_THP_ALGS}; do
            srv="$(jose jwk thp -i- -f "${thp}" -a "${alg}" <<< "${ver}")" \
                   && break
        done
        if [ -z "${srv}" ]; then
            echo "Trusted JWK '$thp' did not sign the advertisement!" >&2
            exit 1
        fi
    fi
fi

### Perform encryption
if ! enc="$(jose jwk use -i- -r -u deriveKey -o- <<< "$jwks")"; then
    echo "Key derivation key not available!" >&2
    exit 1
fi

jose fmt -j "$enc" -Og keys -A || enc="{\"keys\":[$enc]}"

if ! jwk="$(jose fmt -j- -Og keys -Af- <<< "$enc")"; then
    echo "No exchange keys found!" >&2
    exit 1
fi

jwk="$(jose fmt -j- -Od key_ops -o- <<< "$jwk")"
jwk="$(jose fmt -j- -Od alg -o- <<< "$jwk")"
kid="$(jose jwk thp -i- -a "${CLEVIS_DEFAULT_THP_ALG}"  <<< "$jwk")"
jwe='{"protected":{"alg":"ECDH-ES","enc":"A256GCM","clevis":{"pin":"tang","tang":{}}}}'
jwe="$(jose fmt -j "$jwe" -g protected -q "$kid" -s kid -UUo-)"
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tang -q "$url" -s url -UUUUo-)"
# Persist any (m)TLS parameters so decryption can reuse them. These are file
# paths (not secrets); the JWE header is stored in plaintext.
[ -n "$cacert" ] && jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tang -q "$cacert" -s cacert -UUUUo-)"
[ -n "$cert" ]   && jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tang -q "$cert" -s cert -UUUUo-)"
[ -n "$key" ]    && jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tang -q "$key" -s key -UUUUo-)"
jwe="$(jose fmt -j "$jwe" -g protected -g clevis -g tang -j- -s adv -UUUUo- <<< "$jwks")"
exec jose jwe enc -i- -k- -I- -c < <(echo -n "$jwe$jwk"; /bin/cat)
