#!/bin/bash
#
# init_hpkp
#
# This script initializes HTTP Public Key Pinning for our HTTPS configuration page
# It pins the public key generated by createsslcert.sh and the openVPN key
#
# RE (re@mlu.eu)

MYSELF=$( basename $0 )
NOW=$( date +%Y.%m.%d.%H.%M )

if [[ $UID -gt 0 ]]
then
    echo "$MYSELF needs to be run as superuser. You are $USER."
    exit 1
fi

VPNROOT=/etc/openvpn
VPNPREFIX=${VPNROOT}/keys
HOSTPREFIX=/etc/ssl/certs
HOST_NAME=$( cat /etc/hostname )
# suffix based upon portal
#   old: crt [default]
#   new: recordum.net.crt
VPNSUFFIX=crt
ISNEW=$( grep "remote 136.243.69.104 1194" ${VPNROOT}/client.conf )
if [[ ! -z "$ISNEW" ]]
then
    VPNSUFFIX=recordum.net.${VPNSUFFIX}
fi

VPNCERT=${VPNPREFIX}/${HOST_NAME}.${VPNSUFFIX}
HOSTCERT=${HOSTPREFIX}/server.crt
if [[ ! -f "$VPNCERT" ]] || [[ ! -f "$HOSTCERT" ]]
then
    echo "certificates are missing: host <$HOSTCERT> vpn <$VPNCERT>"
    exit 2
fi

openssl x509 -noout -in ${HOSTCERT} -pubkey | openssl asn1parse -noout -inform pem -out /tmp/host_hpkp.key;
HOSTPIN=$( openssl dgst -sha256 -binary /tmp/host_hpkp.key | openssl enc -base64 )
openssl x509 -noout -in ${VPNCERT} -pubkey | openssl asn1parse -noout -inform pem -out /tmp/vpn_hpkp.key;
VPNPIN=$( openssl dgst -sha256 -binary /tmp/vpn_hpkp.key | openssl enc -base64 )
# check for null strings
if [[ -z "$HOSTPIN" ]] || [[ -z "$VPNPIN" ]]
then
    echo "pins are empty: host <$HOSTPIN> vpn <$VPNPIN>"
    exit 3
fi

TMPCFG=/tmp/${HOST_NAME}.hpkp
MAXAGE=2592000
cat > ${TMPCFG} <<EOF
# generated by init_hpkp: ${NOW}
<VirtualHost *:443>

	ServerAdmin webmaster@localhost

	SSLEngine on
	SSLCertificateFile	/etc/ssl/certs/server.crt
	SSLCertificateKeyFile /etc/ssl/private/server.key

	<IfModule mod_headers.c>
		Header set Public-Key-Pins "pin-sha256=\"${HOSTPIN}\"; pin-sha256=\"${VPNPIN}\"; max-age=${MAXAGE}; includeSubDomains"
	</IfModule>

	DocumentRoot /var/www/public
	<Directory />
		Options FollowSymLinks
		AllowOverride None
	</Directory>
	<Directory /var/www/public/>
		Options FollowSymLinks MultiViews
		AllowOverride all
		Order allow,deny
		allow from all
	</Directory>

	ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
	<Directory "/usr/lib/cgi-bin">
		AllowOverride None
		Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
		Order allow,deny
		Allow from all
	</Directory>

	ErrorLog \${APACHE_LOG_DIR}/error.log

	# Possible values include: debug, info, notice, warn, error, crit,
	# alert, emerg.
	LogLevel warn

	CustomLog \${APACHE_LOG_DIR}/access.log combined
	DefineExternalAuth SystemAuth pipe /usr/sbin/pwauth
</VirtualHost>
EOF

# copy new site configuration into apache2 tree
if [[ -f "$TMPCFG" ]]
then
    cp -f ${TMPCFG} /etc/apache2/sites-available/default-ssl
    # enable new site if link is missing
    if [[ ! -e /etc/apache2/sites-enabled/001-default-ssl ]]
    then
        ln -s /etc/apache2/sites-available/default-ssl /etc/apache2/sites-enabled/001-default-ssl
    fi
fi

exit 0
