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