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