#!/bin/sh
#
# Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
# (Royal Institute of Technology, Stockholm, Sweden).
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the Institute nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
# $Id$
#

top_srcdir="@top_srcdir@"
env_setup="@env_setup@"
srcdir="@srcdir@"
objdir="@objdir@"

. ${env_setup}
. ${top_srcdir}/tests/bin/test-lib.sh

# If there is no useful db support compiled in, disable test
../db/have-db || exit 77

R=TEST.H5L.SE

port=@port@

keytabfile=${objdir}/server.keytab
keytab="FILE:${keytabfile}"
nokeytab="FILE:no-such-keytab"
cache="FILE:krb5ccfile"

kinit="${TESTS_ENVIRONMENT} ../../kuser/kinit -c $cache ${afs_no_afslog}"
kdestroy="${TESTS_ENVIRONMENT} ../../kuser/kdestroy -c $cache"
klist="${TESTS_ENVIRONMENT} ../../kuser/heimtools klist -c $cache"
kgetcred="${TESTS_ENVIRONMENT} ../../kuser/kgetcred -c $cache"
kadmin="${TESTS_ENVIRONMENT} ../../kadmin/kadmin -l -A -r $R"
kdc="${TESTS_ENVIRONMENT} ../../kdc/kdc --addresses=localhost -P $port"
ktutil="${TESTS_ENVIRONMENT} ../../admin/ktutil"

context="${TESTS_ENVIRONMENT} ../../lib/gssapi/test_context"

KRB5_CONFIG="${objdir}/krb5.conf"
export KRB5_CONFIG

KRB5CCNAME=${cache}
export KRB5CCNAME

rm -f ${keytabfile}
rm -f current-db*
rm -f out-*
rm -f mkey.file*

test_init

alias test_run=test_run_x

test_section "Creating database"
# add both lucid and lucid.test.h5l.se to simulate aliases
# XXX ext should ext aliases too
test_run ${kadmin} <<EOF
init --realm-max-ticket-life=1day --realm-max-renewable-life=1month ${R}
mod --attributes=+ok-as-delegate krbtgt/${R}@${R}
add -p p1 --use-defaults host/lucid.test.h5l.se@${R}
ext -k ${keytab} host/lucid.test.h5l.se@${R}
add -p p1 --use-defaults host/ok-delegate.test.h5l.se@${R}
mod --attributes=+ok-as-delegate host/ok-delegate.test.h5l.se@${R}
ext -k ${keytab} host/ok-delegate.test.h5l.se@${R}
add -p p1 --use-defaults host/short@${R}
mod --alias=host/long.test.h5l.se@${R} host/short@${R}
ext -k ${keytab} host/short@${R}
EOF
test_run ${ktutil} -k ${keytab} rename --no-delete host/short@${R} host/long.test.h5l.se@${R}

# Create a server principal with no AES
test_run ${kadmin} <<EOF
add -p kaka --use-defaults digest/${R}@${R}
add -p u1 --use-defaults user1@${R}
mod --alias=user1.alias user1@${R}
add -p p1 --use-defaults host/no-aes.test.h5l.se@${R}
del_enctype host/no-aes.test.h5l.se@${R} aes256-cts-hmac-sha1-96 aes128-cts-hmac-sha1-96
ext -k ${keytab} host/no-aes.test.h5l.se@${R}
check ${R}
EOF

test_run ${kadmin} get host/no-aes.test.h5l.se@${R}

echo u1 > ${objdir}/foopassword

test_section "Starting kdc"
test_run ${kdc} --detach --testing
kdcpid=`getpid kdc`

cleanup() {
    echo signal killing kdc
    kill -9 ${kdcpid} 2>/dev/null
    trap '' EXIT INT TERM
    cat messages.log
    exit 1
}
trap cleanup EXIT INT TERM

test_section "gss_acquire_cred_with_password"
${kdestroy} 2>/dev/null || true
test_run ${context} --client-name=user1@${R} --client-password=u1 --mech-type=krb5 \
        host@lucid.test.h5l.se
