]> git.street.me.uk Git - andy/dehydrated.git/blob - letsencrypt.sh
pass IO descriptors to HOOK transparently
[andy/dehydrated.git] / letsencrypt.sh
1 #!/usr/bin/env bash
2
3 # letsencrypt.sh by lukas2511
4 # Source: https://github.com/lukas2511/letsencrypt.sh
5
6 set -e
7 set -u
8 set -o pipefail
9 umask 077 # paranoid umask, we're creating private keys
10
11 # duplicate scripts IO handles
12 exec 4<&0 5>&1 6>&2
13
14 # Get the directory in which this script is stored
15 SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
16 BASEDIR="${SCRIPTDIR}"
17
18 # Check for script dependencies
19 check_dependencies() {
20   # just execute some dummy and/or version commands to see if required tools exist and are actually usable
21   openssl version > /dev/null 2>&1 || _exiterr "This script requires an openssl binary."
22   _sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requires sed with support for extended (modern) regular expressions."
23   grep -V > /dev/null 2>&1 || _exiterr "This script requires grep."
24   mktemp -u -t XXXXXX > /dev/null 2>&1 || _exiterr "This script requires mktemp."
25
26   # curl returns with an error code in some ancient versions so we have to catch that
27   set +e
28   curl -V > /dev/null 2>&1
29   set -e
30   retcode="$?"
31   if [[ ! "${retcode}" = "0" ]] && [[ ! "${retcode}" = "2" ]]; then
32     _exiterr "This script requires curl."
33   fi
34 }
35
36 # Setup default config values, search for and load configuration files
37 load_config() {
38   # Check for config in various locations
39   if [[ -z "${CONFIG:-}" ]]; then
40     for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
41       if [[ -e "${check_config}/config.sh" ]]; then
42         BASEDIR="${check_config}"
43         CONFIG="${check_config}/config.sh"
44         break
45       fi
46     done
47   fi
48
49   # Default values
50   CA="https://acme-v01.api.letsencrypt.org/directory"
51   LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
52   CHALLENGETYPE="http-01"
53   CONFIG_D=
54   HOOK=
55   RENEW_DAYS="30"
56   PRIVATE_KEY=
57   KEYSIZE="4096"
58   WELLKNOWN=
59   PRIVATE_KEY_RENEW="no"
60   KEY_ALGO=rsa
61   OPENSSL_CNF="$(openssl version -d | cut -d\" -f2)/openssl.cnf"
62   CONTACT_EMAIL=
63   LOCKFILE=
64
65   if [[ -z "${CONFIG:-}" ]]; then
66     echo "#" >&2
67     echo "# !! WARNING !! No main config file found, using default config!" >&2
68     echo "#" >&2
69   elif [[ -e "${CONFIG}" ]]; then
70     echo "# INFO: Using main config file ${CONFIG}"
71     BASEDIR="$(dirname "${CONFIG}")"
72     # shellcheck disable=SC1090
73     . "${CONFIG}"
74   else
75     _exiterr "Specified config file doesn't exist."
76   fi
77
78   if [[ -n "${CONFIG_D}" ]]; then
79     if [[ ! -d "${CONFIG_D}" ]]; then
80       _exiterr "The path ${CONFIG_D} specified for CONFIG_D does not point to a directory." >&2
81     fi
82
83     for check_config_d in ${CONFIG_D}/*.sh; do
84       if [[ ! -e "${check_config_d}" ]]; then
85         echo "# !! WARNING !! Extra configuration directory ${CONFIG_D} exists, but no configuration found in it." >&2
86         break
87       elif [[ -f "${check_config_d}" ]] && [[ -r "${check_config_d}" ]]; then
88         echo "# INFO: Using additional config file ${check_config_d}"
89         . ${check_config_d}
90       else
91         _exiterr "Specified additional config ${check_config_d} is not readable or not a file at all." >&2
92       fi
93    done
94   fi
95
96   # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
97   BASEDIR="${BASEDIR%%/}"
98
99   # Check BASEDIR and set default variables
100   [[ -d "${BASEDIR}" ]] || _exiterr "BASEDIR does not exist: ${BASEDIR}"
101
102   [[ -z "${PRIVATE_KEY}" ]] && PRIVATE_KEY="${BASEDIR}/private_key.pem"
103   [[ -z "${WELLKNOWN}" ]] && WELLKNOWN="${BASEDIR}/.acme-challenges"
104   [[ -z "${LOCKFILE}" ]] && LOCKFILE="${BASEDIR}/lock"
105
106   [[ -n "${PARAM_HOOK:-}" ]] && HOOK="${PARAM_HOOK}"
107   [[ -n "${PARAM_CHALLENGETYPE:-}" ]] && CHALLENGETYPE="${PARAM_CHALLENGETYPE}"
108   [[ -n "${PARAM_KEY_ALGO:-}" ]] && KEY_ALGO="${PARAM_KEY_ALGO}"
109
110   [[ "${CHALLENGETYPE}" =~ (http-01|dns-01) ]] || _exiterr "Unknown challenge type ${CHALLENGETYPE}... can not continue."
111   if [[ "${CHALLENGETYPE}" = "dns-01" ]] && [[ -z "${HOOK}" ]]; then
112    _exiterr "Challenge type dns-01 needs a hook script for deployment... can not continue."
113   fi
114   [[ "${KEY_ALGO}" =~ ^(rsa|prime256v1|secp384r1)$ ]] || _exiterr "Unknown public key algorithm ${KEY_ALGO}... can not continue."
115 }
116
117 # Initialize system
118 init_system() {
119   load_config
120
121   # Lockfile handling (prevents concurrent access)
122   LOCKDIR="$(dirname "${LOCKFILE}")"
123   [[ -w "${LOCKDIR}" ]] || _exiterr "Directory ${LOCKDIR} for LOCKFILE ${LOCKFILE} is not writable, aborting."
124   ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
125   remove_lock() { rm -f "${LOCKFILE}"; }
126   trap 'remove_lock' EXIT
127
128   # Get CA URLs
129   CA_DIRECTORY="$(http_request get "${CA}")"
130   CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
131   CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
132   CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
133   # shellcheck disable=SC2015
134   CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
135   _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
136
137   # Export some environment variables to be used in hook script
138   export WELLKNOWN BASEDIR CONFIG
139
140   # Checking for private key ...
141   register_new_key="no"
142   if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
143     # a private key was specified from the command line so use it for this run
144     echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
145     PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
146   else
147     # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
148     if [[ ! -e "${PRIVATE_KEY}" ]]; then
149       echo "+ Generating account key..."
150       _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
151       register_new_key="yes"
152     fi
153   fi
154   openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Private key is not valid, can not continue."
155
156   # Get public components from private key and calculate thumbprint
157   pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
158   pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
159
160   thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
161
162   # If we generated a new private key in the step above we have to register it with the acme-server
163   if [[ "${register_new_key}" = "yes" ]]; then
164     echo "+ Registering account key with letsencrypt..."
165     [[ ! -z "${CA_NEW_REG}" ]] || _exiterr "Certificate authority doesn't allow registrations."
166     # If an email for the contact has been provided then adding it to the registration request
167     if [[ -n "${CONTACT_EMAIL}" ]]; then
168       signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
169     else
170       signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
171     fi
172   fi
173
174   if [[ "${CHALLENGETYPE}" = "http-01" && ! -d "${WELLKNOWN}" ]]; then
175       _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
176   fi
177 }
178
179 # Different sed version for different os types...
180 _sed() {
181   if [[ "${OSTYPE}" = "Linux" ]]; then
182     sed -r "${@}"
183   else
184     sed -E "${@}"
185   fi
186 }
187
188 # Print error message and exit with error
189 _exiterr() {
190   echo "ERROR: ${1}" >&2
191   exit 1
192 }
193
194 # Encode data as url-safe formatted base64
195 urlbase64() {
196   # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
197   openssl base64 -e | tr -d '\n\r' | _sed -e 's:=*$::g' -e 'y:+/:-_:'
198 }
199
200 # Convert hex string to binary data
201 hex2bin() {
202   # Remove spaces, add leading zero, escape as hex string and parse with printf
203   printf -- "$(cat | _sed -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
204 }
205
206 # Get string value from json dictionary
207 get_json_string_value() {
208   grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
209 }
210
211 # OpenSSL writes to stderr/stdout even when there are no errors. So just
212 # display the output if the exit code was != 0 to simplify debugging.
213 _openssl() {
214   set +e
215   out="$(openssl "${@}" 2>&1)"
216   res=$?
217   set -e
218   if [[ $res -ne 0 ]]; then
219     echo "  + ERROR: failed to run $* (Exitcode: $res)" >&2
220     echo >&2
221     echo "Details:" >&2
222     echo "$out" >&2
223     exit $res
224   fi
225 }
226
227 # Send http(s) request with specified method
228 http_request() {
229   tempcont="$(mktemp -t XXXXXX)"
230
231   if [[ "${1}" = "head" ]]; then
232     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
233   elif [[ "${1}" = "get" ]]; then
234     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
235   elif [[ "${1}" = "post" ]]; then
236     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
237   else
238     _exiterr "Unknown request method: ${1}"
239   fi
240
241   if [[ ! "${statuscode:0:1}" = "2" ]]; then
242     echo "  + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
243     echo >&2
244     echo "Details:" >&2
245     cat "${tempcont}" >&2
246     rm -f "${tempcont}"
247
248     # Wait for hook script to clean the challenge if used
249     if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
250       ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}" <&4 >&5 2>&6
251     fi
252
253     # remove temporary domains.txt file if used
254     [[ -n "${PARAM_DOMAIN:-}" ]] && rm "${DOMAINS_TXT}"
255     exit 1
256   fi
257
258   cat "${tempcont}"
259   rm -f "${tempcont}"
260 }
261
262 # Send signed request
263 signed_request() {
264   # Encode payload as urlbase64
265   payload64="$(printf '%s' "${2}" | urlbase64)"
266
267   # Retrieve nonce from acme-server
268   nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
269
270   # Build header with just our public key and algorithm information
271   header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
272
273   # Build another header which also contains the previously received nonce and encode it as urlbase64
274   protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
275   protected64="$(printf '%s' "${protected}" | urlbase64)"
276
277   # Sign header with nonce and our payload with our private key and encode signature as urlbase64
278   signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
279
280   # Send header + extended header + payload + signature to the acme-server
281   data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
282
283   http_request post "${1}" "${data}"
284 }
285
286 # Extracts all subject names from a CSR
287 # Outputs either the CN, or the SANs, one per line
288 extract_altnames() {
289   csr="${1}" # the CSR itself (not a file)
290
291   if ! <<<"${csr}" openssl req -verify -noout 2>/dev/null; then
292     _exiterr "Certificate signing request isn't valid"
293   fi
294
295   reqtext="$( <<<"${csr}" openssl req -noout -text )"
296   if <<<"$reqtext" grep -q '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$'; then
297     # SANs used, extract these
298     altnames="$( <<<"${reqtext}" grep -A1 '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$' | tail -n1 )"
299     # split to one per line:
300     altnames="$( <<<"${altnames}" _sed -e 's/^[[:space:]]*//; s/, /\'$'\n''/' )"
301     # we can only get DNS: ones signed
302     if [ -n "$( <<<"${altnames}" grep -v '^DNS:' )" ]; then
303       _exiterr "Certificate signing request contains non-DNS Subject Alternative Names"
304     fi
305     # strip away the DNS: prefix
306     altnames="$( <<<"${altnames}" _sed -e 's/^DNS://' )"
307     echo "$altnames"
308
309   else
310     # No SANs, extract CN
311     altnames="$( <<<"${reqtext}" grep '^[[:space:]]*Subject:' | _sed -e 's/.* CN=([^ /,]*).*/\1/' )"
312     echo "$altnames"
313   fi
314 }
315
316 # Create certificate for domain(s) and outputs it FD 3
317 sign_csr() {
318   csr="${1}" # the CSR itself (not a file)
319
320   if { true >&3; } 2>/dev/null; then
321     : # fd 3 looks OK
322   else
323     _exiterr "sign_csr: FD 3 not open"
324   fi
325
326   shift 1 || true
327   altnames="${*:-}"
328   if [ -z "$altnames" ]; then
329     altnames="$( extract_altnames "$csr" )"
330   fi
331
332   if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
333     _exiterr "Certificate authority doesn't allow certificate signing"
334   fi
335
336   # Request and respond to challenges
337   for altname in ${altnames}; do
338     # Ask the acme-server for new challenge token and extract them from the resulting json block
339     echo " + Requesting challenge for ${altname}..."
340     response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
341
342     challenges="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]')"
343     repl=$'\n''{' # fix syntax highlighting in Vim
344     challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep \""${CHALLENGETYPE}"\")"
345     challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | _sed 's/[^A-Za-z0-9_\-]/_/g')"
346     challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
347
348     if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
349       _exiterr "Can't retrieve challenges (${response})"
350     fi
351
352     # Challenge response consists of the challenge token and the thumbprint of our public certificate
353     keyauth="${challenge_token}.${thumbprint}"
354
355     case "${CHALLENGETYPE}" in
356       "http-01")
357         # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
358         printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
359         chmod a+r "${WELLKNOWN}/${challenge_token}"
360         keyauth_hook="${keyauth}"
361         ;;
362       "dns-01")
363         # Generate DNS entry content for dns-01 validation
364         keyauth_hook="$(printf '%s' "${keyauth}" | openssl sha -sha256 -binary | urlbase64)"
365         ;;
366     esac
367
368     # Wait for hook script to deploy the challenge if used
369     [[ -n "${HOOK}" ]] && ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth_hook}" <&4 >&5 2>&6
370
371     # Ask the acme-server to verify our challenge and wait until it is no longer pending
372     echo " + Responding to challenge for ${altname}..."
373     result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
374
375     status="$(printf '%s\n' "${result}" | get_json_string_value status)"
376
377     while [[ "${status}" = "pending" ]]; do
378       sleep 1
379       result="$(http_request get "${challenge_uri}")"
380       status="$(printf '%s\n' "${result}" | get_json_string_value status)"
381     done
382
383     [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_token}"
384
385     # Wait for hook script to clean the challenge if used
386     if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
387       ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth_hook}" <&4 >&5 2>&6
388     fi
389
390     if [[ "${status}" = "valid" ]]; then
391       echo " + Challenge is valid!"
392     else
393       _exiterr "Challenge is invalid! (returned: ${status}) (result: ${result})"
394     fi
395   done
396
397   # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
398   echo " + Requesting certificate..."
399   csr64="$( <<<"${csr}" openssl req -outform DER | urlbase64)"
400   crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
401   crt="$( printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" )"
402
403   # Try to load the certificate to detect corruption
404   echo " + Checking certificate..."
405   _openssl x509 -text <<<"${crt}"
406
407   echo "${crt}" >&3
408
409   unset challenge_token
410   echo " + Done!"
411 }
412
413 # Create certificate for domain(s)
414 sign_domain() {
415   domain="${1}"
416   altnames="${*}"
417   timestamp="$(date +%s)"
418
419   echo " + Signing domains..."
420   if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
421     _exiterr "Certificate authority doesn't allow certificate signing"
422   fi
423
424   # If there is no existing certificate directory => make it
425   if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
426     echo " + Creating new directory ${BASEDIR}/certs/${domain} ..."
427     mkdir -p "${BASEDIR}/certs/${domain}"
428   fi
429
430   privkey="privkey.pem"
431   # generate a new private key if we need or want one
432   if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
433     echo " + Generating private key..."
434     privkey="privkey-${timestamp}.pem"
435     case "${KEY_ALGO}" in
436       rsa) _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}";;
437       prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem";;
438     esac
439   fi
440
441   # Generate signing request config and the actual signing request
442   echo " + Generating signing request..."
443   SAN=""
444   for altname in ${altnames}; do
445     SAN+="DNS:${altname}, "
446   done
447   SAN="${SAN%%, }"
448   local tmp_openssl_cnf
449   tmp_openssl_cnf="$(mktemp -t XXXXXX)"
450   cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
451   printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
452   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}"
453   rm -f "${tmp_openssl_cnf}"
454
455   crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
456   sign_csr "$(< "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" )" ${altnames} 3>"${crt_path}"
457
458   # Create fullchain.pem
459   echo " + Creating fullchain.pem..."
460   cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
461   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"
462   if ! grep -q "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"; then
463     openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
464   fi
465   cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
466
467   # Update symlinks
468   [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
469
470   ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
471   ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
472   ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
473   ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
474
475   # Wait for hook script to clean the challenge and to deploy cert if used
476   [[ -n "${HOOK}" ]] && ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem" <&4 >&5 2>&6
477
478   unset challenge_token
479   echo " + Done!"
480 }
481
482 # Usage: --cron (-c)
483 # Description: Sign/renew non-existant/changed/expiring certificates.
484 command_sign_domains() {
485   init_system
486
487   if [[ -n "${PARAM_DOMAIN:-}" ]]; then
488     DOMAINS_TXT="$(mktemp -t XXXXXX)"
489     printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
490   elif [[ -e "${BASEDIR}/domains.txt" ]]; then
491     DOMAINS_TXT="${BASEDIR}/domains.txt"
492   else
493     _exiterr "domains.txt not found and --domain not given"
494   fi
495
496   # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
497   <"${DOMAINS_TXT}" _sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e 's/[[:space:]]+/ /g' | (grep -vE '^(#|$)' || true) | while read -r line; do
498     domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
499     morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
500     cert="${BASEDIR}/certs/${domain}/cert.pem"
501
502     force_renew="${PARAM_FORCE:-no}"
503
504     if [[ -z "${morenames}" ]];then
505       echo "Processing ${domain}"
506     else
507       echo "Processing ${domain} with alternative names: ${morenames}"
508     fi
509
510     if [[ -e "${cert}" ]]; then
511       printf " + Checking domain name(s) of existing cert..."
512
513       certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | _sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//')"
514       givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//' | _sed 's/^ //')"
515
516       if [[ "${certnames}" = "${givennames}" ]]; then
517         echo " unchanged."
518       else
519         echo " changed!"
520         echo " + Domain name(s) are not matching!"
521         echo " + Names in old certificate: ${certnames}"
522         echo " + Configured names: ${givennames}"
523         echo " + Forcing renew."
524         force_renew="yes"
525       fi
526     fi
527
528     if [[ -e "${cert}" ]]; then
529       echo " + Checking expire date of existing cert..."
530       valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
531
532       printf " + Valid till %s " "${valid}"
533       if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
534         printf "(Longer than %d days). " "${RENEW_DAYS}"
535         if [[ "${force_renew}" = "yes" ]]; then
536           echo "Ignoring because renew was forced!"
537         else
538           echo "Skipping!"
539           continue
540         fi
541       else
542         echo "(Less than ${RENEW_DAYS} days). Renewing!"
543       fi
544     fi
545
546     # shellcheck disable=SC2086
547     sign_domain ${line}
548   done
549
550   # remove temporary domains.txt file if used
551   [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
552
553   exit 0
554 }
555
556 # Usage: --signcsr (-s) path/to/csr.pem
557 # Description: Sign a given CSR, output CRT on stdout (advanced usage)
558 command_sign_csr() {
559   # redirect stdout to stderr
560   # leave stdout over at fd 3 to output the cert
561   exec 3>&1 1>&2
562
563   init_system
564
565   csrfile="${1}"
566   if [ ! -r "${csrfile}" ]; then
567     _exiterr "Could not read certificate signing request ${csrfile}"
568   fi
569
570   sign_csr "$(< "${csrfile}" )"
571
572   exit 0
573 }
574
575 # Usage: --revoke (-r) path/to/cert.pem
576 # Description: Revoke specified certificate
577 command_revoke() {
578   init_system
579
580   [[ -n "${CA_REVOKE_CERT}" ]] || _exiterr "Certificate authority doesn't allow certificate revocation."
581
582   cert="${1}"
583   if [[ -L "${cert}" ]]; then
584     # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
585     local link_target
586     link_target="$(readlink -n "${cert}")"
587     if [[ "${link_target}" =~ ^/ ]]; then
588       cert="${link_target}"
589     else
590       cert="$(dirname "${cert}")/${link_target}"
591     fi
592   fi
593   [[ -f "${cert}" ]] || _exiterr "Could not find certificate ${cert}"
594
595   echo "Revoking ${cert}"
596
597   cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
598   response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
599   # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
600   # so if we are here, it is safe to assume the request was successful
601   echo " + Done."
602   echo " + Renaming certificate to ${cert}-revoked"
603   mv -f "${cert}" "${cert}-revoked"
604 }
605
606 # Usage: --help (-h)
607 # Description: Show help text
608 command_help() {
609   printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
610   printf "Default command: help\n\n"
611   echo "Commands:"
612   grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
613     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
614       _exiterr "Error generating help text."
615     fi
616     printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
617   done
618   printf -- "\nParameters:\n"
619   grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
620     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
621       _exiterr "Error generating help text."
622     fi
623     printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
624   done
625 }
626
627 # Usage: --env (-e)
628 # Description: Output configuration variables for use in other scripts
629 command_env() {
630   echo "# letsencrypt.sh configuration"
631   load_config
632   typeset -p CA LICENSE CHALLENGETYPE HOOK RENEW_DAYS PRIVATE_KEY KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
633 }
634
635 # Main method (parses script arguments and calls command_* methods)
636 main() {
637   COMMAND=""
638   set_command() {
639     [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
640     COMMAND="${1}"
641   }
642
643   check_parameters() {
644     if [[ -z "${1:-}" ]]; then
645       echo "The specified command requires additional parameters. See help:" >&2
646       echo >&2
647       command_help >&2
648       exit 1
649     elif [[ "${1:0:1}" = "-" ]]; then
650       _exiterr "Invalid argument: ${1}"
651     fi
652   }
653
654   [[ -z "${@}" ]] && eval set -- "--help"
655
656   while (( "${#}" )); do
657     case "${1}" in
658       --help|-h)
659         command_help
660         exit 0
661         ;;
662
663       --env|-e)
664         set_command env
665         ;;
666
667       --cron|-c)
668         set_command sign_domains
669         ;;
670
671       --signcsr|-s)
672         shift 1
673         set_command sign_csr
674         check_parameters "${1:-}"
675         PARAM_CSR="${1}"
676         ;;
677
678       --revoke|-r)
679         shift 1
680         set_command revoke
681         check_parameters "${1:-}"
682         PARAM_REVOKECERT="${1}"
683         ;;
684
685       # PARAM_Usage: --domain (-d) domain.tld
686       # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
687       --domain|-d)
688         shift 1
689         check_parameters "${1:-}"
690         if [[ -z "${PARAM_DOMAIN:-}" ]]; then
691           PARAM_DOMAIN="${1}"
692         else
693           PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
694          fi
695         ;;
696
697
698       # PARAM_Usage: --force (-x)
699       # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
700       --force|-x)
701         PARAM_FORCE="yes"
702         ;;
703
704       # PARAM_Usage: --privkey (-p) path/to/key.pem
705       # PARAM_Description: Use specified private key instead of account key (useful for revocation)
706       --privkey|-p)
707         shift 1
708         check_parameters "${1:-}"
709         PARAM_PRIVATE_KEY="${1}"
710         ;;
711
712       # PARAM_Usage: --config (-f) path/to/config.sh
713       # PARAM_Description: Use specified config file
714       --config|-f)
715         shift 1
716         check_parameters "${1:-}"
717         CONFIG="${1}"
718         ;;
719
720       # PARAM_Usage: --hook (-k) path/to/hook.sh
721       # PARAM_Description: Use specified script for hooks
722       --hook|-k)
723         shift 1
724         check_parameters "${1:-}"
725         PARAM_HOOK="${1}"
726         ;;
727
728       # PARAM_Usage: --challenge (-t) http-01|dns-01
729       # PARAM_Description: Which challenge should be used? Currently http-01 and dns-01 are supported
730       --challenge|-t)
731         shift 1
732         check_parameters "${1:-}"
733         PARAM_CHALLENGETYPE="${1}"
734         ;;
735
736       # PARAM_Usage: --algo (-a) rsa|prime256v1|secp384r1
737       # PARAM_Description: Which public key algorithm should be used? Supported: rsa, prime256v1 and secp384r1
738       --algo|-a)
739         shift 1
740         check_parameters "${1:-}"
741         PARAM_KEY_ALGO="${1}"
742         ;;
743
744       *)
745         echo "Unknown parameter detected: ${1}" >&2
746         echo >&2
747         command_help >&2
748         exit 1
749         ;;
750     esac
751
752     shift 1
753   done
754
755   case "${COMMAND}" in
756     env) command_env;;
757     sign_domains) command_sign_domains;;
758     sign_csr) command_sign_csr "${PARAM_CSR}";;
759     revoke) command_revoke "${PARAM_REVOKECERT}";;
760     *) command_help; exit 1;;
761   esac
762 }
763
764 # Determine OS type
765 OSTYPE="$(uname)"
766
767 # Check for missing dependencies
768 check_dependencies
769
770 # Run script
771 main "${@:-}"