Skip to content

Instantly share code, notes, and snippets.

@baszoetekouw
Last active June 2, 2016 14:39
Show Gist options
  • Save baszoetekouw/531d13c2eaa458864d9327631c72105a to your computer and use it in GitHub Desktop.
Save baszoetekouw/531d13c2eaa458864d9327631c72105a to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# This script can be used to generate/renew/refresh Letsencrypt SSL certificates
# Simply edit the config variables below, and run it (as root, or make sure your user has access to write to all approriate directories).
# It depends on acem-tiny (https://github.com/diafygi/acme-tiny) for the actual interaction with the Letsencrypt ACME service
#
set -e
# base dir where Letsencrypt this script is installed and acme-tiny is checked out
LETSE_HOME=/etc/ssl/letsencrypt
# base dir where Letsencrypt certificates will be installed
SSL_HOME=/etc/ssl/private/
# hostname for which to request certificates
HOST=shib-idp-test.conext.surfnetlabs.nl
# private key for AuthN at Letsencrypt
LETSE_KEY=${LETSE_HOME}/letsencrypt.key
# web dir where acme challenges can be written
ACME_HOME=/srv/www/html/.well-known/acme-challenge
# there should be no need to edit the vars below
KEY=$SSL_HOME/letsencrypt/${HOST}.key
CSR=$SSL_HOME/letsencrypt/${HOST}.csr
CRT=$SSL_HOME/letsencrypt/${HOST}.crt
CHAIN=$SSL_HOME/letsencrypt/chain.pem
CHAIN_FULL=$SSL_HOME/letsencrypt/${HOST}.fullchain.pem
TMPCRT=$(mktemp $CRT.XXXXXXXX)
# generate new Letsencrypt key if not exists
if ! [ -e $LETSE_KEY ]
then
echo "Letsencrypt private key not found, generate new one: $LETSE_KET"
touch $LETSE_KEY
chmod 600 $LETSE_KEY
openssl genrsa 4096 > $LETSE_KEY
fi
# generate new private key/csa if not exists
if ! [ -e $KEY ]
then
echo "Private key for $HOST not found, generating..."
touch $KEY $CSR
chmod 600 $KEY $CSR
openssl genrsa 4096 > $KEY
openssl req -new -sha256 -key "$KEY" -subj "/CN=$HOST" > $CSR
fi
# check if csr exist
if ! [ -e $CSR ]
then
echo "CSR ofr $HOST is missing"
exit 1
fi
# check if .well-known works
mkdir -p ${ACME_HOME} || true
TMPURL=$(mktemp --tmpdir=${ACME_HOME})
chmod 644 $TMPURL
echo $$ > $TMPURL
URL="http://${HOST}/.well-known/acme-challenge/"$(basename $TMPURL)
TEST=$( curl $URL )
echo "Checking if $URL works..."
if [ "$TEST" != $$ ]
then
echo "Sorry, something went wrong while fetching well-known url '$URL'"
exit 1
fi
rm $TMPURL
# do the real thing
python acme-tiny/acme_tiny.py --account-key $LETSE_KEY --acme-dir $ACME_HOME --csr $CSR > $TMPCRT
mv $TMPCRT $CRT
# fetch chain
echo Fetching chain
curl -s -o $CHAIN https://letsencrypt.org/certs/lets-encrypt-x3-cross-signed.pem
cat $CRT $CHAIN > $CHAIN_FULL
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment