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 # Setup default config values, search for and load configuration files
14 CA="https://acme-v01.api.letsencrypt.org/directory"
15 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
18 PRIVATE_KEY="${BASEDIR}/private_key.pem"
20 WELLKNOWN="${BASEDIR}/.acme-challenges"
21 PRIVATE_KEY_RENEW="no"
22 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
24 LOCKFILE="${BASEDIR}/lock"
26 # Check for config in various locations
27 if [[ -z "${CONFIG:-}" ]]; then
28 for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
29 if [[ -e "${check_config}/config.sh" ]]; then
30 BASEDIR="${check_config}"
31 CONFIG="${check_config}/config.sh"
37 if [[ -z "${CONFIG:-}" ]]; then
39 echo "# !! WARNING !! No config file found, using default config!" >&2
41 elif [[ -e "${CONFIG}" ]]; then
42 echo "# INFO: Using config file ${CONFIG}"
43 BASEDIR="$(dirname "${CONFIG}")"
44 # shellcheck disable=SC1090
47 echo "Specified config file doesn't exist." >&2
51 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
52 BASEDIR="${BASEDIR%%/}"
54 # Check BASEDIR and set default variables
55 if [[ ! -d "${BASEDIR}" ]]; then
56 echo "BASEDIR does not exist: ${BASEDIR}" >&2
64 if [[ "${COMMAND}" = "env" ]]; then
68 # Lockfile handling (prevents concurrent access)
70 if ! { date > "${LOCKFILE}"; } 2>/dev/null; then
71 echo " + ERROR: Lock file '${LOCKFILE}' present, aborting." >&2
72 LOCKFILE="" # so remove_lock doesn't remove it
78 if [[ -n "${LOCKFILE}" ]]; then
82 trap 'remove_lock' EXIT
84 # Export some environment variables to be used in hook script
90 CA_DIRECTORY="$(http_request get "${CA}")"
91 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
92 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
93 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
94 # shellcheck disable=SC2015
95 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
96 (echo "Error retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint." >&2; exit 1)
99 # check private key ...
101 if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
102 # a private key was specified from the command line so use it for this run
103 echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
104 PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
105 if ! openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null; then
106 echo " + ERROR: private key is not valid, can not continue" >&2
110 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
111 if [[ ! -e "${PRIVATE_KEY}" ]]; then
112 echo "+ Generating account key..."
113 _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
118 # Get public components from private key and calculate thumbprint
119 pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
120 pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
122 thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
124 # If we generated a new private key in the step above we have to register it with the acme-server
125 if [[ "${register}" = "1" ]]; then
126 echo "+ Registering account key with letsencrypt..."
127 if [ -z "${CA_NEW_REG}" ]; then
128 echo " + ERROR: Certificate authority doesn't allow registrations." >&2
131 # if an email for the contact has been provided then adding it to the registration request
132 if [[ -n "${CONTACT_EMAIL}" ]]; then
133 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
135 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
139 if [[ -e "${BASEDIR}/domains.txt" ]]; then
140 DOMAINS_TXT="${BASEDIR}/domains.txt"
142 echo " + ERROR: domains.txt not found" >&2
146 if [[ ! -e "${WELLKNOWN}" ]]; then
147 echo " + ERROR: WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions." >&2
157 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
158 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
162 # Store hex string from stdin
167 for ((i=0; i<${#tmphex}; i+=1)); do
168 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
172 test $((${#hex} & 1)) == 0 || hex="0${hex}"
174 # Convert to escaped string
176 for ((i=0; i<${#hex}; i+=2)); do
177 escapedhex=$escapedhex\\x${hex:$i:2}
180 # Convert to binary data
181 printf -- "${escapedhex}"
184 get_json_string_value() {
185 grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
189 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
195 if [[ "${1}" = "head" ]]; then
196 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
197 elif [[ "${1}" = "get" ]]; then
198 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
199 elif [[ "${1}" = "post" ]]; then
200 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
203 if [[ ! "${statuscode:0:1}" = "2" ]]; then
204 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
207 cat "${tempcont}" >&2
210 # Wait for hook script to clean the challenge if used
211 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
212 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
215 # remove temporary domains.txt file if used
216 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
227 # OpenSSL writes to stderr/stdout even when there are no errors. So just
228 # display the output if the exit code was != 0 to simplify debugging.
231 out="$(openssl "${@}" 2>&1)"
234 if [[ $res -ne 0 ]]; then
235 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
244 # Encode payload as urlbase64
245 payload64="$(printf '%s' "${2}" | urlbase64)"
247 # Retrieve nonce from acme-server
248 nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
250 # Build header with just our public key and algorithm information
251 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
253 # Build another header which also contains the previously received nonce and encode it as urlbase64
254 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
255 protected64="$(printf '%s' "${protected}" | urlbase64)"
257 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
258 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
260 # Send header + extended header + payload + signature to the acme-server
261 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
263 http_request post "${1}" "${data}"
270 echo " + Signing domains..."
271 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
272 echo " + ERROR: Certificate authority doesn't allow certificate signing" >&2
275 timestamp="$(date +%s)"
277 # If there is no existing certificate directory => make it
278 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
279 echo " + make directory ${BASEDIR}/certs/${domain} ..."
280 mkdir -p "${BASEDIR}/certs/${domain}"
283 privkey="privkey.pem"
284 # generate a new private key if we need or want one
285 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
286 echo " + Generating private key..."
287 privkey="privkey-${timestamp}.pem"
288 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
291 # Generate signing request config and the actual signing request
293 for altname in $altnames; do
294 SAN+="DNS:${altname}, "
297 echo " + Generating signing request..."
298 local tmp_openssl_cnf
299 tmp_openssl_cnf="$(mktemp)"
300 cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
301 printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
302 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}"
303 rm -f "${tmp_openssl_cnf}"
305 # Request and respond to challenges
306 for altname in $altnames; do
307 # Ask the acme-server for new challenge token and extract them from the resulting json block
308 echo " + Requesting challenge for ${altname}..."
309 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
311 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
312 repl=$'\n''{' # fix syntax highlighting in Vim
313 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
314 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
315 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
317 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
318 echo " + Error: Can't retrieve challenges (${response})" >&2
322 # Challenge response consists of the challenge token and the thumbprint of our public certificate
323 keyauth="${challenge_token}.${thumbprint}"
325 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
326 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
327 chmod a+r "${WELLKNOWN}/${challenge_token}"
329 # Wait for hook script to deploy the challenge if used
330 if [[ -n "${HOOK}" ]]; then
331 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
334 # Ask the acme-server to verify our challenge and wait until it becomes valid
335 echo " + Responding to challenge for ${altname}..."
336 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
338 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
340 # get status until a result is reached => not pending anymore
341 while [[ "${status}" = "pending" ]]; do
343 status="$(http_request get "${challenge_uri}" | get_json_string_value status)"
346 rm -f "${WELLKNOWN}/${challenge_token}"
348 # Wait for hook script to clean the challenge if used
349 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
350 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
353 if [[ "${status}" = "valid" ]]; then
354 echo " + Challenge is valid!"
356 echo " + Challenge is invalid! (returned: ${status})" >&2
362 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
363 echo " + Requesting certificate..."
364 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
365 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
366 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
367 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
368 # try to load the certificate to detect corruption
369 echo " + Checking certificate..."
370 _openssl x509 -text < "${crt_path}"
372 # Create fullchain.pem
373 echo " + Creating fullchain.pem..."
374 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
375 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"
376 if ! grep "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" > /dev/null 2>&1; then
377 openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
379 ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
380 cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
381 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
383 # Update remaining symlinks
384 if [ ! "${privkey}" = "privkey.pem" ]; then
385 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
388 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
389 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
391 # Wait for hook script to clean the challenge and to deploy cert if used
392 if [[ -n "${HOOK}" ]]; then
393 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
396 unset challenge_token
402 # Description: Sign/renew non-existant/changed/expiring certificates.
403 command_sign_domains() {
404 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
405 # we are using a temporary domains.txt file so we don't need to duplicate any code
406 DOMAINS_TXT="$(mktemp)"
407 echo "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
409 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
410 <"${DOMAINS_TXT}" sed 's/^[[:space:]]*//g;s/[[:space:]]*$//g' | grep -vE '^(#|$)' | while read -r line; do
411 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
412 morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
413 cert="${BASEDIR}/certs/${domain}/cert.pem"
415 force_renew="${PARAM_FORCE:-no}"
417 if [[ -z "${morenames}" ]];then
418 echo "Processing ${domain}"
420 echo "Processing ${domain} with SAN: ${morenames}"
423 if [[ -e "${cert}" ]]; then
424 echo -n " + Checking domain name(s) of existing cert..."
426 certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')"
427 givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//' | sed 's/^ //')"
429 if [[ "${certnames}" = "${givennames}" ]]; then
433 echo " + Domain name(s) are not matching!"
434 echo " + Names in old certificate: ${certnames}"
435 echo " + Configured names: ${givennames}"
436 echo " + Forcing renew."
441 if [[ -e "${cert}" ]]; then
442 echo " + Checking expire date of existing cert..."
444 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
446 echo -n " + Valid till ${valid} "
447 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
448 echo -n "(Longer than ${RENEW_DAYS} days). "
449 if [[ "${force_renew}" = "yes" ]]; then
450 echo "Ignoring because renew was forced!"
456 echo "(Less than ${RENEW_DAYS} days). Renewing!"
460 # shellcheck disable=SC2086
464 # remove temporary domains.txt file if used
465 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
466 rm -f "${DOMAINS_TXT}"
470 # Usage: --revoke (-r) path/to/cert.pem
471 # Description: Revoke specified certificate
474 if [[ -L "${cert}" ]]; then
475 # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
477 link_target="$(readlink -n "${cert}")"
478 if [[ "${link_target}" =~ ^/ ]]; then
479 cert="${link_target}"
481 cert="$(dirname "${cert}")/${link_target}"
484 if [[ ! -f "${cert}" ]]; then
485 echo "ERROR: Could not find certificate ${cert}"
488 echo "Revoking ${cert}"
489 if [[ -z "${CA_REVOKE_CERT}" ]]; then
490 echo " + ERROR: Certificate authority doesn't allow certificate revocation." >&2
493 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
494 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
495 # if there is a problem with our revoke request http_request (via signed_request) will report this and "exit 1" out
496 # so if we are here, it is safe to assume the request was successful
498 echo " + renaming certificate to ${cert}-revoked"
499 mv -f "${cert}" "${cert}-revoked"
503 # Description: Show help text
505 echo "Usage: ${0} [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ..."
507 echo "Default command: help"
511 grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
512 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
513 echo "Error generating help text." >&2
516 printf " %s\t%s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
520 grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
521 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
522 echo "Error generating help text." >&2
525 printf " %s\t%s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
527 ) | column -t -s $'\t' | sed 's/^---$//g'
531 # Description: Output configuration variables for use in other scripts
533 echo "# letsencrypt.sh configuration"
534 typeset -p CA LICENSE BASEDIR WELLKNOWN PRIVATE_KEY KEYSIZE OPENSSL_CNF HOOK RENEW_DAYS PRIVATE_KEY_RENEW CONTACT_EMAIL
539 # change long args to short args
540 # inspired by http://kirk.webfinish.com/?p=45
543 --help) args="${args}-h ";;
544 --cron) args="${args}-c ";;
545 --domain) args="${args}-d ";;
546 --force ) args="${args}-x ";;
547 --revoke) args="${args}-r ";;
548 --privkey) args="${args}-p ";;
549 --config) args="${args}-f ";;
550 --env) args="${args}-e ";;
552 echo "Unknown parameter detected: ${arg}" >&2
557 # pass through anything else
558 *) args="${args}\"${arg}\" ";;
562 # Reset the positional parameters to the short options
563 eval set -- "${args}"
567 if [[ ! -z "${COMMAND}" ]]; then
568 echo "Only one command can be executed at a time." >&2
569 echo "See help (-h) for more information." >&2
576 if [[ -z "${@}" ]]; then
577 echo "The specified command requires additional parameters. See help:" >&2
584 while getopts ":hcer:d:xf:p:" option; do
591 set_command sign_domains
598 check_parameters "${OPTARG:-}"
599 revoke_me="${OPTARG}"
602 # PARAM_Usage: --domain (-d) domain.tld
603 # PARAM_Description: Use specified domain name instead of domains.txt, use multiple times for certificate with SAN names
604 check_parameters "${OPTARG:-}"
605 if [[ -z "${PARAM_DOMAIN:-}" ]]; then
606 PARAM_DOMAIN="${OPTARG}"
608 PARAM_DOMAIN="${PARAM_DOMAIN} ${OPTARG}"
612 # PARAM_Usage: --force (-x)
613 # PARAM_Description: force renew of certificate even if it is longer valid than value in RENEW_DAYS
617 # PARAM_Usage: --config (-f) path/to/config.sh
618 # PARAM_Description: Use specified config file
619 check_parameters "${OPTARG:-}"
623 # PARAM_Usage: --privkey (-p) path/to/key.pem
624 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
625 check_parameters "${OPTARG:-}"
626 PARAM_PRIVATE_KEY="${OPTARG}"
629 echo "Unknown parameter detected: -${OPTARG}" >&2
637 if [[ -z "${COMMAND}" ]]; then
652 command_revoke "${revoke_me}"