]> git.street.me.uk Git - andy/dehydrated.git/blob - letsencrypt.sh
Added option to select IP version of name to address resolution (#231)
[andy/dehydrated.git] / letsencrypt.sh
1 #!/usr/bin/env bash
2
3 # letsencrypt.sh by lukas2511
4 # Source: https://github.com/lukas2511/letsencrypt.sh
5 #
6 # This script is licensed under The MIT License (see LICENSE for more information).
7
8 set -e
9 set -u
10 set -o pipefail
11 [[ -n "${ZSH_VERSION:-}" ]] && set -o SH_WORD_SPLIT && set +o FUNCTION_ARGZERO
12 umask 077 # paranoid umask, we're creating private keys
13
14 # Find directory in which this script is stored by traversing all symbolic links
15 SOURCE="${0}"
16 while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
17   DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
18   SOURCE="$(readlink "$SOURCE")"
19   [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
20 done
21 SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
22
23 BASEDIR="${SCRIPTDIR}"
24
25 # Create (identifiable) temporary files
26 _mktemp() {
27   # shellcheck disable=SC2068
28   mktemp ${@:-} "${TMPDIR:-/tmp}/letsencrypt.sh-XXXXXX"
29 }
30
31 # Check for script dependencies
32 check_dependencies() {
33   # just execute some dummy and/or version commands to see if required tools exist and are actually usable
34   openssl version > /dev/null 2>&1 || _exiterr "This script requires an openssl binary."
35   _sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requires sed with support for extended (modern) regular expressions."
36   command -v grep > /dev/null 2>&1 || _exiterr "This script requires grep."
37   _mktemp -u > /dev/null 2>&1 || _exiterr "This script requires mktemp."
38   diff -u /dev/null /dev/null || _exiterr "This script requires diff."
39
40   # curl returns with an error code in some ancient versions so we have to catch that
41   set +e
42   curl -V > /dev/null 2>&1
43   retcode="$?"
44   set -e
45   if [[ ! "${retcode}" = "0" ]] && [[ ! "${retcode}" = "2" ]]; then
46     _exiterr "This script requires curl."
47   fi
48 }
49
50 store_configvars() {
51   __KEY_ALGO="${KEY_ALGO}"
52   __OCSP_MUST_STAPLE="${OCSP_MUST_STAPLE}"
53   __PRIVATE_KEY_RENEW="${PRIVATE_KEY_RENEW}"
54   __KEYSIZE="${KEYSIZE}"
55   __CHALLENGETYPE="${CHALLENGETYPE}"
56   __HOOK="${HOOK}"
57   __WELLKNOWN="${WELLKNOWN}"
58   __HOOK_CHAIN="${HOOK_CHAIN}"
59   __OPENSSL_CNF="${OPENSSL_CNF}"
60   __RENEW_DAYS="${RENEW_DAYS}"
61   __IP_VERSION="${IP_VERSION}"
62 }
63
64 reset_configvars() {
65   KEY_ALGO="${__KEY_ALGO}"
66   OCSP_MUST_STAPLE="${__OCSP_MUST_STAPLE}"
67   PRIVATE_KEY_RENEW="${__PRIVATE_KEY_RENEW}"
68   KEYSIZE="${__KEYSIZE}"
69   CHALLENGETYPE="${__CHALLENGETYPE}"
70   HOOK="${__HOOK}"
71   WELLKNOWN="${__WELLKNOWN}"
72   HOOK_CHAIN="${__HOOK_CHAIN}"
73   OPENSSL_CNF="${__OPENSSL_CNF}"
74   RENEW_DAYS="${__RENEW_DAYS}"
75   IP_VERSION="${__IP_VERSION}"
76 }
77
78 # verify configuration values
79 verify_config() {
80   [[ "${CHALLENGETYPE}" =~ (http-01|dns-01) ]] || _exiterr "Unknown challenge type ${CHALLENGETYPE}... can not continue."
81   if [[ "${CHALLENGETYPE}" = "dns-01" ]] && [[ -z "${HOOK}" ]]; then
82     _exiterr "Challenge type dns-01 needs a hook script for deployment... can not continue."
83   fi
84   if [[ "${CHALLENGETYPE}" = "http-01" && ! -d "${WELLKNOWN}" ]]; then
85     _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
86   fi
87   [[ "${KEY_ALGO}" =~ ^(rsa|prime256v1|secp384r1)$ ]] || _exiterr "Unknown public key algorithm ${KEY_ALGO}... can not continue."
88   if [[ -n "${IP_VERSION}" ]]; then
89     [[ "${IP_VERSION}" = "4" || "${IP_VERSION}" = "6" ]] || _exiterr "Unknown IP version ${IP_VERSION}... can not continue."
90   fi
91 }
92
93 # Setup default config values, search for and load configuration files
94 load_config() {
95   # Check for config in various locations
96   if [[ -z "${CONFIG:-}" ]]; then
97     for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
98       if [[ -f "${check_config}/config" ]]; then
99         BASEDIR="${check_config}"
100         CONFIG="${check_config}/config"
101         break
102       fi
103     done
104   fi
105
106   # Default values
107   CA="https://acme-v01.api.letsencrypt.org/directory"
108   LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
109   CERTDIR=
110   ACCOUNTDIR=
111   CHALLENGETYPE="http-01"
112   CONFIG_D=
113   DOMAINS_D=
114   DOMAINS_TXT=
115   HOOK=
116   HOOK_CHAIN="no"
117   RENEW_DAYS="30"
118   KEYSIZE="4096"
119   WELLKNOWN=
120   PRIVATE_KEY_RENEW="yes"
121   KEY_ALGO=rsa
122   OPENSSL_CNF="$(openssl version -d | cut -d\" -f2)/openssl.cnf"
123   CONTACT_EMAIL=
124   LOCKFILE=
125   OCSP_MUST_STAPLE="no"
126   IP_VERSION=
127
128   if [[ -z "${CONFIG:-}" ]]; then
129     echo "#" >&2
130     echo "# !! WARNING !! No main config file found, using default config!" >&2
131     echo "#" >&2
132   elif [[ -f "${CONFIG}" ]]; then
133     echo "# INFO: Using main config file ${CONFIG}"
134     BASEDIR="$(dirname "${CONFIG}")"
135     # shellcheck disable=SC1090
136     . "${CONFIG}"
137   else
138     _exiterr "Specified config file doesn't exist."
139   fi
140
141   if [[ -n "${CONFIG_D}" ]]; then
142     if [[ ! -d "${CONFIG_D}" ]]; then
143       _exiterr "The path ${CONFIG_D} specified for CONFIG_D does not point to a directory." >&2
144     fi
145
146     for check_config_d in "${CONFIG_D}"/*.sh; do
147       if [[ ! -e "${check_config_d}" ]]; then
148         echo "# !! WARNING !! Extra configuration directory ${CONFIG_D} exists, but no configuration found in it." >&2
149         break
150       elif [[ -f "${check_config_d}" ]] && [[ -r "${check_config_d}" ]]; then
151         echo "# INFO: Using additional config file ${check_config_d}"
152         # shellcheck disable=SC1090
153         . "${check_config_d}"
154       else
155         _exiterr "Specified additional config ${check_config_d} is not readable or not a file at all." >&2
156       fi
157    done
158   fi
159
160   # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
161   BASEDIR="${BASEDIR%%/}"
162
163   # Check BASEDIR and set default variables
164   [[ -d "${BASEDIR}" ]] || _exiterr "BASEDIR does not exist: ${BASEDIR}"
165
166   CAHASH="$(echo "${CA}" | urlbase64)"
167   [[ -z "${ACCOUNTDIR}" ]] && ACCOUNTDIR="${BASEDIR}/accounts"
168   mkdir -p "${ACCOUNTDIR}/${CAHASH}"
169   [[ -f "${ACCOUNTDIR}/${CAHASH}/config" ]] && . "${ACCOUNTDIR}/${CAHASH}/config"
170   ACCOUNT_KEY="${ACCOUNTDIR}/${CAHASH}/account_key.pem"
171   ACCOUNT_KEY_JSON="${ACCOUNTDIR}/${CAHASH}/registration_info.json"
172
173   if [[ -f "${BASEDIR}/private_key.pem" ]] && [[ ! -f "${ACCOUNT_KEY}" ]]; then
174     echo "! Moving private_key.pem to ${ACCOUNT_KEY}"
175     mv "${BASEDIR}/private_key.pem" "${ACCOUNT_KEY}"
176   fi
177   if [[ -f "${BASEDIR}/private_key.json" ]] && [[ ! -f "${ACCOUNT_KEY_JSON}" ]]; then
178     echo "! Moving private_key.json to ${ACCOUNT_KEY_JSON}"
179     mv "${BASEDIR}/private_key.json" "${ACCOUNT_KEY_JSON}"
180   fi
181
182   [[ -z "${CERTDIR}" ]] && CERTDIR="${BASEDIR}/certs"
183   [[ -z "${DOMAINS_TXT}" ]] && DOMAINS_TXT="${BASEDIR}/domains.txt"
184   [[ -z "${WELLKNOWN}" ]] && WELLKNOWN="${BASEDIR}/.acme-challenges"
185   [[ -z "${LOCKFILE}" ]] && LOCKFILE="${BASEDIR}/lock"
186
187   [[ -n "${PARAM_HOOK:-}" ]] && HOOK="${PARAM_HOOK}"
188   [[ -n "${PARAM_CERTDIR:-}" ]] && CERTDIR="${PARAM_CERTDIR}"
189   [[ -n "${PARAM_CHALLENGETYPE:-}" ]] && CHALLENGETYPE="${PARAM_CHALLENGETYPE}"
190   [[ -n "${PARAM_KEY_ALGO:-}" ]] && KEY_ALGO="${PARAM_KEY_ALGO}"
191   [[ -n "${PARAM_OCSP_MUST_STAPLE:-}" ]] && OCSP_MUST_STAPLE="${PARAM_OCSP_MUST_STAPLE}"
192   [[ -n "${PARAM_IP_VERSION:-}" ]] && IP_VERSION="${PARAM_IP_VERSION}"
193
194   verify_config
195   store_configvars
196 }
197
198 # Initialize system
199 init_system() {
200   load_config
201
202   # Lockfile handling (prevents concurrent access)
203   LOCKDIR="$(dirname "${LOCKFILE}")"
204   [[ -w "${LOCKDIR}" ]] || _exiterr "Directory ${LOCKDIR} for LOCKFILE ${LOCKFILE} is not writable, aborting."
205   ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
206   remove_lock() { rm -f "${LOCKFILE}"; }
207   trap 'remove_lock' EXIT
208
209   # Get CA URLs
210   CA_DIRECTORY="$(http_request get "${CA}")"
211   CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
212   CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
213   CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
214   # shellcheck disable=SC2015
215   CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
216   _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
217
218   # Export some environment variables to be used in hook script
219   export WELLKNOWN BASEDIR CERTDIR CONFIG
220
221   # Checking for private key ...
222   register_new_key="no"
223   if [[ -n "${PARAM_ACCOUNT_KEY:-}" ]]; then
224     # a private key was specified from the command line so use it for this run
225     echo "Using private key ${PARAM_ACCOUNT_KEY} instead of account key"
226     ACCOUNT_KEY="${PARAM_ACCOUNT_KEY}"
227     ACCOUNT_KEY_JSON="${PARAM_ACCOUNT_KEY}.json"
228   else
229     # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
230     if [[ ! -e "${ACCOUNT_KEY}" ]]; then
231       echo "+ Generating account key..."
232       _openssl genrsa -out "${ACCOUNT_KEY}" "${KEYSIZE}"
233       register_new_key="yes"
234     fi
235   fi
236   openssl rsa -in "${ACCOUNT_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Account key is not valid, can not continue."
237
238   # Get public components from private key and calculate thumbprint
239   pubExponent64="$(printf '%x' "$(openssl rsa -in "${ACCOUNT_KEY}" -noout -text | awk '/publicExponent/ {print $2}')" | hex2bin | urlbase64)"
240   pubMod64="$(openssl rsa -in "${ACCOUNT_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
241
242   thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl dgst -sha256 -binary | urlbase64)"
243
244   # If we generated a new private key in the step above we have to register it with the acme-server
245   if [[ "${register_new_key}" = "yes" ]]; then
246     echo "+ Registering account key with letsencrypt..."
247     [[ ! -z "${CA_NEW_REG}" ]] || _exiterr "Certificate authority doesn't allow registrations."
248     # If an email for the contact has been provided then adding it to the registration request
249     FAILED=false
250     if [[ -n "${CONTACT_EMAIL}" ]]; then
251       (signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > "${ACCOUNT_KEY_JSON}") || FAILED=true
252     else
253       (signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > "${ACCOUNT_KEY_JSON}") || FAILED=true
254     fi
255     if [[ "${FAILED}" = "true" ]]; then
256       echo
257       echo
258       echo "Error registering account key. See message above for more information."
259       rm "${ACCOUNT_KEY}" "${ACCOUNT_KEY_JSON}"
260       exit 1
261     fi
262   fi
263
264 }
265
266 # Different sed version for different os types...
267 _sed() {
268   if [[ "${OSTYPE}" = "Linux" ]]; then
269     sed -r "${@}"
270   else
271     sed -E "${@}"
272   fi
273 }
274
275 # Print error message and exit with error
276 _exiterr() {
277   echo "ERROR: ${1}" >&2
278   exit 1
279 }
280
281 # Remove newlines and whitespace from json
282 clean_json() {
283   tr -d '\r\n' | _sed -e 's/ +/ /g' -e 's/\{ /{/g' -e 's/ \}/}/g' -e 's/\[ /[/g' -e 's/ \]/]/g'
284 }
285
286 # Encode data as url-safe formatted base64
287 urlbase64() {
288   # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
289   openssl base64 -e | tr -d '\n\r' | _sed -e 's:=*$::g' -e 'y:+/:-_:'
290 }
291
292 # Convert hex string to binary data
293 hex2bin() {
294   # Remove spaces, add leading zero, escape as hex string and parse with printf
295   printf -- "$(cat | _sed -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
296 }
297
298 # Get string value from json dictionary
299 get_json_string_value() {
300   local filter
301   filter=$(printf 's/.*"%s": *"\([^"]*\)".*/\\1/p' "$1")
302   sed -n "${filter}"
303 }
304
305 # OpenSSL writes to stderr/stdout even when there are no errors. So just
306 # display the output if the exit code was != 0 to simplify debugging.
307 _openssl() {
308   set +e
309   out="$(openssl "${@}" 2>&1)"
310   res=$?
311   set -e
312   if [[ ${res} -ne 0 ]]; then
313     echo "  + ERROR: failed to run $* (Exitcode: ${res})" >&2
314     echo >&2
315     echo "Details:" >&2
316     echo "${out}" >&2
317     echo >&2
318     exit ${res}
319   fi
320 }
321
322 # Send http(s) request with specified method
323 http_request() {
324   tempcont="$(_mktemp)"
325
326   if [[ -n "${IP_VERSION:-}" ]]; then
327       ip_version="-${IP_VERSION}"
328   fi
329
330   set +e
331   if [[ "${1}" = "head" ]]; then
332     statuscode="$(curl ${ip_version:-} -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
333     curlret="${?}"
334   elif [[ "${1}" = "get" ]]; then
335     statuscode="$(curl ${ip_version:-} -s -w "%{http_code}" -o "${tempcont}" "${2}")"
336     curlret="${?}"
337   elif [[ "${1}" = "post" ]]; then
338     statuscode="$(curl ${ip_version:-} -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
339     curlret="${?}"
340   else
341     set -e
342     _exiterr "Unknown request method: ${1}"
343   fi
344   set -e
345
346   if [[ ! "${curlret}" = "0" ]]; then
347     _exiterr "Problem connecting to server (${1} for ${2}; curl returned with ${curlret})"
348   fi
349
350   if [[ ! "${statuscode:0:1}" = "2" ]]; then
351     echo "  + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
352     echo >&2
353     echo "Details:" >&2
354     cat "${tempcont}" >&2
355     rm -f "${tempcont}"
356
357     # Wait for hook script to clean the challenge if used
358     if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token:+set}" ]]; then
359       "${HOOK}" "clean_challenge" '' "${challenge_token}" "${keyauth}"
360     fi
361
362     # remove temporary domains.txt file if used
363     [[ -n "${PARAM_DOMAIN:-}" && -n "${DOMAINS_TXT:-}" ]] && rm "${DOMAINS_TXT}"
364     exit 1
365   fi
366
367   cat "${tempcont}"
368   rm -f "${tempcont}"
369 }
370
371 # Send signed request
372 signed_request() {
373   # Encode payload as urlbase64
374   payload64="$(printf '%s' "${2}" | urlbase64)"
375
376   # Retrieve nonce from acme-server
377   nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
378
379   # Build header with just our public key and algorithm information
380   header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
381
382   # Build another header which also contains the previously received nonce and encode it as urlbase64
383   protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
384   protected64="$(printf '%s' "${protected}" | urlbase64)"
385
386   # Sign header with nonce and our payload with our private key and encode signature as urlbase64
387   signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${ACCOUNT_KEY}" | urlbase64)"
388
389   # Send header + extended header + payload + signature to the acme-server
390   data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
391
392   http_request post "${1}" "${data}"
393 }
394
395 # Extracts all subject names from a CSR
396 # Outputs either the CN, or the SANs, one per line
397 extract_altnames() {
398   csr="${1}" # the CSR itself (not a file)
399
400   if ! <<<"${csr}" openssl req -verify -noout 2>/dev/null; then
401     _exiterr "Certificate signing request isn't valid"
402   fi
403
404   reqtext="$( <<<"${csr}" openssl req -noout -text )"
405   if <<<"${reqtext}" grep -q '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$'; then
406     # SANs used, extract these
407     altnames="$( <<<"${reqtext}" grep -A1 '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$' | tail -n1 )"
408     # split to one per line:
409     # shellcheck disable=SC1003
410     altnames="$( <<<"${altnames}" _sed -e 's/^[[:space:]]*//; s/, /\'$'\n''/g' )"
411     # we can only get DNS: ones signed
412     if grep -qv '^DNS:' <<<"${altnames}"; then
413       _exiterr "Certificate signing request contains non-DNS Subject Alternative Names"
414     fi
415     # strip away the DNS: prefix
416     altnames="$( <<<"${altnames}" _sed -e 's/^DNS://' )"
417     echo "${altnames}"
418
419   else
420     # No SANs, extract CN
421     altnames="$( <<<"${reqtext}" grep '^[[:space:]]*Subject:' | _sed -e 's/.* CN=([^ /,]*).*/\1/' )"
422     echo "${altnames}"
423   fi
424 }
425
426 # Create certificate for domain(s) and outputs it FD 3
427 sign_csr() {
428   csr="${1}" # the CSR itself (not a file)
429
430   if { true >&3; } 2>/dev/null; then
431     : # fd 3 looks OK
432   else
433     _exiterr "sign_csr: FD 3 not open"
434   fi
435
436   shift 1 || true
437   altnames="${*:-}"
438   if [ -z "${altnames}" ]; then
439     altnames="$( extract_altnames "${csr}" )"
440   fi
441
442   if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
443     _exiterr "Certificate authority doesn't allow certificate signing"
444   fi
445
446   local idx=0
447   if [[ -n "${ZSH_VERSION:-}" ]]; then
448     local -A challenge_uris challenge_tokens keyauths deploy_args
449   else
450     local -a challenge_uris challenge_tokens keyauths deploy_args
451   fi
452
453   # Request challenges
454   for altname in ${altnames}; do
455     # Ask the acme-server for new challenge token and extract them from the resulting json block
456     echo " + Requesting challenge for ${altname}..."
457     response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}' | clean_json)"
458
459     challenges="$(printf '%s\n' "${response}" | sed -n 's/.*\("challenges":[^\[]*\[[^]]*]\).*/\1/p')"
460     repl=$'\n''{' # fix syntax highlighting in Vim
461     challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep \""${CHALLENGETYPE}"\")"
462     challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | _sed 's/[^A-Za-z0-9_\-]/_/g')"
463     challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
464
465     if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
466       _exiterr "Can't retrieve challenges (${response})"
467     fi
468
469     # Challenge response consists of the challenge token and the thumbprint of our public certificate
470     keyauth="${challenge_token}.${thumbprint}"
471
472     case "${CHALLENGETYPE}" in
473       "http-01")
474         # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
475         printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
476         chmod a+r "${WELLKNOWN}/${challenge_token}"
477         keyauth_hook="${keyauth}"
478         ;;
479       "dns-01")
480         # Generate DNS entry content for dns-01 validation
481         keyauth_hook="$(printf '%s' "${keyauth}" | openssl dgst -sha256 -binary | urlbase64)"
482         ;;
483     esac
484
485     challenge_uris[${idx}]="${challenge_uri}"
486     keyauths[${idx}]="${keyauth}"
487     challenge_tokens[${idx}]="${challenge_token}"
488     # Note: assumes args will never have spaces!
489     deploy_args[${idx}]="${altname} ${challenge_token} ${keyauth_hook}"
490     idx=$((idx+1))
491   done
492
493   # Wait for hook script to deploy the challenges if used
494   # shellcheck disable=SC2068
495   [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[@]}
496
497   # Respond to challenges
498   idx=0
499   for altname in ${altnames}; do
500     challenge_token="${challenge_tokens[${idx}]}"
501     keyauth="${keyauths[${idx}]}"
502
503     # Wait for hook script to deploy the challenge if used
504     # shellcheck disable=SC2086
505     [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[${idx}]}
506
507     # Ask the acme-server to verify our challenge and wait until it is no longer pending
508     echo " + Responding to challenge for ${altname}..."
509     result="$(signed_request "${challenge_uris[${idx}]}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}' | clean_json)"
510
511     reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
512
513     while [[ "${reqstatus}" = "pending" ]]; do
514       sleep 1
515       result="$(http_request get "${challenge_uris[${idx}]}")"
516       reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
517     done
518
519     [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_token}"
520
521     # Wait for hook script to clean the challenge if used
522     if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token}" ]]; then
523       # shellcheck disable=SC2086
524       "${HOOK}" "clean_challenge" ${deploy_args[${idx}]}
525     fi
526     idx=$((idx+1))
527
528     if [[ "${reqstatus}" = "valid" ]]; then
529       echo " + Challenge is valid!"
530     else
531       break
532     fi
533   done
534
535   # Wait for hook script to clean the challenges if used
536   # shellcheck disable=SC2068
537   [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "clean_challenge" ${deploy_args[@]}
538
539   if [[ "${reqstatus}" != "valid" ]]; then
540     # Clean up any remaining challenge_tokens if we stopped early
541     if [[ "${CHALLENGETYPE}" = "http-01" ]]; then
542       while [ ${idx} -lt ${#challenge_tokens[@]} ]; do
543         rm -f "${WELLKNOWN}/${challenge_tokens[${idx}]}"
544         idx=$((idx+1))
545       done
546     fi
547
548     _exiterr "Challenge is invalid! (returned: ${reqstatus}) (result: ${result})"
549   fi
550
551   # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
552   echo " + Requesting certificate..."
553   csr64="$( <<<"${csr}" openssl req -outform DER | urlbase64)"
554   crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
555   crt="$( printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" )"
556
557   # Try to load the certificate to detect corruption
558   echo " + Checking certificate..."
559   _openssl x509 -text <<<"${crt}"
560
561   echo "${crt}" >&3
562
563   unset challenge_token
564   echo " + Done!"
565 }
566
567 # Create certificate for domain(s)
568 sign_domain() {
569   domain="${1}"
570   altnames="${*}"
571   timestamp="$(date +%s)"
572
573   echo " + Signing domains..."
574   if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
575     _exiterr "Certificate authority doesn't allow certificate signing"
576   fi
577
578   # If there is no existing certificate directory => make it
579   if [[ ! -e "${CERTDIR}/${domain}" ]]; then
580     echo " + Creating new directory ${CERTDIR}/${domain} ..."
581     mkdir -p "${CERTDIR}/${domain}" || _exiterr "Unable to create directory ${CERTDIR}/${domain}"
582   fi
583
584   privkey="privkey.pem"
585   # generate a new private key if we need or want one
586   if [[ ! -r "${CERTDIR}/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
587     echo " + Generating private key..."
588     privkey="privkey-${timestamp}.pem"
589     case "${KEY_ALGO}" in
590       rsa) _openssl genrsa -out "${CERTDIR}/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}";;
591       prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${CERTDIR}/${domain}/privkey-${timestamp}.pem";;
592     esac
593   fi
594
595   # Generate signing request config and the actual signing request
596   echo " + Generating signing request..."
597   SAN=""
598   for altname in ${altnames}; do
599     SAN+="DNS:${altname}, "
600   done
601   SAN="${SAN%%, }"
602   local tmp_openssl_cnf
603   tmp_openssl_cnf="$(_mktemp)"
604   cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
605   printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
606   if [ "${OCSP_MUST_STAPLE}" = "yes" ]; then
607     printf "\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >> "${tmp_openssl_cnf}"
608   fi
609   openssl req -new -sha256 -key "${CERTDIR}/${domain}/${privkey}" -out "${CERTDIR}/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
610   rm -f "${tmp_openssl_cnf}"
611
612   crt_path="${CERTDIR}/${domain}/cert-${timestamp}.pem"
613   # shellcheck disable=SC2086
614   sign_csr "$(< "${CERTDIR}/${domain}/cert-${timestamp}.csr" )" ${altnames} 3>"${crt_path}"
615
616   # Create fullchain.pem
617   echo " + Creating fullchain.pem..."
618   cat "${crt_path}" > "${CERTDIR}/${domain}/fullchain-${timestamp}.pem"
619   http_request get "$(openssl x509 -in "${CERTDIR}/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${CERTDIR}/${domain}/chain-${timestamp}.pem"
620   if ! grep -q "BEGIN CERTIFICATE" "${CERTDIR}/${domain}/chain-${timestamp}.pem"; then
621     openssl x509 -in "${CERTDIR}/${domain}/chain-${timestamp}.pem" -inform DER -out "${CERTDIR}/${domain}/chain-${timestamp}.pem" -outform PEM
622   fi
623   cat "${CERTDIR}/${domain}/chain-${timestamp}.pem" >> "${CERTDIR}/${domain}/fullchain-${timestamp}.pem"
624
625   # Update symlinks
626   [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${CERTDIR}/${domain}/privkey.pem"
627
628   ln -sf "chain-${timestamp}.pem" "${CERTDIR}/${domain}/chain.pem"
629   ln -sf "fullchain-${timestamp}.pem" "${CERTDIR}/${domain}/fullchain.pem"
630   ln -sf "cert-${timestamp}.csr" "${CERTDIR}/${domain}/cert.csr"
631   ln -sf "cert-${timestamp}.pem" "${CERTDIR}/${domain}/cert.pem"
632
633   # Wait for hook script to clean the challenge and to deploy cert if used
634   export KEY_ALGO
635   [[ -n "${HOOK}" ]] && "${HOOK}" "deploy_cert" "${domain}" "${CERTDIR}/${domain}/privkey.pem" "${CERTDIR}/${domain}/cert.pem" "${CERTDIR}/${domain}/fullchain.pem" "${CERTDIR}/${domain}/chain.pem" "${timestamp}"
636
637   unset challenge_token
638   echo " + Done!"
639 }
640
641 # Usage: --cron (-c)
642 # Description: Sign/renew non-existant/changed/expiring certificates.
643 command_sign_domains() {
644   init_system
645
646   if [[ -n "${PARAM_DOMAIN:-}" ]]; then
647     DOMAINS_TXT="$(_mktemp)"
648     printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
649   elif [[ -e "${DOMAINS_TXT}" ]]; then
650     if [[ ! -r "${DOMAINS_TXT}" ]]; then
651       _exiterr "domains.txt found but not readable"
652     fi
653   else
654     _exiterr "domains.txt not found and --domain not given"
655   fi
656
657   # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
658   ORIGIFS="${IFS}"
659   IFS=$'\n'
660   for line in $(<"${DOMAINS_TXT}" tr -d '\r' | tr '[:upper:]' '[:lower:]' | _sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e 's/[[:space:]]+/ /g' | (grep -vE '^(#|$)' || true)); do
661     reset_configvars
662     IFS="${ORIGIFS}"
663     domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
664     morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
665     cert="${CERTDIR}/${domain}/cert.pem"
666
667     force_renew="${PARAM_FORCE:-no}"
668
669     if [[ -z "${morenames}" ]];then
670       echo "Processing ${domain}"
671     else
672       echo "Processing ${domain} with alternative names: ${morenames}"
673     fi
674
675     # read cert config
676     # for now this loads the certificate specific config in a subshell and parses a diff of set variables.
677     # we could just source the config file but i decided to go this way to protect people from accidentally overriding
678     # variables used internally by this script itself.
679     if [[ -n "${DOMAINS_D}" ]]; then
680       certconfig="${DOMAINS_D}/${domain}"
681     else
682       certconfig="${CERTDIR}/${domain}/config"
683     fi
684
685     if [ -f "${certconfig}" ]; then
686       echo " + Using certificate specific config file!"
687       ORIGIFS="${IFS}"
688       IFS=$'\n'
689       for cfgline in $(
690         beforevars="$(_mktemp)"
691         aftervars="$(_mktemp)"
692         set > "${beforevars}"
693         # shellcheck disable=SC1090
694         . "${certconfig}"
695         set > "${aftervars}"
696         diff -u "${beforevars}" "${aftervars}" | grep -E '^\+[^+]'
697         rm "${beforevars}"
698         rm "${aftervars}"
699       ); do
700         config_var="$(echo "${cfgline:1}" | cut -d'=' -f1)"
701         config_value="$(echo "${cfgline:1}" | cut -d'=' -f2-)"
702         case "${config_var}" in
703           KEY_ALGO|OCSP_MUST_STAPLE|PRIVATE_KEY_RENEW|KEYSIZE|CHALLENGETYPE|HOOK|WELLKNOWN|HOOK_CHAIN|OPENSSL_CNF|RENEW_DAYS)
704             echo "   + ${config_var} = ${config_value}"
705             declare -- "${config_var}=${config_value}"
706             ;;
707           _) ;;
708           *) echo "   ! Setting ${config_var} on a per-certificate base is not (yet) supported"
709         esac
710       done
711       IFS="${ORIGIFS}"
712     fi
713     verify_config
714
715     if [[ -e "${cert}" ]]; then
716       printf " + Checking domain name(s) of existing cert..."
717
718       certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | _sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//')"
719       givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//' | _sed 's/^ //')"
720
721       if [[ "${certnames}" = "${givennames}" ]]; then
722         echo " unchanged."
723       else
724         echo " changed!"
725         echo " + Domain name(s) are not matching!"
726         echo " + Names in old certificate: ${certnames}"
727         echo " + Configured names: ${givennames}"
728         echo " + Forcing renew."
729         force_renew="yes"
730       fi
731     fi
732
733     if [[ -e "${cert}" ]]; then
734       echo " + Checking expire date of existing cert..."
735       valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
736
737       printf " + Valid till %s " "${valid}"
738       if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
739         printf "(Longer than %d days). " "${RENEW_DAYS}"
740         if [[ "${force_renew}" = "yes" ]]; then
741           echo "Ignoring because renew was forced!"
742         else
743           # Certificate-Names unchanged and cert is still valid
744           echo "Skipping renew!"
745           [[ -n "${HOOK}" ]] && "${HOOK}" "unchanged_cert" "${domain}" "${CERTDIR}/${domain}/privkey.pem" "${CERTDIR}/${domain}/cert.pem" "${CERTDIR}/${domain}/fullchain.pem" "${CERTDIR}/${domain}/chain.pem"
746           continue
747         fi
748       else
749         echo "(Less than ${RENEW_DAYS} days). Renewing!"
750       fi
751     fi
752
753     # shellcheck disable=SC2086
754     sign_domain ${line}
755   done
756
757   # remove temporary domains.txt file if used
758   [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
759
760   exit 0
761 }
762
763 # Usage: --signcsr (-s) path/to/csr.pem
764 # Description: Sign a given CSR, output CRT on stdout (advanced usage)
765 command_sign_csr() {
766   # redirect stdout to stderr
767   # leave stdout over at fd 3 to output the cert
768   exec 3>&1 1>&2
769
770   init_system
771
772   csrfile="${1}"
773   if [ ! -r "${csrfile}" ]; then
774     _exiterr "Could not read certificate signing request ${csrfile}"
775   fi
776
777   # gen cert
778   certfile="$(_mktemp)"
779   sign_csr "$(< "${csrfile}" )" 3> "${certfile}"
780
781   # get and convert ca cert
782   chainfile="$(_mktemp)"
783   http_request get "$(openssl x509 -in "${certfile}" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${chainfile}"
784
785   if ! grep -q "BEGIN CERTIFICATE" "${chainfile}"; then
786     openssl x509 -inform DER -in "${chainfile}" -outform PEM -out "${chainfile}"
787   fi
788
789   # output full chain
790   echo "# CERT #" >&3
791   cat "${certfile}" >&3
792   echo >&3
793   echo "# CHAIN #" >&3
794   cat "${chainfile}" >&3
795
796   # cleanup
797   rm "${certfile}"
798   rm "${chainfile}"
799
800   exit 0
801 }
802
803 # Usage: --revoke (-r) path/to/cert.pem
804 # Description: Revoke specified certificate
805 command_revoke() {
806   init_system
807
808   [[ -n "${CA_REVOKE_CERT}" ]] || _exiterr "Certificate authority doesn't allow certificate revocation."
809
810   cert="${1}"
811   if [[ -L "${cert}" ]]; then
812     # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
813     local link_target
814     link_target="$(readlink -n "${cert}")"
815     if [[ "${link_target}" =~ ^/ ]]; then
816       cert="${link_target}"
817     else
818       cert="$(dirname "${cert}")/${link_target}"
819     fi
820   fi
821   [[ -f "${cert}" ]] || _exiterr "Could not find certificate ${cert}"
822
823   echo "Revoking ${cert}"
824
825   cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
826   response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}' | clean_json)"
827   # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
828   # so if we are here, it is safe to assume the request was successful
829   echo " + Done."
830   echo " + Renaming certificate to ${cert}-revoked"
831   mv -f "${cert}" "${cert}-revoked"
832 }
833
834 # Usage: --cleanup (-gc)
835 # Description: Move unused certificate files to archive directory
836 command_cleanup() {
837   load_config
838
839   # Create global archive directory if not existant
840   if [[ ! -e "${BASEDIR}/archive" ]]; then
841     mkdir "${BASEDIR}/archive"
842   fi
843
844   # Loop over all certificate directories
845   for certdir in "${CERTDIR}/"*; do
846     # Skip if entry is not a folder
847     [[ -d "${certdir}" ]] || continue
848
849     # Get certificate name
850     certname="$(basename "${certdir}")"
851
852     # Create certitifaces archive directory if not existant
853     archivedir="${BASEDIR}/archive/${certname}"
854     if [[ ! -e "${archivedir}" ]]; then
855       mkdir "${archivedir}"
856     fi
857
858     # Loop over file-types (certificates, keys, signing-requests, ...)
859     for filetype in cert.csr cert.pem chain.pem fullchain.pem privkey.pem; do
860       # Skip if symlink is broken
861       [[ -r "${certdir}/${filetype}" ]] || continue
862
863       # Look up current file in use
864       current="$(basename "$(readlink "${certdir}/${filetype}")")"
865
866       # Split filetype into name and extension
867       filebase="$(echo "${filetype}" | cut -d. -f1)"
868       fileext="$(echo "${filetype}" | cut -d. -f2)"
869
870       # Loop over all files of this type
871       for file in "${certdir}/${filebase}-"*".${fileext}"; do
872         # Handle case where no files match the wildcard
873         [[ -f "${file}" ]] || break
874
875         # Check if current file is in use, if unused move to archive directory
876         filename="$(basename "${file}")"
877         if [[ ! "${filename}" = "${current}" ]]; then
878           echo "Moving unused file to archive directory: ${certname}/${filename}"
879           mv "${certdir}/${filename}" "${archivedir}/${filename}"
880         fi
881       done
882     done
883   done
884
885   exit 0
886 }
887
888 # Usage: --help (-h)
889 # Description: Show help text
890 command_help() {
891   printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
892   printf "Default command: help\n\n"
893   echo "Commands:"
894   grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
895     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
896       _exiterr "Error generating help text."
897     fi
898     printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
899   done
900   printf -- "\nParameters:\n"
901   grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
902     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
903       _exiterr "Error generating help text."
904     fi
905     printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
906   done
907 }
908
909 # Usage: --env (-e)
910 # Description: Output configuration variables for use in other scripts
911 command_env() {
912   echo "# letsencrypt.sh configuration"
913   load_config
914   typeset -p CA LICENSE CERTDIR CHALLENGETYPE DOMAINS_D DOMAINS_TXT HOOK HOOK_CHAIN RENEW_DAYS ACCOUNT_KEY ACCOUNT_KEY_JSON KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
915 }
916
917 # Main method (parses script arguments and calls command_* methods)
918 main() {
919   COMMAND=""
920   set_command() {
921     [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
922     COMMAND="${1}"
923   }
924
925   check_parameters() {
926     if [[ -z "${1:-}" ]]; then
927       echo "The specified command requires additional parameters. See help:" >&2
928       echo >&2
929       command_help >&2
930       exit 1
931     elif [[ "${1:0:1}" = "-" ]]; then
932       _exiterr "Invalid argument: ${1}"
933     fi
934   }
935
936   [[ -z "${@}" ]] && eval set -- "--help"
937
938   while (( ${#} )); do
939     case "${1}" in
940       --help|-h)
941         command_help
942         exit 0
943         ;;
944
945       --env|-e)
946         set_command env
947         ;;
948
949       --cron|-c)
950         set_command sign_domains
951         ;;
952
953       --signcsr|-s)
954         shift 1
955         set_command sign_csr
956         check_parameters "${1:-}"
957         PARAM_CSR="${1}"
958         ;;
959
960       --revoke|-r)
961         shift 1
962         set_command revoke
963         check_parameters "${1:-}"
964         PARAM_REVOKECERT="${1}"
965         ;;
966
967       --cleanup|-gc)
968         set_command cleanup
969         ;;
970
971       # PARAM_Usage: --ipv4 (-4)
972       # PARAM_Description: Resolve names to IPv4 addresses only
973       --ipv4|-4)
974         PARAM_IP_VERSION="4"
975         ;;
976
977       # PARAM_Usage: --ipv6 (-6)
978       # PARAM_Description: Resolve names to IPv6 addresses only
979       --ipv6|-6)
980         PARAM_IP_VERSION="6"
981         ;;
982
983       # PARAM_Usage: --domain (-d) domain.tld
984       # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
985       --domain|-d)
986         shift 1
987         check_parameters "${1:-}"
988         if [[ -z "${PARAM_DOMAIN:-}" ]]; then
989           PARAM_DOMAIN="${1}"
990         else
991           PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
992          fi
993         ;;
994
995
996       # PARAM_Usage: --force (-x)
997       # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
998       --force|-x)
999         PARAM_FORCE="yes"
1000         ;;
1001
1002       # PARAM_Usage: --ocsp
1003       # PARAM_Description: Sets option in CSR indicating OCSP stapling to be mandatory
1004       --ocsp)
1005         PARAM_OCSP_MUST_STAPLE="yes"
1006         ;;
1007
1008       # PARAM_Usage: --privkey (-p) path/to/key.pem
1009       # PARAM_Description: Use specified private key instead of account key (useful for revocation)
1010       --privkey|-p)
1011         shift 1
1012         check_parameters "${1:-}"
1013         PARAM_ACCOUNT_KEY="${1}"
1014         ;;
1015
1016       # PARAM_Usage: --config (-f) path/to/config
1017       # PARAM_Description: Use specified config file
1018       --config|-f)
1019         shift 1
1020         check_parameters "${1:-}"
1021         CONFIG="${1}"
1022         ;;
1023
1024       # PARAM_Usage: --hook (-k) path/to/hook.sh
1025       # PARAM_Description: Use specified script for hooks
1026       --hook|-k)
1027         shift 1
1028         check_parameters "${1:-}"
1029         PARAM_HOOK="${1}"
1030         ;;
1031
1032       # PARAM_Usage: --out (-o) certs/directory
1033       # PARAM_Description: Output certificates into the specified directory
1034       --out|-o)
1035         shift 1
1036         check_parameters "${1:-}"
1037         PARAM_CERTDIR="${1}"
1038         ;;
1039
1040       # PARAM_Usage: --challenge (-t) http-01|dns-01
1041       # PARAM_Description: Which challenge should be used? Currently http-01 and dns-01 are supported
1042       --challenge|-t)
1043         shift 1
1044         check_parameters "${1:-}"
1045         PARAM_CHALLENGETYPE="${1}"
1046         ;;
1047
1048       # PARAM_Usage: --algo (-a) rsa|prime256v1|secp384r1
1049       # PARAM_Description: Which public key algorithm should be used? Supported: rsa, prime256v1 and secp384r1
1050       --algo|-a)
1051         shift 1
1052         check_parameters "${1:-}"
1053         PARAM_KEY_ALGO="${1}"
1054         ;;
1055
1056       *)
1057         echo "Unknown parameter detected: ${1}" >&2
1058         echo >&2
1059         command_help >&2
1060         exit 1
1061         ;;
1062     esac
1063
1064     shift 1
1065   done
1066
1067   case "${COMMAND}" in
1068     env) command_env;;
1069     sign_domains) command_sign_domains;;
1070     sign_csr) command_sign_csr "${PARAM_CSR}";;
1071     revoke) command_revoke "${PARAM_REVOKECERT}";;
1072     cleanup) command_cleanup;;
1073     *) command_help; exit 1;;
1074   esac
1075 }
1076
1077 # Determine OS type
1078 OSTYPE="$(uname)"
1079
1080 # Check for missing dependencies
1081 check_dependencies
1082
1083 # Run script
1084 main "${@:-}"