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