]> git.street.me.uk Git - andy/dehydrated.git/blame - letsencrypt.sh
Edit test according to unchanged-certificate hook.
[andy/dehydrated.git] / letsencrypt.sh
CommitLineData
2e8454b4 1#!/usr/bin/env bash
a1a9c8a4
LS
2
3# letsencrypt.sh by lukas2511
4# Source: https://github.com/lukas2511/letsencrypt.sh
5
69f3e78b
LS
6set -e
7set -u
8set -o pipefail
da2eeda9 9[[ -n "${ZSH_VERSION:-}" ]] && set -o SH_WORD_SPLIT && set +o FUNCTION_ARGZERO
81882a64 10umask 077 # paranoid umask, we're creating private keys
61f0b7ed 11
0c429af9
VH
12# duplicate scripts IO handles
13exec 4<&0 5>&1 6>&2
14
85a25b56
LS
15# Find directory in which this script is stored by traversing all symbolic links
16SOURCE="${0}"
17while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
18 DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
19 SOURCE="$(readlink "$SOURCE")"
20 [[ $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
21done
22SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
23
0e92aba2
MG
24BASEDIR="${SCRIPTDIR}"
25
bc580335 26# Check for script dependencies
9f66bfdb 27check_dependencies() {
0af7f388 28 # just execute some dummy and/or version commands to see if required tools exist and are actually usable
115041cd 29 openssl version > /dev/null 2>&1 || _exiterr "This script requires an openssl binary."
f7c7d8c5 30 _sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requires sed with support for extended (modern) regular expressions."
115041cd 31 grep -V > /dev/null 2>&1 || _exiterr "This script requires grep."
d6ce8823 32 mktemp -u -t XXXXXX > /dev/null 2>&1 || _exiterr "This script requires mktemp."
0af7f388
LS
33
34 # curl returns with an error code in some ancient versions so we have to catch that
35 set +e
36 curl -V > /dev/null 2>&1
0af7f388 37 retcode="$?"
36a03146 38 set -e
0af7f388
LS
39 if [[ ! "${retcode}" = "0" ]] && [[ ! "${retcode}" = "2" ]]; then
40 _exiterr "This script requires curl."
41 fi
9f66bfdb
LS
42}
43
ff116396
LS
44# Setup default config values, search for and load configuration files
45load_config() {
00810795
LS
46 # Check for config in various locations
47 if [[ -z "${CONFIG:-}" ]]; then
48 for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
49 if [[ -e "${check_config}/config.sh" ]]; then
50 BASEDIR="${check_config}"
51 CONFIG="${check_config}/config.sh"
52 break
53 fi
54 done
55 fi
56
ff116396
LS
57 # Default values
58 CA="https://acme-v01.api.letsencrypt.org/directory"
59 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
de173892 60 CHALLENGETYPE="http-01"
a1cb7ccc 61 CONFIG_D=
ff116396 62 HOOK=
6e048f7f 63 HOOK_CHAIN="no"
30ad9584 64 RENEW_DAYS="30"
9baf3532 65 PRIVATE_KEY=
ff116396 66 KEYSIZE="4096"
9baf3532 67 WELLKNOWN=
ff116396 68 PRIVATE_KEY_RENEW="no"
c71ca3a8 69 KEY_ALGO=rsa
f0323faf 70 OPENSSL_CNF="$(openssl version -d | cut -d\" -f2)/openssl.cnf"
ff116396 71 CONTACT_EMAIL=
9baf3532 72 LOCKFILE=
1e33cfe5 73
81882a64 74 if [[ -z "${CONFIG:-}" ]]; then
ff116396 75 echo "#" >&2
a1cb7ccc 76 echo "# !! WARNING !! No main config file found, using default config!" >&2
ff116396 77 echo "#" >&2
81882a64 78 elif [[ -e "${CONFIG}" ]]; then
a1cb7ccc 79 echo "# INFO: Using main config file ${CONFIG}"
81882a64
LS
80 BASEDIR="$(dirname "${CONFIG}")"
81 # shellcheck disable=SC1090
82 . "${CONFIG}"
83 else
f06f764f 84 _exiterr "Specified config file doesn't exist."
81882a64 85 fi
61f0b7ed 86
a1cb7ccc
DB
87 if [[ -n "${CONFIG_D}" ]]; then
88 if [[ ! -d "${CONFIG_D}" ]]; then
89 _exiterr "The path ${CONFIG_D} specified for CONFIG_D does not point to a directory." >&2
90 fi
91
92 for check_config_d in ${CONFIG_D}/*.sh; do
93 if [[ ! -e "${check_config_d}" ]]; then
94 echo "# !! WARNING !! Extra configuration directory ${CONFIG_D} exists, but no configuration found in it." >&2
95 break
96 elif [[ -f "${check_config_d}" ]] && [[ -r "${check_config_d}" ]]; then
97 echo "# INFO: Using additional config file ${check_config_d}"
98 . ${check_config_d}
99 else
100 _exiterr "Specified additional config ${check_config_d} is not readable or not a file at all." >&2
101 fi
102 done
103 fi
104
81882a64
LS
105 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
106 BASEDIR="${BASEDIR%%/}"
401f5f75 107
1e33cfe5 108 # Check BASEDIR and set default variables
f06f764f 109 [[ -d "${BASEDIR}" ]] || _exiterr "BASEDIR does not exist: ${BASEDIR}"
ed27e013 110
9baf3532
DB
111 [[ -z "${PRIVATE_KEY}" ]] && PRIVATE_KEY="${BASEDIR}/private_key.pem"
112 [[ -z "${WELLKNOWN}" ]] && WELLKNOWN="${BASEDIR}/.acme-challenges"
113 [[ -z "${LOCKFILE}" ]] && LOCKFILE="${BASEDIR}/lock"
114
de173892
LS
115 [[ -n "${PARAM_HOOK:-}" ]] && HOOK="${PARAM_HOOK}"
116 [[ -n "${PARAM_CHALLENGETYPE:-}" ]] && CHALLENGETYPE="${PARAM_CHALLENGETYPE}"
c71ca3a8 117 [[ -n "${PARAM_KEY_ALGO:-}" ]] && KEY_ALGO="${PARAM_KEY_ALGO}"
e925b293 118
de173892 119 [[ "${CHALLENGETYPE}" =~ (http-01|dns-01) ]] || _exiterr "Unknown challenge type ${CHALLENGETYPE}... can not continue."
e925b293 120 if [[ "${CHALLENGETYPE}" = "dns-01" ]] && [[ -z "${HOOK}" ]]; then
de173892 121 _exiterr "Challenge type dns-01 needs a hook script for deployment... can not continue."
e925b293 122 fi
c71ca3a8 123 [[ "${KEY_ALGO}" =~ ^(rsa|prime256v1|secp384r1)$ ]] || _exiterr "Unknown public key algorithm ${KEY_ALGO}... can not continue."
ff116396
LS
124}
125
93cd114f 126# Initialize system
ff116396
LS
127init_system() {
128 load_config
81882a64 129
1e33cfe5 130 # Lockfile handling (prevents concurrent access)
291b9f24 131 LOCKDIR="$(dirname "${LOCKFILE}")"
61ba0daf 132 [[ -w "${LOCKDIR}" ]] || _exiterr "Directory ${LOCKDIR} for LOCKFILE ${LOCKFILE} is not writable, aborting."
93cd114f
LS
133 ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
134 remove_lock() { rm -f "${LOCKFILE}"; }
81882a64
LS
135 trap 'remove_lock' EXIT
136
81882a64 137 # Get CA URLs
3a9e97f9 138 CA_DIRECTORY="$(http_request get "${CA}")"
81882a64
LS
139 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
140 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
141 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
10d9f342 142 # shellcheck disable=SC2015
81882a64 143 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
93cd114f 144 _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
81882a64 145
93cd114f
LS
146 # Export some environment variables to be used in hook script
147 export WELLKNOWN BASEDIR CONFIG
0e92aba2 148
93cd114f
LS
149 # Checking for private key ...
150 register_new_key="no"
0e92aba2
MG
151 if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
152 # a private key was specified from the command line so use it for this run
10d9f342 153 echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
0e92aba2 154 PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
0e92aba2
MG
155 else
156 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
0e92aba2 157 if [[ ! -e "${PRIVATE_KEY}" ]]; then
81882a64 158 echo "+ Generating account key..."
0e92aba2 159 _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
93cd114f 160 register_new_key="yes"
81882a64 161 fi
81882a64 162 fi
93cd114f 163 openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Private key is not valid, can not continue."
1ab6a436 164
81882a64 165 # Get public components from private key and calculate thumbprint
f70f3048
LS
166 pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
167 pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
81882a64 168
21c18dd3 169 thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl dgst -sha256 -binary | urlbase64)"
81882a64
LS
170
171 # If we generated a new private key in the step above we have to register it with the acme-server
93cd114f 172 if [[ "${register_new_key}" = "yes" ]]; then
81882a64 173 echo "+ Registering account key with letsencrypt..."
93cd114f
LS
174 [[ ! -z "${CA_NEW_REG}" ]] || _exiterr "Certificate authority doesn't allow registrations."
175 # If an email for the contact has been provided then adding it to the registration request
81882a64
LS
176 if [[ -n "${CONTACT_EMAIL}" ]]; then
177 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
178 else
179 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
180 fi
181 fi
181dd0ff 182
d9de894c
JTM
183 if [[ "${CHALLENGETYPE}" = "http-01" && ! -d "${WELLKNOWN}" ]]; then
184 _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
185 fi
81882a64 186}
c24843c6 187
f7c7d8c5
LS
188# Different sed version for different os types...
189_sed() {
c3c9ff4c 190 if [[ "${OSTYPE}" = "Linux" ]]; then
f7c7d8c5
LS
191 sed -r "${@}"
192 else
193 sed -E "${@}"
194 fi
195}
196
9f66bfdb
LS
197# Print error message and exit with error
198_exiterr() {
199 echo "ERROR: ${1}" >&2
200 exit 1
201}
202
994803bf 203# Encode data as url-safe formatted base64
61f0b7ed 204urlbase64() {
c6e60302 205 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
f7c7d8c5 206 openssl base64 -e | tr -d '\n\r' | _sed -e 's:=*$::g' -e 'y:+/:-_:'
61f0b7ed 207}
91ce50af 208
16bef17e 209# Convert hex string to binary data
9fe313d8 210hex2bin() {
16bef17e 211 # Remove spaces, add leading zero, escape as hex string and parse with printf
f7c7d8c5 212 printf -- "$(cat | _sed -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
9fe313d8 213}
61f0b7ed 214
bc580335 215# Get string value from json dictionary
09729186 216get_json_string_value() {
760b6894 217 grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
09729186
LS
218}
219
cc605a22
LS
220# OpenSSL writes to stderr/stdout even when there are no errors. So just
221# display the output if the exit code was != 0 to simplify debugging.
222_openssl() {
223 set +e
224 out="$(openssl "${@}" 2>&1)"
225 res=$?
226 set -e
39c01fd7
LS
227 if [[ ${res} -ne 0 ]]; then
228 echo " + ERROR: failed to run $* (Exitcode: ${res})" >&2
cc605a22
LS
229 echo >&2
230 echo "Details:" >&2
39c01fd7 231 echo "${out}" >&2
676d15c5 232 echo >&2
39c01fd7 233 exit ${res}
cc605a22
LS
234 fi
235}
236
59f16407 237# Send http(s) request with specified method
3a9e97f9 238http_request() {
d6ce8823 239 tempcont="$(mktemp -t XXXXXX)"
3cb292cb 240
1233dc95 241 set +e
dd5f36e5 242 if [[ "${1}" = "head" ]]; then
3cb292cb 243 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
1233dc95 244 curlret="${?}"
dd5f36e5 245 elif [[ "${1}" = "get" ]]; then
3cb292cb 246 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
1233dc95 247 curlret="${?}"
dd5f36e5 248 elif [[ "${1}" = "post" ]]; then
3cb292cb 249 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
1233dc95 250 curlret="${?}"
59f16407 251 else
1233dc95 252 set -e
59f16407 253 _exiterr "Unknown request method: ${1}"
91ce50af 254 fi
1233dc95
LS
255 set -e
256
257 if [[ ! "${curlret}" = "0" ]]; then
258 _exiterr "Problem connecting to server (curl returned with ${curlret})"
259 fi
dd5f36e5 260
3cb292cb 261 if [[ ! "${statuscode:0:1}" = "2" ]]; then
84fac541 262 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
3cb292cb
LS
263 echo >&2
264 echo "Details:" >&2
9e79c066 265 cat "${tempcont}" >&2
3cb292cb 266 rm -f "${tempcont}"
c24843c6 267
268 # Wait for hook script to clean the challenge if used
676d15c5 269 if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token:+set}" ]]; then
2099c77f 270 "${HOOK}" "clean_challenge" '' "${challenge_token}" "${keyauth}"
c24843c6 271 fi
272
8f6c2328 273 # remove temporary domains.txt file if used
79ff846e 274 [[ -n "${PARAM_DOMAIN:-}" && -n "${DOMAINS_TXT:-}" ]] && rm "${DOMAINS_TXT}"
dd5f36e5 275 exit 1
130ea6ab 276 fi
dd5f36e5 277
31111265 278 cat "${tempcont}"
3cb292cb 279 rm -f "${tempcont}"
91ce50af 280}
81882a64 281
1446fd88 282# Send signed request
61f0b7ed 283signed_request() {
c6e60302 284 # Encode payload as urlbase64
4aa48d33 285 payload64="$(printf '%s' "${2}" | urlbase64)"
61f0b7ed 286
c6e60302 287 # Retrieve nonce from acme-server
994803bf 288 nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
61f0b7ed 289
c6e60302 290 # Build header with just our public key and algorithm information
61f0b7ed
LS
291 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
292
c6e60302 293 # Build another header which also contains the previously received nonce and encode it as urlbase64
61f0b7ed 294 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
4aa48d33 295 protected64="$(printf '%s' "${protected}" | urlbase64)"
61f0b7ed 296
c6e60302 297 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
0e92aba2 298 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
61f0b7ed 299
c6e60302 300 # Send header + extended header + payload + signature to the acme-server
61f0b7ed
LS
301 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
302
3a9e97f9 303 http_request post "${1}" "${data}"
61f0b7ed
LS
304}
305
a62968c9
NL
306# Extracts all subject names from a CSR
307# Outputs either the CN, or the SANs, one per line
308extract_altnames() {
309 csr="${1}" # the CSR itself (not a file)
81882a64 310
a62968c9
NL
311 if ! <<<"${csr}" openssl req -verify -noout 2>/dev/null; then
312 _exiterr "Certificate signing request isn't valid"
09729186 313 fi
3cc587c2 314
a62968c9 315 reqtext="$( <<<"${csr}" openssl req -noout -text )"
39c01fd7 316 if <<<"${reqtext}" grep -q '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$'; then
a62968c9
NL
317 # SANs used, extract these
318 altnames="$( <<<"${reqtext}" grep -A1 '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$' | tail -n1 )"
319 # split to one per line:
34f94322 320 altnames="$( <<<"${altnames}" _sed -e 's/^[[:space:]]*//; s/, /\'$'\n''/g' )"
a62968c9
NL
321 # we can only get DNS: ones signed
322 if [ -n "$( <<<"${altnames}" grep -v '^DNS:' )" ]; then
323 _exiterr "Certificate signing request contains non-DNS Subject Alternative Names"
324 fi
325 # strip away the DNS: prefix
326 altnames="$( <<<"${altnames}" _sed -e 's/^DNS://' )"
39c01fd7 327 echo "${altnames}"
a62968c9
NL
328
329 else
330 # No SANs, extract CN
331 altnames="$( <<<"${reqtext}" grep '^[[:space:]]*Subject:' | _sed -e 's/.* CN=([^ /,]*).*/\1/' )"
39c01fd7 332 echo "${altnames}"
3dbbb461 333 fi
a62968c9 334}
3dbbb461 335
50e7a072
NL
336# Create certificate for domain(s) and outputs it FD 3
337sign_csr() {
338 csr="${1}" # the CSR itself (not a file)
81882a64 339
50e7a072
NL
340 if { true >&3; } 2>/dev/null; then
341 : # fd 3 looks OK
342 else
343 _exiterr "sign_csr: FD 3 not open"
61f0b7ed
LS
344 fi
345
50e7a072
NL
346 shift 1 || true
347 altnames="${*:-}"
39c01fd7
LS
348 if [ -z "${altnames}" ]; then
349 altnames="$( extract_altnames "${csr}" )"
a62968c9 350 fi
3dbbb461 351
50e7a072
NL
352 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
353 _exiterr "Certificate authority doesn't allow certificate signing"
61f0b7ed 354 fi
c6e60302 355
6e048f7f 356 local idx=0
da2eeda9
LS
357 if [[ -n "${ZSH_VERSION:-}" ]]; then
358 local -A challenge_uris challenge_tokens keyauths deploy_args
359 else
360 local -a challenge_uris challenge_tokens keyauths deploy_args
361 fi
39c01fd7 362
6e048f7f 363 # Request challenges
1446fd88 364 for altname in ${altnames}; do
c6e60302 365 # Ask the acme-server for new challenge token and extract them from the resulting json block
579e2316 366 echo " + Requesting challenge for ${altname}..."
09729186 367 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
61f0b7ed 368
1446fd88 369 challenges="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]')"
526843d6 370 repl=$'\n''{' # fix syntax highlighting in Vim
e925b293 371 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep \""${CHALLENGETYPE}"\")"
f7c7d8c5 372 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | _sed 's/[^A-Za-z0-9_\-]/_/g')"
09729186 373 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
61f0b7ed 374
dd5f36e5 375 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
1446fd88 376 _exiterr "Can't retrieve challenges (${response})"
abb95693
LS
377 fi
378
c6e60302 379 # Challenge response consists of the challenge token and the thumbprint of our public certificate
61f0b7ed
LS
380 keyauth="${challenge_token}.${thumbprint}"
381
de173892
LS
382 case "${CHALLENGETYPE}" in
383 "http-01")
384 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
385 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
386 chmod a+r "${WELLKNOWN}/${challenge_token}"
387 keyauth_hook="${keyauth}"
388 ;;
389 "dns-01")
390 # Generate DNS entry content for dns-01 validation
21c18dd3 391 keyauth_hook="$(printf '%s' "${keyauth}" | openssl dgst -sha256 -binary | urlbase64)"
de173892
LS
392 ;;
393 esac
61f0b7ed 394
39c01fd7
LS
395 challenge_uris[${idx}]="${challenge_uri}"
396 keyauths[${idx}]="${keyauth}"
397 challenge_tokens[${idx}]="${challenge_token}"
6e048f7f 398 # Note: assumes args will never have spaces!
39c01fd7 399 deploy_args[${idx}]="${altname} ${challenge_token} ${keyauth_hook}"
6e048f7f
GD
400 idx=$((idx+1))
401 done
402
403 # Wait for hook script to deploy the challenges if used
2099c77f 404 [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[@]}
6e048f7f
GD
405
406 # Respond to challenges
407 idx=0
408 for altname in ${altnames}; do
39c01fd7
LS
409 challenge_token="${challenge_tokens[${idx}]}"
410 keyauth="${keyauths[${idx}]}"
6e048f7f 411
b33f1288 412 # Wait for hook script to deploy the challenge if used
2099c77f 413 [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[${idx}]}
b33f1288 414
1446fd88 415 # Ask the acme-server to verify our challenge and wait until it is no longer pending
579e2316 416 echo " + Responding to challenge for ${altname}..."
39c01fd7 417 result="$(signed_request "${challenge_uris[${idx}]}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
61f0b7ed 418
da2eeda9 419 reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
61f0b7ed 420
da2eeda9 421 while [[ "${reqstatus}" = "pending" ]]; do
c6e60302 422 sleep 1
39c01fd7 423 result="$(http_request get "${challenge_uris[${idx}]}")"
da2eeda9 424 reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
61f0b7ed
LS
425 done
426
de173892 427 [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_token}"
81882a64 428
ab301951 429 # Wait for hook script to clean the challenge if used
6e048f7f 430 if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token}" ]]; then
2099c77f 431 "${HOOK}" "clean_challenge" ${deploy_args[${idx}]}
ab301951 432 fi
6e048f7f 433 idx=$((idx+1))
81882a64 434
da2eeda9 435 if [[ "${reqstatus}" = "valid" ]]; then
579e2316 436 echo " + Challenge is valid!"
76a37834 437 else
6e048f7f 438 break
76a37834 439 fi
61f0b7ed
LS
440 done
441
6e048f7f 442 # Wait for hook script to clean the challenges if used
75be937a 443 [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "clean_challenge" ${deploy_args[@]}
6e048f7f 444
da2eeda9 445 if [[ "${reqstatus}" != "valid" ]]; then
6e048f7f
GD
446 # Clean up any remaining challenge_tokens if we stopped early
447 if [[ "${CHALLENGETYPE}" = "http-01" ]]; then
39c01fd7
LS
448 while [ ${idx} -lt ${#challenge_tokens[@]} ]; do
449 rm -f "${WELLKNOWN}/${challenge_tokens[${idx}]}"
6e048f7f
GD
450 idx=$((idx+1))
451 done
452 fi
453
da2eeda9 454 _exiterr "Challenge is invalid! (returned: ${reqstatus}) (result: ${result})"
6e048f7f
GD
455 fi
456
b7439a83 457 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
579e2316 458 echo " + Requesting certificate..."
50e7a072 459 csr64="$( <<<"${csr}" openssl req -outform DER | urlbase64)"
09729186 460 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
50e7a072 461 crt="$( printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" )"
1446fd88
LS
462
463 # Try to load the certificate to detect corruption
a4e7c43a 464 echo " + Checking certificate..."
50e7a072
NL
465 _openssl x509 -text <<<"${crt}"
466
467 echo "${crt}" >&3
468
469 unset challenge_token
470 echo " + Done!"
471}
472
473# Create certificate for domain(s)
474sign_domain() {
475 domain="${1}"
476 altnames="${*}"
477 timestamp="$(date +%s)"
478
479 echo " + Signing domains..."
480 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
481 _exiterr "Certificate authority doesn't allow certificate signing"
482 fi
483
484 # If there is no existing certificate directory => make it
485 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
486 echo " + Creating new directory ${BASEDIR}/certs/${domain} ..."
487 mkdir -p "${BASEDIR}/certs/${domain}"
488 fi
489
490 privkey="privkey.pem"
491 # generate a new private key if we need or want one
5c189483 492 if [[ ! -r "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
50e7a072
NL
493 echo " + Generating private key..."
494 privkey="privkey-${timestamp}.pem"
495 case "${KEY_ALGO}" in
496 rsa) _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}";;
497 prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem";;
498 esac
499 fi
500
501 # Generate signing request config and the actual signing request
502 echo " + Generating signing request..."
503 SAN=""
504 for altname in ${altnames}; do
505 SAN+="DNS:${altname}, "
506 done
507 SAN="${SAN%%, }"
508 local tmp_openssl_cnf
509 tmp_openssl_cnf="$(mktemp -t XXXXXX)"
510 cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
511 printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
512 openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
513 rm -f "${tmp_openssl_cnf}"
514
515 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
516 sign_csr "$(< "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" )" ${altnames} 3>"${crt_path}"
329acb58
LS
517
518 # Create fullchain.pem
1eb6f6d2
LS
519 echo " + Creating fullchain.pem..."
520 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
3a9e97f9 521 http_request get "$(openssl x509 -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"
1446fd88 522 if ! grep -q "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"; then
a733f789
LS
523 openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
524 fi
a733f789 525 cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
329acb58 526
1446fd88
LS
527 # Update symlinks
528 [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
f343dc11 529
1446fd88
LS
530 ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
531 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
3f6ff8f7
SR
532 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
533 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
f343dc11 534
c24843c6 535 # Wait for hook script to clean the challenge and to deploy cert if used
2099c77f 536 [[ -n "${HOOK}" ]] && "${HOOK}" "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem" "${BASEDIR}/certs/${domain}/chain.pem"
c24843c6 537
538 unset challenge_token
579e2316 539 echo " + Done!"
61f0b7ed
LS
540}
541
0a859a19 542# Usage: --cron (-c)
083c6736 543# Description: Sign/renew non-existant/changed/expiring certificates.
8f6c2328 544command_sign_domains() {
9f66bfdb
LS
545 init_system
546
8f6c2328 547 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
d6ce8823 548 DOMAINS_TXT="$(mktemp -t XXXXXX)"
93cd114f
LS
549 printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
550 elif [[ -e "${BASEDIR}/domains.txt" ]]; then
551 DOMAINS_TXT="${BASEDIR}/domains.txt"
552 else
553 _exiterr "domains.txt not found and --domain not given"
8f6c2328 554 fi
93cd114f 555
81882a64 556 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
2099c77f
LS
557 ORIGIFS="${IFS}"
558 IFS=$'\n'
559 for line in $(cat "${DOMAINS_TXT}" | tr -d '\r' | _sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e 's/[[:space:]]+/ /g' | (grep -vE '^(#|$)' || true)); do
560 IFS="${ORIGIFS}"
81882a64 561 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
8f6c2328 562 morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
81882a64 563 cert="${BASEDIR}/certs/${domain}/cert.pem"
f9126627 564
2d097c92
MG
565 force_renew="${PARAM_FORCE:-no}"
566
8f6c2328
MG
567 if [[ -z "${morenames}" ]];then
568 echo "Processing ${domain}"
569 else
93cd114f 570 echo "Processing ${domain} with alternative names: ${morenames}"
8f6c2328
MG
571 fi
572
81882a64 573 if [[ -e "${cert}" ]]; then
93cd114f 574 printf " + Checking domain name(s) of existing cert..."
2d097c92 575
f7c7d8c5
LS
576 certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | _sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//')"
577 givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//' | _sed 's/^ //')"
2d097c92
MG
578
579 if [[ "${certnames}" = "${givennames}" ]]; then
580 echo " unchanged."
581 else
582 echo " changed!"
583 echo " + Domain name(s) are not matching!"
584 echo " + Names in old certificate: ${certnames}"
585 echo " + Configured names: ${givennames}"
586 echo " + Forcing renew."
587 force_renew="yes"
588 fi
589 fi
590
591 if [[ -e "${cert}" ]]; then
592 echo " + Checking expire date of existing cert..."
81882a64 593 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
8221727a 594
93cd114f 595 printf " + Valid till %s " "${valid}"
81882a64 596 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
93cd114f 597 printf "(Longer than %d days). " "${RENEW_DAYS}"
2d097c92
MG
598 if [[ "${force_renew}" = "yes" ]]; then
599 echo "Ignoring because renew was forced!"
8f6c2328 600 else
705fb54e 601 # Certificate-Names unchanged and cert is still valid
602 echo "Skipping renew! Calling unchanged-hook."
603 [[ -n "${HOOK}" ]] && "${HOOK}" "unchanged_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem" "${BASEDIR}/certs/${domain}/chain.pem"
8f6c2328
MG
604 continue
605 fi
606 else
607 echo "(Less than ${RENEW_DAYS} days). Renewing!"
81882a64 608 fi
81882a64 609 fi
8221727a 610
81882a64 611 # shellcheck disable=SC2086
93cd114f 612 sign_domain ${line}
a7934fe7 613 done
f13eaa7f 614
8f6c2328 615 # remove temporary domains.txt file if used
93cd114f
LS
616 [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
617
618 exit 0
81882a64 619}
3390080c 620
429ec400
NL
621# Usage: --signcsr (-s) path/to/csr.pem
622# Description: Sign a given CSR, output CRT on stdout (advanced usage)
623command_sign_csr() {
624 # redirect stdout to stderr
625 # leave stdout over at fd 3 to output the cert
626 exec 3>&1 1>&2
627
628 init_system
629
630 csrfile="${1}"
631 if [ ! -r "${csrfile}" ]; then
632 _exiterr "Could not read certificate signing request ${csrfile}"
633 fi
634
635 sign_csr "$(< "${csrfile}" )"
636
637 exit 0
638}
639
0a859a19
LS
640# Usage: --revoke (-r) path/to/cert.pem
641# Description: Revoke specified certificate
81882a64 642command_revoke() {
9f66bfdb
LS
643 init_system
644
3dcfa8b4
LS
645 [[ -n "${CA_REVOKE_CERT}" ]] || _exiterr "Certificate authority doesn't allow certificate revocation."
646
81882a64 647 cert="${1}"
c7018036
MG
648 if [[ -L "${cert}" ]]; then
649 # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
3bc1cf91
LS
650 local link_target
651 link_target="$(readlink -n "${cert}")"
652 if [[ "${link_target}" =~ ^/ ]]; then
c7018036
MG
653 cert="${link_target}"
654 else
655 cert="$(dirname "${cert}")/${link_target}"
656 fi
657 fi
3dcfa8b4
LS
658 [[ -f "${cert}" ]] || _exiterr "Could not find certificate ${cert}"
659
81882a64 660 echo "Revoking ${cert}"
3dcfa8b4 661
81882a64
LS
662 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
663 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
3dcfa8b4 664 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
81882a64 665 # so if we are here, it is safe to assume the request was successful
3dcfa8b4
LS
666 echo " + Done."
667 echo " + Renaming certificate to ${cert}-revoked"
81882a64
LS
668 mv -f "${cert}" "${cert}-revoked"
669}
c24843c6 670
e60682c0
LS
671# Usage: --cleanup (-gc)
672# Description: Move unused certificate files to archive directory
673command_cleanup() {
dec95fff
LS
674 load_config
675
e60682c0
LS
676 # Create global archive directory if not existant
677 if [[ ! -e "${BASEDIR}/archive" ]]; then
678 mkdir "${BASEDIR}/archive"
679 fi
680
681 # Loop over all certificate directories
682 for certdir in "${BASEDIR}/certs/"*; do
f9430025
JB
683 # Skip if entry is not a folder
684 [[ -d "${certdir}" ]] || continue
685
e60682c0
LS
686 # Get certificate name
687 certname="$(basename "${certdir}")"
688
689 # Create certitifaces archive directory if not existant
690 archivedir="${BASEDIR}/archive/${certname}"
691 if [[ ! -e "${archivedir}" ]]; then
692 mkdir "${archivedir}"
693 fi
694
695 # Loop over file-types (certificates, keys, signing-requests, ...)
696 for filetype in cert.csr cert.pem chain.pem fullchain.pem privkey.pem; do
697 # Skip if symlink is broken
698 [[ -r "${certdir}/${filetype}" ]] || continue
699
700 # Look up current file in use
701 current="$(basename $(readlink "${certdir}/${filetype}"))"
702
703 # Split filetype into name and extension
704 filebase="$(echo "${filetype}" | cut -d. -f1)"
705 fileext="$(echo "${filetype}" | cut -d. -f2)"
706
707 # Loop over all files of this type
708 for file in "${certdir}/${filebase}-"*".${fileext}"; do
ac2d8303
JB
709 # Handle case where no files match the wildcard
710 [[ -f "${file}" ]] || break
711
e60682c0
LS
712 # Check if current file is in use, if unused move to archive directory
713 filename="$(basename "${file}")"
714 if [[ ! "${filename}" = "${current}" ]]; then
715 echo "Moving unused file to archive directory: ${certname}/$filename"
716 mv "${certdir}/${filename}" "${archivedir}/${filename}"
717 fi
718 done
719 done
720 done
721
722 exit 0
723}
724
0a859a19
LS
725# Usage: --help (-h)
726# Description: Show help text
81882a64 727command_help() {
7727f5ea
LS
728 printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
729 printf "Default command: help\n\n"
0a859a19 730 echo "Commands:"
760b6894 731 grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
31111265 732 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
7727f5ea 733 _exiterr "Error generating help text."
0a859a19 734 fi
7727f5ea 735 printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
0a859a19 736 done
7727f5ea 737 printf -- "\nParameters:\n"
760b6894 738 grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
31111265 739 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
7727f5ea 740 _exiterr "Error generating help text."
0a859a19 741 fi
7727f5ea 742 printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
0a859a19 743 done
81882a64 744}
063d28a6 745
1ab6a436
LS
746# Usage: --env (-e)
747# Description: Output configuration variables for use in other scripts
748command_env() {
749 echo "# letsencrypt.sh configuration"
9f66bfdb 750 load_config
6e048f7f 751 typeset -p CA LICENSE CHALLENGETYPE HOOK HOOK_CHAIN RENEW_DAYS PRIVATE_KEY KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
1ab6a436
LS
752}
753
bc580335 754# Main method (parses script arguments and calls command_* methods)
9f66bfdb
LS
755main() {
756 COMMAND=""
757 set_command() {
758 [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
759 COMMAND="${1}"
760 }
761
762 check_parameters() {
763 if [[ -z "${1:-}" ]]; then
764 echo "The specified command requires additional parameters. See help:" >&2
31111265
LS
765 echo >&2
766 command_help >&2
81882a64 767 exit 1
9f66bfdb
LS
768 elif [[ "${1:0:1}" = "-" ]]; then
769 _exiterr "Invalid argument: ${1}"
770 fi
771 }
579e2316 772
2a7b4882 773 [[ -z "${@}" ]] && eval set -- "--help"
fb0242a4 774
da2eeda9 775 while (( ${#} )); do
9f66bfdb
LS
776 case "${1}" in
777 --help|-h)
778 command_help
779 exit 0
780 ;;
579e2316 781
9f66bfdb
LS
782 --env|-e)
783 set_command env
784 ;;
579e2316 785
9f66bfdb
LS
786 --cron|-c)
787 set_command sign_domains
788 ;;
789
429ec400
NL
790 --signcsr|-s)
791 shift 1
792 set_command sign_csr
793 check_parameters "${1:-}"
794 PARAM_CSR="${1}"
795 ;;
796
9f66bfdb
LS
797 --revoke|-r)
798 shift 1
799 set_command revoke
800 check_parameters "${1:-}"
801 PARAM_REVOKECERT="${1}"
802 ;;
5060dea0 803
e60682c0
LS
804 --cleanup|-gc)
805 set_command cleanup
806 ;;
807
8f6c2328 808 # PARAM_Usage: --domain (-d) domain.tld
9f66bfdb
LS
809 # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
810 --domain|-d)
811 shift 1
812 check_parameters "${1:-}"
813 if [[ -z "${PARAM_DOMAIN:-}" ]]; then
814 PARAM_DOMAIN="${1}"
815 else
816 PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
817 fi
818 ;;
819
820
8f6c2328 821 # PARAM_Usage: --force (-x)
9f66bfdb
LS
822 # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
823 --force|-x)
824 PARAM_FORCE="yes"
825 ;;
826
0a859a19
LS
827 # PARAM_Usage: --privkey (-p) path/to/key.pem
828 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
9f66bfdb
LS
829 --privkey|-p)
830 shift 1
831 check_parameters "${1:-}"
832 PARAM_PRIVATE_KEY="${1}"
833 ;;
834
835 # PARAM_Usage: --config (-f) path/to/config.sh
836 # PARAM_Description: Use specified config file
837 --config|-f)
838 shift 1
839 check_parameters "${1:-}"
840 CONFIG="${1}"
841 ;;
842
ed27e013
MG
843 # PARAM_Usage: --hook (-k) path/to/hook.sh
844 # PARAM_Description: Use specified script for hooks
845 --hook|-k)
846 shift 1
847 check_parameters "${1:-}"
848 PARAM_HOOK="${1}"
849 ;;
850
e925b293
MG
851 # PARAM_Usage: --challenge (-t) http-01|dns-01
852 # PARAM_Description: Which challenge should be used? Currently http-01 and dns-01 are supported
853 --challenge|-t)
854 shift 1
855 check_parameters "${1:-}"
856 PARAM_CHALLENGETYPE="${1}"
857 ;;
858
c71ca3a8
MG
859 # PARAM_Usage: --algo (-a) rsa|prime256v1|secp384r1
860 # PARAM_Description: Which public key algorithm should be used? Supported: rsa, prime256v1 and secp384r1
861 --algo|-a)
862 shift 1
863 check_parameters "${1:-}"
864 PARAM_KEY_ALGO="${1}"
865 ;;
866
9f66bfdb
LS
867 *)
868 echo "Unknown parameter detected: ${1}" >&2
869 echo >&2
870 command_help >&2
871 exit 1
872 ;;
873 esac
874
875 shift 1
876 done
877
878 case "${COMMAND}" in
879 env) command_env;;
880 sign_domains) command_sign_domains;;
429ec400 881 sign_csr) command_sign_csr "${PARAM_CSR}";;
9f66bfdb 882 revoke) command_revoke "${PARAM_REVOKECERT}";;
e60682c0 883 cleanup) command_cleanup;;
7191ed25 884 *) command_help; exit 1;;
81882a64 885 esac
9f66bfdb 886}
81882a64 887
c3c9ff4c
LS
888# Determine OS type
889OSTYPE="$(uname)"
890
9f66bfdb
LS
891# Check for missing dependencies
892check_dependencies
893
894# Run script
895main "${@:-}"