# klist should fail (no tickets saved)
test_run not ${klist}
# These must fail (because wrong password)
test_run not ${context} --client-name=user1@${R} --client-password=u2 --mech-type=krb5 \
        host@lucid.test.h5l.se
test_run not ${klist}
test_run not ${context} --client-name=user1@${R} --client-password=u2 --mech-types='' \
        --mech-type=krb5 host@lucid.test.h5l.se
test_run not ${klist}
test_run not ${context} --client-name=user1@${R} --client-password=u2 --mech-types=krb5 \
        --mech-type=krb5 host@lucid.test.h5l.se
test_run not ${klist}
test_run not ${context} --client-name=user1@${R} --client-password=u2 --mech-types=all \
        --mech-type=krb5 host@lucid.test.h5l.se
test_run not ${klist}
test_run not ${context} --client-name=user1@${R} --client-password=u2 \
        --mech-types=krb5 --mech-type=krb5 host@lucid.test.h5l.se
# gss_acquire_cred_with_password() must not have side-effects
test_run not ${klist}

test_section "Getting client initial tickets"
test_run ${kinit} --password-file=${objdir}/foopassword --forwardable user1@${R}

test_section "test unreadable/non existant keytab and its error message"
test_run ${context} --mech-type=krb5 host@lucid.test.h5l.se

mv ${keytabfile} ${keytabfile}.no

test_section "checking non existant keytabfile (krb5)"
test_run not ${context} --mech-type=krb5 host@lucid.test.h5l.se

test_section "checking non existant keytabfile (spnego)"
test_run not ${context} --mech-type=spnego --mech-types=spnego,krb5 \
	host@lucid.test.h5l.se

mv ${keytabfile}.no ${keytabfile}

test_section "test naming combinations - plain"
test_run ${context} --name-type=hostbased-service host@lucid.test.h5l.se

test_section "test naming combinations - plain w/ short-form hostname"
test_run ${context} --name-type=hostbased-service host@lucid

test_section "test naming combinations - plain (krb5)"
test_run ${context} --name-type=krb5-principal-name host/lucid.test.h5l.se@${R}

test_section "test naming combinations - plain (krb5 realmless)"
test_run ${context} --name-type=krb5-principal-name host/lucid.test.h5l.se

test_section "test naming combinations - plain (krb5 realmless short-form)"
test_run ${context} --name-type=krb5-principal-name host/lucid

test_section "creating short-form princ"
test_run ${kadmin} add -p p1 --use-defaults host/lucid@${R}
test_run ${kadmin} ext -k ${keytab} host/lucid@${R}

#test_section "dns canon on (long name) OFF, need dns_wrapper"
#test_run ${context} --dns-canon host@lucid.test.h5l.se

test_section "dns canon off (long name)"
test_run ${context} --no-dns-canon host@lucid.test.h5l.se

test_section "dns canon off (short name)"
test_run ${context} --no-dns-canon host@lucid

test_section "dns canon off (short name, krb5)"
test_run ${context} --no-dns-canon --name-type=krb5-principal-name host/lucid@${R}

test_section "dns canon off (short name, krb5, no realm)"
test_run ${context} --no-dns-canon --name-type=krb5-principal-name host/lucid

test_section "test context building"
for mech in krb5 krb5iov spnego spnegoiov; do
	if [ "$mech" = "krb5iov" ] ; then
	    mech="krb5"
	    iov="--iov"
	fi
	if [ "$mech" = "spnegoiov" ] ; then
	    mech="spnego"
	    iov="--iov"
	fi

	test_section "${mech} no-mutual ${iov}"
	test_run ${context} --mech-type=${mech} \
	    --wrapunwrap ${iov} \
            --localname=mapped_user1 \
	    --name-type=hostbased-service host@lucid.test.h5l.se

	test_section "${mech} mutual ${iov}"
	test_run ${context} --mech-type=${mech} \
	    --mutual \
	    --wrapunwrap ${iov} \
	    --name-type=hostbased-service host@lucid.test.h5l.se

	test_section "${mech} delegate ${iov}"
	test_run ${context} --mech-type=${mech} \
	    --delegate \
	    --wrapunwrap ${iov} \
	    --name-type=hostbased-service host@lucid.test.h5l.se

	test_section "${mech} mutual delegate ${iov}"
	test_run ${context} --mech-type=${mech} \
	    --mutual --delegate \
	    --wrapunwrap ${iov} \
	    --name-type=hostbased-service host@lucid.test.h5l.se
