#!/bin/bash
# vim: cindent:shiftwidth=4:tabstop=4:smarttab:textwidth=100

set -o errexit
set -o pipefail
set -o nounset
set -o xtrace

# Guide to Deploying Diffie-Hellman for TLS
# https://weakdh.org/sysadmin.html

#CHANGELOG
#0.50	created initial version
#0.60	reload Postfix to activate the change right away
#0.61	document dhparam comparison procedure (file vs network)
#0.70	unify for all TLS applications

PARAM_FILE='/etc/ssl/dhparam.pem'
NUMBITS=3072
RANDOM_DATA_FILE='/dev/random'

TMP=$(mktemp)
openssl dhparam -rand $RANDOM_DATA_FILE -out $TMP $NUMBITS
chmod 444 $TMP
mv $TMP $PARAM_FILE.new
mv $PARAM_FILE.new $PARAM_FILE # atomic rename

logger -t $0 -p daemon.info "updated $PARAM_FILE ($NUMBITS bits) in $SECONDS seconds"

cd /etc/init.d
for SERVICE in *; do
	RELOAD=0
	case $SERVICE in
		postfix) RELOAD=1;;
		apache2) RELOAD=1;;
	esac
	if [[ $RELOAD -gt 0 ]]; then
		service $SERVICE reload
	fi
done

# to compare:
# openssl dhparam -inform PEM -in $PARAM_FILE -check -text
# openssl s_client -msg -starttls smtp -cipher "EDH" -connect ip6-localhost:25
# <<< TLS 1.2 Handshake [length 030f], ServerKeyExchange
#   0c 00 03 0b 01 [DH Parameters]
