]> git.street.me.uk Git - andy/dehydrated.git/blame - letsencrypt.sh
fixed output of config location
[andy/dehydrated.git] / letsencrypt.sh
CommitLineData
2e8454b4 1#!/usr/bin/env bash
61f0b7ed 2
69f3e78b
LS
3set -e
4set -u
5set -o pipefail
61f0b7ed 6
16943702
LS
7# Get the directory in which this script is stored
8SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
9
401f5f75 10# Default config values
09729186 11CA="https://acme-v01.api.letsencrypt.org/directory"
00a0937c 12LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
c24843c6 13HOOK=
e300c0a1 14RENEW_DAYS="14"
5a213f5f 15KEYSIZE="4096"
16943702
LS
16WELLKNOWN="${SCRIPTDIR}/.acme-challenges"
17PRIVATE_KEY_RENEW="no"
1f08fda7 18BASEDIR="${SCRIPTDIR}"
474f33d2 19OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
329acb58 20ROOTCERT="lets-encrypt-x1-cross-signed.pem"
ea5b70a3 21CONTACT_EMAIL=
f11bb1db 22
454c164b
LS
23# Check for config in various locations
24CONFIG=""
25for check_config in "${SCRIPTDIR}" "${HOME}/.letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "/etc/letsencrypt.sh" "${PWD}"; do
26 if [[ -e "${check_config}/config.sh" ]]; then
27 BASEDIR="${check_config}"
28 CONFIG="${check_config}/config.sh"
29 break
30 fi
31done
32
33if [[ -z "${CONFIG}" ]]; then
34 echo "WARNING: No config file found, using default config!"
35 sleep 2
36else
43b00611 37 echo "Using config file ${CONFIG}"
219b3e9d 38 # shellcheck disable=SC1090
454c164b 39 . "${CONFIG}"
440dc30d 40fi
61f0b7ed 41
401f5f75
LS
42# Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
43BASEDIR="${BASEDIR%%/}"
44
181dd0ff
SR
45umask 077 # paranoid umask, we're creating private keys
46
c24843c6 47# Export some environment variables to be used in hook script
48export WELLKNOWN
49export BASEDIR
454c164b 50export CONFIG
c24843c6 51
c6e60302
LS
52anti_newline() {
53 tr -d '\n\r'
54}
181dd0ff 55
61f0b7ed 56urlbase64() {
c6e60302 57 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
81cb6ac7 58 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
61f0b7ed 59}
91ce50af 60
9fe313d8 61hex2bin() {
c6e60302 62 # Store hex string from stdin
20e7d9d7
LS
63 tmphex="$(cat)"
64
c6e60302 65 # Remove spaces
20e7d9d7
LS
66 hex=''
67 for ((i=0; i<${#tmphex}; i+=1)); do
68 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
69 done
70
c6e60302 71 # Add leading zero
20e7d9d7
LS
72 test $((${#hex} & 1)) == 0 || hex="0${hex}"
73
c6e60302 74 # Convert to escaped string
20e7d9d7
LS
75 escapedhex=''
76 for ((i=0; i<${#hex}; i+=2)); do
77 escapedhex=$escapedhex\\x${hex:$i:2}
78 done
79
c6e60302 80 # Convert to binary data
219b3e9d 81 printf -- "${escapedhex}"
9fe313d8 82}
61f0b7ed 83
09729186
LS
84get_json_string_value() {
85 grep -Eo '"'"${1}"'":\s*"[^"]*"' | cut -d'"' -f4
86}
87
88get_json_array() {
89 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
90}
91
91ce50af 92_request() {
3cb292cb
LS
93 tempcont="$(mktemp)"
94
dd5f36e5 95 if [[ "${1}" = "head" ]]; then
3cb292cb 96 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
dd5f36e5 97 elif [[ "${1}" = "get" ]]; then
3cb292cb 98 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
dd5f36e5 99 elif [[ "${1}" = "post" ]]; then
3cb292cb 100 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
91ce50af 101 fi
dd5f36e5 102
3cb292cb 103 if [[ ! "${statuscode:0:1}" = "2" ]]; then
84fac541 104 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
3cb292cb
LS
105 echo >&2
106 echo "Details:" >&2
107 echo "$(<"${tempcont}"))" >&2
108 rm -f "${tempcont}"
c24843c6 109
110 # Wait for hook script to clean the challenge if used
0b2119c4 111 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
e32ea24c 112 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
c24843c6 113 fi
114
dd5f36e5 115 exit 1
130ea6ab 116 fi
dd5f36e5 117
3cb292cb
LS
118 cat "${tempcont}"
119 rm -f "${tempcont}"
91ce50af 120}
7f8ea450
SR
121_output_on_error() {
122 # Only way to capture the output and exit code is to disable set -e.
123 set +e
124 out="$("$@" 2>&1)"
125 res=$?
126 set -e
127 if [[ $res -ne 0 ]]; then
128 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
129 echo >&2
130 echo "Details:" >&2
131 echo "$out" >&2
132 exit $res
133 fi
134}
135# OpenSSL writes to stderr/stdout even when there are no errors. So just
136# display the output if the exit code was != 0 to simplify debugging.
137_openssl() {
138 _output_on_error openssl "$@"
139}
91ce50af 140
61f0b7ed 141signed_request() {
c6e60302 142 # Encode payload as urlbase64
4aa48d33 143 payload64="$(printf '%s' "${2}" | urlbase64)"
61f0b7ed 144
c6e60302 145 # Retrieve nonce from acme-server
09729186 146 nonce="$(_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
61f0b7ed 147
c6e60302 148 # Build header with just our public key and algorithm information
61f0b7ed
LS
149 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
150
c6e60302 151 # Build another header which also contains the previously received nonce and encode it as urlbase64
61f0b7ed 152 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
4aa48d33 153 protected64="$(printf '%s' "${protected}" | urlbase64)"
61f0b7ed 154
c6e60302 155 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
5b29db97 156 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
61f0b7ed 157
c6e60302 158 # Send header + extended header + payload + signature to the acme-server
61f0b7ed
LS
159 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
160
91ce50af 161 _request post "${1}" "${data}"
61f0b7ed
LS
162}
163
063d28a6 164revoke_cert() {
09729186
LS
165 if [ -z "${CA_REVOKE_CERT}" ]; then
166 echo " + ERROR: Certificate authority doesn't allow certificate revocation."
167 exit 1
168 fi
063d28a6
MG
169 cert="${1}"
170 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
09729186 171 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
063d28a6
MG
172 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
173 # so if we are here, it is safe to assume the request was successful
174 echo " + SUCCESS"
175 echo " + renaming certificate to ${cert}-revoked"
176 mv -f "${cert}" "${cert}-revoked"
177}
178
61f0b7ed
LS
179sign_domain() {
180 domain="${1}"
1f65a335 181 altnames="${*}"
579e2316 182 echo " + Signing domains..."
09729186
LS
183 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
184 echo " + ERROR: Certificate authority doesn't allow certificate signing"
185 exit 1
186 fi
3cc587c2
LS
187 timestamp="$(date +%s)"
188
3dbbb461 189 # If there is no existing certificate directory => make it
5b29db97
AJM
190 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
191 echo " + make directory ${BASEDIR}/certs/${domain} ..."
192 mkdir -p "${BASEDIR}/certs/${domain}"
3dbbb461
MG
193 fi
194
f343dc11 195 privkey="privkey.pem"
3dbbb461 196 # generate a new private key if we need or want one
5b29db97 197 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
579e2316 198 echo " + Generating private key..."
f343dc11 199 privkey="privkey-${timestamp}.pem"
7f8ea450 200 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
61f0b7ed
LS
201 fi
202
c6e60302
LS
203 # Generate signing request config and the actual signing request
204 SAN=""
61f0b7ed 205 for altname in $altnames; do
c6e60302
LS
206 SAN+="DNS:${altname}, "
207 done
cd13a9c2 208 SAN="${SAN%%, }"
579e2316 209 echo " + Generating signing request..."
7f8ea450 210 openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config <(cat "${OPENSSL_CNF}" <(printf "[SAN]\nsubjectAltName=%s" "${SAN}"))
c6e60302
LS
211
212 # Request and respond to challenges
213 for altname in $altnames; do
214 # Ask the acme-server for new challenge token and extract them from the resulting json block
579e2316 215 echo " + Requesting challenge for ${altname}..."
09729186 216 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
61f0b7ed 217
09729186 218 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
526843d6
SR
219 repl=$'\n''{' # fix syntax highlighting in Vim
220 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
09729186
LS
221 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
222 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
61f0b7ed 223
dd5f36e5 224 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
a1621214 225 echo " + Error: Can't retrieve challenges (${response})"
abb95693
LS
226 exit 1
227 fi
228
c6e60302 229 # Challenge response consists of the challenge token and the thumbprint of our public certificate
61f0b7ed
LS
230 keyauth="${challenge_token}.${thumbprint}"
231
c6e60302 232 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
4aa48d33 233 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
2b5df371 234 chmod a+r "${WELLKNOWN}/${challenge_token}"
61f0b7ed 235
b33f1288 236 # Wait for hook script to deploy the challenge if used
c24843c6 237 if [[ -n "${HOOK}" ]]; then
e32ea24c 238 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
b33f1288
SR
239 fi
240
c6e60302 241 # Ask the acme-server to verify our challenge and wait until it becomes valid
579e2316 242 echo " + Responding to challenge for ${altname}..."
61f0b7ed
LS
243 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
244
09729186 245 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
61f0b7ed 246
cbe1eb2c 247 # get status until a result is reached => not pending anymore
dd5f36e5 248 while [[ "${status}" = "pending" ]]; do
c6e60302 249 sleep 1
09729186 250 status="$(_request get "${challenge_uri}" | get_json_string_value status)"
61f0b7ed
LS
251 done
252
00837b86
LS
253 rm -f "${WELLKNOWN}/${challenge_token}"
254
76a37834 255 if [[ "${status}" = "valid" ]]; then
579e2316 256 echo " + Challenge is valid!"
76a37834 257 else
579e2316 258 echo " + Challenge is invalid! (returned: ${status})"
c24843c6 259
260 # Wait for hook script to clean the challenge if used
261 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
e32ea24c 262 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
c24843c6 263 fi
264
76a37834
MG
265 exit 1
266 fi
267
61f0b7ed
LS
268 done
269
b7439a83 270 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
579e2316 271 echo " + Requesting certificate..."
f343dc11 272 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
09729186 273 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
5b29db97 274 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
329acb58
LS
275
276 # Create fullchain.pem
277 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]] || [[ -e "${SCRIPTDIR}/certs/${ROOTCERT}" ]]; then
278 echo " + Creating fullchain.pem..."
15accf90 279 cat "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
329acb58 280 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]]; then
15accf90 281 cat "${BASEDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
329acb58 282 else
15accf90 283 cat "${SCRIPTDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
329acb58 284 fi
3f6ff8f7 285 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
329acb58
LS
286 fi
287
f343dc11
LS
288 # Update remaining symlinks
289 if [ ! "${privkey}" = "privkey.pem" ]; then
3f6ff8f7 290 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
f343dc11
LS
291 fi
292
3f6ff8f7
SR
293 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
294 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
f343dc11 295
c24843c6 296 # Wait for hook script to clean the challenge and to deploy cert if used
297 if [[ -n "${HOOK}" ]]; then
e32ea24c 298 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
c24843c6 299 fi
300
301 unset challenge_token
579e2316 302 echo " + Done!"
61f0b7ed
LS
303}
304
09729186
LS
305# Get CA URLs
306CA_DIRECTORY="$(_request get "${CA}")"
307CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)"
308CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)"
309CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)"
310CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)"
311
5a213f5f 312# Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
8221727a 313register="0"
5b29db97 314if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
f13eaa7f 315 echo "+ Generating account key..."
7f8ea450 316 _openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}"
8221727a
LS
317 register="1"
318fi
319
c6e60302 320# Get public components from private key and calculate thumbprint
5b29db97
AJM
321pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
322pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
8221727a 323
c6e60302 324thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
8221727a 325
c6e60302 326# If we generated a new private key in the step above we have to register it with the acme-server
dd5f36e5 327if [[ "${register}" = "1" ]]; then
f13eaa7f 328 echo "+ Registering account key with letsencrypt..."
09729186
LS
329 if [ -z "${CA_NEW_REG}" ]; then
330 echo " + ERROR: Certificate authority doesn't allow registrations."
331 exit 1
332 fi
ea5b70a3 333 # if an email for the contact has been provided then adding it to the registration request
09729186
LS
334 if [[ -n "${CONTACT_EMAIL}" ]]; then
335 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
ea5b70a3 336 else
09729186 337 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
ea5b70a3 338 fi
f13eaa7f
LS
339fi
340
1f08fda7
LS
341if [[ -e "${BASEDIR}/domains.txt" ]]; then
342 DOMAINS_TXT="${BASEDIR}/domains.txt"
343elif [[ -e "${SCRIPTDIR}/domains.txt" ]]; then
344 DOMAINS_TXT="${SCRIPTDIR}/domains.txt"
345else
440dc30d
LS
346 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
347 exit 1
348fi
349
3390080c
LS
350if [[ ! -e "${WELLKNOWN}" ]]; then
351 mkdir -p "${WELLKNOWN}"
352fi
353
063d28a6
MG
354# revoke certificate by user request
355if [[ "${1:-}" = "revoke" ]]; then
356 if [[ -z "{2:-}" ]] || [[ ! -f "${2}" ]]; then
ead15632 357 echo "Usage: ${0} revoke path/to/cert.pem"
063d28a6
MG
358 exit 1
359 fi
c24843c6 360
063d28a6
MG
361 echo "Revoking ${2}"
362 revoke_cert "${2}"
363
364 exit 0
365fi
366
1f08fda7
LS
367# Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
368<"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
1369c9af 369 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
5b29db97 370 cert="${BASEDIR}/certs/${domain}/cert.pem"
579e2316
MG
371
372 echo "Processing ${domain}"
373 if [[ -e "${cert}" ]]; then
374 echo " + Found existing cert..."
375
5b29db97 376 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
579e2316
MG
377
378 echo -n " + Valid till ${valid} "
c10390fb 379 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
579e2316
MG
380 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
381 continue
5060dea0 382 fi
579e2316 383 echo "(Less than ${RENEW_DAYS} days). Renewing!"
5060dea0
MG
384 fi
385
219b3e9d 386 # shellcheck disable=SC2086
6221526d 387 sign_domain $line
61f0b7ed 388done