#!/bin/sh

#set -v
#####################################################ABOUT#####################################################
# This script will generate all needed files for SAS SSL setup (9.3 and 9.4)
# If a password is needed it is always $pass
# 
# Requirement: openssl needs to be installed 
#
# You need to define the following variables:
# tmpPath - Path where all files/folders will be placed
# years - certificate will be valid for X years
# hostn - hostname of the machine
# jbin - home of JRE
# C OU O ST L CN - input needed for the Subject of the SSL Certificate (explanation of the variables is beside it f(see blow))
###############################################################################################################

tmpPath="/tmp/sasssl"
years=10
hostn="$( hostname )"
jbin="/applications/sas94/SASHome/SASPrivateJavaRuntimeEnvironment/9.4/jre/bin"
pass="changeit"

###FOR SSL SUBJECT###
C=DE         #two letter country code
OU=SE      #organisation unit
O="SAS"        #organisation
ST=H        #two letter state code
L=Frankfurt #location
CN=$hostn    #client name - is set to the hostname of the machine

function calcy () {
	if [ $[$1%4] -eq 0 ]; then
		ay=$(expr $ay + 1)
	fi

	if [ $[$1%100] -eq 0 ]; then
		if [ $[$1%400] -eq 0 ]; then
			ay=$(expr $ay + 1)
		else
			ay=$ay
		fi
	fi
}

start=$(date +%Y)
calcy $start
end=$(expr $start + $years)

for i in $(seq $(expr $start + 1) $end) 
	do 
		calcy $i 
	done 

vald=$(expr $years \* 365 + $ay)

if [ "$hostn" == "" ]; then 
	hostn="any"
fi

#rm -r $tmpPath/{keys,certs,requests,keystores,truststores,chain,scripts/java} $tmpPath/scripts $tmpPath
mkdir -p $tmpPath/{keys,certs,requests,keystores,truststores,chain,scripts/java}

echo "generating CA private key  ..."
openssl genrsa -des3 -passout pass:$pass -out $tmpPath/keys/SelfSignedRootCA.key 1024 > /dev/null 2>&1
echo

if [ "$hostn" == "any" ]; then 
	CN="*$(hostname | awk -F'$(hostname -s)' '{print $2}')"
fi

echo "generating server-identity private key  ..."
openssl genrsa -des3 -passout pass:$pass -out $tmpPath/keys/$hostn.key 1024 > /dev/null 2>&1
echo

echo "removing passphrase from CA private key ..."
openssl rsa -passin pass:$pass -in $tmpPath/keys/SelfSignedRootCA.key -out $tmpPath/keys/SelfSignedRootCA-nopw.key > /dev/null 2>&1
mv $tmpPath/keys/SelfSignedRootCA-nopw.key $tmpPath/keys/SelfSignedRootCA.key
echo 

echo "removing passphrase from $hostn private key ..."
openssl rsa -passin pass:$pass -in $tmpPath/keys/$hostn.key -out $tmpPath/keys/$hostn-nopw.key > /dev/null 2>&1
# mv $tmpPath/keys/$hostn-nopw.key $tmpPath/keys/$hostn.key
echo 

echo "generating CA root certificate ($subject) ..."
subject="/C=$C/OU=$OU/O=$O/ST=$ST/L=$L/CN=SelfSignedRootCA"
openssl req -new -key $tmpPath/keys/SelfSignedRootCA.key -x509 -days $vald -out $tmpPath/certs/SelfSignedRootCA.crt -subj $subject
echo

if [ "$hostn" == "any" ]; then
        subject="/C=$C/OU=$OU/O=$O/ST=$ST/L=$L/CN=*$(hostname | awk -F"$(hostname -s)" '{print $2}')"
else
        subject="/C=$C/OU=$OU/O=$O/ST=$ST/L=$L/CN=$CN"
fi

echo "generating certificate sign request ..."
openssl req -new -key $tmpPath/keys/$hostn.key -passin pass:$pass -out $tmpPath/requests/$hostn.csr -subj $subject
echo

echo "generating server-identity certificate ..."
openssl x509 -req -days $vald -in $tmpPath/requests/$hostn.csr -CA $tmpPath/certs/SelfSignedRootCA.crt -CAkey $tmpPath/keys/SelfSignedRootCA.key -CAcreateserial -out $tmpPath/certs/$hostn.crt 
echo

