]> git.street.me.uk Git - andy/dehydrated.git/blame - dehydrated
updated changelog
[andy/dehydrated.git] / dehydrated
CommitLineData
2e8454b4 1#!/usr/bin/env bash
a1a9c8a4 2
ec49a443 3# dehydrated by lukas2511
64e35463 4# Source: https://github.com/lukas2511/dehydrated
0fa381ff
LS
5#
6# This script is licensed under The MIT License (see LICENSE for more information).
a1a9c8a4 7
69f3e78b
LS
8set -e
9set -u
10set -o pipefail
da2eeda9 11[[ -n "${ZSH_VERSION:-}" ]] && set -o SH_WORD_SPLIT && set +o FUNCTION_ARGZERO
81882a64 12umask 077 # paranoid umask, we're creating private keys
61f0b7ed 13
85a25b56
LS
14# Find directory in which this script is stored by traversing all symbolic links
15SOURCE="${0}"
16while [ -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
20done
21SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
22
0e92aba2
MG
23BASEDIR="${SCRIPTDIR}"
24
1f6a80a0
LS
25# Create (identifiable) temporary files
26_mktemp() {
75985c6a 27 # shellcheck disable=SC2068
ec49a443 28 mktemp ${@:-} "${TMPDIR:-/tmp}/dehydrated-XXXXXX"
1f6a80a0
LS
29}
30
bc580335 31# Check for script dependencies
9f66bfdb 32check_dependencies() {
0af7f388 33 # just execute some dummy and/or version commands to see if required tools exist and are actually usable
115041cd 34 openssl version > /dev/null 2>&1 || _exiterr "This script requires an openssl binary."
f7c7d8c5 35 _sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requires sed with support for extended (modern) regular expressions."
4b8883b4 36 command -v grep > /dev/null 2>&1 || _exiterr "This script requires grep."
e2e2c362 37 command -v mktemp > /dev/null 2>&1 || _exiterr "This script requires mktemp."
cfc00c42 38 command -v diff > /dev/null 2>&1 || _exiterr "This script requires diff."
0af7f388
LS
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
0af7f388 43 retcode="$?"
36a03146 44 set -e
0af7f388
LS
45 if [[ ! "${retcode}" = "0" ]] && [[ ! "${retcode}" = "2" ]]; then
46 _exiterr "This script requires curl."
47 fi
9f66bfdb
LS
48}
49
ec489069
LS
50store_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}"
364bcccf 61 __IP_VERSION="${IP_VERSION}"
ec489069
LS
62}
63
64reset_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}"
364bcccf 75 IP_VERSION="${__IP_VERSION}"
ec489069
LS
76}
77
78# verify configuration values
79verify_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."
364bcccf 88 if [[ -n "${IP_VERSION}" ]]; then
89 [[ "${IP_VERSION}" = "4" || "${IP_VERSION}" = "6" ]] || _exiterr "Unknown IP version ${IP_VERSION}... can not continue."
90 fi
ec489069
LS
91}
92
ff116396
LS
93# Setup default config values, search for and load configuration files
94load_config() {
00810795
LS
95 # Check for config in various locations
96 if [[ -z "${CONFIG:-}" ]]; then
ec49a443 97 for check_config in "/etc/dehydrated" "/usr/local/etc/dehydrated" "${PWD}" "${SCRIPTDIR}"; do
0d8b9289 98 if [[ -f "${check_config}/config" ]]; then
00810795 99 BASEDIR="${check_config}"
d5b28586 100 CONFIG="${check_config}/config"
00810795
LS
101 break
102 fi
103 done
104 fi
105
ff116396
LS
106 # Default values
107 CA="https://acme-v01.api.letsencrypt.org/directory"
afabfff0 108 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
785ffa55 109 CERTDIR=
034ec30c 110 ACCOUNTDIR=
de173892 111 CHALLENGETYPE="http-01"
a1cb7ccc 112 CONFIG_D=
44aca90c 113 DOMAINS_D=
a3e5ed36 114 DOMAINS_TXT=
ff116396 115 HOOK=
6e048f7f 116 HOOK_CHAIN="no"
30ad9584 117 RENEW_DAYS="30"
ff116396 118 KEYSIZE="4096"
9baf3532 119 WELLKNOWN=
e608dc2b 120 PRIVATE_KEY_RENEW="yes"
a13e4103 121 PRIVATE_KEY_ROLLOVER="no"
c71ca3a8 122 KEY_ALGO=rsa
f0323faf 123 OPENSSL_CNF="$(openssl version -d | cut -d\" -f2)/openssl.cnf"
ff116396 124 CONTACT_EMAIL=
9baf3532 125 LOCKFILE=
8e77ba5e 126 OCSP_MUST_STAPLE="no"
364bcccf 127 IP_VERSION=
1e33cfe5 128
81882a64 129 if [[ -z "${CONFIG:-}" ]]; then
ff116396 130 echo "#" >&2
a1cb7ccc 131 echo "# !! WARNING !! No main config file found, using default config!" >&2
ff116396 132 echo "#" >&2
0d8b9289 133 elif [[ -f "${CONFIG}" ]]; then
a1cb7ccc 134 echo "# INFO: Using main config file ${CONFIG}"
81882a64
LS
135 BASEDIR="$(dirname "${CONFIG}")"
136 # shellcheck disable=SC1090
137 . "${CONFIG}"
138 else
f06f764f 139 _exiterr "Specified config file doesn't exist."
81882a64 140 fi
61f0b7ed 141
a1cb7ccc
DB
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
e2d8bfa4 147 for check_config_d in "${CONFIG_D}"/*.sh; do
a1cb7ccc
DB
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}"
5c68c221 153 # shellcheck disable=SC1090
e2d8bfa4 154 . "${check_config_d}"
a1cb7ccc
DB
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
81882a64
LS
161 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
162 BASEDIR="${BASEDIR%%/}"
401f5f75 163
1e33cfe5 164 # Check BASEDIR and set default variables
f06f764f 165 [[ -d "${BASEDIR}" ]] || _exiterr "BASEDIR does not exist: ${BASEDIR}"
ed27e013 166
034ec30c
LS
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
785ffa55 183 [[ -z "${CERTDIR}" ]] && CERTDIR="${BASEDIR}/certs"
a3e5ed36 184 [[ -z "${DOMAINS_TXT}" ]] && DOMAINS_TXT="${BASEDIR}/domains.txt"
64e35463 185 [[ -z "${WELLKNOWN}" ]] && WELLKNOWN="/var/www/dehydrated"
9baf3532 186 [[ -z "${LOCKFILE}" ]] && LOCKFILE="${BASEDIR}/lock"
8456855e 187 [[ -n "${PARAM_LOCKFILE_SUFFIX:-}" ]] && LOCKFILE="${LOCKFILE}-${PARAM_LOCKFILE_SUFFIX}"
bd9cc5b0 188 [[ -n "${PARAM_NO_LOCK:-}" ]] && LOCKFILE=""
9baf3532 189
de173892 190 [[ -n "${PARAM_HOOK:-}" ]] && HOOK="${PARAM_HOOK}"
785ffa55 191 [[ -n "${PARAM_CERTDIR:-}" ]] && CERTDIR="${PARAM_CERTDIR}"
de173892 192 [[ -n "${PARAM_CHALLENGETYPE:-}" ]] && CHALLENGETYPE="${PARAM_CHALLENGETYPE}"
c71ca3a8 193 [[ -n "${PARAM_KEY_ALGO:-}" ]] && KEY_ALGO="${PARAM_KEY_ALGO}"
8e77ba5e 194 [[ -n "${PARAM_OCSP_MUST_STAPLE:-}" ]] && OCSP_MUST_STAPLE="${PARAM_OCSP_MUST_STAPLE}"
364bcccf 195 [[ -n "${PARAM_IP_VERSION:-}" ]] && IP_VERSION="${PARAM_IP_VERSION}"
e925b293 196
ec489069
LS
197 verify_config
198 store_configvars
ff116396
LS
199}
200
93cd114f 201# Initialize system
ff116396
LS
202init_system() {
203 load_config
81882a64 204
1e33cfe5 205 # Lockfile handling (prevents concurrent access)
bd9cc5b0
LS
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
81882a64 213
81882a64 214 # Get CA URLs
3a9e97f9 215 CA_DIRECTORY="$(http_request get "${CA}")"
81882a64
LS
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)" &&
10d9f342 219 # shellcheck disable=SC2015
81882a64 220 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
93cd114f 221 _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
81882a64 222
93cd114f 223 # Export some environment variables to be used in hook script
785ffa55 224 export WELLKNOWN BASEDIR CERTDIR CONFIG
0e92aba2 225
93cd114f
LS
226 # Checking for private key ...
227 register_new_key="no"
8aa1a05b 228 if [[ -n "${PARAM_ACCOUNT_KEY:-}" ]]; then
0e92aba2 229 # a private key was specified from the command line so use it for this run
8aa1a05b
LS
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"
0e92aba2
MG
233 else
234 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
8aa1a05b 235 if [[ ! -e "${ACCOUNT_KEY}" ]]; then
81882a64 236 echo "+ Generating account key..."
8aa1a05b 237 _openssl genrsa -out "${ACCOUNT_KEY}" "${KEYSIZE}"
93cd114f 238 register_new_key="yes"
81882a64 239 fi
81882a64 240 fi
8aa1a05b 241 openssl rsa -in "${ACCOUNT_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Account key is not valid, can not continue."
1ab6a436 242
81882a64 243 # Get public components from private key and calculate thumbprint
8aa1a05b
LS
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)"
81882a64 246
21c18dd3 247 thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl dgst -sha256 -binary | urlbase64)"
81882a64
LS
248
249 # If we generated a new private key in the step above we have to register it with the acme-server
93cd114f 250 if [[ "${register_new_key}" = "yes" ]]; then
64e35463 251 echo "+ Registering account key with ACME server..."
93cd114f
LS
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
034ec30c 254 FAILED=false
81882a64 255 if [[ -n "${CONTACT_EMAIL}" ]]; then
034ec30c 256 (signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > "${ACCOUNT_KEY_JSON}") || FAILED=true
81882a64 257 else
034ec30c
LS
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
81882a64
LS
266 fi
267 fi
181dd0ff 268
81882a64 269}
c24843c6 270
f7c7d8c5
LS
271# Different sed version for different os types...
272_sed() {
c3c9ff4c 273 if [[ "${OSTYPE}" = "Linux" ]]; then
f7c7d8c5
LS
274 sed -r "${@}"
275 else
276 sed -E "${@}"
277 fi
278}
279
9f66bfdb
LS
280# Print error message and exit with error
281_exiterr() {
282 echo "ERROR: ${1}" >&2
283 exit 1
284}
285
561f0626
LS
286# Remove newlines and whitespace from json
287clean_json() {
288 tr -d '\r\n' | _sed -e 's/ +/ /g' -e 's/\{ /{/g' -e 's/ \}/}/g' -e 's/\[ /[/g' -e 's/ \]/]/g'
289}
290
994803bf 291# Encode data as url-safe formatted base64
61f0b7ed 292urlbase64() {
c6e60302 293 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
a316a094 294 openssl base64 -e | tr -d '\n\r' | _sed -e 's:=*$::g' -e 'y:+/:-_:'
61f0b7ed 295}
91ce50af 296
16bef17e 297# Convert hex string to binary data
9fe313d8 298hex2bin() {
16bef17e 299 # Remove spaces, add leading zero, escape as hex string and parse with printf
f7c7d8c5 300 printf -- "$(cat | _sed -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
9fe313d8 301}
61f0b7ed 302
bc580335 303# Get string value from json dictionary
09729186 304get_json_string_value() {
5c68c221
LS
305 local filter
306 filter=$(printf 's/.*"%s": *"\([^"]*\)".*/\\1/p' "$1")
307 sed -n "${filter}"
09729186
LS
308}
309
9729751d 310rm_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
cc605a22
LS
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
39c01fd7
LS
324 if [[ ${res} -ne 0 ]]; then
325 echo " + ERROR: failed to run $* (Exitcode: ${res})" >&2
cc605a22
LS
326 echo >&2
327 echo "Details:" >&2
39c01fd7 328 echo "${out}" >&2
676d15c5 329 echo >&2
39c01fd7 330 exit ${res}
cc605a22
LS
331 fi
332}
333
59f16407 334# Send http(s) request with specified method
3a9e97f9 335http_request() {
1f6a80a0 336 tempcont="$(_mktemp)"
3cb292cb 337
364bcccf 338 if [[ -n "${IP_VERSION:-}" ]]; then
339 ip_version="-${IP_VERSION}"
340 fi
341
1233dc95 342 set +e
dd5f36e5 343 if [[ "${1}" = "head" ]]; then
364bcccf 344 statuscode="$(curl ${ip_version:-} -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
1233dc95 345 curlret="${?}"
dd5f36e5 346 elif [[ "${1}" = "get" ]]; then
364bcccf 347 statuscode="$(curl ${ip_version:-} -s -w "%{http_code}" -o "${tempcont}" "${2}")"
1233dc95 348 curlret="${?}"
dd5f36e5 349 elif [[ "${1}" = "post" ]]; then
364bcccf 350 statuscode="$(curl ${ip_version:-} -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
1233dc95 351 curlret="${?}"
59f16407 352 else
1233dc95 353 set -e
59f16407 354 _exiterr "Unknown request method: ${1}"
91ce50af 355 fi
1233dc95
LS
356 set -e
357
358 if [[ ! "${curlret}" = "0" ]]; then
df292dec 359 _exiterr "Problem connecting to server (${1} for ${2}; curl returned with ${curlret})"
1233dc95 360 fi
dd5f36e5 361
3cb292cb 362 if [[ ! "${statuscode:0:1}" = "2" ]]; then
84fac541 363 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
3cb292cb
LS
364 echo >&2
365 echo "Details:" >&2
9e79c066 366 cat "${tempcont}" >&2
117d5d62
B
367 echo >&2
368 echo >&2
404dc3fe 369
370 # An exclusive hook for the {1}-request error might be useful (e.g., for sending an e-mail to admins)
371 if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]]; then
372 errtxt=`cat ${tempcont}`
373 "${HOOK}" "request_failure" "${statuscode}" "${errtxt}" "${1}"
374 fi
375
3cb292cb 376 rm -f "${tempcont}"
c24843c6 377
378 # Wait for hook script to clean the challenge if used
676d15c5 379 if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token:+set}" ]]; then
2099c77f 380 "${HOOK}" "clean_challenge" '' "${challenge_token}" "${keyauth}"
c24843c6 381 fi
382
8f6c2328 383 # remove temporary domains.txt file if used
79ff846e 384 [[ -n "${PARAM_DOMAIN:-}" && -n "${DOMAINS_TXT:-}" ]] && rm "${DOMAINS_TXT}"
dd5f36e5 385 exit 1
130ea6ab 386 fi
dd5f36e5 387
31111265 388 cat "${tempcont}"
3cb292cb 389 rm -f "${tempcont}"
91ce50af 390}
81882a64 391
1446fd88 392# Send signed request
61f0b7ed 393signed_request() {
c6e60302 394 # Encode payload as urlbase64
4aa48d33 395 payload64="$(printf '%s' "${2}" | urlbase64)"
61f0b7ed 396
c6e60302 397 # Retrieve nonce from acme-server
994803bf 398 nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
61f0b7ed 399
c6e60302 400 # Build header with just our public key and algorithm information
61f0b7ed
LS
401 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
402
c6e60302 403 # Build another header which also contains the previously received nonce and encode it as urlbase64
61f0b7ed 404 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
4aa48d33 405 protected64="$(printf '%s' "${protected}" | urlbase64)"
61f0b7ed 406
c6e60302 407 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
8aa1a05b 408 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${ACCOUNT_KEY}" | urlbase64)"
61f0b7ed 409
c6e60302 410 # Send header + extended header + payload + signature to the acme-server
61f0b7ed
LS
411 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
412
3a9e97f9 413 http_request post "${1}" "${data}"
61f0b7ed
LS
414}
415
a62968c9
NL
416# Extracts all subject names from a CSR
417# Outputs either the CN, or the SANs, one per line
418extract_altnames() {
419 csr="${1}" # the CSR itself (not a file)
81882a64 420
a62968c9
NL
421 if ! <<<"${csr}" openssl req -verify -noout 2>/dev/null; then
422 _exiterr "Certificate signing request isn't valid"
09729186 423 fi
3cc587c2 424
a62968c9 425 reqtext="$( <<<"${csr}" openssl req -noout -text )"
39c01fd7 426 if <<<"${reqtext}" grep -q '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$'; then
a62968c9
NL
427 # SANs used, extract these
428 altnames="$( <<<"${reqtext}" grep -A1 '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$' | tail -n1 )"
429 # split to one per line:
5c68c221 430 # shellcheck disable=SC1003
34f94322 431 altnames="$( <<<"${altnames}" _sed -e 's/^[[:space:]]*//; s/, /\'$'\n''/g' )"
a62968c9 432 # we can only get DNS: ones signed
5c68c221 433 if grep -qv '^DNS:' <<<"${altnames}"; then
a62968c9
NL
434 _exiterr "Certificate signing request contains non-DNS Subject Alternative Names"
435 fi
436 # strip away the DNS: prefix
437 altnames="$( <<<"${altnames}" _sed -e 's/^DNS://' )"
39c01fd7 438 echo "${altnames}"
a62968c9
NL
439
440 else
441 # No SANs, extract CN
442 altnames="$( <<<"${reqtext}" grep '^[[:space:]]*Subject:' | _sed -e 's/.* CN=([^ /,]*).*/\1/' )"
39c01fd7 443 echo "${altnames}"
3dbbb461 444 fi
a62968c9 445}
3dbbb461 446
50e7a072
NL
447# Create certificate for domain(s) and outputs it FD 3
448sign_csr() {
449 csr="${1}" # the CSR itself (not a file)
81882a64 450
50e7a072
NL
451 if { true >&3; } 2>/dev/null; then
452 : # fd 3 looks OK
453 else
454 _exiterr "sign_csr: FD 3 not open"
61f0b7ed
LS
455 fi
456
50e7a072
NL
457 shift 1 || true
458 altnames="${*:-}"
39c01fd7
LS
459 if [ -z "${altnames}" ]; then
460 altnames="$( extract_altnames "${csr}" )"
a62968c9 461 fi
3dbbb461 462
50e7a072
NL
463 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
464 _exiterr "Certificate authority doesn't allow certificate signing"
61f0b7ed 465 fi
c6e60302 466
6e048f7f 467 local idx=0
da2eeda9 468 if [[ -n "${ZSH_VERSION:-}" ]]; then
9729751d 469 local -A challenge_altnames challenge_uris challenge_tokens keyauths deploy_args
da2eeda9 470 else
9729751d 471 local -a challenge_altnames challenge_uris challenge_tokens keyauths deploy_args
da2eeda9 472 fi
39c01fd7 473
6e048f7f 474 # Request challenges
1446fd88 475 for altname in ${altnames}; do
c6e60302 476 # Ask the acme-server for new challenge token and extract them from the resulting json block
579e2316 477 echo " + Requesting challenge for ${altname}..."
561f0626 478 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}' | clean_json)"
61f0b7ed 479
9729751d 480 challenge_status="$(printf '%s' "${response}" | rm_json_arrays | get_json_string_value status)"
481 if [ "${challenge_status}" = "valid" ]; then
3c1d2673 482 echo " + Already validated!"
9729751d 483 continue
484 fi
485
4b8883b4 486 challenges="$(printf '%s\n' "${response}" | sed -n 's/.*\("challenges":[^\[]*\[[^]]*]\).*/\1/p')"
526843d6 487 repl=$'\n''{' # fix syntax highlighting in Vim
e925b293 488 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep \""${CHALLENGETYPE}"\")"
f7c7d8c5 489 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | _sed 's/[^A-Za-z0-9_\-]/_/g')"
09729186 490 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
61f0b7ed 491
dd5f36e5 492 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
1446fd88 493 _exiterr "Can't retrieve challenges (${response})"
abb95693
LS
494 fi
495
c6e60302 496 # Challenge response consists of the challenge token and the thumbprint of our public certificate
61f0b7ed
LS
497 keyauth="${challenge_token}.${thumbprint}"
498
de173892
LS
499 case "${CHALLENGETYPE}" in
500 "http-01")
501 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
502 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
503 chmod a+r "${WELLKNOWN}/${challenge_token}"
504 keyauth_hook="${keyauth}"
505 ;;
506 "dns-01")
507 # Generate DNS entry content for dns-01 validation
21c18dd3 508 keyauth_hook="$(printf '%s' "${keyauth}" | openssl dgst -sha256 -binary | urlbase64)"
de173892
LS
509 ;;
510 esac
61f0b7ed 511
9729751d 512 challenge_altnames[${idx}]="${altname}"
39c01fd7
LS
513 challenge_uris[${idx}]="${challenge_uri}"
514 keyauths[${idx}]="${keyauth}"
515 challenge_tokens[${idx}]="${challenge_token}"
6e048f7f 516 # Note: assumes args will never have spaces!
39c01fd7 517 deploy_args[${idx}]="${altname} ${challenge_token} ${keyauth_hook}"
6e048f7f
GD
518 idx=$((idx+1))
519 done
3c1d2673 520 challenge_count="${idx}"
6e048f7f
GD
521
522 # Wait for hook script to deploy the challenges if used
3c1d2673 523 if [[ ${challenge_count} -ne 0 ]]; then
9729751d 524 # shellcheck disable=SC2068
525 [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[@]}
526 fi
6e048f7f
GD
527
528 # Respond to challenges
9729751d 529 reqstatus="valid"
6e048f7f 530 idx=0
3c1d2673 531 if [ ${challenge_count} -ne 0 ]; then
636fa1a5
AR
532 for altname in "${challenge_altnames[@]:0}"; do
533 challenge_token="${challenge_tokens[${idx}]}"
534 keyauth="${keyauths[${idx}]}"
69eea952 535
636fa1a5
AR
536 # Wait for hook script to deploy the challenge if used
537 # shellcheck disable=SC2086
538 [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[${idx}]}
69eea952 539
636fa1a5
AR
540 # Ask the acme-server to verify our challenge and wait until it is no longer pending
541 echo " + Responding to challenge for ${altname}..."
542 result="$(signed_request "${challenge_uris[${idx}]}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}' | clean_json)"
69eea952 543
da2eeda9 544 reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
69eea952 545
636fa1a5
AR
546 while [[ "${reqstatus}" = "pending" ]]; do
547 sleep 1
548 result="$(http_request get "${challenge_uris[${idx}]}")"
549 reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
550 done
69eea952 551
636fa1a5 552 [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_token}"
69eea952 553
636fa1a5
AR
554 # Wait for hook script to clean the challenge if used
555 if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token}" ]]; then
556 # shellcheck disable=SC2086
557 "${HOOK}" "clean_challenge" ${deploy_args[${idx}]}
558 fi
559 idx=$((idx+1))
69eea952 560
636fa1a5
AR
561 if [[ "${reqstatus}" = "valid" ]]; then
562 echo " + Challenge is valid!"
563 else
564 [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && "${HOOK}" "invalid_challenge" "${altname}" "${result}"
565 fi
61f0b7ed 566 done
636fa1a5 567 fi
61f0b7ed 568
6e048f7f 569 # Wait for hook script to clean the challenges if used
5c68c221 570 # shellcheck disable=SC2068
3c1d2673
LS
571 if [[ ${challenge_count} -ne 0 ]]; then
572 [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "clean_challenge" ${deploy_args[@]}
573 fi
6e048f7f 574
da2eeda9 575 if [[ "${reqstatus}" != "valid" ]]; then
6e048f7f 576 # Clean up any remaining challenge_tokens if we stopped early
3c1d2673 577 if [[ "${CHALLENGETYPE}" = "http-01" ]] && [[ ${challenge_count} -ne 0 ]]; then
39c01fd7
LS
578 while [ ${idx} -lt ${#challenge_tokens[@]} ]; do
579 rm -f "${WELLKNOWN}/${challenge_tokens[${idx}]}"
6e048f7f
GD
580 idx=$((idx+1))
581 done
582 fi
583
da2eeda9 584 _exiterr "Challenge is invalid! (returned: ${reqstatus}) (result: ${result})"
6e048f7f
GD
585 fi
586
b7439a83 587 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
579e2316 588 echo " + Requesting certificate..."
50e7a072 589 csr64="$( <<<"${csr}" openssl req -outform DER | urlbase64)"
09729186 590 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
50e7a072 591 crt="$( printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" )"
1446fd88
LS
592
593 # Try to load the certificate to detect corruption
a4e7c43a 594 echo " + Checking certificate..."
50e7a072
NL
595 _openssl x509 -text <<<"${crt}"
596
597 echo "${crt}" >&3
598
599 unset challenge_token
600 echo " + Done!"
601}
602
603# Create certificate for domain(s)
604sign_domain() {
605 domain="${1}"
606 altnames="${*}"
607 timestamp="$(date +%s)"
608
609 echo " + Signing domains..."
610 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
611 _exiterr "Certificate authority doesn't allow certificate signing"
612 fi
613
614 # If there is no existing certificate directory => make it
785ffa55
AM
615 if [[ ! -e "${CERTDIR}/${domain}" ]]; then
616 echo " + Creating new directory ${CERTDIR}/${domain} ..."
617 mkdir -p "${CERTDIR}/${domain}" || _exiterr "Unable to create directory ${CERTDIR}/${domain}"
50e7a072
NL
618 fi
619
af2bc7a9
LS
620 privkey="privkey.pem"
621 # generate a new private key if we need or want one
785ffa55 622 if [[ ! -r "${CERTDIR}/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
af2bc7a9
LS
623 echo " + Generating private key..."
624 privkey="privkey-${timestamp}.pem"
625 case "${KEY_ALGO}" in
785ffa55
AM
626 rsa) _openssl genrsa -out "${CERTDIR}/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}";;
627 prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${CERTDIR}/${domain}/privkey-${timestamp}.pem";;
af2bc7a9
LS
628 esac
629 fi
a13e4103 630 # move rolloverkey into position (if any)
631 if [[ -r "${CERTDIR}/${domain}/privkey.pem" && -r "${CERTDIR}/${domain}/privkey.roll.pem" && "${PRIVATE_KEY_RENEW}" = "yes" && "${PRIVATE_KEY_ROLLOVER}" = "yes" ]]; then
632 echo " + Moving Rolloverkey into position.... "
633 mv "${CERTDIR}/${domain}/privkey.roll.pem" "${CERTDIR}/${domain}/privkey-tmp.pem"
634 mv "${CERTDIR}/${domain}/privkey-${timestamp}.pem" "${CERTDIR}/${domain}/privkey.roll.pem"
635 mv "${CERTDIR}/${domain}/privkey-tmp.pem" "${CERTDIR}/${domain}/privkey-${timestamp}.pem"
636 fi
637 # generate a new private rollover key if we need or want one
638 if [[ ! -r "${CERTDIR}/${domain}/privkey.roll.pem" && "${PRIVATE_KEY_ROLLOVER}" = "yes" && "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
639 echo " + Generating private rollover key..."
640 case "${KEY_ALGO}" in
641 rsa) _openssl genrsa -out "${CERTDIR}/${domain}/privkey.roll.pem" "${KEYSIZE}";;
642 prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${CERTDIR}/${domain}/privkey.roll.pem";;
643 esac
644 fi
645 # delete rolloverkeys if disabled
646 if [[ -r "${CERTDIR}/${domain}/privkey.roll.pem" && ! "${PRIVATE_KEY_ROLLOVER}" = "yes" ]]; then
647 echo " + Removing Rolloverkey (feature disabled)..."
648 rm -f "${CERTDIR}/${domain}/privkey.roll.pem"
649 fi
50e7a072
NL
650
651 # Generate signing request config and the actual signing request
652 echo " + Generating signing request..."
653 SAN=""
654 for altname in ${altnames}; do
655 SAN+="DNS:${altname}, "
656 done
657 SAN="${SAN%%, }"
658 local tmp_openssl_cnf
1f6a80a0 659 tmp_openssl_cnf="$(_mktemp)"
50e7a072
NL
660 cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
661 printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
8e77ba5e
LS
662 if [ "${OCSP_MUST_STAPLE}" = "yes" ]; then
663 printf "\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >> "${tmp_openssl_cnf}"
664 fi
785ffa55 665 openssl req -new -sha256 -key "${CERTDIR}/${domain}/${privkey}" -out "${CERTDIR}/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
50e7a072
NL
666 rm -f "${tmp_openssl_cnf}"
667
785ffa55 668 crt_path="${CERTDIR}/${domain}/cert-${timestamp}.pem"
5c68c221 669 # shellcheck disable=SC2086
785ffa55 670 sign_csr "$(< "${CERTDIR}/${domain}/cert-${timestamp}.csr" )" ${altnames} 3>"${crt_path}"
329acb58
LS
671
672 # Create fullchain.pem
1eb6f6d2 673 echo " + Creating fullchain.pem..."
785ffa55 674 cat "${crt_path}" > "${CERTDIR}/${domain}/fullchain-${timestamp}.pem"
7eca8aec
LS
675 tmpchain="$(_mktemp)"
676 http_request get "$(openssl x509 -in "${CERTDIR}/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${tmpchain}"
677 if grep -q "BEGIN CERTIFICATE" "${tmpchain}"; then
678 mv "${tmpchain}" "${CERTDIR}/${domain}/chain-${timestamp}.pem"
679 else
680 openssl x509 -in "${tmpchain}" -inform DER -out "${CERTDIR}/${domain}/chain-${timestamp}.pem" -outform PEM
681 rm "${tmpchain}"
a733f789 682 fi
785ffa55 683 cat "${CERTDIR}/${domain}/chain-${timestamp}.pem" >> "${CERTDIR}/${domain}/fullchain-${timestamp}.pem"
329acb58 684
1446fd88 685 # Update symlinks
785ffa55 686 [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${CERTDIR}/${domain}/privkey.pem"
f343dc11 687
785ffa55
AM
688 ln -sf "chain-${timestamp}.pem" "${CERTDIR}/${domain}/chain.pem"
689 ln -sf "fullchain-${timestamp}.pem" "${CERTDIR}/${domain}/fullchain.pem"
690 ln -sf "cert-${timestamp}.csr" "${CERTDIR}/${domain}/cert.csr"
691 ln -sf "cert-${timestamp}.pem" "${CERTDIR}/${domain}/cert.pem"
f343dc11 692
c24843c6 693 # Wait for hook script to clean the challenge and to deploy cert if used
d5c9dd65 694 export KEY_ALGO
785ffa55 695 [[ -n "${HOOK}" ]] && "${HOOK}" "deploy_cert" "${domain}" "${CERTDIR}/${domain}/privkey.pem" "${CERTDIR}/${domain}/cert.pem" "${CERTDIR}/${domain}/fullchain.pem" "${CERTDIR}/${domain}/chain.pem" "${timestamp}"
c24843c6 696
697 unset challenge_token
579e2316 698 echo " + Done!"
61f0b7ed
LS
699}
700
0a859a19 701# Usage: --cron (-c)
083c6736 702# Description: Sign/renew non-existant/changed/expiring certificates.
8f6c2328 703command_sign_domains() {
9f66bfdb
LS
704 init_system
705
8f6c2328 706 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
1f6a80a0 707 DOMAINS_TXT="$(_mktemp)"
93cd114f 708 printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
a3e5ed36
DB
709 elif [[ -e "${DOMAINS_TXT}" ]]; then
710 if [[ ! -r "${DOMAINS_TXT}" ]]; then
711 _exiterr "domains.txt found but not readable"
712 fi
93cd114f
LS
713 else
714 _exiterr "domains.txt not found and --domain not given"
8f6c2328 715 fi
93cd114f 716
81882a64 717 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
2099c77f
LS
718 ORIGIFS="${IFS}"
719 IFS=$'\n'
5d92c3b3 720 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
ec489069 721 reset_configvars
2099c77f 722 IFS="${ORIGIFS}"
81882a64 723 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
8f6c2328 724 morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
785ffa55 725 cert="${CERTDIR}/${domain}/cert.pem"
f9126627 726
2d097c92
MG
727 force_renew="${PARAM_FORCE:-no}"
728
8f6c2328
MG
729 if [[ -z "${morenames}" ]];then
730 echo "Processing ${domain}"
731 else
93cd114f 732 echo "Processing ${domain} with alternative names: ${morenames}"
8f6c2328
MG
733 fi
734
ec489069
LS
735 # read cert config
736 # for now this loads the certificate specific config in a subshell and parses a diff of set variables.
737 # we could just source the config file but i decided to go this way to protect people from accidentally overriding
738 # variables used internally by this script itself.
44aca90c
MS
739 if [[ -n "${DOMAINS_D}" ]]; then
740 certconfig="${DOMAINS_D}/${domain}"
741 else
742 certconfig="${CERTDIR}/${domain}/config"
743 fi
744
745 if [ -f "${certconfig}" ]; then
ec489069
LS
746 echo " + Using certificate specific config file!"
747 ORIGIFS="${IFS}"
748 IFS=$'\n'
749 for cfgline in $(
750 beforevars="$(_mktemp)"
751 aftervars="$(_mktemp)"
752 set > "${beforevars}"
753 # shellcheck disable=SC1090
44aca90c 754 . "${certconfig}"
ec489069
LS
755 set > "${aftervars}"
756 diff -u "${beforevars}" "${aftervars}" | grep -E '^\+[^+]'
757 rm "${beforevars}"
758 rm "${aftervars}"
759 ); do
760 config_var="$(echo "${cfgline:1}" | cut -d'=' -f1)"
761 config_value="$(echo "${cfgline:1}" | cut -d'=' -f2-)"
762 case "${config_var}" in
a13e4103 763 KEY_ALGO|OCSP_MUST_STAPLE|PRIVATE_KEY_RENEW|PRIVATE_KEY_ROLLOVER|KEYSIZE|CHALLENGETYPE|HOOK|WELLKNOWN|HOOK_CHAIN|OPENSSL_CNF|RENEW_DAYS)
ec489069
LS
764 echo " + ${config_var} = ${config_value}"
765 declare -- "${config_var}=${config_value}"
766 ;;
767 _) ;;
768 *) echo " ! Setting ${config_var} on a per-certificate base is not (yet) supported"
769 esac
770 done
771 IFS="${ORIGIFS}"
772 fi
773 verify_config
774
81882a64 775 if [[ -e "${cert}" ]]; then
93cd114f 776 printf " + Checking domain name(s) of existing cert..."
2d097c92 777
f7c7d8c5
LS
778 certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | _sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//')"
779 givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//' | _sed 's/^ //')"
2d097c92
MG
780
781 if [[ "${certnames}" = "${givennames}" ]]; then
782 echo " unchanged."
783 else
784 echo " changed!"
785 echo " + Domain name(s) are not matching!"
786 echo " + Names in old certificate: ${certnames}"
787 echo " + Configured names: ${givennames}"
788 echo " + Forcing renew."
789 force_renew="yes"
790 fi
791 fi
792
793 if [[ -e "${cert}" ]]; then
794 echo " + Checking expire date of existing cert..."
81882a64 795 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
8221727a 796
93cd114f 797 printf " + Valid till %s " "${valid}"
81882a64 798 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
93cd114f 799 printf "(Longer than %d days). " "${RENEW_DAYS}"
2d097c92
MG
800 if [[ "${force_renew}" = "yes" ]]; then
801 echo "Ignoring because renew was forced!"
8f6c2328 802 else
705fb54e 803 # Certificate-Names unchanged and cert is still valid
dd33de59 804 echo "Skipping renew!"
785ffa55 805 [[ -n "${HOOK}" ]] && "${HOOK}" "unchanged_cert" "${domain}" "${CERTDIR}/${domain}/privkey.pem" "${CERTDIR}/${domain}/cert.pem" "${CERTDIR}/${domain}/fullchain.pem" "${CERTDIR}/${domain}/chain.pem"
8f6c2328
MG
806 continue
807 fi
808 else
809 echo "(Less than ${RENEW_DAYS} days). Renewing!"
81882a64 810 fi
81882a64 811 fi
8221727a 812
81882a64 813 # shellcheck disable=SC2086
34565c19
B
814 if [[ "${PARAM_KEEP_GOING:-}" = "yes" ]]; then
815 sign_domain ${line} &
816 wait $! || true
817 else
818 sign_domain ${line}
819 fi
a7934fe7 820 done
f13eaa7f 821
8f6c2328 822 # remove temporary domains.txt file if used
93cd114f
LS
823 [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
824
825 exit 0
81882a64 826}
3390080c 827
429ec400
NL
828# Usage: --signcsr (-s) path/to/csr.pem
829# Description: Sign a given CSR, output CRT on stdout (advanced usage)
830command_sign_csr() {
831 # redirect stdout to stderr
832 # leave stdout over at fd 3 to output the cert
833 exec 3>&1 1>&2
834
835 init_system
836
837 csrfile="${1}"
838 if [ ! -r "${csrfile}" ]; then
839 _exiterr "Could not read certificate signing request ${csrfile}"
840 fi
841
620c7eb2
LS
842 # gen cert
843 certfile="$(_mktemp)"
844 sign_csr "$(< "${csrfile}" )" 3> "${certfile}"
845
d81eb585 846 # print cert
620c7eb2
LS
847 echo "# CERT #" >&3
848 cat "${certfile}" >&3
849 echo >&3
d81eb585
LS
850
851 # print chain
852 if [ -n "${PARAM_FULL_CHAIN:-}" ]; then
853 # get and convert ca cert
854 chainfile="$(_mktemp)"
7eca8aec
LS
855 tmpchain="$(_mktemp)"
856 http_request get "$(openssl x509 -in "${certfile}" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${tmpchain}"
857 if grep -q "BEGIN CERTIFICATE" "${tmpchain}"; then
858 mv "${tmpchain}" "${chainfile}"
859 else
860 openssl x509 -in "${tmpchain}" -inform DER -out "${chainfile}" -outform PEM
861 rm "${tmpchain}"
d81eb585
LS
862 fi
863
864 echo "# CHAIN #" >&3
865 cat "${chainfile}" >&3
866
867 rm "${chainfile}"
868 fi
620c7eb2
LS
869
870 # cleanup
871 rm "${certfile}"
429ec400
NL
872
873 exit 0
874}
875
0a859a19
LS
876# Usage: --revoke (-r) path/to/cert.pem
877# Description: Revoke specified certificate
81882a64 878command_revoke() {
9f66bfdb
LS
879 init_system
880
3dcfa8b4
LS
881 [[ -n "${CA_REVOKE_CERT}" ]] || _exiterr "Certificate authority doesn't allow certificate revocation."
882
81882a64 883 cert="${1}"
c7018036
MG
884 if [[ -L "${cert}" ]]; then
885 # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
3bc1cf91
LS
886 local link_target
887 link_target="$(readlink -n "${cert}")"
888 if [[ "${link_target}" =~ ^/ ]]; then
c7018036
MG
889 cert="${link_target}"
890 else
891 cert="$(dirname "${cert}")/${link_target}"
892 fi
893 fi
3dcfa8b4
LS
894 [[ -f "${cert}" ]] || _exiterr "Could not find certificate ${cert}"
895
81882a64 896 echo "Revoking ${cert}"
3dcfa8b4 897
81882a64 898 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
561f0626 899 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}' | clean_json)"
3dcfa8b4 900 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
81882a64 901 # so if we are here, it is safe to assume the request was successful
3dcfa8b4
LS
902 echo " + Done."
903 echo " + Renaming certificate to ${cert}-revoked"
81882a64
LS
904 mv -f "${cert}" "${cert}-revoked"
905}
c24843c6 906
e60682c0
LS
907# Usage: --cleanup (-gc)
908# Description: Move unused certificate files to archive directory
909command_cleanup() {
dec95fff
LS
910 load_config
911
e60682c0
LS
912 # Create global archive directory if not existant
913 if [[ ! -e "${BASEDIR}/archive" ]]; then
914 mkdir "${BASEDIR}/archive"
915 fi
916
917 # Loop over all certificate directories
785ffa55 918 for certdir in "${CERTDIR}/"*; do
f9430025
JB
919 # Skip if entry is not a folder
920 [[ -d "${certdir}" ]] || continue
921
e60682c0
LS
922 # Get certificate name
923 certname="$(basename "${certdir}")"
924
925 # Create certitifaces archive directory if not existant
926 archivedir="${BASEDIR}/archive/${certname}"
927 if [[ ! -e "${archivedir}" ]]; then
928 mkdir "${archivedir}"
929 fi
930
931 # Loop over file-types (certificates, keys, signing-requests, ...)
932 for filetype in cert.csr cert.pem chain.pem fullchain.pem privkey.pem; do
933 # Skip if symlink is broken
934 [[ -r "${certdir}/${filetype}" ]] || continue
935
936 # Look up current file in use
5c68c221 937 current="$(basename "$(readlink "${certdir}/${filetype}")")"
e60682c0
LS
938
939 # Split filetype into name and extension
940 filebase="$(echo "${filetype}" | cut -d. -f1)"
941 fileext="$(echo "${filetype}" | cut -d. -f2)"
942
943 # Loop over all files of this type
944 for file in "${certdir}/${filebase}-"*".${fileext}"; do
ac2d8303
JB
945 # Handle case where no files match the wildcard
946 [[ -f "${file}" ]] || break
947
e60682c0
LS
948 # Check if current file is in use, if unused move to archive directory
949 filename="$(basename "${file}")"
950 if [[ ! "${filename}" = "${current}" ]]; then
5c68c221 951 echo "Moving unused file to archive directory: ${certname}/${filename}"
e60682c0
LS
952 mv "${certdir}/${filename}" "${archivedir}/${filename}"
953 fi
954 done
955 done
956 done
957
958 exit 0
959}
960
0a859a19
LS
961# Usage: --help (-h)
962# Description: Show help text
81882a64 963command_help() {
7727f5ea
LS
964 printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
965 printf "Default command: help\n\n"
0a859a19 966 echo "Commands:"
760b6894 967 grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
31111265 968 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
7727f5ea 969 _exiterr "Error generating help text."
0a859a19 970 fi
7727f5ea 971 printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
0a859a19 972 done
7727f5ea 973 printf -- "\nParameters:\n"
760b6894 974 grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
31111265 975 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
7727f5ea 976 _exiterr "Error generating help text."
0a859a19 977 fi
7727f5ea 978 printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
0a859a19 979 done
81882a64 980}
063d28a6 981
1ab6a436
LS
982# Usage: --env (-e)
983# Description: Output configuration variables for use in other scripts
984command_env() {
ec49a443 985 echo "# dehydrated configuration"
9f66bfdb 986 load_config
44aca90c 987 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
1ab6a436
LS
988}
989
bc580335 990# Main method (parses script arguments and calls command_* methods)
9f66bfdb
LS
991main() {
992 COMMAND=""
993 set_command() {
994 [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
995 COMMAND="${1}"
996 }
997
998 check_parameters() {
999 if [[ -z "${1:-}" ]]; then
1000 echo "The specified command requires additional parameters. See help:" >&2
31111265
LS
1001 echo >&2
1002 command_help >&2
81882a64 1003 exit 1
9f66bfdb
LS
1004 elif [[ "${1:0:1}" = "-" ]]; then
1005 _exiterr "Invalid argument: ${1}"
1006 fi
1007 }
579e2316 1008
2a7b4882 1009 [[ -z "${@}" ]] && eval set -- "--help"
fb0242a4 1010
da2eeda9 1011 while (( ${#} )); do
9f66bfdb
LS
1012 case "${1}" in
1013 --help|-h)
1014 command_help
1015 exit 0
1016 ;;
579e2316 1017
9f66bfdb
LS
1018 --env|-e)
1019 set_command env
1020 ;;
579e2316 1021
9f66bfdb
LS
1022 --cron|-c)
1023 set_command sign_domains
1024 ;;
1025
429ec400
NL
1026 --signcsr|-s)
1027 shift 1
1028 set_command sign_csr
1029 check_parameters "${1:-}"
1030 PARAM_CSR="${1}"
1031 ;;
1032
9f66bfdb
LS
1033 --revoke|-r)
1034 shift 1
1035 set_command revoke
1036 check_parameters "${1:-}"
1037 PARAM_REVOKECERT="${1}"
1038 ;;
5060dea0 1039
e60682c0
LS
1040 --cleanup|-gc)
1041 set_command cleanup
1042 ;;
1043
d81eb585
LS
1044 # PARAM_Usage: --full-chain (-fc)
1045 # PARAM_Description: Print full chain when using --signcsr
1046 --full-chain|-fc)
1047 PARAM_FULL_CHAIN="1"
1048 ;;
1049
364bcccf 1050 # PARAM_Usage: --ipv4 (-4)
1051 # PARAM_Description: Resolve names to IPv4 addresses only
1052 --ipv4|-4)
1053 PARAM_IP_VERSION="4"
1054 ;;
1055
1056 # PARAM_Usage: --ipv6 (-6)
1057 # PARAM_Description: Resolve names to IPv6 addresses only
1058 --ipv6|-6)
1059 PARAM_IP_VERSION="6"
1060 ;;
1061
8f6c2328 1062 # PARAM_Usage: --domain (-d) domain.tld
9f66bfdb
LS
1063 # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
1064 --domain|-d)
1065 shift 1
1066 check_parameters "${1:-}"
1067 if [[ -z "${PARAM_DOMAIN:-}" ]]; then
1068 PARAM_DOMAIN="${1}"
1069 else
1070 PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
1071 fi
1072 ;;
1073
34565c19
B
1074 # PARAM_Usage: --keep-going (-g)
1075 # PARAM_Description: Keep going after encountering an error while creating/renewing multiple certificates in cron mode
1076 --keep-going|-g)
1077 PARAM_KEEP_GOING="yes"
1078 ;;
1079
8f6c2328 1080 # PARAM_Usage: --force (-x)
9f66bfdb
LS
1081 # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
1082 --force|-x)
1083 PARAM_FORCE="yes"
1084 ;;
1085
bd9cc5b0
LS
1086 # PARAM_Usage: --no-lock (-n)
1087 # PARAM_Description: Don't use lockfile (potentially dangerous!)
1088 --no-lock|-n)
1089 PARAM_NO_LOCK="yes"
1090 ;;
1091
8456855e
E
1092 # PARAM_Usage: --lock-suffix example.com
1093 # PARAM_Description: Suffix lockfile name with a string (useful for with -d)
1094 --lock-suffix)
1095 shift 1
1096 check_parameters "${1:-}"
1097 PARAM_LOCKFILE_SUFFIX="${1}"
1098 ;;
1099
8e77ba5e
LS
1100 # PARAM_Usage: --ocsp
1101 # PARAM_Description: Sets option in CSR indicating OCSP stapling to be mandatory
1102 --ocsp)
1103 PARAM_OCSP_MUST_STAPLE="yes"
1104 ;;
1105
0a859a19
LS
1106 # PARAM_Usage: --privkey (-p) path/to/key.pem
1107 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
9f66bfdb
LS
1108 --privkey|-p)
1109 shift 1
1110 check_parameters "${1:-}"
8aa1a05b 1111 PARAM_ACCOUNT_KEY="${1}"
9f66bfdb
LS
1112 ;;
1113
d5b28586 1114 # PARAM_Usage: --config (-f) path/to/config
9f66bfdb
LS
1115 # PARAM_Description: Use specified config file
1116 --config|-f)
1117 shift 1
1118 check_parameters "${1:-}"
1119 CONFIG="${1}"
1120 ;;
1121
ed27e013
MG
1122 # PARAM_Usage: --hook (-k) path/to/hook.sh
1123 # PARAM_Description: Use specified script for hooks
1124 --hook|-k)
1125 shift 1
1126 check_parameters "${1:-}"
1127 PARAM_HOOK="${1}"
1128 ;;
1129
785ffa55
AM
1130 # PARAM_Usage: --out (-o) certs/directory
1131 # PARAM_Description: Output certificates into the specified directory
1132 --out|-o)
1133 shift 1
1134 check_parameters "${1:-}"
1135 PARAM_CERTDIR="${1}"
1136 ;;
1137
e925b293
MG
1138 # PARAM_Usage: --challenge (-t) http-01|dns-01
1139 # PARAM_Description: Which challenge should be used? Currently http-01 and dns-01 are supported
1140 --challenge|-t)
1141 shift 1
1142 check_parameters "${1:-}"
1143 PARAM_CHALLENGETYPE="${1}"
1144 ;;
1145
c71ca3a8
MG
1146 # PARAM_Usage: --algo (-a) rsa|prime256v1|secp384r1
1147 # PARAM_Description: Which public key algorithm should be used? Supported: rsa, prime256v1 and secp384r1
1148 --algo|-a)
1149 shift 1
1150 check_parameters "${1:-}"
1151 PARAM_KEY_ALGO="${1}"
1152 ;;
1153
9f66bfdb
LS
1154 *)
1155 echo "Unknown parameter detected: ${1}" >&2
1156 echo >&2
1157 command_help >&2
1158 exit 1
1159 ;;
1160 esac
1161
1162 shift 1
1163 done
1164
1165 case "${COMMAND}" in
1166 env) command_env;;
1167 sign_domains) command_sign_domains;;
429ec400 1168 sign_csr) command_sign_csr "${PARAM_CSR}";;
9f66bfdb 1169 revoke) command_revoke "${PARAM_REVOKECERT}";;
e60682c0 1170 cleanup) command_cleanup;;
7191ed25 1171 *) command_help; exit 1;;
81882a64 1172 esac
9f66bfdb 1173}
81882a64 1174
c3c9ff4c
LS
1175# Determine OS type
1176OSTYPE="$(uname)"
1177
9f66bfdb
LS
1178# Check for missing dependencies
1179check_dependencies
1180
1181# Run script
1182main "${@:-}"