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