echo "generating server-identity keystores ..."
openssl pkcs12 -export -name $hostn -in $tmpPath/certs/$hostn.crt -inkey $tmpPath/keys/$hostn.key -out $tmpPath/keystores/$hostn.p12 -passin pass:$pass -passout pass:$pass
$jbin/keytool -importkeystore -destkeystore $tmpPath/keystores/$hostn.jks -srckeystore $tmpPath/keystores/$hostn.p12 -srcstoretype pkcs12 -alias $hostn  -srcstorepass $pass -deststorepass $pass
echo

echo "generating certificate chain ..."
cat $tmpPath/certs/$hostn.crt > $tmpPath/chain/chain.pem
cat $tmpPath/certs/SelfSignedRootCA.crt >> $tmpPath/chain/chain.pem
echo

echo "generate the Trusted CA Certificates keystore and import SelfSignedRootCA certificate..."
$jbin/keytool -import -noprompt -alias SelfSignedRootCA -file $tmpPath/certs/SelfSignedRootCA.crt -keystore $tmpPath/truststores/trusted-ca.jks -storepass $pass
echo

echo "check if privte key and certificate match"
echo certificate hash: $(openssl x509 -noout -modulus -in $tmpPath/certs/$hostn.crt | openssl md5 | awk -F"=" '{print $2}')
echo private key hash: $(openssl rsa -noout -modulus -in $tmpPath/keys/$hostn-nopw.key | openssl md5 | awk -F"=" '{print $2}')
echo

echo "display contents of server-identity keystore"
$jbin/keytool -list -keystore $tmpPath/keystores/$hostn.jks -storepass $pass
echo

echo "display contents of Trusted CA Certificates keystore"
$jbin/keytool -list -keystore $tmpPath/truststores/trusted-ca.jks -storepass $pass
echo

echo "######################################################################################################"
echo "THE PASSWORD FOR THE CERTIFICATES AND THE KEYSTORES IS: $pass"
echo "######################################################################################################"
echo
echo
echo "######################################################################################################"
echo "the following files where created:"
echo "$tmpPath/certs/SelfSignedRootCA.crt   - self-signed Root CA certificate"
echo "$tmpPath/certs/SelfSignedRootCA.srl   - self-signed Root CA serial number file"
echo "$tmpPath/certs/$hostn.crt   - server-identity certificate"
echo "$tmpPath/chain/chain.pem   - certificate chain holding server-identiy and self-signed RootCA certificates"
echo "$tmpPath/keys/SelfSignedRootCA.key   - self-signed Root CA key"
echo "$tmpPath/keys/$hostn-nopw.key   - server-identity key without password"
echo "$tmpPath/keys/$hostn.key   - server-identity key with password"
echo "$tmpPath/keystores/$hostn.jks   - java keystore for $hostn"
echo "$tmpPath/keystores/$hostn.p12   - PCK12 keystore for $hostn"
echo "$tmpPath/request/$hostn.csr   - server-identity signing request"
echo "$tmpPath/truststores/trusted-ca.jks   - java keystore holding self-signed Root CA certificate"
echo "$tmpPath/scripts/import_selfsignrootca.bat   - script to run on clients to import SelfSignedRootCA into Windows Keystore"
echo "$tmpPath/ssl/scripts/java/SslWebServer.java   - java code to setup a ssl enabled server in order to test the certificates" 
echo "$tmpPath/ssl/scripts/java/SslWebServer.class   - compiled java code" 
echo "$tmpPath/ssl/scripts/java/SslPoke.java   - java code to setup a ssl client (can be used for testing after the configuration)" 
echo "$tmpPath/ssl/scripts/java/SslPoke.class   - compiled java code (execute: cd $tmpPath/scripts/java; $jbin/java SslPoke [Host] [SSL Port]))" 
echo "$hostn.zip   - contains all of the above"
echo "######################################################################################################"
echo
echo
echo "######################################################################################################"
echo "you need the following files when you will use the SDW to setup SSL:"
echo "$tmpPath/certs/$hostn.crt"
echo "$tmpPath/keys/$hostn-nopw.key"
echo
echo "specify the SSLCALISTLOC in the sasv9.cfg of the SASApp:"
echo "sslcalistloc $tmpPath/certs/SelfSignedRootCA.crt"
echo
echo "to import the certificate into the JRE on the client you need to change to the JRE location with a command prompt"
echo "and the run the following command:"
echo "bin\\keytool -import -alias SelfSignedRootCA -storepass changeit -noprompt -file [path-to-the-SelfSignedRootCA.crt]\\SelfSignedRootCA.crt -keystore lib\\security\\cacerts"
echo "you also need to import the SelfSignedRootCA.crt als Trusted Root Certificate Authority in Windows (double click on the file and then install it)"
echo "######################################################################################################"
