#!/bin/bash

# ocsp-stapling.test


./examples/client/client -v 3 2>&1 | grep -- 'Bad SSL version'
if [ $? -eq 0 ]; then
    echo "TLS 1.2 or lower required"
    echo "Skipped"
    exit 0
fi


# create a unique ready file ending in PID for the script instance ($$) to take
# advantage of port zero solution
WORKSPACE=`pwd`
CERT_DIR="./certs/ocsp"
resume_port=0
ready_file=`pwd`/wolf_ocsp_s1_readyF$$
ready_file2=`pwd`/wolf_ocsp_s1_readyF2$$
printf '%s\n' "ready file:  $ready_file"

test_cnf="ocsp_s1.cnf"

copy_originals() {
    cd $CERT_DIR
    cp intermediate1-ca-cert.pem bak-intermediate1-ca-cert.pem
    cp intermediate2-ca-cert.pem bak-intermediate2-ca-cert.pem
    cp intermediate3-ca-cert.pem bak-intermediate3-ca-cert.pem
    cp ocsp-responder-cert.pem bak-ocsp-responder-cert.pem
    cp root-ca-cert.pem bak-root-ca-cert.pem
    cp server1-cert.pem bak-server1-cert.pem
    cp server2-cert.pem bak-server2-cert.pem
    cp server3-cert.pem bak-server3-cert.pem
    cp server4-cert.pem bak-server4-cert.pem
    cp server5-cert.pem bak-server5-cert.pem
    cd $WORKSPACE
}

restore_originals() {
    cd $CERT_DIR
    mv bak-intermediate1-ca-cert.pem intermediate1-ca-cert.pem
    mv bak-intermediate2-ca-cert.pem intermediate2-ca-cert.pem
    mv bak-intermediate3-ca-cert.pem intermediate3-ca-cert.pem
    mv bak-ocsp-responder-cert.pem ocsp-responder-cert.pem
    mv bak-root-ca-cert.pem root-ca-cert.pem
    mv bak-server1-cert.pem server1-cert.pem
    mv bak-server2-cert.pem server2-cert.pem
    mv bak-server3-cert.pem server3-cert.pem
    mv bak-server4-cert.pem server4-cert.pem
    mv bak-server5-cert.pem server5-cert.pem
}

wait_for_readyFile(){

    counter=0

    while [ ! -s $1 -a "$counter" -lt 20 ]; do
        echo -e "waiting for ready file..."
        sleep 0.1
        counter=$((counter+ 1))
    done

    if test -e $1; then
        echo -e "found ready file, starting client..."
    else
        echo -e "NO ready file ending test..."
        exit 1
    fi

}

remove_single_rF(){
    if test -e $1; then
        printf '%s\n' "removing ready file: $1"
        rm $1
    fi
}

