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