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