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