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