]> git.street.me.uk Git - andy/dehydrated.git/blame - letsencrypt.sh
rewritten help method to get rid of `column` dependency
[andy/dehydrated.git] / letsencrypt.sh
CommitLineData
2e8454b4 1#!/usr/bin/env bash
69f3e78b
LS
2set -e
3set -u
4set -o pipefail
81882a64 5umask 077 # paranoid umask, we're creating private keys
61f0b7ed 6
16943702
LS
7# Get the directory in which this script is stored
8SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
0e92aba2
MG
9BASEDIR="${SCRIPTDIR}"
10
9f66bfdb
LS
11check_dependencies() {
12 curl -V > /dev/null 2>&1 || _exiterr "This script requires curl."
13 openssl version > /dev/null 2>&1 || _exiterr "This script requres an openssl binary."
14 sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requres sed."
15 grep -V > /dev/null 2>&1 || _exiterr "This script requres grep."
16}
17
ff116396
LS
18# Setup default config values, search for and load configuration files
19load_config() {
20 # Default values
21 CA="https://acme-v01.api.letsencrypt.org/directory"
22 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
23 HOOK=
24 RENEW_DAYS="14"
25 PRIVATE_KEY="${BASEDIR}/private_key.pem"
26 KEYSIZE="4096"
27 WELLKNOWN="${BASEDIR}/.acme-challenges"
28 PRIVATE_KEY_RENEW="no"
29 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
30 CONTACT_EMAIL=
1e33cfe5 31 LOCKFILE="${BASEDIR}/lock"
1e33cfe5 32
81882a64
LS
33 # Check for config in various locations
34 if [[ -z "${CONFIG:-}" ]]; then
ff116396 35 for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
81882a64
LS
36 if [[ -e "${check_config}/config.sh" ]]; then
37 BASEDIR="${check_config}"
38 CONFIG="${check_config}/config.sh"
39 break
40 fi
41 done
454c164b 42 fi
454c164b 43
81882a64 44 if [[ -z "${CONFIG:-}" ]]; then
ff116396
LS
45 echo "#" >&2
46 echo "# !! WARNING !! No config file found, using default config!" >&2
47 echo "#" >&2
81882a64 48 elif [[ -e "${CONFIG}" ]]; then
ff116396 49 echo "# INFO: Using config file ${CONFIG}"
81882a64
LS
50 BASEDIR="$(dirname "${CONFIG}")"
51 # shellcheck disable=SC1090
52 . "${CONFIG}"
53 else
ff116396 54 echo "Specified config file doesn't exist." >&2
81882a64
LS
55 exit 1
56 fi
61f0b7ed 57
81882a64
LS
58 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
59 BASEDIR="${BASEDIR%%/}"
401f5f75 60
1e33cfe5
AB
61 # Check BASEDIR and set default variables
62 if [[ ! -d "${BASEDIR}" ]]; then
ff116396
LS
63 echo "BASEDIR does not exist: ${BASEDIR}" >&2
64 exit 1
1e33cfe5 65 fi
ff116396
LS
66}
67
68init_system() {
69 load_config
81882a64 70
1ab6a436
LS
71 if [[ "${COMMAND}" = "env" ]]; then
72 return
73 fi
74
1e33cfe5 75 # Lockfile handling (prevents concurrent access)
81882a64
LS
76 set -o noclobber
77 if ! { date > "${LOCKFILE}"; } 2>/dev/null; then
78 echo " + ERROR: Lock file '${LOCKFILE}' present, aborting." >&2
10d9f342 79 LOCKFILE="" # so remove_lock doesn't remove it
81882a64
LS
80 exit 1
81 fi
82 set +o noclobber
83
84 remove_lock() {
85 if [[ -n "${LOCKFILE}" ]]; then
86 rm -f "${LOCKFILE}"
87 fi
88 }
89 trap 'remove_lock' EXIT
90
91 # Export some environment variables to be used in hook script
92 export WELLKNOWN
93 export BASEDIR
94 export CONFIG
95
96 # Get CA URLs
3a9e97f9 97 CA_DIRECTORY="$(http_request get "${CA}")"
81882a64
LS
98 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
99 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
100 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
10d9f342 101 # shellcheck disable=SC2015
81882a64 102 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
31111265 103 (echo "Error retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint." >&2; exit 1)
81882a64 104
0e92aba2
MG
105
106 # check private key ...
81882a64 107 register="0"
0e92aba2
MG
108 if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
109 # a private key was specified from the command line so use it for this run
10d9f342 110 echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
0e92aba2
MG
111 PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
112 if ! openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null; then
31111265 113 echo " + ERROR: private key is not valid, can not continue" >&2
0e92aba2
MG
114 exit 1
115 fi
116 else
117 # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
0e92aba2 118 if [[ ! -e "${PRIVATE_KEY}" ]]; then
81882a64 119 echo "+ Generating account key..."
0e92aba2 120 _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
81882a64
LS
121 register="1"
122 fi
81882a64 123 fi
1ab6a436 124
81882a64 125 # Get public components from private key and calculate thumbprint
f70f3048
LS
126 pubExponent64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | grep publicExponent | grep -oE "0x[a-f0-9]+" | cut -d'x' -f2 | hex2bin | urlbase64)"
127 pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
81882a64 128
07149196 129 thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl sha -sha256 -binary | urlbase64)"
81882a64
LS
130
131 # If we generated a new private key in the step above we have to register it with the acme-server
132 if [[ "${register}" = "1" ]]; then
133 echo "+ Registering account key with letsencrypt..."
134 if [ -z "${CA_NEW_REG}" ]; then
31111265 135 echo " + ERROR: Certificate authority doesn't allow registrations." >&2
81882a64
LS
136 exit 1
137 fi
138 # if an email for the contact has been provided then adding it to the registration request
139 if [[ -n "${CONTACT_EMAIL}" ]]; then
140 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
141 else
142 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
143 fi
144 fi
181dd0ff 145
81882a64
LS
146 if [[ -e "${BASEDIR}/domains.txt" ]]; then
147 DOMAINS_TXT="${BASEDIR}/domains.txt"
81882a64 148 else
31111265 149 echo " + ERROR: domains.txt not found" >&2
81882a64
LS
150 exit 1
151 fi
152
153 if [[ ! -e "${WELLKNOWN}" ]]; then
5a29d185
LS
154 echo " + ERROR: WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions." >&2
155 exit 1
81882a64
LS
156 fi
157}
c24843c6 158
9f66bfdb
LS
159# Print error message and exit with error
160_exiterr() {
161 echo "ERROR: ${1}" >&2
162 exit 1
163}
164
c6e60302
LS
165anti_newline() {
166 tr -d '\n\r'
167}
181dd0ff 168
61f0b7ed 169urlbase64() {
c6e60302 170 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
81cb6ac7 171 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
61f0b7ed 172}
91ce50af 173
16bef17e 174# Convert hex string to binary data
9fe313d8 175hex2bin() {
16bef17e
LS
176 # Remove spaces, add leading zero, escape as hex string and parse with printf
177 printf -- "$(cat | sed -E -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
9fe313d8 178}
61f0b7ed 179
09729186 180get_json_string_value() {
760b6894 181 grep -Eo '"'"${1}"'":[[:space:]]*"[^"]*"' | cut -d'"' -f4
09729186
LS
182}
183
184get_json_array() {
185 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
186}
187
3a9e97f9 188http_request() {
3cb292cb
LS
189 tempcont="$(mktemp)"
190
dd5f36e5 191 if [[ "${1}" = "head" ]]; then
3cb292cb 192 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
dd5f36e5 193 elif [[ "${1}" = "get" ]]; then
3cb292cb 194 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
dd5f36e5 195 elif [[ "${1}" = "post" ]]; then
3cb292cb 196 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
91ce50af 197 fi
dd5f36e5 198
3cb292cb 199 if [[ ! "${statuscode:0:1}" = "2" ]]; then
84fac541 200 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
3cb292cb
LS
201 echo >&2
202 echo "Details:" >&2
9e79c066 203 cat "${tempcont}" >&2
3cb292cb 204 rm -f "${tempcont}"
c24843c6 205
206 # Wait for hook script to clean the challenge if used
0b2119c4 207 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
e32ea24c 208 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
c24843c6 209 fi
210
8f6c2328
MG
211 # remove temporary domains.txt file if used
212 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
213 rm "${DOMAINS_TXT}"
214 fi
215
dd5f36e5 216 exit 1
130ea6ab 217 fi
dd5f36e5 218
31111265 219 cat "${tempcont}"
3cb292cb 220 rm -f "${tempcont}"
91ce50af 221}
81882a64
LS
222
223# OpenSSL writes to stderr/stdout even when there are no errors. So just
224# display the output if the exit code was != 0 to simplify debugging.
225_openssl() {
7f8ea450 226 set +e
10d9f342 227 out="$(openssl "${@}" 2>&1)"
7f8ea450
SR
228 res=$?
229 set -e
230 if [[ $res -ne 0 ]]; then
231 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
232 echo >&2
233 echo "Details:" >&2
234 echo "$out" >&2
235 exit $res
236 fi
237}
91ce50af 238
61f0b7ed 239signed_request() {
c6e60302 240 # Encode payload as urlbase64
4aa48d33 241 payload64="$(printf '%s' "${2}" | urlbase64)"
61f0b7ed 242
c6e60302 243 # Retrieve nonce from acme-server
3a9e97f9 244 nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
61f0b7ed 245
c6e60302 246 # Build header with just our public key and algorithm information
61f0b7ed
LS
247 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
248
c6e60302 249 # Build another header which also contains the previously received nonce and encode it as urlbase64
61f0b7ed 250 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
4aa48d33 251 protected64="$(printf '%s' "${protected}" | urlbase64)"
61f0b7ed 252
c6e60302 253 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
0e92aba2 254 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
61f0b7ed 255
c6e60302 256 # Send header + extended header + payload + signature to the acme-server
61f0b7ed
LS
257 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
258
3a9e97f9 259 http_request post "${1}" "${data}"
61f0b7ed
LS
260}
261
61f0b7ed
LS
262sign_domain() {
263 domain="${1}"
1f65a335 264 altnames="${*}"
81882a64 265
579e2316 266 echo " + Signing domains..."
09729186 267 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
31111265 268 echo " + ERROR: Certificate authority doesn't allow certificate signing" >&2
09729186
LS
269 exit 1
270 fi
3cc587c2
LS
271 timestamp="$(date +%s)"
272
3dbbb461 273 # If there is no existing certificate directory => make it
5b29db97
AJM
274 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
275 echo " + make directory ${BASEDIR}/certs/${domain} ..."
276 mkdir -p "${BASEDIR}/certs/${domain}"
3dbbb461
MG
277 fi
278
f343dc11 279 privkey="privkey.pem"
3dbbb461 280 # generate a new private key if we need or want one
5b29db97 281 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
579e2316 282 echo " + Generating private key..."
f343dc11 283 privkey="privkey-${timestamp}.pem"
7f8ea450 284 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
61f0b7ed
LS
285 fi
286
c6e60302
LS
287 # Generate signing request config and the actual signing request
288 SAN=""
61f0b7ed 289 for altname in $altnames; do
c6e60302
LS
290 SAN+="DNS:${altname}, "
291 done
cd13a9c2 292 SAN="${SAN%%, }"
579e2316 293 echo " + Generating signing request..."
3bc1cf91
LS
294 local tmp_openssl_cnf
295 tmp_openssl_cnf="$(mktemp)"
296 cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
9e79c066
LS
297 printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
298 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}"
299 rm -f "${tmp_openssl_cnf}"
c6e60302
LS
300
301 # Request and respond to challenges
302 for altname in $altnames; do
303 # Ask the acme-server for new challenge token and extract them from the resulting json block
579e2316 304 echo " + Requesting challenge for ${altname}..."
09729186 305 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
61f0b7ed 306
09729186 307 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
526843d6
SR
308 repl=$'\n''{' # fix syntax highlighting in Vim
309 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
09729186
LS
310 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
311 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
61f0b7ed 312
dd5f36e5 313 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
31111265 314 echo " + Error: Can't retrieve challenges (${response})" >&2
abb95693
LS
315 exit 1
316 fi
317
c6e60302 318 # Challenge response consists of the challenge token and the thumbprint of our public certificate
61f0b7ed
LS
319 keyauth="${challenge_token}.${thumbprint}"
320
c6e60302 321 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
4aa48d33 322 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
2b5df371 323 chmod a+r "${WELLKNOWN}/${challenge_token}"
61f0b7ed 324
b33f1288 325 # Wait for hook script to deploy the challenge if used
c24843c6 326 if [[ -n "${HOOK}" ]]; then
e32ea24c 327 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
b33f1288
SR
328 fi
329
c6e60302 330 # Ask the acme-server to verify our challenge and wait until it becomes valid
579e2316 331 echo " + Responding to challenge for ${altname}..."
61f0b7ed
LS
332 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
333
09729186 334 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
61f0b7ed 335
cbe1eb2c 336 # get status until a result is reached => not pending anymore
dd5f36e5 337 while [[ "${status}" = "pending" ]]; do
c6e60302 338 sleep 1
3a9e97f9 339 status="$(http_request get "${challenge_uri}" | get_json_string_value status)"
61f0b7ed
LS
340 done
341
00837b86 342 rm -f "${WELLKNOWN}/${challenge_token}"
81882a64 343
ab301951
E
344 # Wait for hook script to clean the challenge if used
345 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
346 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
347 fi
81882a64 348
76a37834 349 if [[ "${status}" = "valid" ]]; then
579e2316 350 echo " + Challenge is valid!"
76a37834 351 else
31111265 352 echo " + Challenge is invalid! (returned: ${status})" >&2
76a37834
MG
353 exit 1
354 fi
355
61f0b7ed
LS
356 done
357
b7439a83 358 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
579e2316 359 echo " + Requesting certificate..."
f343dc11 360 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
09729186 361 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
85da9090
SR
362 crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
363 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${crt_path}"
10cf2299 364 # try to load the certificate to detect corruption
a4e7c43a 365 echo " + Checking certificate..."
10cf2299 366 _openssl x509 -text < "${crt_path}"
329acb58
LS
367
368 # Create fullchain.pem
1eb6f6d2
LS
369 echo " + Creating fullchain.pem..."
370 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
3a9e97f9 371 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"
f090fbcf 372 if ! grep "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" > /dev/null 2>&1; then
a733f789
LS
373 openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
374 fi
375 ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
376 cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
1eb6f6d2 377 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
329acb58 378
f343dc11
LS
379 # Update remaining symlinks
380 if [ ! "${privkey}" = "privkey.pem" ]; then
3f6ff8f7 381 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
f343dc11
LS
382 fi
383
3f6ff8f7
SR
384 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
385 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
f343dc11 386
c24843c6 387 # Wait for hook script to clean the challenge and to deploy cert if used
388 if [[ -n "${HOOK}" ]]; then
e32ea24c 389 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
c24843c6 390 fi
391
392 unset challenge_token
579e2316 393 echo " + Done!"
61f0b7ed
LS
394}
395
f9126627 396
0a859a19 397# Usage: --cron (-c)
083c6736 398# Description: Sign/renew non-existant/changed/expiring certificates.
8f6c2328 399command_sign_domains() {
9f66bfdb
LS
400 init_system
401
8f6c2328
MG
402 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
403 # we are using a temporary domains.txt file so we don't need to duplicate any code
404 DOMAINS_TXT="$(mktemp)"
405 echo "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
406 fi
81882a64 407 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
760b6894 408 <"${DOMAINS_TXT}" sed 's/^[[:space:]]*//g;s/[[:space:]]*$//g' | grep -vE '^(#|$)' | while read -r line; do
81882a64 409 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
8f6c2328 410 morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
81882a64 411 cert="${BASEDIR}/certs/${domain}/cert.pem"
f9126627 412
2d097c92
MG
413 force_renew="${PARAM_FORCE:-no}"
414
8f6c2328
MG
415 if [[ -z "${morenames}" ]];then
416 echo "Processing ${domain}"
417 else
418 echo "Processing ${domain} with SAN: ${morenames}"
419 fi
420
81882a64 421 if [[ -e "${cert}" ]]; then
2d097c92
MG
422 echo -n " + Checking domain name(s) of existing cert..."
423
424 certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//')"
425 givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | sed 's/ $//' | sed 's/^ //')"
426
427 if [[ "${certnames}" = "${givennames}" ]]; then
428 echo " unchanged."
429 else
430 echo " changed!"
431 echo " + Domain name(s) are not matching!"
432 echo " + Names in old certificate: ${certnames}"
433 echo " + Configured names: ${givennames}"
434 echo " + Forcing renew."
435 force_renew="yes"
436 fi
437 fi
438
439 if [[ -e "${cert}" ]]; then
440 echo " + Checking expire date of existing cert..."
8221727a 441
81882a64 442 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
8221727a 443
81882a64
LS
444 echo -n " + Valid till ${valid} "
445 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
8f6c2328 446 echo -n "(Longer than ${RENEW_DAYS} days). "
2d097c92
MG
447 if [[ "${force_renew}" = "yes" ]]; then
448 echo "Ignoring because renew was forced!"
8f6c2328
MG
449 else
450 echo "Skipping!"
451 continue
452 fi
453 else
454 echo "(Less than ${RENEW_DAYS} days). Renewing!"
81882a64 455 fi
81882a64 456 fi
8221727a 457
81882a64
LS
458 # shellcheck disable=SC2086
459 sign_domain $line
e4666acb 460 done || true
f13eaa7f 461
8f6c2328
MG
462 # remove temporary domains.txt file if used
463 if [[ -n "${PARAM_DOMAIN:-}" ]]; then
9e79c066 464 rm -f "${DOMAINS_TXT}"
8f6c2328 465 fi
81882a64 466}
3390080c 467
0a859a19
LS
468# Usage: --revoke (-r) path/to/cert.pem
469# Description: Revoke specified certificate
81882a64 470command_revoke() {
9f66bfdb
LS
471 init_system
472
81882a64 473 cert="${1}"
c7018036
MG
474 if [[ -L "${cert}" ]]; then
475 # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
3bc1cf91
LS
476 local link_target
477 link_target="$(readlink -n "${cert}")"
478 if [[ "${link_target}" =~ ^/ ]]; then
c7018036
MG
479 cert="${link_target}"
480 else
481 cert="$(dirname "${cert}")/${link_target}"
482 fi
483 fi
484 if [[ ! -f "${cert}" ]]; then
485 echo "ERROR: Could not find certificate ${cert}"
486 exit 1
487 fi
81882a64 488 echo "Revoking ${cert}"
c7018036 489 if [[ -z "${CA_REVOKE_CERT}" ]]; then
31111265 490 echo " + ERROR: Certificate authority doesn't allow certificate revocation." >&2
063d28a6
MG
491 exit 1
492 fi
81882a64
LS
493 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
494 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
3a9e97f9 495 # if there is a problem with our revoke request http_request (via signed_request) will report this and "exit 1" out
81882a64
LS
496 # so if we are here, it is safe to assume the request was successful
497 echo " + SUCCESS"
498 echo " + renaming certificate to ${cert}-revoked"
499 mv -f "${cert}" "${cert}-revoked"
500}
c24843c6 501
0a859a19
LS
502# Usage: --help (-h)
503# Description: Show help text
81882a64 504command_help() {
7727f5ea
LS
505 printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
506 printf "Default command: help\n\n"
0a859a19 507 echo "Commands:"
760b6894 508 grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
31111265 509 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
7727f5ea 510 _exiterr "Error generating help text."
0a859a19 511 fi
7727f5ea 512 printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
0a859a19 513 done
7727f5ea 514 printf -- "\nParameters:\n"
760b6894 515 grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
31111265 516 if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
7727f5ea 517 _exiterr "Error generating help text."
0a859a19 518 fi
7727f5ea 519 printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
0a859a19 520 done
81882a64 521}
063d28a6 522
1ab6a436
LS
523# Usage: --env (-e)
524# Description: Output configuration variables for use in other scripts
525command_env() {
526 echo "# letsencrypt.sh configuration"
9f66bfdb
LS
527 load_config
528 typeset -p CA LICENSE HOOK RENEW_DAYS PRIVATE_KEY KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
1ab6a436
LS
529}
530
9f66bfdb
LS
531main() {
532 COMMAND=""
533 set_command() {
534 [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
535 COMMAND="${1}"
536 }
537
538 check_parameters() {
539 if [[ -z "${1:-}" ]]; then
540 echo "The specified command requires additional parameters. See help:" >&2
31111265
LS
541 echo >&2
542 command_help >&2
81882a64 543 exit 1
9f66bfdb
LS
544 elif [[ "${1:0:1}" = "-" ]]; then
545 _exiterr "Invalid argument: ${1}"
546 fi
547 }
579e2316 548
9f66bfdb
LS
549 while (( "${#}" )); do
550 case "${1}" in
551 --help|-h)
552 command_help
553 exit 0
554 ;;
579e2316 555
9f66bfdb
LS
556 --env|-e)
557 set_command env
558 ;;
579e2316 559
9f66bfdb
LS
560 --cron|-c)
561 set_command sign_domains
562 ;;
563
564 --revoke|-r)
565 shift 1
566 set_command revoke
567 check_parameters "${1:-}"
568 PARAM_REVOKECERT="${1}"
569 ;;
5060dea0 570
8f6c2328 571 # PARAM_Usage: --domain (-d) domain.tld
9f66bfdb
LS
572 # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
573 --domain|-d)
574 shift 1
575 check_parameters "${1:-}"
576 if [[ -z "${PARAM_DOMAIN:-}" ]]; then
577 PARAM_DOMAIN="${1}"
578 else
579 PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
580 fi
581 ;;
582
583
8f6c2328 584 # PARAM_Usage: --force (-x)
9f66bfdb
LS
585 # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
586 --force|-x)
587 PARAM_FORCE="yes"
588 ;;
589
0a859a19
LS
590 # PARAM_Usage: --privkey (-p) path/to/key.pem
591 # PARAM_Description: Use specified private key instead of account key (useful for revocation)
9f66bfdb
LS
592 --privkey|-p)
593 shift 1
594 check_parameters "${1:-}"
595 PARAM_PRIVATE_KEY="${1}"
596 ;;
597
598 # PARAM_Usage: --config (-f) path/to/config.sh
599 # PARAM_Description: Use specified config file
600 --config|-f)
601 shift 1
602 check_parameters "${1:-}"
603 CONFIG="${1}"
604 ;;
605
606 *)
607 echo "Unknown parameter detected: ${1}" >&2
608 echo >&2
609 command_help >&2
610 exit 1
611 ;;
612 esac
613
614 shift 1
615 done
616
617 case "${COMMAND}" in
618 env) command_env;;
619 sign_domains) command_sign_domains;;
620 revoke) command_revoke "${PARAM_REVOKECERT}";;
621 *) command_help; exit1;;
81882a64 622 esac
9f66bfdb 623}
81882a64 624
9f66bfdb
LS
625# Check for missing dependencies
626check_dependencies
627
628# Run script
629main "${@:-}"