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