]> git.street.me.uk Git - andy/dehydrated.git/blobdiff - letsencrypt.sh
compatibility with "pretty" json (fixes #202)
[andy/dehydrated.git] / letsencrypt.sh
index d9405012d6ef5f900d4852f9b6ce5f2088f6fa94..fccad50af2716f0e55d0f1023f74ca1a0e5b08ad 100755 (executable)
@@ -1,35 +1,53 @@
 #!/usr/bin/env bash
+
+# letsencrypt.sh by lukas2511
+# Source: https://github.com/lukas2511/letsencrypt.sh
+#
+# This script is licensed under The MIT License (see LICENSE for more information).
+
 set -e
 set -u
 set -o pipefail
+[[ -n "${ZSH_VERSION:-}" ]] && set -o SH_WORD_SPLIT && set +o FUNCTION_ARGZERO
 umask 077 # paranoid umask, we're creating private keys
 
-# Get the directory in which this script is stored
-SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+# Find directory in which this script is stored by traversing all symbolic links
+SOURCE="${0}"
+while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
+  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
+  SOURCE="$(readlink "$SOURCE")"
+  [[ $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
+done
+SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
+
 BASEDIR="${SCRIPTDIR}"
 
+# Create (identifiable) temporary files
+_mktemp() {
+  # shellcheck disable=SC2068
+  mktemp ${@:-} "${TMPDIR:-/tmp}/letsencrypt.sh-XXXXXX"
+}
+
+# Check for script dependencies
 check_dependencies() {
-  curl -V > /dev/null 2>&1 || _exiterr "This script requires curl."
-  openssl version > /dev/null 2>&1 || _exiterr "This script requres an openssl binary."
-  sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requres sed."
-  grep -V > /dev/null 2>&1 || _exiterr "This script requres grep."
+  # just execute some dummy and/or version commands to see if required tools exist and are actually usable
+  openssl version > /dev/null 2>&1 || _exiterr "This script requires an openssl binary."
+  _sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requires sed with support for extended (modern) regular expressions."
+  command -v grep > /dev/null 2>&1 || _exiterr "This script requires grep."
+  _mktemp -u > /dev/null 2>&1 || _exiterr "This script requires mktemp."
+
+  # curl returns with an error code in some ancient versions so we have to catch that
+  set +e
+  curl -V > /dev/null 2>&1
+  retcode="$?"
+  set -e
+  if [[ ! "${retcode}" = "0" ]] && [[ ! "${retcode}" = "2" ]]; then
+    _exiterr "This script requires curl."
+  fi
 }
 
 # Setup default config values, search for and load configuration files
 load_config() {
-  # Default values
-  CA="https://acme-v01.api.letsencrypt.org/directory"
-  LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
-  HOOK=
-  RENEW_DAYS="14"
-  PRIVATE_KEY="${BASEDIR}/private_key.pem"
-  KEYSIZE="4096"
-  WELLKNOWN="${BASEDIR}/.acme-challenges"
-  PRIVATE_KEY_RENEW="no"
-  OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
-  CONTACT_EMAIL=
-  LOCKFILE="${BASEDIR}/lock"
-
   # Check for config in various locations
   if [[ -z "${CONFIG:-}" ]]; then
     for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
@@ -41,28 +59,76 @@ load_config() {
     done
   fi
 
+  # Default values
+  CA="https://acme-v01.api.letsencrypt.org/directory"
+  LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
+  CHALLENGETYPE="http-01"
+  CONFIG_D=
+  HOOK=
+  HOOK_CHAIN="no"
+  RENEW_DAYS="30"
+  ACCOUNT_KEY=
+  ACCOUNT_KEY_JSON=
+  KEYSIZE="4096"
+  WELLKNOWN=
+  PRIVATE_KEY_RENEW="yes"
+  KEY_ALGO=rsa
+  OPENSSL_CNF="$(openssl version -d | cut -d\" -f2)/openssl.cnf"
+  CONTACT_EMAIL=
+  LOCKFILE=
+
   if [[ -z "${CONFIG:-}" ]]; then
     echo "#" >&2
-    echo "# !! WARNING !! No config file found, using default config!" >&2
+    echo "# !! WARNING !! No main config file found, using default config!" >&2
     echo "#" >&2
   elif [[ -e "${CONFIG}" ]]; then
-    echo "# INFO: Using config file ${CONFIG}"
+    echo "# INFO: Using main config file ${CONFIG}"
     BASEDIR="$(dirname "${CONFIG}")"
     # shellcheck disable=SC1090
     . "${CONFIG}"
   else
-    echo "Specified config file doesn't exist." >&2
-    exit 1
+    _exiterr "Specified config file doesn't exist."
+  fi
+
+  if [[ -n "${CONFIG_D}" ]]; then
+    if [[ ! -d "${CONFIG_D}" ]]; then
+      _exiterr "The path ${CONFIG_D} specified for CONFIG_D does not point to a directory." >&2
+    fi
+
+    for check_config_d in "${CONFIG_D}"/*.sh; do
+      if [[ ! -e "${check_config_d}" ]]; then
+        echo "# !! WARNING !! Extra configuration directory ${CONFIG_D} exists, but no configuration found in it." >&2
+        break
+      elif [[ -f "${check_config_d}" ]] && [[ -r "${check_config_d}" ]]; then
+        echo "# INFO: Using additional config file ${check_config_d}"
+        # shellcheck disable=SC1090
+        . "${check_config_d}"
+      else
+        _exiterr "Specified additional config ${check_config_d} is not readable or not a file at all." >&2
+      fi
+   done
   fi
 
   # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
   BASEDIR="${BASEDIR%%/}"
 
   # Check BASEDIR and set default variables
-  if [[ ! -d "${BASEDIR}" ]]; then
-   echo "BASEDIR does not exist: ${BASEDIR}" >&2
-   exit 1
+  [[ -d "${BASEDIR}" ]] || _exiterr "BASEDIR does not exist: ${BASEDIR}"
+
+  [[ -z "${ACCOUNT_KEY}" ]] && ACCOUNT_KEY="${BASEDIR}/private_key.pem"
+  [[ -z "${ACCOUNT_KEY_JSON}" ]] && ACCOUNT_KEY_JSON="${BASEDIR}/private_key.json"
+  [[ -z "${WELLKNOWN}" ]] && WELLKNOWN="${BASEDIR}/.acme-challenges"
+  [[ -z "${LOCKFILE}" ]] && LOCKFILE="${BASEDIR}/lock"
+
+  [[ -n "${PARAM_HOOK:-}" ]] && HOOK="${PARAM_HOOK}"
+  [[ -n "${PARAM_CHALLENGETYPE:-}" ]] && CHALLENGETYPE="${PARAM_CHALLENGETYPE}"
+  [[ -n "${PARAM_KEY_ALGO:-}" ]] && KEY_ALGO="${PARAM_KEY_ALGO}"
+
+  [[ "${CHALLENGETYPE}" =~ (http-01|dns-01) ]] || _exiterr "Unknown challenge type ${CHALLENGETYPE}... can not continue."
+  if [[ "${CHALLENGETYPE}" = "dns-01" ]] && [[ -z "${HOOK}" ]]; then
+   _exiterr "Challenge type dns-01 needs a hook script for deployment... can not continue."
   fi
+  [[ "${KEY_ALGO}" =~ ^(rsa|prime256v1|secp384r1)$ ]] || _exiterr "Unknown public key algorithm ${KEY_ALGO}... can not continue."
 }
 
 # Initialize system
@@ -70,6 +136,8 @@ init_system() {
   load_config
 
   # Lockfile handling (prevents concurrent access)
+  LOCKDIR="$(dirname "${LOCKFILE}")"
+  [[ -w "${LOCKDIR}" ]] || _exiterr "Directory ${LOCKDIR} for LOCKFILE ${LOCKFILE} is not writable, aborting."
   ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
   remove_lock() { rm -f "${LOCKFILE}"; }
   trap 'remove_lock' EXIT
@@ -88,25 +156,26 @@ init_system() {
 
   # Checking for private key ...
   register_new_key="no"
-  if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
+  if [[ -n "${PARAM_ACCOUNT_KEY:-}" ]]; then
     # a private key was specified from the command line so use it for this run
-    echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
-    PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
+    echo "Using private key ${PARAM_ACCOUNT_KEY} instead of account key"
+    ACCOUNT_KEY="${PARAM_ACCOUNT_KEY}"
+    ACCOUNT_KEY_JSON="${PARAM_ACCOUNT_KEY}.json"
   else
     # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
-    if [[ ! -e "${PRIVATE_KEY}" ]]; then
+    if [[ ! -e "${ACCOUNT_KEY}" ]]; then
       echo "+ Generating account key..."
-      _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
+      _openssl genrsa -out "${ACCOUNT_KEY}" "${KEYSIZE}"
       register_new_key="yes"
     fi
   fi
-  openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Private key is not valid, can not continue."
+  openssl rsa -in "${ACCOUNT_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Account key is not valid, can not continue."
 
   # Get public components from private key and calculate thumbprint
-  pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
-  pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
+  pubExponent64="$(printf '%x' "$(openssl rsa -in "${ACCOUNT_KEY}" -noout -text | awk '/publicExponent/ {print $2}')" | hex2bin | urlbase64)"
+  pubMod64="$(openssl rsa -in "${ACCOUNT_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
 
-  thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
+  thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl dgst -sha256 -binary | urlbase64)"
 
   # If we generated a new private key in the step above we have to register it with the acme-server
   if [[ "${register_new_key}" = "yes" ]]; then
@@ -114,13 +183,24 @@ init_system() {
     [[ ! -z "${CA_NEW_REG}" ]] || _exiterr "Certificate authority doesn't allow registrations."
     # If an email for the contact has been provided then adding it to the registration request
     if [[ -n "${CONTACT_EMAIL}" ]]; then
-      signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
+      signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > "${ACCOUNT_KEY_JSON}"
     else
-      signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
+      signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > "${ACCOUNT_KEY_JSON}"
     fi
   fi
 
-  [[ -d "${WELLKNOWN}" ]] || _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
+  if [[ "${CHALLENGETYPE}" = "http-01" && ! -d "${WELLKNOWN}" ]]; then
+      _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
+  fi
+}
+
+# Different sed version for different os types...
+_sed() {
+  if [[ "${OSTYPE}" = "Linux" ]]; then
+    sed -r "${@}"
+  else
+    sed -E "${@}"
+  fi
 }
 
 # Print error message and exit with error
@@ -129,24 +209,28 @@ _exiterr() {
   exit 1
 }
 
+# Remove newlines and whitespace from json
+clean_json() {
+  tr -d '\r\n' | _sed -e 's/ +/ /g' -e 's/\{ /{/g' -e 's/ \}/}/g' -e 's/\[ /[/g' -e 's/ \]/]/g'
+}
+
 # Encode data as url-safe formatted base64
 urlbase64() {
   # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
-  openssl base64 -e | tr -d '\n\r' | sed 's/=*$//g' | tr '+/' '-_'
+  openssl base64 -e | tr -d '\n\r' | _sed -e 's:=*$::g' -e 'y:+/:-_:'
 }
 
 # Convert hex string to binary data
 hex2bin() {
   # Remove spaces, add leading zero, escape as hex string and parse with printf
-  printf -- "$(cat | sed -E -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
+  printf -- "$(cat | _sed -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
 }
 
+# Get string value from json dictionary
 get_json_string_value() {
-  grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
-}
-
-get_json_array() {
-  grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
+  local filter
+  filter=$(printf 's/.*"%s": *"\([^"]*\)".*/\\1/p' "$1")
+  sed -n "${filter}"
 }
 
 # OpenSSL writes to stderr/stdout even when there are no errors. So just
@@ -156,28 +240,39 @@ _openssl() {
   out="$(openssl "${@}" 2>&1)"
   res=$?
   set -e
-  if [[ $res -ne 0 ]]; then
-    echo "  + ERROR: failed to run $* (Exitcode: $res)" >&2
+  if [[ ${res} -ne 0 ]]; then
+    echo "  + ERROR: failed to run $* (Exitcode: ${res})" >&2
     echo >&2
     echo "Details:" >&2
-    echo "$out" >&2
-    exit $res
+    echo "${out}" >&2
+    echo >&2
+    exit ${res}
   fi
 }
 
 # Send http(s) request with specified method
 http_request() {
-  tempcont="$(mktemp)"
+  tempcont="$(_mktemp)"
 
+  set +e
   if [[ "${1}" = "head" ]]; then
     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
+    curlret="${?}"
   elif [[ "${1}" = "get" ]]; then
     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
+    curlret="${?}"
   elif [[ "${1}" = "post" ]]; then
     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
+    curlret="${?}"
   else
+    set -e
     _exiterr "Unknown request method: ${1}"
   fi
+  set -e
+
+  if [[ ! "${curlret}" = "0" ]]; then
+    _exiterr "Problem connecting to server (curl returned with ${curlret})"
+  fi
 
   if [[ ! "${statuscode:0:1}" = "2" ]]; then
     echo "  + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
@@ -187,12 +282,12 @@ http_request() {
     rm -f "${tempcont}"
 
     # Wait for hook script to clean the challenge if used
-    if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
-      ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
+    if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token:+set}" ]]; then
+      "${HOOK}" "clean_challenge" '' "${challenge_token}" "${keyauth}"
     fi
 
     # remove temporary domains.txt file if used
-    [[ -n "${PARAM_DOMAIN:-}" ]] && rm "${DOMAINS_TXT}"
+    [[ -n "${PARAM_DOMAIN:-}" && -n "${DOMAINS_TXT:-}" ]] && rm "${DOMAINS_TXT}"
     exit 1
   fi
 
@@ -200,6 +295,7 @@ http_request() {
   rm -f "${tempcont}"
 }
 
+# Send signed request
 signed_request() {
   # Encode payload as urlbase64
   payload64="$(printf '%s' "${2}" | urlbase64)"
@@ -215,7 +311,7 @@ signed_request() {
   protected64="$(printf '%s' "${protected}" | urlbase64)"
 
   # Sign header with nonce and our payload with our private key and encode signature as urlbase64
-  signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
+  signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${ACCOUNT_KEY}" | urlbase64)"
 
   # Send header + extended header + payload + signature to the acme-server
   data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
@@ -223,148 +319,256 @@ signed_request() {
   http_request post "${1}" "${data}"
 }
 
-sign_domain() {
-  domain="${1}"
-  altnames="${*}"
+# Extracts all subject names from a CSR
+# Outputs either the CN, or the SANs, one per line
+extract_altnames() {
+  csr="${1}" # the CSR itself (not a file)
 
-  echo " + Signing domains..."
-  if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
-    echo " + ERROR: Certificate authority doesn't allow certificate signing" >&2
-    exit 1
+  if ! <<<"${csr}" openssl req -verify -noout 2>/dev/null; then
+    _exiterr "Certificate signing request isn't valid"
   fi
-  timestamp="$(date +%s)"
 
-  # If there is no existing certificate directory => make it
-  if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
-    echo " + make directory ${BASEDIR}/certs/${domain} ..."
-    mkdir -p "${BASEDIR}/certs/${domain}"
+  reqtext="$( <<<"${csr}" openssl req -noout -text )"
+  if <<<"${reqtext}" grep -q '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$'; then
+    # SANs used, extract these
+    altnames="$( <<<"${reqtext}" grep -A1 '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$' | tail -n1 )"
+    # split to one per line:
+    # shellcheck disable=SC1003
+    altnames="$( <<<"${altnames}" _sed -e 's/^[[:space:]]*//; s/, /\'$'\n''/g' )"
+    # we can only get DNS: ones signed
+    if grep -qv '^DNS:' <<<"${altnames}"; then
+      _exiterr "Certificate signing request contains non-DNS Subject Alternative Names"
+    fi
+    # strip away the DNS: prefix
+    altnames="$( <<<"${altnames}" _sed -e 's/^DNS://' )"
+    echo "${altnames}"
+
+  else
+    # No SANs, extract CN
+    altnames="$( <<<"${reqtext}" grep '^[[:space:]]*Subject:' | _sed -e 's/.* CN=([^ /,]*).*/\1/' )"
+    echo "${altnames}"
   fi
+}
 
-  privkey="privkey.pem"
-  # generate a new private key if we need or want one
-  if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
-    echo " + Generating private key..."
-    privkey="privkey-${timestamp}.pem"
-    _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
+# Create certificate for domain(s) and outputs it FD 3
+sign_csr() {
+  csr="${1}" # the CSR itself (not a file)
+
+  if { true >&3; } 2>/dev/null; then
+    : # fd 3 looks OK
+  else
+    _exiterr "sign_csr: FD 3 not open"
   fi
 
-  # Generate signing request config and the actual signing request
-  SAN=""
-  for altname in $altnames; do
-    SAN+="DNS:${altname}, "
-  done
-  SAN="${SAN%%, }"
-  echo " + Generating signing request..."
-  local tmp_openssl_cnf
-  tmp_openssl_cnf="$(mktemp)"
-  cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
-  printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
-  openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
-  rm -f "${tmp_openssl_cnf}"
+  shift 1 || true
+  altnames="${*:-}"
+  if [ -z "${altnames}" ]; then
+    altnames="$( extract_altnames "${csr}" )"
+  fi
 
-  # Request and respond to challenges
-  for altname in $altnames; do
+  if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
+    _exiterr "Certificate authority doesn't allow certificate signing"
+  fi
+
+  local idx=0
+  if [[ -n "${ZSH_VERSION:-}" ]]; then
+    local -A challenge_uris challenge_tokens keyauths deploy_args
+  else
+    local -a challenge_uris challenge_tokens keyauths deploy_args
+  fi
+
+  # Request challenges
+  for altname in ${altnames}; do
     # Ask the acme-server for new challenge token and extract them from the resulting json block
     echo " + Requesting challenge for ${altname}..."
-    response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
+    response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}' | clean_json)"
 
-    challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
+    challenges="$(printf '%s\n' "${response}" | sed -n 's/.*\("challenges":[^\[]*\[[^]]*]\).*/\1/p')"
     repl=$'\n''{' # fix syntax highlighting in Vim
-    challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
-    challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
+    challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep \""${CHALLENGETYPE}"\")"
+    challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | _sed 's/[^A-Za-z0-9_\-]/_/g')"
     challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
 
     if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
-      echo "  + Error: Can't retrieve challenges (${response})" >&2
-      exit 1
+      _exiterr "Can't retrieve challenges (${response})"
     fi
 
     # Challenge response consists of the challenge token and the thumbprint of our public certificate
     keyauth="${challenge_token}.${thumbprint}"
 
-    # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
-    printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
-    chmod a+r "${WELLKNOWN}/${challenge_token}"
+    case "${CHALLENGETYPE}" in
+      "http-01")
+        # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
+        printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
+        chmod a+r "${WELLKNOWN}/${challenge_token}"
+        keyauth_hook="${keyauth}"
+        ;;
+      "dns-01")
+        # Generate DNS entry content for dns-01 validation
+        keyauth_hook="$(printf '%s' "${keyauth}" | openssl dgst -sha256 -binary | urlbase64)"
+        ;;
+    esac
+
+    challenge_uris[${idx}]="${challenge_uri}"
+    keyauths[${idx}]="${keyauth}"
+    challenge_tokens[${idx}]="${challenge_token}"
+    # Note: assumes args will never have spaces!
+    deploy_args[${idx}]="${altname} ${challenge_token} ${keyauth_hook}"
+    idx=$((idx+1))
+  done
+
+  # Wait for hook script to deploy the challenges if used
+  # shellcheck disable=SC2068
+  [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[@]}
+
+  # Respond to challenges
+  idx=0
+  for altname in ${altnames}; do
+    challenge_token="${challenge_tokens[${idx}]}"
+    keyauth="${keyauths[${idx}]}"
 
     # Wait for hook script to deploy the challenge if used
-    if [[ -n "${HOOK}" ]]; then
-        ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
-    fi
+    # shellcheck disable=SC2086
+    [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[${idx}]}
 
-    # Ask the acme-server to verify our challenge and wait until it becomes valid
+    # Ask the acme-server to verify our challenge and wait until it is no longer pending
     echo " + Responding to challenge for ${altname}..."
-    result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
+    result="$(signed_request "${challenge_uris[${idx}]}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}' | clean_json)"
 
-    status="$(printf '%s\n' "${result}" | get_json_string_value status)"
+    reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
 
-    # get status until a result is reached => not pending anymore
-    while [[ "${status}" = "pending" ]]; do
+    while [[ "${reqstatus}" = "pending" ]]; do
       sleep 1
-      status="$(http_request get "${challenge_uri}" | get_json_string_value status)"
+      result="$(http_request get "${challenge_uris[${idx}]}")"
+      reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
     done
 
-    rm -f "${WELLKNOWN}/${challenge_token}"
+    [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_token}"
 
     # Wait for hook script to clean the challenge if used
-    if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
-      ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
+    if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token}" ]]; then
+      # shellcheck disable=SC2086
+      "${HOOK}" "clean_challenge" ${deploy_args[${idx}]}
     fi
+    idx=$((idx+1))
 
-    if [[ "${status}" = "valid" ]]; then
+    if [[ "${reqstatus}" = "valid" ]]; then
       echo " + Challenge is valid!"
     else
-      echo " + Challenge is invalid! (returned: ${status})" >&2
-      exit 1
+      break
     fi
-
   done
 
+  # Wait for hook script to clean the challenges if used
+  # shellcheck disable=SC2068
+  [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "clean_challenge" ${deploy_args[@]}
+
+  if [[ "${reqstatus}" != "valid" ]]; then
+    # Clean up any remaining challenge_tokens if we stopped early
+    if [[ "${CHALLENGETYPE}" = "http-01" ]]; then
+      while [ ${idx} -lt ${#challenge_tokens[@]} ]; do
+        rm -f "${WELLKNOWN}/${challenge_tokens[${idx}]}"
+        idx=$((idx+1))
+      done
+    fi
+
+    _exiterr "Challenge is invalid! (returned: ${reqstatus}) (result: ${result})"
+  fi
+
   # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
   echo " + Requesting certificate..."
-  csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
+  csr64="$( <<<"${csr}" openssl req -outform DER | urlbase64)"
   crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
-  crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
-  printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
-  # try to load the certificate to detect corruption
+  crt="$( printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" )"
+
+  # Try to load the certificate to detect corruption
   echo " + Checking certificate..."
-  _openssl x509 -text < "${crt_path}"
+  _openssl x509 -text <<<"${crt}"
+
+  echo "${crt}" >&3
+
+  unset challenge_token
+  echo " + Done!"
+}
+
+# Create certificate for domain(s)
+sign_domain() {
+  domain="${1}"
+  altnames="${*}"
+  timestamp="$(date +%s)"
+
+  echo " + Signing domains..."
+  if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
+    _exiterr "Certificate authority doesn't allow certificate signing"
+  fi
+
+  # If there is no existing certificate directory => make it
+  if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
+    echo " + Creating new directory ${BASEDIR}/certs/${domain} ..."
+    mkdir -p "${BASEDIR}/certs/${domain}"
+  fi
+
+  privkey="privkey.pem"
+  # generate a new private key if we need or want one
+  if [[ ! -r "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
+    echo " + Generating private key..."
+    privkey="privkey-${timestamp}.pem"
+    case "${KEY_ALGO}" in
+      rsa) _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}";;
+      prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem";;
+    esac
+  fi
+
+  # Generate signing request config and the actual signing request
+  echo " + Generating signing request..."
+  SAN=""
+  for altname in ${altnames}; do
+    SAN+="DNS:${altname}, "
+  done
+  SAN="${SAN%%, }"
+  local tmp_openssl_cnf
+  tmp_openssl_cnf="$(_mktemp)"
+  cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
+  printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
+  openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
+  rm -f "${tmp_openssl_cnf}"
+
+  crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
+  # shellcheck disable=SC2086
+  sign_csr "$(< "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" )" ${altnames} 3>"${crt_path}"
 
   # Create fullchain.pem
   echo " + Creating fullchain.pem..."
   cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
   http_request get "$(openssl x509 -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"
-  if ! grep "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" > /dev/null 2>&1; then
+  if ! grep -q "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"; then
     openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
   fi
-  ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
   cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
-  ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
 
-  # Update remaining symlinks
-  if [ ! "${privkey}" = "privkey.pem" ]; then
-    ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
-  fi
+  # Update symlinks
+  [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
 
+  ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
+  ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
   ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
   ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
 
   # Wait for hook script to clean the challenge and to deploy cert if used
-  if [[ -n "${HOOK}" ]]; then
-      ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
-  fi
+  export KEY_ALGO
+  [[ -n "${HOOK}" ]] && "${HOOK}" "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem" "${BASEDIR}/certs/${domain}/chain.pem" "${timestamp}"
 
   unset challenge_token
   echo " + Done!"
 }
 
-
 # Usage: --cron (-c)
 # Description: Sign/renew non-existant/changed/expiring certificates.
 command_sign_domains() {
   init_system
 
   if [[ -n "${PARAM_DOMAIN:-}" ]]; then
-    DOMAINS_TXT="$(mktemp)"
+    DOMAINS_TXT="$(_mktemp)"
     printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
   elif [[ -e "${BASEDIR}/domains.txt" ]]; then
     DOMAINS_TXT="${BASEDIR}/domains.txt"
@@ -373,7 +577,10 @@ command_sign_domains() {
   fi
 
   # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
-  <"${DOMAINS_TXT}" sed 's/^[[:space:]]*//g;s/[[:space:]]*$//g' | grep -vE '^(#|$)' | while read -r line; do
+  ORIGIFS="${IFS}"
+  IFS=$'\n'
+  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
+    IFS="${ORIGIFS}"
     domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
     morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
     cert="${BASEDIR}/certs/${domain}/cert.pem"
@@ -389,8 +596,8 @@ command_sign_domains() {
     if [[ -e "${cert}" ]]; then
       printf " + Checking domain name(s) of existing cert..."
 
-      certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')"
-      givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//' | sed 's/^ //')"
+      certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | _sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//')"
+      givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//' | _sed 's/^ //')"
 
       if [[ "${certnames}" = "${givennames}" ]]; then
         echo " unchanged."
@@ -414,7 +621,9 @@ command_sign_domains() {
         if [[ "${force_renew}" = "yes" ]]; then
           echo "Ignoring because renew was forced!"
         else
-          echo "Skipping!"
+          # Certificate-Names unchanged and cert is still valid
+          echo "Skipping renew!"
+          [[ -n "${HOOK}" ]] && "${HOOK}" "unchanged_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem" "${BASEDIR}/certs/${domain}/chain.pem"
           continue
         fi
       else
@@ -424,7 +633,7 @@ command_sign_domains() {
 
     # shellcheck disable=SC2086
     sign_domain ${line}
-  done || true
+  done
 
   # remove temporary domains.txt file if used
   [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
@@ -432,6 +641,25 @@ command_sign_domains() {
   exit 0
 }
 
+# Usage: --signcsr (-s) path/to/csr.pem
+# Description: Sign a given CSR, output CRT on stdout (advanced usage)
+command_sign_csr() {
+  # redirect stdout to stderr
+  # leave stdout over at fd 3 to output the cert
+  exec 3>&1 1>&2
+
+  init_system
+
+  csrfile="${1}"
+  if [ ! -r "${csrfile}" ]; then
+    _exiterr "Could not read certificate signing request ${csrfile}"
+  fi
+
+  sign_csr "$(< "${csrfile}" )"
+
+  exit 0
+}
+
 # Usage: --revoke (-r) path/to/cert.pem
 # Description: Revoke specified certificate
 command_revoke() {
@@ -455,7 +683,7 @@ command_revoke() {
   echo "Revoking ${cert}"
 
   cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
-  response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
+  response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}' | clean_json)"
   # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
   # so if we are here, it is safe to assume the request was successful
   echo " + Done."
@@ -463,6 +691,60 @@ command_revoke() {
   mv -f "${cert}" "${cert}-revoked"
 }
 
+# Usage: --cleanup (-gc)
+# Description: Move unused certificate files to archive directory
+command_cleanup() {
+  load_config
+
+  # Create global archive directory if not existant
+  if [[ ! -e "${BASEDIR}/archive" ]]; then
+    mkdir "${BASEDIR}/archive"
+  fi
+
+  # Loop over all certificate directories
+  for certdir in "${BASEDIR}/certs/"*; do
+    # Skip if entry is not a folder
+    [[ -d "${certdir}" ]] || continue
+
+    # Get certificate name
+    certname="$(basename "${certdir}")"
+
+    # Create certitifaces archive directory if not existant
+    archivedir="${BASEDIR}/archive/${certname}"
+    if [[ ! -e "${archivedir}" ]]; then
+      mkdir "${archivedir}"
+    fi
+
+    # Loop over file-types (certificates, keys, signing-requests, ...)
+    for filetype in cert.csr cert.pem chain.pem fullchain.pem privkey.pem; do
+      # Skip if symlink is broken
+      [[ -r "${certdir}/${filetype}" ]] || continue
+
+      # Look up current file in use
+      current="$(basename "$(readlink "${certdir}/${filetype}")")"
+
+      # Split filetype into name and extension
+      filebase="$(echo "${filetype}" | cut -d. -f1)"
+      fileext="$(echo "${filetype}" | cut -d. -f2)"
+
+      # Loop over all files of this type
+      for file in "${certdir}/${filebase}-"*".${fileext}"; do
+        # Handle case where no files match the wildcard
+        [[ -f "${file}" ]] || break
+
+        # Check if current file is in use, if unused move to archive directory
+        filename="$(basename "${file}")"
+        if [[ ! "${filename}" = "${current}" ]]; then
+          echo "Moving unused file to archive directory: ${certname}/${filename}"
+          mv "${certdir}/${filename}" "${archivedir}/${filename}"
+        fi
+      done
+    done
+  done
+
+  exit 0
+}
+
 # Usage: --help (-h)
 # Description: Show help text
 command_help() {
@@ -489,9 +771,10 @@ command_help() {
 command_env() {
   echo "# letsencrypt.sh configuration"
   load_config
-  typeset -p CA LICENSE HOOK RENEW_DAYS PRIVATE_KEY KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
+  typeset -p CA LICENSE CHALLENGETYPE HOOK HOOK_CHAIN RENEW_DAYS ACCOUNT_KEY ACCOUNT_KEY_JSON KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
 }
 
+# Main method (parses script arguments and calls command_* methods)
 main() {
   COMMAND=""
   set_command() {
@@ -510,7 +793,9 @@ main() {
     fi
   }
 
-  while (( "${#}" )); do
+  [[ -z "${@}" ]] && eval set -- "--help"
+
+  while (( ${#} )); do
     case "${1}" in
       --help|-h)
         command_help
@@ -525,6 +810,13 @@ main() {
         set_command sign_domains
         ;;
 
+      --signcsr|-s)
+        shift 1
+        set_command sign_csr
+        check_parameters "${1:-}"
+        PARAM_CSR="${1}"
+        ;;
+
       --revoke|-r)
         shift 1
         set_command revoke
@@ -532,6 +824,10 @@ main() {
         PARAM_REVOKECERT="${1}"
         ;;
 
+      --cleanup|-gc)
+        set_command cleanup
+        ;;
+
       # PARAM_Usage: --domain (-d) domain.tld
       # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
       --domain|-d)
@@ -556,7 +852,7 @@ main() {
       --privkey|-p)
         shift 1
         check_parameters "${1:-}"
-        PARAM_PRIVATE_KEY="${1}"
+        PARAM_ACCOUNT_KEY="${1}"
         ;;
 
       # PARAM_Usage: --config (-f) path/to/config.sh
@@ -567,6 +863,30 @@ main() {
         CONFIG="${1}"
         ;;
 
+      # PARAM_Usage: --hook (-k) path/to/hook.sh
+      # PARAM_Description: Use specified script for hooks
+      --hook|-k)
+        shift 1
+        check_parameters "${1:-}"
+        PARAM_HOOK="${1}"
+        ;;
+
+      # PARAM_Usage: --challenge (-t) http-01|dns-01
+      # PARAM_Description: Which challenge should be used? Currently http-01 and dns-01 are supported
+      --challenge|-t)
+        shift 1
+        check_parameters "${1:-}"
+        PARAM_CHALLENGETYPE="${1}"
+        ;;
+
+      # PARAM_Usage: --algo (-a) rsa|prime256v1|secp384r1
+      # PARAM_Description: Which public key algorithm should be used? Supported: rsa, prime256v1 and secp384r1
+      --algo|-a)
+        shift 1
+        check_parameters "${1:-}"
+        PARAM_KEY_ALGO="${1}"
+        ;;
+
       *)
         echo "Unknown parameter detected: ${1}" >&2
         echo >&2
@@ -581,11 +901,16 @@ main() {
   case "${COMMAND}" in
     env) command_env;;
     sign_domains) command_sign_domains;;
+    sign_csr) command_sign_csr "${PARAM_CSR}";;
     revoke) command_revoke "${PARAM_REVOKECERT}";;
-    *) command_help; exit1;;
+    cleanup) command_cleanup;;
+    *) command_help; exit 1;;
   esac
 }
 
+# Determine OS type
+OSTYPE="$(uname)"
+
 # Check for missing dependencies
 check_dependencies