6 umask 077 # paranoid umask, we're creating private keys
8 # Get the directory in which this script is stored
9 SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
11 # directory for config, private key and certificates
12 BASEDIR="${SCRIPTDIR}"
14 # Default config values
15 CA="https://acme-v01.api.letsencrypt.org/directory"
16 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
22 PRIVATE_KEY_RENEW="no"
23 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
27 # Default config variables depending on BASEDIR
28 if [[ -z "${PRIVATE_KEY}" ]]; then
29 PRIVATE_KEY="${BASEDIR}/private_key.pem"
31 if [[ -z "${WELLKNOWN}" ]]; then
32 WELLKNOWN="${BASEDIR}/.acme-challenges"
35 LOCKFILE="${BASEDIR}/lock"
39 # Check for config in various locations
40 if [[ -z "${CONFIG:-}" ]]; then
41 for check_config in "${HOME}/.letsencrypt.sh" "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
42 if [[ -e "${check_config}/config.sh" ]]; then
43 BASEDIR="${check_config}"
44 CONFIG="${check_config}/config.sh"
50 if [[ -z "${CONFIG:-}" ]]; then
51 echo "WARNING: No config file found, using default config!"
53 elif [[ -e "${CONFIG}" ]]; then
54 if [[ ! "${COMMAND}" = "env" ]]; then
55 echo "Using config file ${CONFIG}"
57 BASEDIR="$(dirname "${CONFIG}")"
58 # shellcheck disable=SC1090
61 echo "ERROR: Specified config file doesn't exist."
65 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
66 BASEDIR="${BASEDIR%%/}"
68 # Check BASEDIR and set default variables
69 if [[ ! -d "${BASEDIR}" ]]; then
70 echo "ERROR: BASEDIR does not exist: ${BASEDIR}"
75 if [[ "${COMMAND}" = "env" ]]; then
79 # Lockfile handling (prevents concurrent access)
81 if ! { date > "${LOCKFILE}"; } 2>/dev/null; then
82 echo " + ERROR: Lock file '${LOCKFILE}' present, aborting." >&2
83 LOCKFILE="" # so remove_lock doesn't remove it
89 if [[ -n "${LOCKFILE}" ]]; then
93 trap 'remove_lock' EXIT
95 # Export some environment variables to be used in hook script
101 CA_DIRECTORY="$(_request get "${CA}")"
102 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
103 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
104 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
105 # shellcheck disable=SC2015
106 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
107 (echo "Error retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."; exit 1)
110 # check private key ...
112 if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
113 # a private key was specified from the command line so use it for this run
114 echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
115 PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
116 if ! openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null; then
117 echo " + ERROR: private key is not valid, can not continue"
121 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
122 if [[ ! -e "${PRIVATE_KEY}" ]]; then
123 echo "+ Generating account key..."
124 _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
129 # Get public components from private key and calculate thumbprint
130 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
131 pubMod64="$(printf '%s' "$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
133 thumbprint="$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | openssl sha -sha256 -binary | urlbase64)"
135 # If we generated a new private key in the step above we have to register it with the acme-server
136 if [[ "${register}" = "1" ]]; then
137 echo "+ Registering account key with letsencrypt..."
138 if [ -z "${CA_NEW_REG}" ]; then
139 echo " + ERROR: Certificate authority doesn't allow registrations."
142 # if an email for the contact has been provided then adding it to the registration request
143 if [[ -n "${CONTACT_EMAIL}" ]]; then
144 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
146 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
150 if [[ -e "${BASEDIR}/domains.txt" ]]; then
151 DOMAINS_TXT="${BASEDIR}/domains.txt"
153 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
157 if [[ ! -e "${WELLKNOWN}" ]]; then
158 mkdir -p "${WELLKNOWN}"
167 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
168 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
172 # Store hex string from stdin
177 for ((i=0; i<${#tmphex}; i+=1)); do
178 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
182 test $((${#hex} & 1)) == 0 || hex="0${hex}"
184 # Convert to escaped string
186 for ((i=0; i<${#hex}; i+=2)); do
187 escapedhex=$escapedhex\\x${hex:$i:2}
190 # Convert to binary data
191 printf -- "${escapedhex}"
194 get_json_string_value() {
195 grep -Eo '"'"${1}"'":\s*"[^"]*"' | cut -d'"' -f4
199 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
205 if [[ "${1}" = "head" ]]; then
206 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
207 elif [[ "${1}" = "get" ]]; then
208 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
209 elif [[ "${1}" = "post" ]]; then
210 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
213 if [[ ! "${statuscode:0:1}" = "2" ]]; then
214 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
217 echo "$(<"${tempcont}"))" >&2
220 # Wait for hook script to clean the challenge if used
221 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
222 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
225 # remove temporary domains.txt file if used
226 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
237 # OpenSSL writes to stderr/stdout even when there are no errors. So just
238 # display the output if the exit code was != 0 to simplify debugging.
241 out="$(openssl "${@}" 2>&1)"
244 if [[ $res -ne 0 ]]; then
245 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
254 # Encode payload as urlbase64
255 payload64="$(printf '%s' "${2}" | urlbase64)"
257 # Retrieve nonce from acme-server
258 nonce="$(_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
260 # Build header with just our public key and algorithm information
261 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
263 # Build another header which also contains the previously received nonce and encode it as urlbase64
264 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
265 protected64="$(printf '%s' "${protected}" | urlbase64)"
267 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
268 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
270 # Send header + extended header + payload + signature to the acme-server
271 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
273 _request post "${1}" "${data}"
280 echo " + Signing domains..."
281 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
282 echo " + ERROR: Certificate authority doesn't allow certificate signing"
285 timestamp="$(date +%s)"
287 # If there is no existing certificate directory => make it
288 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
289 echo " + make directory ${BASEDIR}/certs/${domain} ..."
290 mkdir -p "${BASEDIR}/certs/${domain}"
293 privkey="privkey.pem"
294 # generate a new private key if we need or want one
295 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
296 echo " + Generating private key..."
297 privkey="privkey-${timestamp}.pem"
298 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
301 # Generate signing request config and the actual signing request
303 for altname in $altnames; do
304 SAN+="DNS:${altname}, "
307 echo " + Generating signing request..."
308 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}"))
310 # Request and respond to challenges
311 for altname in $altnames; do
312 # Ask the acme-server for new challenge token and extract them from the resulting json block
313 echo " + Requesting challenge for ${altname}..."
314 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
316 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
317 repl=$'\n''{' # fix syntax highlighting in Vim
318 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
319 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
320 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
322 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
323 echo " + Error: Can't retrieve challenges (${response})"
327 # Challenge response consists of the challenge token and the thumbprint of our public certificate
328 keyauth="${challenge_token}.${thumbprint}"
330 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
331 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
332 chmod a+r "${WELLKNOWN}/${challenge_token}"
334 # Wait for hook script to deploy the challenge if used
335 if [[ -n "${HOOK}" ]]; then
336 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
339 # Ask the acme-server to verify our challenge and wait until it becomes valid
340 echo " + Responding to challenge for ${altname}..."
341 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
343 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
345 # get status until a result is reached => not pending anymore
346 while [[ "${status}" = "pending" ]]; do
348 status="$(_request get "${challenge_uri}" | get_json_string_value status)"
351 rm -f "${WELLKNOWN}/${challenge_token}"
353 # Wait for hook script to clean the challenge if used
354 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
355 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
358 if [[ "${status}" = "valid" ]]; then
359 echo " + Challenge is valid!"
361 echo " + Challenge is invalid! (returned: ${status})"
367 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
368 echo " + Requesting certificate..."
369 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
370 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
371 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
372 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
373 # try to load the certificate to detect corruption
374 echo " + Checking certificate..." >&2
375 _openssl x509 -text < "${crt_path}"
377 # Create fullchain.pem
378 echo " + Creating fullchain.pem..."
379 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
380 _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"
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(TODO)/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/^[ ]*//g;s/[ ]*$//g' | grep -v '^#' | grep -v '^$' | 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 if [[ -z "${morenames}" ]];then
416 echo "Processing ${domain}"
418 echo "Processing ${domain} with SAN: ${morenames}"
421 if [[ -e "${cert}" ]]; then
422 echo " + Found existing cert..."
424 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
426 echo -n " + Valid till ${valid} "
427 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
428 echo -n "(Longer than ${RENEW_DAYS} days). "
429 if [[ "${PARAM_FORCE:-}" = "yes" ]]; then
430 echo "Ignoring because --force was specified!"
436 echo "(Less than ${RENEW_DAYS} days). Renewing!"
440 # shellcheck disable=SC2086
444 # remove temporary domains.txt file if used
445 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
450 # Usage: --revoke (-r) path/to/cert.pem
451 # Description: Revoke specified certificate
454 echo "Revoking ${cert}"
455 if [ -z "${CA_REVOKE_CERT}" ]; then
456 echo " + ERROR: Certificate authority doesn't allow certificate revocation."
459 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
460 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
461 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
462 # so if we are here, it is safe to assume the request was successful
464 echo " + renaming certificate to ${cert}-revoked"
465 mv -f "${cert}" "${cert}-revoked"
469 # Description: Show help text
471 echo "Usage: ${0} [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ..."
473 echo "Default command: cron"
477 grep -e '^\s*# Usage:' -e '^\s*# Description:' -e '^command_.*()\s*{' "${0}" | while read -r usage; read -r description; read -r command; do
478 if [[ ! "${usage}" =~ Usage ]]; then
479 echo "Error generating help text."
481 elif [[ ! "${description}" =~ Description ]]; then
482 echo "Error generating help text."
484 elif [[ ! "${command}" =~ ^command_ ]]; then
485 echo "Error generating help text."
488 printf " %s\t%s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
492 grep -E -e '^\s*# PARAM_Usage:' -e '^\s*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
493 if [[ ! "${usage}" =~ Usage ]]; then
494 echo "Error generating help text."
496 elif [[ ! "${description}" =~ Description ]]; then
497 echo "Error generating help text."
500 printf " %s\t%s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
502 ) | column -t -s $'\t' | sed 's/^---$//g'
506 # Description: Output configuration variables for use in other scripts
508 echo "# letsencrypt.sh configuration"
510 typeset -p CA LICENSE BASEDIR WELLKNOWN PRIVATE_KEY KEYSIZE OPENSSL_CNF HOOK RENEW_DAYS PRIVATE_KEY_RENEW CONTACT_EMAIL
515 # change long args to short args
516 # inspired by http://kirk.webfinish.com/?p=45
519 --help) args="${args}-h ";;
520 --cron) args="${args}-c ";;
521 --domain) args="${args}-d ";;
522 --force ) args="${args}-x ";;
523 --revoke) args="${args}-r ";;
524 --privkey) args="${args}-p ";;
525 --config) args="${args}-f ";;
526 --env) args="${args}-e ";;
528 echo "Unknown parameter detected: ${arg}"
533 # pass through anything else
534 *) args="${args}\"${arg}\" ";;
538 # Reset the positional parameters to the short options
539 eval set -- "${args}"
543 if [[ ! -z "${COMMAND}" ]]; then
544 echo "Only one command can be executed at a time."
545 echo "See help (-h) for more information."
552 if [[ -z "${@}" ]]; then
553 echo "The specified command requires additional parameters. See help:"
560 while getopts ":hcer:d:xf:p:" option; do
574 check_parameters "${OPTARG:-}"
575 revoke_me="${OPTARG}"
578 # PARAM_Usage: --domain (-d) domain.tld
579 # PARAM_Description: Use specified domain name instead of domains.txt, use multiple times for certificate with SAN names
580 check_parameters "${OPTARG:-}"
581 if [[ -z "${PARAM_DOMAIN:-}" ]]; then
582 PARAM_DOMAIN="${OPTARG}"
584 PARAM_DOMAIN="${PARAM_DOMAIN} ${OPTARG}"
588 # PARAM_Usage: --force (-x)
589 # PARAM_Description: force renew of certificate even if it is longer valid than value in RENEW_DAYS
593 # PARAM_Usage: --config (-f) path/to/config.sh
594 # PARAM_Description: Use specified config file
595 check_parameters "${OPTARG:-}"
599 # PARAM_Usage: --privkey (-p) path/to/key.pem
600 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
601 check_parameters "${OPTARG:-}"
602 PARAM_PRIVATE_KEY="${OPTARG}"
605 echo "Unknown parameter detected: -${OPTARG}"
613 if [[ -z "${COMMAND}" ]]; then
627 command_revoke "${revoke_me}"