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