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