done

test_section "test authz-data (krb5)"
test_run ${context} --mech-type=krb5 \
    --mutual \
    --wrapunwrap \
    --on-behalf-of=foo@BAR.TEST.H5L.SE \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "dce-style"
for mech in krb5 krb5iov spnego; do
	iov=""
	if [ "$mech" = "krb5iov" ] ; then
	    mech="krb5"
	    iov="--iov"
	fi
	if [ "$mech" = "spnegoiov" ] ; then
	    mech="spnego"
	    iov="--iov"
	fi

	test_section "${mech}: dce-style ${iov}"
	test_run ${context} \
	    --mech-type=${mech} \
	    --mutual \
	    --dce-style \
	    --wrapunwrap ${iov} \
	    --name-type=hostbased-service host@lucid.test.h5l.se
done

test_section "export-import-context"
for mech in krb5 krb5iov spnego spnegoiov; do
	iov=""
	if [ "$mech" = "krb5iov" ] ; then
	    mech="krb5"
	    iov="--iov"
	fi
	if [ "$mech" = "spnegoiov" ] ; then
	    mech="spnego"
	    iov="--iov"
	fi

	test_section "${mech}: export-import-context ${iov}"
	test_run ${context} \
	    --mech-type=${mech} \
	    --mutual \
	    --export-import-context \
	    --wrapunwrap ${iov} \
	    --name-type=hostbased-service host@lucid.test.h5l.se
done

test_section "test gsskrb5_register_acceptor_identity"

cp ${keytabfile} ${keytabfile}.new
for mech in krb5 spnego; do
	test_section "${mech}: acceptor_identity positive"
	test_run ${context} --gsskrb5-acceptor-identity=${keytabfile}.new \
		--mech-type=$mech host@lucid.test.h5l.se

	test_section "${mech}: acceptor_identity positive (prefix)"
	test_run ${context} --gsskrb5-acceptor-identity=FILE:${keytabfile}.new \
		--mech-type=$mech host@lucid.test.h5l.se

	test_section "${mech}: acceptor_identity negative (expected failure)"
	test_run not ${context} --gsskrb5-acceptor-identity=${keytabfile}.foo \
		--mech-type=$mech host@lucid.test.h5l.se
done

rm ${keytabfile}.new

test_section "test PAC-based name canonicalization"

${kdestroy} 2>/dev/null || true
test_run ${kinit} --password-file=${objdir}/foopassword user1.alias@${R}

for mech in krb5 spnego; do
	test_section "${mech}: PAC name canonicalization"
	KRB5_CONFIG="${objdir}/new_clients_k5.conf" ${context} -v \
		--mech-type=$mech host@lucid.test.h5l.se > name-canon.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "client name:" name-canon.log | grep "user1.alias@TEST.H5L.SE" > /dev/null && \
		{ echo "client name not canonicalized"; exit 1; }
	grep "client name:" name-canon.log | grep "user1@TEST.H5L.SE" > /dev/null || \
		{ echo "wrong client name"; exit 1; }
done

test_section "test channel-bindings"

