#!/bin/sh
# =============================================================================
# autopkgtest "tls": self-test of the tls module (throw-away CAs and
# server/client certificates).  Every positive check is paired with a negative
# one ("openssl verify" must REJECT the wrong purpose, CA, or date), otherwise
# a verification that is accidentally switched off would pass unnoticed.
#
# HOW TO ADAPT THIS FILE
#  * Typical use in your own test:
#        fx_load tls
#        fx_cert --server dbserver DNS:db.example      # server certificate
#        fx_cert --client --subject /O=Test/CN=alice alice email:alice@example.org
#        fx_ca other; fx_cert --ca other stranger      # a certificate nobody trusts
#    and hand $FX_CA_CERT, $FX_CERTDIR/NAME.crt and NAME.key to the software.
#  * Run from a checkout:  FX_LIBDIR=$PWD/lib sh debian/tests/tls
# =============================================================================
set -eu

LIB="${FX_LIBDIR:-/usr/share/autopkgtest-helper}"
export FX_LIBDIR="$LIB"
. "$LIB/fixtures.sh"
fx_init
fx_load tls

T=$FX_ROOT/selftest
mkdir "$T"
C=$FX_CERTDIR

# verify_ok CA CERT [openssl verify options]; verify_bad likewise, and the
# output must contain a word that says WHY it failed (so that we do not
# accept a failure for the wrong reason).
verify_ok() {
    _ca=$1 _crt=$2
    shift 2
    openssl verify -CAfile "$_ca" "$@" "$_crt" >"$T/verify.out" 2>&1 ||
        { cat "$T/verify.out"; fx_fail "$_crt not accepted"; }
}
verify_bad() {
    _why=$1 _ca=$2 _crt=$3
    shift 3
    if openssl verify -CAfile "$_ca" "$@" "$_crt" >"$T/verify.out" 2>&1; then
        fx_fail "$_crt was accepted but should fail ($_why)"
    fi
    fx_assert_contains "$T/verify.out" "$_why"
}
# expect_die DESCRIPTION MESSAGE COMMAND...: the library call must abort with
# MESSAGE (a subshell, because fx_die exits)
expect_die() {
    _desc=$1 _msg=$2
    shift 2
    if ( "$@" ) >/dev/null 2>"$T/die.err"; then
        fx_fail "$_desc was accepted"
    fi
    fx_assert_contains "$T/die.err" "$_msg"
}

# ---------------------------------------------------------------------------
fx_step "default certificate: SANs, validity, chains to the CA"
fx_cert testhost DNS:testhost.example IP:192.0.2.1
verify_ok "$FX_CA_CERT" "$C/testhost.crt"
openssl x509 -in "$C/testhost.crt" -noout -ext subjectAltName >"$T/san"
fx_assert_contains "$T/san" "DNS:testhost.example" "IP Address:192.0.2.1"
# Default validity is 3 days: "-checkend N" succeeds only if the certificate
# is still valid N seconds from now.  Two days must pass, four must not.
openssl x509 -in "$C/testhost.crt" -noout -checkend $((2 * 86400)) >/dev/null ||
    fx_fail "certificate valid for less than 2 days"
if openssl x509 -in "$C/testhost.crt" -noout -checkend $((4 * 86400)) >/dev/null; then
    fx_fail "certificate valid for more than 4 days"
fi
# The CA gets one day more than the certificates it signs.
openssl x509 -in "$FX_CA_CERT" -noout -checkend $((3 * 86400 + 3600)) >/dev/null ||
    fx_fail "CA does not outlive the certificate"
# Without SANs the host's names are used.
fx_cert plain
openssl x509 -in "$C/plain.crt" -noout -ext subjectAltName >"$T/san"
fx_assert_contains "$T/san" "DNS:localhost" "IP Address:127.0.0.1"
# FX_CERT_DAYS overrides the default (and is put back afterwards).
FX_CERT_DAYS=10
fx_cert longlived
FX_CERT_DAYS=3
openssl x509 -in "$C/longlived.crt" -noout -checkend $((9 * 86400)) >/dev/null ||
    fx_fail "FX_CERT_DAYS not honoured"

