#!/bin/sh
#
# Copyright (c) 2006 - 2024 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.

#
# Test current (newer) Heimdal clients against older Heimdal KDC
#

top_builddir="@top_builddir@"
env_setup="@env_setup@"
objdir="@objdir@"

. ${env_setup}

# Skip if older Heimdal is not available
OLD_HEIMDAL="@OLD_HEIMDAL@"
if [ -z "$OLD_HEIMDAL" ] || [ ! -d "$OLD_HEIMDAL" ]; then
    echo "Older Heimdal not available (use --with-older-heimdal=PATH), skipping"
    exit 77
fi

# Check for required older Heimdal binaries (for the KDC)
for prog in kdc kadmin; do
    if [ ! -x "${OLD_HEIMDAL}/libexec/${prog}" ] && [ ! -x "${OLD_HEIMDAL}/sbin/${prog}" ] && [ ! -x "${OLD_HEIMDAL}/bin/${prog}" ]; then
        echo "Older Heimdal ${prog} not found, skipping"
        exit 77
    fi
done

testfailed="echo test failed; cat messages.log; exit 1"

R=OLD-TEST.H5L.SE

port=@port@

# Locate older Heimdal kadmin and kdc
if [ -x "${OLD_HEIMDAL}/libexec/kdc" ]; then
    old_kdc="${OLD_HEIMDAL}/libexec/kdc"
elif [ -x "${OLD_HEIMDAL}/sbin/kdc" ]; then
    old_kdc="${OLD_HEIMDAL}/sbin/kdc"
else
    old_kdc="${OLD_HEIMDAL}/bin/kdc"
fi

if [ -x "${OLD_HEIMDAL}/sbin/kadmin" ]; then
    old_kadmin="${OLD_HEIMDAL}/sbin/kadmin"
elif [ -x "${OLD_HEIMDAL}/bin/kadmin" ]; then
    old_kadmin="${OLD_HEIMDAL}/bin/kadmin"
else
    old_kadmin="${OLD_HEIMDAL}/libexec/kadmin"
fi

server=host/datan.test.h5l.se
cache="FILE:${objdir}/new-cache.krb5"
olddir="${objdir}/old-heimdal-kdc"

# Use current (new) client tools
kinit="${kinit} -c $cache ${afs_no_afslog}"
klist="${klist} -c $cache"
kgetcred="${kgetcred} -c $cache"
kdestroy="${kdestroy} -c $cache ${afs_no_unlog}"

# Clean up from previous runs
rm -rf "${olddir}"
rm -f "${cache#FILE:}"

mkdir -p "${olddir}"

> messages.log

ec=0
kdcpid=

cleanup() {
    if [ -n "$kdcpid" ]; then
        echo "Killing older KDC (pid $kdcpid)"
        kill $kdcpid 2>/dev/null
        wait $kdcpid 2>/dev/null
    fi
    trap '' EXIT INT TERM
    cat messages.log
    exit $ec
}
trap cleanup EXIT INT TERM

#
# Create krb5.conf for older KDC
#
cat > ${objdir}/krb5-old-heimdal.conf <<EOF
[libdefaults]
    default_realm = ${R}
    dns_lookup_realm = false
    dns_lookup_kdc = false
    ticket_lifetime = 24h
    forwardable = true

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

[domain_realm]
    .old-test.h5l.se = ${R}
    old-test.h5l.se = ${R}

[kdc]
    database = {
        dbname = ${olddir}/heimdal
        realm = ${R}
        mkey_file = ${olddir}/mkey.file
        log_file = ${olddir}/log
    }

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

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

#
# Create database using older kadmin
#
echo "Creating database with older Heimdal kadmin"
${old_kadmin} -l -r ${R} <<EOF || { echo "Failed to create database"; exit 1; }
init --realm-max-ticket-life=1day --realm-max-renewable-life=1month ${R}
add -p foo --use-defaults foo@${R}
add -p foo --use-defaults ${server}@${R}
EOF

echo foo > ${objdir}/foopassword
echo bar > ${objdir}/barpassword

#
# Start older KDC
#
echo "Starting older Heimdal KDC"
${old_kdc} --addresses=localhost -P ${port} --detach || \
    { echo "Older KDC failed to start"; cat messages.log; exit 1; }

# Find the KDC pid - older Heimdal may use different pid file locations
sleep 1
if [ -f "${olddir}/kdc.pid" ]; then
    kdcpid=$(cat "${olddir}/kdc.pid")
elif [ -f "${HEIM_PIDFILE_DIR}/kdc.pid" ]; then
    kdcpid=$(cat "${HEIM_PIDFILE_DIR}/kdc.pid")
elif [ -f "${HEIM_PIDFILE_DIR}/lt-kdc.pid" ]; then
    kdcpid=$(cat "${HEIM_PIDFILE_DIR}/lt-kdc.pid")
else
    # Try to find by process
    kdcpid=$(pgrep -f "${old_kdc}.*${port}" | head -1)
fi

if [ -z "$kdcpid" ]; then
    echo "Could not determine KDC pid, continuing anyway"
else
    echo "Older KDC running with PID $kdcpid"
fi

# Wait for KDC to be ready
sleep 2

#
# Test 1: Password authentication with current kinit
#
echo ""
echo "=== Test 1: Current Heimdal kinit with password against older KDC ==="

${kinit} --password-file=${objdir}/foopassword foo@${R} || \
    { ec=1; eval "${testfailed}"; }

echo "Verifying ticket"
${klist} || { ec=1; eval "${testfailed}"; }
${klist} | grep "krbtgt/${R}@${R}" > /dev/null || \
    { ec=1; echo "No TGT found"; eval "${testfailed}"; }

echo "Test 1 PASSED"

#
# Test 2: Get service ticket with current kgetcred
#
echo ""
echo "=== Test 2: Current Heimdal kgetcred against older KDC ==="

${kgetcred} ${server}@${R} || { ec=1; eval "${testfailed}"; }
${klist} | grep "${server}@${R}" > /dev/null || \
    { ec=1; echo "No service ticket found"; eval "${testfailed}"; }

echo "Test 2 PASSED"

#
# Test 3: Wrong password should fail
#
echo ""
echo "=== Test 3: Current kinit with wrong password should fail ==="

${kinit} --password-file=${objdir}/barpassword foo@${R} 2>/dev/null && \
    { ec=1; echo "kinit with wrong password should have failed"; eval "${testfailed}"; }

echo "Test 3 PASSED"

#
# Clean up
#
${kdestroy} 2>/dev/null

echo ""
echo "All tests passed!"
ec=0
exit 0
