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_dependencies() {
12 curl -V > /dev/null 2>&1 || _exiterr "This script requires curl."
13 openssl version > /dev/null 2>&1 || _exiterr "This script requres an openssl binary."
14 sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requres sed."
15 grep -V > /dev/null 2>&1 || _exiterr "This script requres grep."
18 # Setup default config values, search for and load configuration files
21 CA="https://acme-v01.api.letsencrypt.org/directory"
22 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
25 PRIVATE_KEY="${BASEDIR}/private_key.pem"
27 WELLKNOWN="${BASEDIR}/.acme-challenges"
28 PRIVATE_KEY_RENEW="no"
29 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
31 LOCKFILE="${BASEDIR}/lock"
33 # Check for config in various locations
34 if [[ -z "${CONFIG:-}" ]]; then
35 for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
36 if [[ -e "${check_config}/config.sh" ]]; then
37 BASEDIR="${check_config}"
38 CONFIG="${check_config}/config.sh"
44 if [[ -z "${CONFIG:-}" ]]; then
46 echo "# !! WARNING !! No config file found, using default config!" >&2
48 elif [[ -e "${CONFIG}" ]]; then
49 echo "# INFO: Using config file ${CONFIG}"
50 BASEDIR="$(dirname "${CONFIG}")"
51 # shellcheck disable=SC1090
54 echo "Specified config file doesn't exist." >&2
58 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
59 BASEDIR="${BASEDIR%%/}"
61 # Check BASEDIR and set default variables
62 if [[ ! -d "${BASEDIR}" ]]; then
63 echo "BASEDIR does not exist: ${BASEDIR}" >&2
72 # Lockfile handling (prevents concurrent access)
73 ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
74 remove_lock() { rm -f "${LOCKFILE}"; }
75 trap 'remove_lock' EXIT
78 CA_DIRECTORY="$(http_request get "${CA}")"
79 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
80 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
81 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
82 # shellcheck disable=SC2015
83 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
84 _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
86 # Export some environment variables to be used in hook script
87 export WELLKNOWN BASEDIR CONFIG
89 # Checking for private key ...
91 if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
92 # a private key was specified from the command line so use it for this run
93 echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
94 PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
96 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
97 if [[ ! -e "${PRIVATE_KEY}" ]]; then
98 echo "+ Generating account key..."
99 _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
100 register_new_key="yes"
103 openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Private key is not valid, can not continue."
105 # Get public components from private key and calculate thumbprint
106 pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
107 pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
109 thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
111 # If we generated a new private key in the step above we have to register it with the acme-server
112 if [[ "${register_new_key}" = "yes" ]]; then
113 echo "+ Registering account key with letsencrypt..."
114 [[ ! -z "${CA_NEW_REG}" ]] || _exiterr "Certificate authority doesn't allow registrations."
115 # If an email for the contact has been provided then adding it to the registration request
116 if [[ -n "${CONTACT_EMAIL}" ]]; then
117 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
119 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
123 [[ -d "${WELLKNOWN}" ]] || _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
126 # Print error message and exit with error
128 echo "ERROR: ${1}" >&2
137 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
138 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
141 # Convert hex string to binary data
143 # Remove spaces, add leading zero, escape as hex string and parse with printf
144 printf -- "$(cat | sed -E -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
147 get_json_string_value() {
148 grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
152 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
158 if [[ "${1}" = "head" ]]; then
159 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
160 elif [[ "${1}" = "get" ]]; then
161 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
162 elif [[ "${1}" = "post" ]]; then
163 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
166 if [[ ! "${statuscode:0:1}" = "2" ]]; then
167 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
170 cat "${tempcont}" >&2
173 # Wait for hook script to clean the challenge if used
174 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
175 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
178 # remove temporary domains.txt file if used
179 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
190 # OpenSSL writes to stderr/stdout even when there are no errors. So just
191 # display the output if the exit code was != 0 to simplify debugging.
194 out="$(openssl "${@}" 2>&1)"
197 if [[ $res -ne 0 ]]; then
198 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
207 # Encode payload as urlbase64
208 payload64="$(printf '%s' "${2}" | urlbase64)"
210 # Retrieve nonce from acme-server
211 nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
213 # Build header with just our public key and algorithm information
214 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
216 # Build another header which also contains the previously received nonce and encode it as urlbase64
217 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
218 protected64="$(printf '%s' "${protected}" | urlbase64)"
220 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
221 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
223 # Send header + extended header + payload + signature to the acme-server
224 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
226 http_request post "${1}" "${data}"
233 echo " + Signing domains..."
234 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
235 echo " + ERROR: Certificate authority doesn't allow certificate signing" >&2
238 timestamp="$(date +%s)"
240 # If there is no existing certificate directory => make it
241 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
242 echo " + make directory ${BASEDIR}/certs/${domain} ..."
243 mkdir -p "${BASEDIR}/certs/${domain}"
246 privkey="privkey.pem"
247 # generate a new private key if we need or want one
248 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
249 echo " + Generating private key..."
250 privkey="privkey-${timestamp}.pem"
251 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
254 # Generate signing request config and the actual signing request
256 for altname in $altnames; do
257 SAN+="DNS:${altname}, "
260 echo " + Generating signing request..."
261 local tmp_openssl_cnf
262 tmp_openssl_cnf="$(mktemp)"
263 cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
264 printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
265 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}"
266 rm -f "${tmp_openssl_cnf}"
268 # Request and respond to challenges
269 for altname in $altnames; do
270 # Ask the acme-server for new challenge token and extract them from the resulting json block
271 echo " + Requesting challenge for ${altname}..."
272 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
274 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
275 repl=$'\n''{' # fix syntax highlighting in Vim
276 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
277 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
278 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
280 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
281 echo " + Error: Can't retrieve challenges (${response})" >&2
285 # Challenge response consists of the challenge token and the thumbprint of our public certificate
286 keyauth="${challenge_token}.${thumbprint}"
288 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
289 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
290 chmod a+r "${WELLKNOWN}/${challenge_token}"
292 # Wait for hook script to deploy the challenge if used
293 if [[ -n "${HOOK}" ]]; then
294 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
297 # Ask the acme-server to verify our challenge and wait until it becomes valid
298 echo " + Responding to challenge for ${altname}..."
299 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
301 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
303 # get status until a result is reached => not pending anymore
304 while [[ "${status}" = "pending" ]]; do
306 status="$(http_request get "${challenge_uri}" | get_json_string_value status)"
309 rm -f "${WELLKNOWN}/${challenge_token}"
311 # Wait for hook script to clean the challenge if used
312 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
313 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
316 if [[ "${status}" = "valid" ]]; then
317 echo " + Challenge is valid!"
319 echo " + Challenge is invalid! (returned: ${status})" >&2
325 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
326 echo " + Requesting certificate..."
327 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
328 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
329 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
330 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
331 # try to load the certificate to detect corruption
332 echo " + Checking certificate..."
333 _openssl x509 -text < "${crt_path}"
335 # Create fullchain.pem
336 echo " + Creating fullchain.pem..."
337 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
338 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"
339 if ! grep "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" > /dev/null 2>&1; then
340 openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
342 ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
343 cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
344 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
346 # Update remaining symlinks
347 if [ ! "${privkey}" = "privkey.pem" ]; then
348 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
351 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
352 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
354 # Wait for hook script to clean the challenge and to deploy cert if used
355 if [[ -n "${HOOK}" ]]; then
356 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
359 unset challenge_token
365 # Description: Sign/renew non-existant/changed/expiring certificates.
366 command_sign_domains() {
369 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
370 DOMAINS_TXT="$(mktemp)"
371 printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
372 elif [[ -e "${BASEDIR}/domains.txt" ]]; then
373 DOMAINS_TXT="${BASEDIR}/domains.txt"
375 _exiterr "domains.txt not found and --domain not given"
378 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
379 <"${DOMAINS_TXT}" sed 's/^[[:space:]]*//g;s/[[:space:]]*$//g' | grep -vE '^(#|$)' | while read -r line; do
380 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
381 morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
382 cert="${BASEDIR}/certs/${domain}/cert.pem"
384 force_renew="${PARAM_FORCE:-no}"
386 if [[ -z "${morenames}" ]];then
387 echo "Processing ${domain}"
389 echo "Processing ${domain} with alternative names: ${morenames}"
392 if [[ -e "${cert}" ]]; then
393 printf " + Checking domain name(s) of existing cert..."
395 certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')"
396 givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//' | sed 's/^ //')"
398 if [[ "${certnames}" = "${givennames}" ]]; then
402 echo " + Domain name(s) are not matching!"
403 echo " + Names in old certificate: ${certnames}"
404 echo " + Configured names: ${givennames}"
405 echo " + Forcing renew."
410 if [[ -e "${cert}" ]]; then
411 echo " + Checking expire date of existing cert..."
412 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
414 printf " + Valid till %s " "${valid}"
415 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
416 printf "(Longer than %d days). " "${RENEW_DAYS}"
417 if [[ "${force_renew}" = "yes" ]]; then
418 echo "Ignoring because renew was forced!"
424 echo "(Less than ${RENEW_DAYS} days). Renewing!"
428 # shellcheck disable=SC2086
432 # remove temporary domains.txt file if used
433 [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
438 # Usage: --revoke (-r) path/to/cert.pem
439 # Description: Revoke specified certificate
444 if [[ -L "${cert}" ]]; then
445 # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
447 link_target="$(readlink -n "${cert}")"
448 if [[ "${link_target}" =~ ^/ ]]; then
449 cert="${link_target}"
451 cert="$(dirname "${cert}")/${link_target}"
454 if [[ ! -f "${cert}" ]]; then
455 echo "ERROR: Could not find certificate ${cert}"
458 echo "Revoking ${cert}"
459 if [[ -z "${CA_REVOKE_CERT}" ]]; then
460 echo " + ERROR: Certificate authority doesn't allow certificate revocation." >&2
463 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
464 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
465 # if there is a problem with our revoke request http_request (via signed_request) will report this and "exit 1" out
466 # so if we are here, it is safe to assume the request was successful
468 echo " + renaming certificate to ${cert}-revoked"
469 mv -f "${cert}" "${cert}-revoked"
473 # Description: Show help text
475 printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
476 printf "Default command: help\n\n"
478 grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
479 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
480 _exiterr "Error generating help text."
482 printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
484 printf -- "\nParameters:\n"
485 grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
486 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
487 _exiterr "Error generating help text."
489 printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
494 # Description: Output configuration variables for use in other scripts
496 echo "# letsencrypt.sh configuration"
498 typeset -p CA LICENSE HOOK RENEW_DAYS PRIVATE_KEY KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
504 [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
509 if [[ -z "${1:-}" ]]; then
510 echo "The specified command requires additional parameters. See help:" >&2
514 elif [[ "${1:0:1}" = "-" ]]; then
515 _exiterr "Invalid argument: ${1}"
519 while (( "${#}" )); do
531 set_command sign_domains
537 check_parameters "${1:-}"
538 PARAM_REVOKECERT="${1}"
541 # PARAM_Usage: --domain (-d) domain.tld
542 # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
545 check_parameters "${1:-}"
546 if [[ -z "${PARAM_DOMAIN:-}" ]]; then
549 PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
554 # PARAM_Usage: --force (-x)
555 # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
560 # PARAM_Usage: --privkey (-p) path/to/key.pem
561 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
564 check_parameters "${1:-}"
565 PARAM_PRIVATE_KEY="${1}"
568 # PARAM_Usage: --config (-f) path/to/config.sh
569 # PARAM_Description: Use specified config file
572 check_parameters "${1:-}"
577 echo "Unknown parameter detected: ${1}" >&2
589 sign_domains) command_sign_domains;;
590 revoke) command_revoke "${PARAM_REVOKECERT}";;
591 *) command_help; exit1;;
595 # Check for missing dependencies