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