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