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 # Default config values
12 CA="https://acme-v01.api.letsencrypt.org/directory"
13 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
17 WELLKNOWN="${SCRIPTDIR}/.acme-challenges"
18 PRIVATE_KEY_RENEW="no"
19 BASEDIR="${SCRIPTDIR}"
20 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
21 ROOTCERT="lets-encrypt-x1-cross-signed.pem"
25 # Check for config in various locations
26 if [[ -z "${CONFIG:-}" ]]; then
27 for check_config in "${SCRIPTDIR}" "${HOME}/.letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "/etc/letsencrypt.sh" "${PWD}"; do
28 if [[ -e "${check_config}/config.sh" ]]; then
29 BASEDIR="${check_config}"
30 CONFIG="${check_config}/config.sh"
36 if [[ -z "${CONFIG:-}" ]]; then
37 echo "WARNING: No config file found, using default config!"
39 elif [[ -e "${CONFIG}" ]]; then
40 echo "Using config file ${CONFIG}"
41 BASEDIR="$(dirname "${CONFIG}")"
42 # shellcheck disable=SC1090
45 echo "ERROR: Specified config file doesn't exist."
49 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
50 BASEDIR="${BASEDIR%%/}"
52 # Lockfile handling (prevents concurrent access)
53 LOCKFILE="${BASEDIR}/lock"
56 if ! { date > "${LOCKFILE}"; } 2>/dev/null; then
57 echo " + ERROR: Lock file '${LOCKFILE}' present, aborting." >&2
58 LOCKFILE= # so remove_lock doesn't remove it
64 if [[ -n "${LOCKFILE}" ]]; then
68 trap 'remove_lock' EXIT
70 # Export some environment variables to be used in hook script
76 CA_DIRECTORY="$(_request get "${CA}")"
77 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
78 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
79 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
80 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
81 (echo "Error retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."; exit 1)
83 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
85 if [[ -z "${USEPRIVATEKEY:-}" ]]; then
86 USEPRIVATEKEY="${BASEDIR}/private_key.pem"
87 if [[ ! -e "${USEPRIVATEKEY}" ]]; then
88 echo "+ Generating account key..."
89 _openssl genrsa -out "${USEPRIVATEKEY}" "${KEYSIZE}"
92 elif [[ ! -e "${USEPRIVATEKEY}" ]]; then
93 echo "ERROR: Unable to find specified private key."
96 echo "Using private key ${USEPRIVATEKEY} instead of account key"
99 # Get public components from private key and calculate thumbprint
100 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${USEPRIVATEKEY}" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
101 pubMod64="$(printf '%s' "$(openssl rsa -in "${USEPRIVATEKEY}" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
103 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
105 # If we generated a new private key in the step above we have to register it with the acme-server
106 if [[ "${register}" = "1" ]]; then
107 echo "+ Registering account key with letsencrypt..."
108 if [ -z "${CA_NEW_REG}" ]; then
109 echo " + ERROR: Certificate authority doesn't allow registrations."
112 # if an email for the contact has been provided then adding it to the registration request
113 if [[ -n "${CONTACT_EMAIL}" ]]; then
114 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
116 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
120 if [[ -e "${BASEDIR}/domains.txt" ]]; then
121 DOMAINS_TXT="${BASEDIR}/domains.txt"
122 elif [[ -e "${SCRIPTDIR}/domains.txt" ]]; then
123 DOMAINS_TXT="${SCRIPTDIR}/domains.txt"
125 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
129 if [[ ! -e "${WELLKNOWN}" ]]; then
130 mkdir -p "${WELLKNOWN}"
139 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
140 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
144 # Store hex string from stdin
149 for ((i=0; i<${#tmphex}; i+=1)); do
150 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
154 test $((${#hex} & 1)) == 0 || hex="0${hex}"
156 # Convert to escaped string
158 for ((i=0; i<${#hex}; i+=2)); do
159 escapedhex=$escapedhex\\x${hex:$i:2}
162 # Convert to binary data
163 printf -- "${escapedhex}"
166 get_json_string_value() {
167 grep -Eo '"'"${1}"'":\s*"[^"]*"' | cut -d'"' -f4
171 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
177 if [[ "${1}" = "head" ]]; then
178 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
179 elif [[ "${1}" = "get" ]]; then
180 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
181 elif [[ "${1}" = "post" ]]; then
182 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
185 if [[ ! "${statuscode:0:1}" = "2" ]]; then
186 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
189 echo "$(<"${tempcont}"))" >&2
192 # Wait for hook script to clean the challenge if used
193 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
194 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
204 # OpenSSL writes to stderr/stdout even when there are no errors. So just
205 # display the output if the exit code was != 0 to simplify debugging.
208 out="$(openssl $@ 2>&1)"
211 if [[ $res -ne 0 ]]; then
212 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
221 # Encode payload as urlbase64
222 payload64="$(printf '%s' "${2}" | urlbase64)"
224 # Retrieve nonce from acme-server
225 nonce="$(_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
227 # Build header with just our public key and algorithm information
228 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
230 # Build another header which also contains the previously received nonce and encode it as urlbase64
231 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
232 protected64="$(printf '%s' "${protected}" | urlbase64)"
234 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
235 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${USEPRIVATEKEY}" | urlbase64)"
237 # Send header + extended header + payload + signature to the acme-server
238 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
240 _request post "${1}" "${data}"
247 echo " + Signing domains..."
248 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
249 echo " + ERROR: Certificate authority doesn't allow certificate signing"
252 timestamp="$(date +%s)"
254 # If there is no existing certificate directory => make it
255 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
256 echo " + make directory ${BASEDIR}/certs/${domain} ..."
257 mkdir -p "${BASEDIR}/certs/${domain}"
260 privkey="privkey.pem"
261 # generate a new private key if we need or want one
262 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
263 echo " + Generating private key..."
264 privkey="privkey-${timestamp}.pem"
265 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
268 # Generate signing request config and the actual signing request
270 for altname in $altnames; do
271 SAN+="DNS:${altname}, "
274 echo " + Generating signing request..."
275 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}"))
277 # Request and respond to challenges
278 for altname in $altnames; do
279 # Ask the acme-server for new challenge token and extract them from the resulting json block
280 echo " + Requesting challenge for ${altname}..."
281 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
283 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
284 repl=$'\n''{' # fix syntax highlighting in Vim
285 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
286 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
287 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
289 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
290 echo " + Error: Can't retrieve challenges (${response})"
294 # Challenge response consists of the challenge token and the thumbprint of our public certificate
295 keyauth="${challenge_token}.${thumbprint}"
297 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
298 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
299 chmod a+r "${WELLKNOWN}/${challenge_token}"
301 # Wait for hook script to deploy the challenge if used
302 if [[ -n "${HOOK}" ]]; then
303 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
306 # Ask the acme-server to verify our challenge and wait until it becomes valid
307 echo " + Responding to challenge for ${altname}..."
308 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
310 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
312 # get status until a result is reached => not pending anymore
313 while [[ "${status}" = "pending" ]]; do
315 status="$(_request get "${challenge_uri}" | get_json_string_value status)"
318 rm -f "${WELLKNOWN}/${challenge_token}"
320 # Wait for hook script to clean the challenge if used
321 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
322 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
325 if [[ "${status}" = "valid" ]]; then
326 echo " + Challenge is valid!"
328 echo " + Challenge is invalid! (returned: ${status})"
334 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
335 echo " + Requesting certificate..."
336 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
337 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
338 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
339 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
340 # try to load the certificate to detect corruption
341 echo " + Checking certificate..." >&2
342 _openssl x509 -text < "${crt_path}"
344 # Create fullchain.pem
345 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]] || [[ -e "${SCRIPTDIR}/certs/${ROOTCERT}" ]]; then
346 echo " + Creating fullchain.pem..."
347 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
348 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]]; then
349 cat "${BASEDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
351 cat "${SCRIPTDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
353 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
356 # Update remaining symlinks
357 if [ ! "${privkey}" = "privkey.pem" ]; then
358 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
361 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
362 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
364 # Wait for hook script to clean the challenge and to deploy cert if used
365 if [[ -n "${HOOK}" ]]; then
366 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
369 unset challenge_token
375 # Description: Sign/renew non-existant/changed(TODO)/expiring certificates.
377 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
378 <"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
379 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
380 cert="${BASEDIR}/certs/${domain}/cert.pem"
382 echo "Processing ${domain}"
383 if [[ -e "${cert}" ]]; then
384 echo " + Found existing cert..."
386 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
388 echo -n " + Valid till ${valid} "
389 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
390 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
393 echo "(Less than ${RENEW_DAYS} days). Renewing!"
396 # shellcheck disable=SC2086
401 # Usage: --sign (-s) domain.tld
402 # Description: Force-sign specific certificate from domains.txt, even if not yet expiring or changed.
404 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
405 <"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -E "^${1}($|\s)" | head -1 | while read -r line; do
406 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
407 cert="${BASEDIR}/certs/${domain}/cert.pem"
409 echo "Processing ${domain}"
410 if [[ -e "${cert}" ]]; then
411 echo " + Found existing cert... ignoring."
414 # shellcheck disable=SC2086
416 done || (echo "No entry for ${1} found in ${DOMAINS_TXT}."; exit 1)
419 # Usage: --revoke (-r) path/to/cert.pem
420 # Description: Revoke specified certificate
423 echo "Revoking ${cert}"
424 if [ -z "${CA_REVOKE_CERT}" ]; then
425 echo " + ERROR: Certificate authority doesn't allow certificate revocation."
428 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
429 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
430 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
431 # so if we are here, it is safe to assume the request was successful
433 echo " + renaming certificate to ${cert}-revoked"
434 mv -f "${cert}" "${cert}-revoked"
438 # Description: Show help text
440 echo "Usage: ${0} [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ..."
442 echo "Default command: cron"
446 grep -e '# Usage:' -e '# Description:' -e '^command_.*()\s*{' "${0}" | while read -r usage; read -r description; read -r command; do
447 if [[ ! "${usage}" =~ Usage ]]; then
448 echo "Error generating help text."
450 elif [[ ! "${description}" =~ Description ]]; then
451 echo "Error generating help text."
453 elif [[ ! "${command}" =~ ^command_ ]]; then
454 echo "Error generating help text."
457 printf " %s\t%s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
461 grep -E -e '^\s*# PARAM_Usage:' -e '^\s*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
462 if [[ ! "${usage}" =~ Usage ]]; then
463 echo "Error generating help text."
465 elif [[ ! "${description}" =~ Description ]]; then
466 echo "Error generating help text."
469 printf " %s\t%s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
471 ) | column -t -s $'\t' | sed 's/^---$//g'
475 # change long args to short args
476 # inspired by http://kirk.webfinish.com/?p=45
479 --help) args="${args}-h ";;
480 --cron) args="${args}-c ";;
481 --sign) args="${args}-s ";;
482 --revoke) args="${args}-r ";;
483 --privkey) args="${args}-p ";;
484 --config) args="${args}-f ";;
486 echo "Unknown parameter detected: ${arg}"
491 # pass through anything else
492 *) args="${args}\"${arg}\" ";;
496 # Reset the positional parameters to the short options
501 if [[ ! -z "${COMMAND}" ]]; then
502 echo "Only one command can be executed at a time."
503 echo "See help (-h) for more information."
510 if [[ -z "${@}" ]]; then
511 echo "The specified command requires additional parameters. See help:"
518 while getopts ":hcr:s:f:p:" option; do
529 check_parameters "${OPTARG:-}"
530 revoke_me="${OPTARG}"
534 check_parameters "${OPTARG:-}"
538 # PARAM_Usage: --config (-f) path/to/config.sh
539 # PARAM_Description: Use specified config file
540 check_parameters "${OPTARG:-}"
544 # PARAM_Usage: --privkey (-p) path/to/key.pem
545 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
546 check_parameters "${OPTARG:-}"
547 USEPRIVATEKEY="${OPTARG}"
550 echo "Unknown parameter detected: -${OPTARG}"
558 if [[ -z "${COMMAND}" ]]; then
569 command_sign ${sign_me}
572 command_revoke ${revoke_me}