for mech in krb5 spnego; do
	test_section "${mech}: initiator only bindings"
	${context} -v --i-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null && \
		{ echo "channel-bound flag unexpected"; exit 1; }

	test_section "${mech}: acceptor only bindings"
	${context} -v --a-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null && \
		{ echo "channel-bound flag unexpected"; exit 1; }

	test_section "${mech}: matching bindings"
	${context} -v --i-channel-bindings=abc --a-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null || \
		{ echo "no channel-bound flag"; exit 1; }

	test_section "${mech}: non matching bindings (expected failure)"
	test_run not ${context} --i-channel-bindings=abc --a-channel-bindings=xyz \
		--mech-type=$mech host@lucid.test.h5l.se

	test_section "${mech}: initiator only bindings (client-aware)"
	KRB5_CONFIG="${objdir}/new_clients_k5.conf" ${context} -v \
		--i-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null && \
		{ echo "channel-bound flag unexpected"; exit 1; }

	test_section "${mech}: acceptor only bindings (client-aware, expected failure)"
	test_run not env KRB5_CONFIG="${objdir}/new_clients_k5.conf" ${context} \
		--a-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se

	test_section "${mech}: matching bindings (client-aware)"
	KRB5_CONFIG="${objdir}/new_clients_k5.conf" ${context} -v \
		--i-channel-bindings=abc --a-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null || \
		{ echo "no channel-bound flag"; exit 1; }

	test_section "${mech}: non matching bindings (client-aware, expected failure)"
	test_run not env KRB5_CONFIG="${objdir}/new_clients_k5.conf" ${context} \
		--i-channel-bindings=abc --a-channel-bindings=xyz \
		--mech-type=$mech host@lucid.test.h5l.se

	test_section "${mech}: initiator null bindings bound (client-aware-flag)"
	${context} -v --i-channel-bound \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null && \
		{ echo "channel-bound flag unexpected"; exit 1; }

	test_section "${mech}: initiator only bindings (client-aware-flag)"
	${context} -v --i-channel-bound \
		--i-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null && \
		{ echo "channel-bound flag unexpected"; exit 1; }

	test_section "${mech}: acceptor only bindings (client-aware-flag, expected failure)"
	test_run not ${context} --i-channel-bound \
		--a-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se

	test_section "${mech}: matching bindings (client-aware-flag)"
	${context} -v --i-channel-bound \
		--i-channel-bindings=abc --a-channel-bindings=abc \
		--mech-type=$mech host@lucid.test.h5l.se > cbinding.log 2>&1 || \
		{ echo "context failed"; exit 1; }
	grep "sflags:" cbinding.log | grep "channel-bound" > /dev/null || \
		{ echo "no channel-bound flag"; exit 1; }

	test_section "${mech}: non matching bindings (client-aware-flag, expected failure)"
	test_run not ${context} --i-channel-bound \
		--i-channel-bindings=abc --a-channel-bindings=xyz \
		--mech-type=$mech host@lucid.test.h5l.se
done

#echo "sasl-digest-md5"
#${context}  --mech-type=sasl-digest-md5 \
#    --name-type=hostbased-service \
#    host@lucid.test.h5l.se || exit 1


test_section "gss-api session key check"

# this will break when oneone invents a cooler enctype then aes256-cts-hmac-sha1-96
coolenctype="aes256-cts-hmac-sha384-192"
limit_enctype="aes256-cts-hmac-sha1-96"

test_section "Getting client initial tickets for session key tests"
test_run ${kinit} --password-file=${objdir}/foopassword user1@${R}

test_section "Building context on cred w/o aes, but still ${coolenctype} session key"
test_run ${context} \
    --mech-type=krb5 \
    --mutual-auth \
    --session-enctype=${coolenctype} \
    --name-type=hostbased-service host@no-aes.test.h5l.se

test_section "Building context on cred, check if its limited still"
test_run ${context} \
    --mech-type=krb5 \
    --client-name=user1@${R} \
    --limit-enctype="${limit_enctype}" \
    --mutual-auth \
    --name-type=hostbased-service host@no-aes.test.h5l.se


test_section "ok-as-delegate"

test_section "Getting client initial tickets (forwardable)"
test_run ${kinit} --forwardable \
    --password-file=${objdir}/foopassword user1@${R}

test_section "ok-as-delegate not used"
test_run ${context} \
    --mech-type=krb5 \
    --delegate \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "host without ok-as-delegate with policy-delegate"
test_run ${context} \
    --mech-type=krb5 \
    --policy-delegate \
    --server-no-delegate \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "ok-as-delegate used by policy"
