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