Skip to content

Instantly share code, notes, and snippets.

@Knetic
Last active February 1, 2021 01:43
Show Gist options
  • Save Knetic/a61aed92d18d1159f5f5d16e521bfe98 to your computer and use it in GitHub Desktop.
Save Knetic/a61aed92d18d1159f5f5d16e521bfe98 to your computer and use it in GitHub Desktop.
Acquires a certificate from LetsEncrypt
#!/bin/bash
# Acquires a certificate for the given domain.
# Runs the certbot container - so as to not litter the host FS with python nonsense.
# If the keys do not already exist, this will generate strong elliptical curve keys (not susceptible to Logjam).
# Resultant certs/keys are placed in `/etc/letsencrypt/certs`, which ought to be mounted into other applications.
# Must be run from a device able to take traffic for the given domain name,
# since this hands-off method uses an http challenge to show LetsEncrypt that we own the domain.
if [ "$#" -lt 1 ];
then
echo "Must specify domain name as a positional argument"
exit 1
fi
DOMAIN="${1}"
EMAIL="owner@${DOMAIN}"
echo "Acquiring cert for ${DOMAIN}"
mkdir -p /etc/letsencrypt/volume
mkdir -p /etc/letsencrypt/volume/keys
mkdir -p /etc/letsencrypt/volume/csr
mkdir -p /etc/letsencrypt/certs
pushd /etc/letsencrypt/volume
# generate key if required
keyPath="keys/${DOMAIN}.ec.key"
csrPath="csr/${DOMAIN}.ec.csr"
if [ ! -f "${keyPath}" ];
then
echo "Private key not found. Generating secp384r1 ec key"
openssl ecparam -genkey -name secp384r1 > "${keyPath}"
fi
# make CSR request
subj="/C=US/ST=/L=/O=/CN=${DOMAIN}"
openssl req -new -sha512 -key "${keyPath}" -out "${csrPath}" -days 90 -subj "${subj}"
docker \
run \
-it \
--net=host \
-v /etc/letsencrypt/volume:/etc/letsencrypt:rw \
-w /etc/letsencrypt \
certbot/certbot \
--non-interactive \
--agree-tos \
--email "${EMAIL}"\
certonly \
--csr "${csrPath}" \
--cert-name "${DOMAIN}" \
--standalone \
--preferred-challenges http \
-d "${DOMAIN}"
status=$?
if [ ${status} -ne 0 ];
then
exit ${status}
fi
echo "copying certs to above folder"
mkdir -p "/etc/letsencrypt/certs/${DOMAIN}"
cp "${keyPath}" "/etc/letsencrypt/certs/${DOMAIN}.key"
mv "0001_chain.pem" "/etc/letsencrypt/certs/${DOMAIN}.crt"
rm *.pem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment