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