5 umask 077 # paranoid umask, we're creating private keys
7 # Get the directory in which this script is stored
8 SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
11 # Check for script dependencies
12 check_dependencies() {
13 curl -V > /dev/null 2>&1 || _exiterr "This script requires curl."
14 openssl version > /dev/null 2>&1 || _exiterr "This script requres an openssl binary."
15 sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requres sed."
16 grep -V > /dev/null 2>&1 || _exiterr "This script requres grep."
19 # Setup default config values, search for and load configuration files
22 CA="https://acme-v01.api.letsencrypt.org/directory"
23 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
26 PRIVATE_KEY="${BASEDIR}/private_key.pem"
28 WELLKNOWN="${BASEDIR}/.acme-challenges"
29 PRIVATE_KEY_RENEW="no"
30 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
32 LOCKFILE="${BASEDIR}/lock"
34 # Check for config in various locations
35 if [[ -z "${CONFIG:-}" ]]; then
36 for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
37 if [[ -e "${check_config}/config.sh" ]]; then
38 BASEDIR="${check_config}"
39 CONFIG="${check_config}/config.sh"
45 if [[ -z "${CONFIG:-}" ]]; then
47 echo "# !! WARNING !! No config file found, using default config!" >&2
49 elif [[ -e "${CONFIG}" ]]; then
50 echo "# INFO: Using config file ${CONFIG}"
51 BASEDIR="$(dirname "${CONFIG}")"
52 # shellcheck disable=SC1090
55 echo "Specified config file doesn't exist." >&2
59 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
60 BASEDIR="${BASEDIR%%/}"
62 # Check BASEDIR and set default variables
63 if [[ ! -d "${BASEDIR}" ]]; then
64 echo "BASEDIR does not exist: ${BASEDIR}" >&2
73 # Lockfile handling (prevents concurrent access)
74 ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
75 remove_lock() { rm -f "${LOCKFILE}"; }
76 trap 'remove_lock' EXIT
79 CA_DIRECTORY="$(http_request get "${CA}")"
80 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
81 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
82 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
83 # shellcheck disable=SC2015
84 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
85 _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
87 # Export some environment variables to be used in hook script
88 export WELLKNOWN BASEDIR CONFIG
90 # Checking for private key ...
92 if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
93 # a private key was specified from the command line so use it for this run
94 echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
95 PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
97 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
98 if [[ ! -e "${PRIVATE_KEY}" ]]; then
99 echo "+ Generating account key..."
100 _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
101 register_new_key="yes"
104 openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Private key is not valid, can not continue."
106 # Get public components from private key and calculate thumbprint
107 pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
108 pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
110 thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
112 # If we generated a new private key in the step above we have to register it with the acme-server
113 if [[ "${register_new_key}" = "yes" ]]; then
114 echo "+ Registering account key with letsencrypt..."
115 [[ ! -z "${CA_NEW_REG}" ]] || _exiterr "Certificate authority doesn't allow registrations."
116 # If an email for the contact has been provided then adding it to the registration request
117 if [[ -n "${CONTACT_EMAIL}" ]]; then
118 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
120 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
124 [[ -d "${WELLKNOWN}" ]] || _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
127 # Print error message and exit with error
129 echo "ERROR: ${1}" >&2
133 # Encode data as url-safe formatted base64
135 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
136 openssl base64 -e | tr -d '\n\r' | sed 's/=*$//g' | tr '+/' '-_'
139 # Convert hex string to binary data
141 # Remove spaces, add leading zero, escape as hex string and parse with printf
142 printf -- "$(cat | sed -E -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
145 # Get string value from json dictionary
146 get_json_string_value() {
147 grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
150 # OpenSSL writes to stderr/stdout even when there are no errors. So just
151 # display the output if the exit code was != 0 to simplify debugging.
154 out="$(openssl "${@}" 2>&1)"
157 if [[ $res -ne 0 ]]; then
158 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
166 # Send http(s) request with specified method
170 if [[ "${1}" = "head" ]]; then
171 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
172 elif [[ "${1}" = "get" ]]; then
173 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
174 elif [[ "${1}" = "post" ]]; then
175 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
177 _exiterr "Unknown request method: ${1}"
180 if [[ ! "${statuscode:0:1}" = "2" ]]; then
181 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
184 cat "${tempcont}" >&2
187 # Wait for hook script to clean the challenge if used
188 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
189 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
192 # remove temporary domains.txt file if used
193 [[ -n "${PARAM_DOMAIN:-}" ]] && rm "${DOMAINS_TXT}"
201 # Send signed request
203 # Encode payload as urlbase64
204 payload64="$(printf '%s' "${2}" | urlbase64)"
206 # Retrieve nonce from acme-server
207 nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
209 # Build header with just our public key and algorithm information
210 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
212 # Build another header which also contains the previously received nonce and encode it as urlbase64
213 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
214 protected64="$(printf '%s' "${protected}" | urlbase64)"
216 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
217 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
219 # Send header + extended header + payload + signature to the acme-server
220 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
222 http_request post "${1}" "${data}"
225 # Create certificate for domain(s)
229 timestamp="$(date +%s)"
231 echo " + Signing domains..."
232 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
233 _exiterr "Certificate authority doesn't allow certificate signing"
236 # If there is no existing certificate directory => make it
237 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
238 echo " + Creating new directory ${BASEDIR}/certs/${domain} ..."
239 mkdir -p "${BASEDIR}/certs/${domain}"
242 privkey="privkey.pem"
243 # generate a new private key if we need or want one
244 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
245 echo " + Generating private key..."
246 privkey="privkey-${timestamp}.pem"
247 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
250 # Generate signing request config and the actual signing request
251 echo " + Generating signing request..."
253 for altname in ${altnames}; do
254 SAN+="DNS:${altname}, "
257 local tmp_openssl_cnf
258 tmp_openssl_cnf="$(mktemp)"
259 cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
260 printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
261 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}"
262 rm -f "${tmp_openssl_cnf}"
264 # Request and respond to challenges
265 for altname in ${altnames}; do
266 # Ask the acme-server for new challenge token and extract them from the resulting json block
267 echo " + Requesting challenge for ${altname}..."
268 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
270 challenges="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]')"
271 repl=$'\n''{' # fix syntax highlighting in Vim
272 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
273 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
274 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
276 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
277 _exiterr "Can't retrieve challenges (${response})"
280 # Challenge response consists of the challenge token and the thumbprint of our public certificate
281 keyauth="${challenge_token}.${thumbprint}"
283 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
284 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
285 chmod a+r "${WELLKNOWN}/${challenge_token}"
287 # Wait for hook script to deploy the challenge if used
288 [[ -n "${HOOK}" ]] && ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
290 # Ask the acme-server to verify our challenge and wait until it is no longer pending
291 echo " + Responding to challenge for ${altname}..."
292 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
294 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
296 while [[ "${status}" = "pending" ]]; do
298 status="$(http_request get "${challenge_uri}" | get_json_string_value status)"
301 rm -f "${WELLKNOWN}/${challenge_token}"
303 # Wait for hook script to clean the challenge if used
304 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
305 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
308 if [[ "${status}" = "valid" ]]; then
309 echo " + Challenge is valid!"
311 _exiterr "Challenge is invalid! (returned: ${status})"
315 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
316 echo " + Requesting certificate..."
317 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
318 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
319 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
320 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
322 # Try to load the certificate to detect corruption
323 echo " + Checking certificate..."
324 _openssl x509 -text < "${crt_path}"
326 # Create fullchain.pem
327 echo " + Creating fullchain.pem..."
328 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
329 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"
330 if ! grep -q "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"; then
331 openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
333 cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
336 [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
338 ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
339 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
340 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
341 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
343 # Wait for hook script to clean the challenge and to deploy cert if used
344 [[ -n "${HOOK}" ]] && ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
346 unset challenge_token
351 # Description: Sign/renew non-existant/changed/expiring certificates.
352 command_sign_domains() {
355 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
356 DOMAINS_TXT="$(mktemp)"
357 printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
358 elif [[ -e "${BASEDIR}/domains.txt" ]]; then
359 DOMAINS_TXT="${BASEDIR}/domains.txt"
361 _exiterr "domains.txt not found and --domain not given"
364 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
365 <"${DOMAINS_TXT}" sed 's/^[[:space:]]*//g;s/[[:space:]]*$//g' | grep -vE '^(#|$)' | while read -r line; do
366 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
367 morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
368 cert="${BASEDIR}/certs/${domain}/cert.pem"
370 force_renew="${PARAM_FORCE:-no}"
372 if [[ -z "${morenames}" ]];then
373 echo "Processing ${domain}"
375 echo "Processing ${domain} with alternative names: ${morenames}"
378 if [[ -e "${cert}" ]]; then
379 printf " + Checking domain name(s) of existing cert..."
381 certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')"
382 givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//' | sed 's/^ //')"
384 if [[ "${certnames}" = "${givennames}" ]]; then
388 echo " + Domain name(s) are not matching!"
389 echo " + Names in old certificate: ${certnames}"
390 echo " + Configured names: ${givennames}"
391 echo " + Forcing renew."
396 if [[ -e "${cert}" ]]; then
397 echo " + Checking expire date of existing cert..."
398 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
400 printf " + Valid till %s " "${valid}"
401 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
402 printf "(Longer than %d days). " "${RENEW_DAYS}"
403 if [[ "${force_renew}" = "yes" ]]; then
404 echo "Ignoring because renew was forced!"
410 echo "(Less than ${RENEW_DAYS} days). Renewing!"
414 # shellcheck disable=SC2086
418 # remove temporary domains.txt file if used
419 [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
424 # Usage: --revoke (-r) path/to/cert.pem
425 # Description: Revoke specified certificate
429 [[ -n "${CA_REVOKE_CERT}" ]] || _exiterr "Certificate authority doesn't allow certificate revocation."
432 if [[ -L "${cert}" ]]; then
433 # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
435 link_target="$(readlink -n "${cert}")"
436 if [[ "${link_target}" =~ ^/ ]]; then
437 cert="${link_target}"
439 cert="$(dirname "${cert}")/${link_target}"
442 [[ -f "${cert}" ]] || _exiterr "Could not find certificate ${cert}"
444 echo "Revoking ${cert}"
446 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
447 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
448 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
449 # so if we are here, it is safe to assume the request was successful
451 echo " + Renaming certificate to ${cert}-revoked"
452 mv -f "${cert}" "${cert}-revoked"
456 # Description: Show help text
458 printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
459 printf "Default command: help\n\n"
461 grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
462 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
463 _exiterr "Error generating help text."
465 printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
467 printf -- "\nParameters:\n"
468 grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
469 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
470 _exiterr "Error generating help text."
472 printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
477 # Description: Output configuration variables for use in other scripts
479 echo "# letsencrypt.sh configuration"
481 typeset -p CA LICENSE HOOK RENEW_DAYS PRIVATE_KEY KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
484 # Main method (parses script arguments and calls command_* methods)
488 [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
493 if [[ -z "${1:-}" ]]; then
494 echo "The specified command requires additional parameters. See help:" >&2
498 elif [[ "${1:0:1}" = "-" ]]; then
499 _exiterr "Invalid argument: ${1}"
503 while (( "${#}" )); do
515 set_command sign_domains
521 check_parameters "${1:-}"
522 PARAM_REVOKECERT="${1}"
525 # PARAM_Usage: --domain (-d) domain.tld
526 # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
529 check_parameters "${1:-}"
530 if [[ -z "${PARAM_DOMAIN:-}" ]]; then
533 PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
538 # PARAM_Usage: --force (-x)
539 # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
544 # PARAM_Usage: --privkey (-p) path/to/key.pem
545 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
548 check_parameters "${1:-}"
549 PARAM_PRIVATE_KEY="${1}"
552 # PARAM_Usage: --config (-f) path/to/config.sh
553 # PARAM_Description: Use specified config file
556 check_parameters "${1:-}"
561 echo "Unknown parameter detected: ${1}" >&2
573 sign_domains) command_sign_domains;;
574 revoke) command_revoke "${PARAM_REVOKECERT}";;
575 *) command_help; exit1;;
579 # Check for missing dependencies