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