test_run ${context} \
    --mech-type=krb5 \
    --policy-delegate \
    --name-type=hostbased-service host@ok-delegate.test.h5l.se

test_section "Getting client initial tickets with --ok-as-delegate"
test_run ${kinit} --ok-as-delegate --forwardable \
    --password-file=${objdir}/foopassword user1@${R}

test_section "policy delegate to non delegate host"
test_run ${context} \
    --mech-type=krb5 \
    --policy-delegate \
    --server-no-delegate \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "ok-as-delegate"
test_run ${context} \
    --mech-type=krb5 \
    --delegate \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "export/import cred"

test_section "export-import cred (krb5)"
test_run ${context} \
    --mech-type=krb5 \
    --delegate \
    --export-import-cred \
    --name-type=hostbased-service host@ok-delegate.test.h5l.se

test_section "export-import cred (spnego)"
test_run ${context} \
    --mech-type=spnego \
    --delegate \
    --export-import-cred \
    --name-type=hostbased-service host@ok-delegate.test.h5l.se


test_section "time diffs between client and server"

test_section "Getting client initial ticket for time offset tests"
test_run ${kinit} --password-file=${objdir}/foopassword user1@${R}

test_section "No time offset"
test_run ${context} \
    --mech-type=krb5 \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "Getting client initial ticket"
test_run ${kinit} --password-file=${objdir}/foopassword user1@${R}

test_section "Server time offset"
test_run ${context} \
    --mech-type=krb5 \
    --mutual-auth \
    --server-time-offset=3600 \
    --max-loops=3 \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "Server time offset (cached ?)"
test_run ${context} \
    --mech-type=krb5 \
    --mutual-auth \
    --server-time-offset=3600 \
    --max-loops=2 \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "Getting client initial ticket for client time offset"
test_run ${kinit} --password-file=${objdir}/foopassword user1@${R}
# Pre-poplute the cache since tgs-req will fail since our time is wrong
test_run ${kgetcred} host/lucid.test.h5l.se@${R}

test_section "Client time offset"
test_run ${context} \
    --mech-type=krb5 \
    --mutual-auth \
    --client-time-offset=3600 \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "Getting client initial tickets (use-referrals)"
test_run ${kinit} \
    --password-file=${objdir}/foopassword \
    --use-referrals user1@${R}

# XXX these tests really need to use somethat that resolve to something
test_section "host@short"
test_run ${context} \
    --mech-type=krb5 \
    host@short

test_section "host/short (krb5-principal-name)"
test_run ${context} \
    --mech-type=krb5 \
    --name-type=krb5-principal-name host/short

test_section "host@long.test.h5l.se"
test_run ${context} \
    --mech-type=krb5 \
    host@long.test.h5l.se

test_section "host/long.test.h5l.se (krb5-principal-name)"
test_run ${context} \
    --mech-type=krb5 \
    --name-type=krb5-principal-name \
    host/long.test.h5l.se

test_section "threaded context establishment"
test_section "Getting client initial tickets for threaded test"
test_run ${kinit} --password-file=${objdir}/foopassword user1@${R}

test_section "threaded gss context (krb5)"
test_run ${context} \
    --mech-type=krb5 \
    --threaded \
    --num-threads=4 \
    --max-loops=5 \
    --name-type=hostbased-service host@lucid.test.h5l.se

test_section "threaded gss context (spnego)"
test_run ${context} \
    --mech-type=spnego \
    --threaded \
    --num-threads=4 \
    --max-loops=5 \
    --name-type=hostbased-service host@lucid.test.h5l.se

# PKINIT credential store tests using gsstool
# These test the new pkinit_* credential store keys

gsstool="${TESTS_ENVIRONMENT} ../../lib/gssapi/gsstool"
hxtool="${TESTS_ENVIRONMENT} ../../lib/hx509/hxtool"
hx509_data="${top_srcdir}/lib/hx509/data"
keyfile="${hx509_data}/key.der"
keyfile2="${hx509_data}/key2.der"

# Check if PKINIT is available
pkinit_available=no
if ${kinit} --help 2>&1 | grep "CA certificates" > /dev/null; then
    pkinit_available=yes
