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