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