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"
24 ROOTCERT="lets-encrypt-x1-cross-signed.pem"
28 # Default config variables depending on BASEDIR
29 if [[ -z "${PRIVATE_KEY}" ]]; then
30 PRIVATE_KEY="${BASEDIR}/private_key.pem"
32 if [[ -z "${WELLKNOWN}" ]]; then
33 WELLKNOWN="${BASEDIR}/.acme-challenges"
36 LOCKFILE="${BASEDIR}/lock"
40 # Check for config in various locations
41 if [[ -z "${CONFIG:-}" ]]; then
42 for check_config in "${SCRIPTDIR}" "${HOME}/.letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "/etc/letsencrypt.sh" "${PWD}"; do
43 if [[ -e "${check_config}/config.sh" ]]; then
44 BASEDIR="${check_config}"
45 CONFIG="${check_config}/config.sh"
51 if [[ -z "${CONFIG:-}" ]]; then
52 echo "WARNING: No config file found, using default config!"
54 elif [[ -e "${CONFIG}" ]]; then
55 echo "Using config file ${CONFIG}"
56 BASEDIR="$(dirname "${CONFIG}")"
57 # shellcheck disable=SC1090
60 echo "ERROR: Specified config file doesn't exist."
64 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
65 BASEDIR="${BASEDIR%%/}"
67 # Check BASEDIR and set default variables
68 if [[ ! -d "${BASEDIR}" ]]; then
69 echo "ERROR: BASEDIR does not exist: ${BASEDIR}"
74 # Lockfile handling (prevents concurrent access)
76 if ! { date > "${LOCKFILE}"; } 2>/dev/null; then
77 echo " + ERROR: Lock file '${LOCKFILE}' present, aborting." >&2
78 LOCKFILE= # so remove_lock doesn't remove it
84 if [[ -n "${LOCKFILE}" ]]; then
88 trap 'remove_lock' EXIT
90 # Export some environment variables to be used in hook script
96 CA_DIRECTORY="$(_request get "${CA}")"
97 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
98 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
99 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
100 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
101 (echo "Error retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."; exit 1)
104 # check private key ...
106 if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
107 # a private key was specified from the command line so use it for this run
108 echo "Using private key "${PARAM_PRIVATE_KEY}" instead of account key"
109 PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
110 if ! openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null; then
111 echo " + ERROR: private key is not valid, can not continue"
115 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
116 PRIVATE_KEY="${BASEDIR}/private_key.pem"
117 if [[ ! -e "${PRIVATE_KEY}" ]]; then
118 echo "+ Generating account key..."
119 _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
124 # Get public components from private key and calculate thumbprint
125 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
126 pubMod64="$(printf '%s' "$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
128 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
130 # If we generated a new private key in the step above we have to register it with the acme-server
131 if [[ "${register}" = "1" ]]; then
132 echo "+ Registering account key with letsencrypt..."
133 if [ -z "${CA_NEW_REG}" ]; then
134 echo " + ERROR: Certificate authority doesn't allow registrations."
137 # if an email for the contact has been provided then adding it to the registration request
138 if [[ -n "${CONTACT_EMAIL}" ]]; then
139 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
141 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
145 if [[ -e "${BASEDIR}/domains.txt" ]]; then
146 DOMAINS_TXT="${BASEDIR}/domains.txt"
148 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
152 if [[ ! -e "${WELLKNOWN}" ]]; then
153 mkdir -p "${WELLKNOWN}"
162 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
163 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
167 # Store hex string from stdin
172 for ((i=0; i<${#tmphex}; i+=1)); do
173 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
177 test $((${#hex} & 1)) == 0 || hex="0${hex}"
179 # Convert to escaped string
181 for ((i=0; i<${#hex}; i+=2)); do
182 escapedhex=$escapedhex\\x${hex:$i:2}
185 # Convert to binary data
186 printf -- "${escapedhex}"
189 get_json_string_value() {
190 grep -Eo '"'"${1}"'":\s*"[^"]*"' | cut -d'"' -f4
194 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
200 if [[ "${1}" = "head" ]]; then
201 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
202 elif [[ "${1}" = "get" ]]; then
203 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
204 elif [[ "${1}" = "post" ]]; then
205 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
208 if [[ ! "${statuscode:0:1}" = "2" ]]; then
209 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
212 echo "$(<"${tempcont}"))" >&2
215 # Wait for hook script to clean the challenge if used
216 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
217 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
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="$(_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 _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"
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 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}"))
300 # Request and respond to challenges
301 for altname in $altnames; do
302 # Ask the acme-server for new challenge token and extract them from the resulting json block
303 echo " + Requesting challenge for ${altname}..."
304 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
306 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
307 repl=$'\n''{' # fix syntax highlighting in Vim
308 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
309 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
310 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
312 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
313 echo " + Error: Can't retrieve challenges (${response})"
317 # Challenge response consists of the challenge token and the thumbprint of our public certificate
318 keyauth="${challenge_token}.${thumbprint}"
320 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
321 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
322 chmod a+r "${WELLKNOWN}/${challenge_token}"
324 # Wait for hook script to deploy the challenge if used
325 if [[ -n "${HOOK}" ]]; then
326 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
329 # Ask the acme-server to verify our challenge and wait until it becomes valid
330 echo " + Responding to challenge for ${altname}..."
331 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
333 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
335 # get status until a result is reached => not pending anymore
336 while [[ "${status}" = "pending" ]]; do
338 status="$(_request get "${challenge_uri}" | get_json_string_value status)"
341 rm -f "${WELLKNOWN}/${challenge_token}"
343 # Wait for hook script to clean the challenge if used
344 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
345 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
348 if [[ "${status}" = "valid" ]]; then
349 echo " + Challenge is valid!"
351 echo " + Challenge is invalid! (returned: ${status})"
357 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
358 echo " + Requesting certificate..."
359 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
360 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
361 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
362 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
363 # try to load the certificate to detect corruption
364 echo " + Checking certificate..." >&2
365 _openssl x509 -text < "${crt_path}"
367 # Create fullchain.pem
368 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]]; then
369 echo " + Creating fullchain.pem..."
370 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
371 cat "${BASEDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
372 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
375 # Update remaining symlinks
376 if [ ! "${privkey}" = "privkey.pem" ]; then
377 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
380 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
381 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
383 # Wait for hook script to clean the challenge and to deploy cert if used
384 if [[ -n "${HOOK}" ]]; then
385 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
388 unset challenge_token
394 # Description: Sign/renew non-existant/changed(TODO)/expiring certificates.
396 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
397 <"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
398 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
399 cert="${BASEDIR}/certs/${domain}/cert.pem"
401 echo "Processing ${domain}"
402 if [[ -e "${cert}" ]]; then
403 echo " + Found existing cert..."
405 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
407 echo -n " + Valid till ${valid} "
408 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
409 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
412 echo "(Less than ${RENEW_DAYS} days). Renewing!"
415 # shellcheck disable=SC2086
420 # Usage: --sign (-s) domain.tld
421 # Description: Force-sign specific certificate from domains.txt, even if not yet expiring or changed.
423 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
424 <"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -E "^${1}($|\s)" | head -1 | while read -r line; do
425 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
426 cert="${BASEDIR}/certs/${domain}/cert.pem"
428 echo "Processing ${domain}"
429 if [[ -e "${cert}" ]]; then
430 echo " + Found existing cert... ignoring."
433 # shellcheck disable=SC2086
435 done || (echo "No entry for ${1} found in ${DOMAINS_TXT}."; exit 1)
438 # Usage: --revoke (-r) path/to/cert.pem
439 # Description: Revoke specified certificate
442 echo "Revoking ${cert}"
443 if [ -z "${CA_REVOKE_CERT}" ]; then
444 echo " + ERROR: Certificate authority doesn't allow certificate revocation."
447 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
448 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
449 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
450 # so if we are here, it is safe to assume the request was successful
452 echo " + renaming certificate to ${cert}-revoked"
453 mv -f "${cert}" "${cert}-revoked"
457 # Description: Show help text
459 echo "Usage: ${0} [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ..."
461 echo "Default command: cron"
465 grep -e '# Usage:' -e '# Description:' -e '^command_.*()\s*{' "${0}" | while read -r usage; read -r description; read -r command; do
466 if [[ ! "${usage}" =~ Usage ]]; then
467 echo "Error generating help text."
469 elif [[ ! "${description}" =~ Description ]]; then
470 echo "Error generating help text."
472 elif [[ ! "${command}" =~ ^command_ ]]; then
473 echo "Error generating help text."
476 printf " %s\t%s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
480 grep -E -e '^\s*# PARAM_Usage:' -e '^\s*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
481 if [[ ! "${usage}" =~ Usage ]]; then
482 echo "Error generating help text."
484 elif [[ ! "${description}" =~ Description ]]; then
485 echo "Error generating help text."
488 printf " %s\t%s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
490 ) | column -t -s $'\t' | sed 's/^---$//g'
494 # change long args to short args
495 # inspired by http://kirk.webfinish.com/?p=45
498 --help) args="${args}-h ";;
499 --cron) args="${args}-c ";;
500 --sign) args="${args}-s ";;
501 --revoke) args="${args}-r ";;
502 --privkey) args="${args}-p ";;
503 --config) args="${args}-f ";;
505 echo "Unknown parameter detected: ${arg}"
510 # pass through anything else
511 *) args="${args}\"${arg}\" ";;
515 # Reset the positional parameters to the short options
520 if [[ ! -z "${COMMAND}" ]]; then
521 echo "Only one command can be executed at a time."
522 echo "See help (-h) for more information."
529 if [[ -z "${@}" ]]; then
530 echo "The specified command requires additional parameters. See help:"
537 while getopts ":hcr:s:f:p:" option; do
548 check_parameters "${OPTARG:-}"
549 revoke_me="${OPTARG}"
553 check_parameters "${OPTARG:-}"
557 # PARAM_Usage: --config (-f) path/to/config.sh
558 # PARAM_Description: Use specified config file
559 check_parameters "${OPTARG:-}"
563 # PARAM_Usage: --privkey (-p) path/to/key.pem
564 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
565 check_parameters "${OPTARG:-}"
566 PARAM_PRIVATE_KEY="${OPTARG}"
569 echo "Unknown parameter detected: -${OPTARG}"
577 if [[ -z "${COMMAND}" ]]; then
588 command_sign ${sign_me}
591 command_revoke ${revoke_me}