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