fi
# Check if we have RSA support
if ${hxtool} info 2>/dev/null | grep 'rsa: hx509 null RSA' > /dev/null; then
    pkinit_available=no
fi
if ${hxtool} info 2>/dev/null | grep 'rand: not available' > /dev/null; then
    pkinit_available=no
fi

if test "$pkinit_available" = yes; then
    test_section "PKINIT credential store tests"

    # Create certificates for PKINIT testing
    echo "Setting up PKINIT certificates"

    ${hxtool} request-create \
        --subject="CN=user1,DC=test,DC=h5l,DC=se" \
        --key=FILE:${keyfile2} \
        ${objdir}/req-pkinit-user1.der || exit 1

    # Issue self-signed CA cert
    ${hxtool} issue-certificate \
        --self-signed \
        --issue-ca \
        --ca-private-key=FILE:${keyfile} \
        --subject="CN=CA,DC=test,DC=h5l,DC=se" \
        --certificate="FILE:${objdir}/pkinit-ca.crt" || exit 1

    # Issue KDC certificate
    ${hxtool} request-create \
        --subject="CN=kdc,DC=test,DC=h5l,DC=se" \
        --key=FILE:${keyfile2} \
        ${objdir}/req-kdc.der || exit 1

    ${hxtool} issue-certificate \
        --ca-certificate=FILE:${objdir}/pkinit-ca.crt,${keyfile} \
        --type="pkinit-kdc" \
        --pk-init-principal="krbtgt/${R}@${R}" \
        --req="PKCS10:${objdir}/req-kdc.der" \
        --certificate="FILE:${objdir}/pkinit-kdc.crt" || exit 1

    # Issue user certificate with PKINIT SAN
    ${hxtool} issue-certificate \
        --ca-certificate=FILE:${objdir}/pkinit-ca.crt,${keyfile} \
        --type="pkinit-client" \
        --pk-init-principal="user1@${R}" \
        --req="PKCS10:${objdir}/req-pkinit-user1.der" \
        --lifetime=7d \
        --certificate="FILE:${objdir}/pkinit-user1.crt" || exit 1

    # Restart KDC with PKINIT configuration
    echo "Restarting KDC with PKINIT support"
    kill ${kdcpid} 2>/dev/null
    sleep 1

    # Create PKINIT-enabled krb5.conf
    cat > ${objdir}/krb5-pkinit-gss.conf <<EOF
[libdefaults]
    default_realm = ${R}
    no-addresses = TRUE
    allow_weak_crypto = TRUE

[realms]
    ${R} = {
        kdc = localhost:${port}
    }

[kdc]
    database = {
        dbname = ${objdir}/current-db
        realm = ${R}
        mkey_file = ${objdir}/mkey.file
    }
    pkinit_identity = FILE:${objdir}/pkinit-kdc.crt,${keyfile2}
    pkinit_anchors = FILE:${objdir}/pkinit-ca.crt
    pkinit_mappings_file = ${objdir}/pki-mapping
    enable-pkinit = true
    pkinit_allow_proxy_certificate = true

[logging]
    kdc = 0-/FILE:${objdir}/messages.log
    default = 0-/FILE:${objdir}/messages.log
EOF

    # Create PKI mapping file
    cat > ${objdir}/pki-mapping <<EOF