# ---------------------------------------------------------------------------
fx_step "purpose: --server and --client are really different"
fx_cert --server srv
fx_cert --client cli email:cli@example.org
fx_cert both
verify_ok  "$FX_CA_CERT" "$C/srv.crt"  -purpose sslserver
verify_bad "unsuitable certificate purpose" "$FX_CA_CERT" "$C/srv.crt" -purpose sslclient
verify_ok  "$FX_CA_CERT" "$C/cli.crt"  -purpose sslclient
verify_bad "unsuitable certificate purpose" "$FX_CA_CERT" "$C/cli.crt" -purpose sslserver
verify_ok  "$FX_CA_CERT" "$C/both.crt" -purpose sslserver
verify_ok  "$FX_CA_CERT" "$C/both.crt" -purpose sslclient
# --server --client together mean both, like no option
fx_cert --server --client both2
verify_ok  "$FX_CA_CERT" "$C/both2.crt" -purpose sslclient
# A client certificate has no SANs unless asked for; its explicit one is kept.
fx_cert --client nosan
openssl x509 -in "$C/nosan.crt" -noout -text >"$T/text"
grep -q 'Subject Alternative Name' "$T/text" && fx_fail "client certificate got default SANs"
openssl x509 -in "$C/cli.crt" -noout -ext subjectAltName >"$T/san"
fx_assert_contains "$T/san" "email:cli@example.org"

# ---------------------------------------------------------------------------
fx_step "subject is independent of the file name"
fx_cert --client --subject "/O=Example/OU=Test/CN=alice" alice email:alice@example.org
test -f "$C/alice.crt" && test -f "$C/alice.key" || fx_fail "files not named after NAME"
openssl x509 -in "$C/alice.crt" -noout -subject -nameopt RFC2253 >"$T/subj"
fx_assert_contains "$T/subj" "CN=alice,OU=Test,O=Example"
openssl x509 -in "$C/srv.crt" -noout -subject -nameopt RFC2253 >"$T/subj"
fx_assert_contains "$T/subj" "CN=srv"
expect_die "subject without leading slash" "needs a subject" fx_cert --subject "CN=x" bad
expect_die "invalid name" "invalid certificate or CA name" fx_cert "../evil"
expect_die "reserved name" "reserved for the default CA" fx_cert ca

# ---------------------------------------------------------------------------
fx_step "validity: --days, --expired, --not-yet-valid"
fx_cert --days 10 tenday
openssl x509 -in "$C/tenday.crt" -noout -checkend $((9 * 86400)) >/dev/null ||
    fx_fail "--days 10 shorter than 9 days"
if openssl x509 -in "$C/tenday.crt" -noout -checkend $((11 * 86400)) >/dev/null; then
    fx_fail "--days 10 longer than 11 days"
fi
fx_cert --expired old
verify_bad "has expired" "$FX_CA_CERT" "$C/old.crt"
if openssl x509 -in "$C/old.crt" -noout -checkend 0 >/dev/null; then
    fx_fail "expired certificate still valid"
fi
# --days gives the length of the (past or future) validity period
fx_cert --expired --days 2 old2
s=$(openssl x509 -in "$C/old2.crt" -noout -startdate | cut -d= -f2)
e=$(openssl x509 -in "$C/old2.crt" -noout -enddate | cut -d= -f2)
[ $(( $(date -u -d "$e" +%s) - $(date -u -d "$s" +%s) )) -eq $((2 * 86400)) ] ||
    fx_fail "--expired --days 2: validity period is not two days"
fx_cert --not-yet-valid future
verify_bad "not yet valid" "$FX_CA_CERT" "$C/future.crt"
s=$(openssl x509 -in "$C/future.crt" -noout -startdate | cut -d= -f2)
[ $(date -u -d "$s" +%s) -gt $(( $(date +%s) + 86400 )) ] ||
    fx_fail "--not-yet-valid starts too early"