#create a configure file for cert generation with the port 0 solution
create_new_cnf() {
    copy_originals

    printf '%s\n' "Random Port Selected: $RPORTSELECTED"

    printf '%s\n' "#" > $test_cnf
    printf '%s\n' "# openssl configuration file for OCSP certificates" >> $test_cnf
    printf '%s\n' "#" >> $test_cnf
    printf '%s\n' "" >> $test_cnf
    printf '%s\n' "# Extensions to add to a certificate request (intermediate1-ca)" >> $test_cnf
    printf '%s\n' "[ v3_req1 ]" >> $test_cnf
    printf '%s\n' "basicConstraints       = CA:false" >> $test_cnf
    printf '%s\n' "subjectKeyIdentifier   = hash" >> $test_cnf
    printf '%s\n' "authorityKeyIdentifier = keyid:always,issuer:always" >> $test_cnf
    printf '%s\n' "keyUsage               = nonRepudiation, digitalSignature, keyEncipherment" >> $test_cnf
    printf '%s\n' "authorityInfoAccess    = OCSP;URI:http://127.0.0.1:$1" >> $test_cnf
    printf '%s\n' "" >> $test_cnf
    printf '%s\n' "# Extensions to add to a certificate request (intermediate2-ca)" >> $test_cnf
    printf '%s\n' "[ v3_req2 ]" >> $test_cnf
    printf '%s\n' "basicConstraints       = CA:false" >> $test_cnf
    printf '%s\n' "subjectKeyIdentifier   = hash" >> $test_cnf
    printf '%s\n' "authorityKeyIdentifier = keyid:always,issuer:always" >> $test_cnf
    printf '%s\n' "keyUsage               = nonRepudiation, digitalSignature, keyEncipherment" >> $test_cnf
    printf '%s\n' "authorityInfoAccess    = OCSP;URI:http://127.0.0.1:22222" >> $test_cnf
    printf '%s\n' "" >> $test_cnf
    printf '%s\n' "# Extensions to add to a certificate request (intermediate3-ca)" >> $test_cnf
    printf '%s\n' "[ v3_req3 ]" >> $test_cnf
    printf '%s\n' "basicConstraints       = CA:false" >> $test_cnf
    printf '%s\n' "subjectKeyIdentifier   = hash" >> $test_cnf
    printf '%s\n' "authorityKeyIdentifier = keyid:always,issuer:always" >> $test_cnf
    printf '%s\n' "keyUsage               = nonRepudiation, digitalSignature, keyEncipherment" >> $test_cnf
    printf '%s\n' "authorityInfoAccess    = OCSP;URI:http://127.0.0.1:22223" >> $test_cnf
    printf '%s\n' "" >> $test_cnf
    printf '%s\n' "# Extensions for a typical CA" >> $test_cnf
    printf '%s\n' "[ v3_ca ]" >> $test_cnf
    printf '%s\n' "basicConstraints       = CA:true" >> $test_cnf
    printf '%s\n' "subjectKeyIdentifier   = hash" >> $test_cnf
    printf '%s\n' "authorityKeyIdentifier = keyid:always,issuer:always" >> $test_cnf
    printf '%s\n' "keyUsage               = keyCertSign, cRLSign" >> $test_cnf
    printf '%s\n' "authorityInfoAccess    = OCSP;URI:http://127.0.0.1:22220" >> $test_cnf
    printf '%s\n' "" >> $test_cnf
    printf '%s\n' "# OCSP extensions." >> $test_cnf
    printf '%s\n' "[ v3_ocsp ]" >> $test_cnf
    printf '%s\n' "basicConstraints       = CA:false" >> $test_cnf
    printf '%s\n' "subjectKeyIdentifier   = hash" >> $test_cnf
    printf '%s\n' "authorityKeyIdentifier = keyid:always,issuer:always" >> $test_cnf
    printf '%s\n' "extendedKeyUsage       = OCSPSigning" >> $test_cnf

    mv $test_cnf $CERT_DIR/$test_cnf
    cd $CERT_DIR
    CURR_LOC=`pwd`
    printf '%s\n' "echo now in $CURR_LOC"
    ./renewcerts-for-test.sh $test_cnf
    cd $WORKSPACE
}

remove_ready_file() {
    if test -e $ready_file; then
        printf '%s\n' "removing ready file"
        rm $ready_file
    fi
    if test -e $ready_file2; then
        printf '%s\n' "removing ready file: $ready_file2"
        rm $ready_file2
    fi
}

cleanup()
{
    for i in $(jobs -pr)
    do
        kill -s HUP "$i"
    done
    remove_ready_file
    rm $CERT_DIR/$test_cnf
    restore_originals
}
trap cleanup EXIT INT TERM HUP

server=login.live.com
ca=certs/external/baltimore-cybertrust-root.pem

[ ! -x ./examples/client/client ] && echo -e "\n\nClient doesn't exist" && exit 1
./examples/client/client -? 2>&1 | grep -- 'Client not compiled in!'
if [ $? -eq 0 ]; then
    exit 0
fi

# check if supported key size is large enough to handle 4096 bit RSA
size=`./examples/client/client -? | grep "Max RSA key"`
size=`echo ${size//[^0-9]/}`
if [ ! -z "$size" ]; then
    printf 'check on max key size of %d ...' $size
    if [ $size -lt 4096 ]; then
        printf '%s\n' "4096 bit RSA keys not supported"
        exit 0
    fi
    printf 'OK\n'
fi

# test interop fail case
ready_file=`pwd`/wolf_ocsp_readyF$$
printf '%s\n' "ready file:  $ready_file"
./examples/server/server -o -R $ready_file &
wolf_pid=$!
wait_for_readyFile $ready_file
if [ ! -f $ready_file ]; then
    printf '%s\n' "Failed to create ready file: \"$ready_file\""
    exit 1
else
    # should fail if ocspstapling is also enabled
    RPORTSELECTED=`cat $ready_file`
    echo "hi" | openssl s_client -status -connect 127.0.0.1:${RPORTSELECTED} -cert ./certs/client-cert.pem -key ./certs/client-key.pem -CAfile ./certs/ocsp/root-ca-cert.pem
    if [ $? -eq 0 ]; then
        printf '%s\n' "Succeeded when should have failed"
        remove_single_rF $ready_file
        exit 1
    fi
    remove_single_rF $ready_file
    wait $wolf_pid
    if [ $? -ne 1 ]; then
        printf '%s\n' "wolfSSL server unexpected fail value"
        exit 1
    fi
fi


# create a port 0 port to use with openssl ocsp responder
./examples/server/server -R $ready_file -p $resume_port &
wait_for_readyFile $ready_file
if [ ! -f $ready_file ]; then
    printf '%s\n' "Failed to create ready file: \"$ready_file\""
    exit 1
