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