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