else
    RPORTSELECTED=`cat $ready_file`
    printf '%s\n' "Random port selected: $RPORTSELECTED"
    # Use client connection to shutdown the server cleanly
    ./examples/client/client -p $RPORTSELECTED
    create_new_cnf $RPORTSELECTED
fi
sleep 1

# is our desired server there? - login.live.com doesn't answers PING
#./scripts/ping.test $server 2

# client test against the server
./examples/client/client -C -h $server -p 443 -A $ca -g -W 1
RESULT=$?
[ $RESULT -ne 0 ] && echo -e "\n\nClient connection failed" && exit 1


# Test with example server

./examples/server/server -? 2>&1 | grep -- 'Server not compiled in!'
if [ $? -eq 0 ]; then
    exit 0
fi

# setup ocsp responder
# OLD: ./certs/ocsp/ocspd-intermediate1-ca-issued-certs.sh &
# NEW: openssl isn't being cleaned up, invoke directly in script for cleanup
# purposes!
openssl ocsp -port $RPORTSELECTED -nmin 1                       \
    -index   certs/ocsp/index-intermediate1-ca-issued-certs.txt \
    -rsigner certs/ocsp/ocsp-responder-cert.pem                 \
    -rkey    certs/ocsp/ocsp-responder-key.pem                  \
    -CA      certs/ocsp/intermediate1-ca-cert.pem               \
    "$@" &

sleep 1
# "jobs" is not portable for posix. Must use bash interpreter!
[ $(jobs -r | wc -l) -ne 1 ] && \
             printf '\n\n%s\n' "Setup ocsp responder failed, skipping" && exit 0

printf '%s\n\n' "------------- TEST CASE 1 SHOULD PASS ------------------------"
# client test against our own server - GOOD CERT
./examples/server/server -c certs/ocsp/server1-cert.pem -R $ready_file2 \
                         -k certs/ocsp/server1-key.pem -p $resume_port &
wait_for_readyFile $ready_file2
CLI_PORT=`cat $ready_file2`
./examples/client/client -C -A certs/ocsp/root-ca-cert.pem -W 1 -p $CLI_PORT
RESULT=$?
[ $RESULT -ne 0 ] && printf '\n\n%s\n' "Client connection 2 failed" && exit 1
printf '%s\n\n' "Test PASSED!"

printf '%s\n\n' "------------- TEST CASE 2 SHOULD REVOKE ----------------------"
# client test against our own server - REVOKED CERT
remove_single_rF $ready_file2
./examples/server/server -c certs/ocsp/server2-cert.pem -R $ready_file2 \
                         -k certs/ocsp/server2-key.pem -p $resume_port &
wait_for_readyFile $ready_file2
sleep 1
CLI_PORT=`cat $ready_file2`
./examples/client/client -C -A certs/ocsp/root-ca-cert.pem -W 1 -p $CLI_PORT
RESULT=$?
[ $RESULT -ne 1 ] && printf '\n\n%s\n' "Client connection suceeded $RESULT" \
                  && exit 1
printf '%s\n\n' "Test successfully REVOKED!"


./examples/client/client -v 4 2>&1 | grep -- 'Bad SSL version'
if [ $? -ne 0 ]; then
    printf '%s\n\n' "------------- TEST CASE 3 SHOULD PASS --------------------"
    # client test against our own server - GOOD CERT
    remove_single_rF $ready_file2
    ./examples/server/server -c certs/ocsp/server1-cert.pem -R $ready_file2 \
                             -k certs/ocsp/server1-key.pem -v 4 \
                             -p $resume_port &
    wait_for_readyFile $ready_file2
    CLI_PORT=`cat $ready_file2`
    ./examples/client/client -C -A certs/ocsp/root-ca-cert.pem -W 1 -v 4 -F 1 \
                             -p $CLI_PORT
    RESULT=$?
    [ $RESULT -ne 0 ] && printf '\n\n%s\n' "Client connection 3 failed" && exit 1
    printf '%s\n\n' "Test PASSED!"

    printf '%s\n\n' "------------- TEST CASE 4 SHOULD REVOKE ------------------"
    # client test against our own server - REVOKED CERT
    remove_single_rF $ready_file2
    ./examples/server/server -c certs/ocsp/server2-cert.pem -R $ready_file2 \
                             -k certs/ocsp/server2-key.pem -v 4 \
                             -p $resume_port &
    wait_for_readyFile $ready_file2
    CLI_PORT=`cat $ready_file2`
    ./examples/client/client -C -A certs/ocsp/root-ca-cert.pem -W 1 -v 4 -F 1 \
                             -p $CLI_PORT
    RESULT=$?
    [ $RESULT -ne 1 ] && \
                      printf '\n\n%s\n' "Client connection suceeded $RESULT" \
                      && exit 1
    printf '%s\n\n' "Test successfully REVOKED!"
fi

exit 0