user1@${R}    CN=user1,DC=test,DC=h5l,DC=se
EOF

    KRB5_CONFIG="${objdir}/krb5-pkinit-gss.conf"
    export KRB5_CONFIG

    ${kdc} --detach --testing || { echo "PKINIT KDC failed to start"; cat messages.log; exit 1; }
    kdcpid=`getpid kdc`

    trap "kill ${kdcpid} 2>/dev/null; exit 1" EXIT INT TERM

    test_section "gsstool acquire-cred with PKINIT credential store"

    # Test basic PKINIT with pkinit_client_certs and pkinit_trust_anchors
    test_run ${gsstool} acquire-cred \
        --name=user1@${R} \
        --mech=krb5 \
        "--from=pkinit_client_certs=FILE:${objdir}/pkinit-user1.crt,${keyfile2}" \
        "--from=pkinit_trust_anchors=FILE:${objdir}/pkinit-ca.crt" \
        "--into=ccache=FILE:${objdir}/pkinit-gss-cache" \
        --verbose

    # Verify the credential was acquired
    test_run ${klist} -c FILE:${objdir}/pkinit-gss-cache

    # Test with multiple pkinit_intermediates (even if empty, tests the parsing)
    test_run ${gsstool} acquire-cred \
        --name=user1@${R} \
        --mech=krb5 \
        "--from=pkinit_client_certs=FILE:${objdir}/pkinit-user1.crt,${keyfile2}" \
        "--from=pkinit_trust_anchors=FILE:${objdir}/pkinit-ca.crt" \
        "--from=pkinit_intermediates=FILE:${objdir}/pkinit-ca.crt" \
        "--into=ccache=FILE:${objdir}/pkinit-gss-cache2" \
        --verbose

    test_run ${klist} -c FILE:${objdir}/pkinit-gss-cache2

    # Note: Anonymous PKINIT via GSS_C_NT_ANONYMOUS name type is not yet fully
    # supported. Anonymous PKINIT requires either:
    # 1. A credential store key to explicitly request anonymous mode
    # 2. Or proper handling of GSS_C_NT_ANONYMOUS name import
    # Skipping anonymous PKINIT test for now.

    # Test fast_anon_pkinit credential store key (informational - may fail if
    # KDC doesn't support FAST or anonymous PKINIT)
    test_section "gsstool acquire-cred with FAST anonymous PKINIT (informational)"

    if ${gsstool} acquire-cred \
        --name=user1@${R} \
        --mech=krb5 \
        "--from=pkinit_client_certs=FILE:${objdir}/pkinit-user1.crt,${keyfile2}" \
        "--from=pkinit_trust_anchors=FILE:${objdir}/pkinit-ca.crt" \
        "--from=fast_anon_pkinit=" \
        "--into=ccache=FILE:${objdir}/pkinit-fast-cache" \
        --verbose 2>&1; then
        echo "FAST anonymous PKINIT succeeded"
        test_run ${klist} -c FILE:${objdir}/pkinit-fast-cache
    else
        echo "FAST anonymous PKINIT not available (expected in some configurations)"
    fi

    # Test fast_anon_pkinit_optimistic credential store key (informational)
    if ${gsstool} acquire-cred \
        --name=user1@${R} \
        --mech=krb5 \
        "--from=pkinit_client_certs=FILE:${objdir}/pkinit-user1.crt,${keyfile2}" \
        "--from=pkinit_trust_anchors=FILE:${objdir}/pkinit-ca.crt" \
        "--from=fast_anon_pkinit_optimistic=" \
        "--into=ccache=FILE:${objdir}/pkinit-fast-opt-cache" \
        --verbose 2>&1; then
        echo "FAST optimistic PKINIT succeeded"
        test_run ${klist} -c FILE:${objdir}/pkinit-fast-opt-cache
    else
        echo "FAST optimistic PKINIT not available (expected in some configurations)"
    fi

    # Clean up PKINIT test files
    rm -f ${objdir}/req-pkinit-user1.der ${objdir}/req-kdc.der
    rm -f ${objdir}/pkinit-ca.crt ${objdir}/pkinit-kdc.crt ${objdir}/pkinit-user1.crt
    rm -f ${objdir}/pkinit-gss-cache ${objdir}/pkinit-gss-cache2
    rm -f ${objdir}/pkinit-anon-cache ${objdir}/pkinit-fast-cache ${objdir}/pkinit-fast-opt-cache
    rm -f ${objdir}/krb5-pkinit-gss.conf ${objdir}/pki-mapping

else
    echo "Skipping PKINIT credential store tests (PKINIT not available)"
fi

trap "" EXIT

echo "killing kdc (${kdcpid})"
kill ${kdcpid} 2> /dev/null

test_finish
exit $?
