CA="https://acme-v01.api.letsencrypt.org/directory"
LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
HOOK=
-RENEW_DAYS="14"
+RENEW_DAYS="30"
PRIVATE_KEY=
KEYSIZE="4096"
WELLKNOWN=
export CONFIG
# Get CA URLs
- CA_DIRECTORY="$(_request get "${CA}")"
+ CA_DIRECTORY="$(http_request get "${CA}")"
CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
fi
# Get public components from private key and calculate thumbprint
- pubExponent64="$(printf "%06x" "$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
- pubMod64="$(printf '%s' "$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
+ pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
+ pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
- thumbprint="$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | openssl sha -sha256 -binary | urlbase64)"
+ thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
# If we generated a new private key in the step above we have to register it with the acme-server
if [[ "${register}" = "1" ]]; then
}
get_json_string_value() {
- grep -Eo '"'"${1}"'":\s*"[^"]*"' | cut -d'"' -f4
+ grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
}
get_json_array() {
grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
}
-_request() {
+http_request() {
tempcont="$(mktemp)"
if [[ "${1}" = "head" ]]; then
echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
echo >&2
echo "Details:" >&2
- echo "$(<"${tempcont}"))" >&2
+ cat "${tempcont}" >&2
rm -f "${tempcont}"
# Wait for hook script to clean the challenge if used
payload64="$(printf '%s' "${2}" | urlbase64)"
# Retrieve nonce from acme-server
- nonce="$(_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
+ nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
# Build header with just our public key and algorithm information
header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
# Send header + extended header + payload + signature to the acme-server
data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
- _request post "${1}" "${data}"
+ http_request post "${1}" "${data}"
}
sign_domain() {
done
SAN="${SAN%%, }"
echo " + Generating signing request..."
- openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config <(cat "${OPENSSL_CNF}" <(printf "[SAN]\nsubjectAltName=%s" "${SAN}"))
+ local tmp_openssl_cnf
+ tmp_openssl_cnf="$(mktemp)"
+ cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
+ printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
+ openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
+ rm -f "${tmp_openssl_cnf}"
# Request and respond to challenges
for altname in $altnames; do
# get status until a result is reached => not pending anymore
while [[ "${status}" = "pending" ]]; do
sleep 1
- status="$(_request get "${challenge_uri}" | get_json_string_value status)"
+ status="$(http_request get "${challenge_uri}" | get_json_string_value status)"
done
rm -f "${WELLKNOWN}/${challenge_token}"
crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
# try to load the certificate to detect corruption
- echo " + Checking certificate..." >&2
+ echo " + Checking certificate..."
_openssl x509 -text < "${crt_path}"
# Create fullchain.pem
echo " + Creating fullchain.pem..."
cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
- _request get "$(openssl x509 -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
+ http_request get "$(openssl x509 -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"
+ if ! grep "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" > /dev/null 2>&1; then
+ openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
+ fi
+ ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
+ cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
# Update remaining symlinks
# Usage: --cron (-c)
-# Description: Sign/renew non-existant/changed(TODO)/expiring certificates.
+# Description: Sign/renew non-existant/changed/expiring certificates.
command_sign_domains() {
if [[ -n "${PARAM_DOMAIN:-}" ]]; then
# we are using a temporary domains.txt file so we don't need to duplicate any code
echo "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
fi
# Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
- <"${DOMAINS_TXT}" sed 's/^[ ]*//g;s/[ ]*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
+ <"${DOMAINS_TXT}" sed 's/^[[:space:]]*//g;s/[[:space:]]*$//g' | grep -vE '^(#|$)' | while read -r line; do
domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
cert="${BASEDIR}/certs/${domain}/cert.pem"
+ force_renew="${PARAM_FORCE:-no}"
+
if [[ -z "${morenames}" ]];then
echo "Processing ${domain}"
else
fi
if [[ -e "${cert}" ]]; then
- echo " + Found existing cert..."
+ echo -n " + Checking domain name(s) of existing cert..."
+
+ certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')"
+ givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//' | sed 's/^ //')"
+
+ if [[ "${certnames}" = "${givennames}" ]]; then
+ echo " unchanged."
+ else
+ echo " changed!"
+ echo " + Domain name(s) are not matching!"
+ echo " + Names in old certificate: ${certnames}"
+ echo " + Configured names: ${givennames}"
+ echo " + Forcing renew."
+ force_renew="yes"
+ fi
+ fi
+
+ if [[ -e "${cert}" ]]; then
+ echo " + Checking expire date of existing cert..."
valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
echo -n " + Valid till ${valid} "
if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
echo -n "(Longer than ${RENEW_DAYS} days). "
- if [[ "${PARAM_FORCE:-}" = "yes" ]]; then
- echo "Ignoring because --force was specified!"
+ if [[ "${force_renew}" = "yes" ]]; then
+ echo "Ignoring because renew was forced!"
else
echo "Skipping!"
continue
# remove temporary domains.txt file if used
if [[ -n "${PARAM_DOMAIN:-}" ]]; then
- rm "${DOMAINS_TXT}"
+ rm -f "${DOMAINS_TXT}"
fi
}
# Description: Revoke specified certificate
command_revoke() {
cert="${1}"
+ if [[ -L "${cert}" ]]; then
+ # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
+ local link_target
+ link_target="$(readlink -n "${cert}")"
+ if [[ "${link_target}" =~ ^/ ]]; then
+ cert="${link_target}"
+ else
+ cert="$(dirname "${cert}")/${link_target}"
+ fi
+ fi
+ if [[ ! -f "${cert}" ]]; then
+ echo "ERROR: Could not find certificate ${cert}"
+ exit 1
+ fi
echo "Revoking ${cert}"
- if [ -z "${CA_REVOKE_CERT}" ]; then
+ if [[ -z "${CA_REVOKE_CERT}" ]]; then
echo " + ERROR: Certificate authority doesn't allow certificate revocation." >&2
exit 1
fi
cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
- # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
+ # if there is a problem with our revoke request http_request (via signed_request) will report this and "exit 1" out
# so if we are here, it is safe to assume the request was successful
echo " + SUCCESS"
echo " + renaming certificate to ${cert}-revoked"
echo
(
echo "Commands:"
- grep -e '^\s*# Usage:' -e '^\s*# Description:' -e '^command_.*()\s*{' "${0}" | while read -r usage; read -r description; read -r command; do
+ grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
echo "Error generating help text." >&2
exit 1
done
echo "---"
echo "Parameters:"
- grep -E -e '^\s*# PARAM_Usage:' -e '^\s*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
+ grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
echo "Error generating help text." >&2
exit 1
# PARAM_Usage: --domain (-d) domain.tld
# PARAM_Description: Use specified domain name instead of domains.txt, use multiple times for certificate with SAN names
check_parameters "${OPTARG:-}"
- set_command sign_domains
if [[ -z "${PARAM_DOMAIN:-}" ]]; then
PARAM_DOMAIN="${OPTARG}"
else