expect_die "--days 0" "needs a positive number" fx_cert --days 0 zero
expect_die "--days abc" "needs a positive number" fx_cert --days abc zero

# ---------------------------------------------------------------------------
fx_step "additional CAs: a certificate nobody trusts"
fx_ca rogue
test -f "$C/rogue.crt" && test -f "$C/rogue.key" || fx_fail "CA files missing"
fx_cert --ca rogue mallory
verify_bad "unable to get local issuer certificate" "$FX_CA_CERT" "$C/mallory.crt"
verify_ok "$C/rogue.crt" "$C/mallory.crt"
# and the default CA's certificates are not trusted by the rogue CA
verify_bad "unable to get local issuer certificate" "$C/rogue.crt" "$C/srv.crt"
openssl x509 -in "$C/mallory.crt" -noout -issuer >"$T/issuer"
fx_assert_contains "$T/issuer" "test CA rogue"
expect_die "second CA of the same name" "exists already" fx_ca rogue
expect_die "certificate named like a CA" "is the name of a CA" fx_cert rogue
expect_die "unknown CA" "does not exist; create it with fx_ca" fx_cert --ca nosuch x
fx_ca shortlived --days 1
if openssl x509 -in "$C/shortlived.crt" -noout -checkend $((2 * 86400)) >/dev/null; then
    fx_fail "fx_ca --days 1 longer than 2 days"
fi
fx_ca custom --subject "/O=Example/CN=Custom Root"
openssl x509 -in "$C/custom.crt" -noout -subject -nameopt RFC2253 >"$T/subj"
fx_assert_contains "$T/subj" "CN=Custom Root,O=Example"

# ---------------------------------------------------------------------------
fx_step "intermediate CA"
fx_ca inter --parent ca
fx_cert --ca inter leaf
# Needs the intermediate certificate; without it the chain is incomplete.
verify_ok  "$FX_CA_CERT" "$C/leaf.crt" -untrusted "$C/inter.crt"
verify_bad "unable to get local issuer certificate" "$FX_CA_CERT" "$C/leaf.crt"
verify_ok  "$FX_CA_CERT" "$C/inter.crt"
openssl x509 -in "$C/leaf.crt" -noout -issuer >"$T/issuer"
fx_assert_contains "$T/issuer" "test CA inter"
# a second level works as well
fx_ca inter2 --parent inter
fx_cert --ca inter2 deepleaf
verify_ok "$FX_CA_CERT" "$C/deepleaf.crt" -untrusted "$C/inter.crt" -untrusted "$C/inter2.crt"
expect_die "unknown parent" "parent CA 'nosuch' does not exist" fx_ca orphan --parent nosuch

# ---------------------------------------------------------------------------
fx_step "--owner gives the key to another user"
if [ "$(id -u)" -eq 0 ] && id nobody >/dev/null 2>&1; then
    grp=$(id -gn nobody)
    fx_cert --owner nobody owned
    [ "$(stat -c '%U %a' "$C/owned.key")" = "nobody 600" ] ||
        fx_fail "key of --owner nobody is $(stat -c '%U %a' "$C/owned.key")"
    [ "$(stat -c '%U' "$C/owned.crt")" = root ] || fx_fail "certificate must stay root's"
    fx_cert --owner "nobody:$grp" owned2
    [ "$(stat -c '%U:%G %a' "$C/owned2.key")" = "nobody:$grp 640" ] ||
        fx_fail "key of --owner nobody:$grp is $(stat -c '%U:%G %a' "$C/owned2.key")"
    expect_die "unknown owner" "cannot give the key to" fx_cert --owner no-such-user-fxt bad
else
    echo "tls: not root or no user 'nobody', skipping the --owner checks"
fi

echo "tls: all tests passed"
