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