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