]> git.street.me.uk Git - andy/dehydrated.git/blob - letsencrypt.sh
replace echo with printf
[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 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}"
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
114 signed_request() {
115   # Encode payload as urlbase64
116   payload64="$(printf '%s' "${2}" | urlbase64)"
117
118   # Retrieve nonce from acme-server
119   nonce="$(_request head "${CA}/directory" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
120
121   # Build header with just our public key and algorithm information
122   header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
123
124   # Build another header which also contains the previously received nonce and encode it as urlbase64
125   protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
126   protected64="$(printf '%s' "${protected}" | urlbase64)"
127
128   # Sign header with nonce and our payload with our private key and encode signature as urlbase64
129   signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
130
131   # Send header + extended header + payload + signature to the acme-server
132   data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
133
134   _request post "${1}" "${data}"
135 }
136
137 revoke_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
148 sign_domain() {
149   domain="${1}"
150   altnames="${*}"
151   echo " + Signing domains..."
152
153   timestamp="$(date +%s)"
154
155   # If there is no existing certificate directory => make it
156   if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
157     echo " + make directory ${BASEDIR}/certs/${domain} ..."
158     mkdir -p "${BASEDIR}/certs/${domain}"
159   fi
160
161   privkey="privkey.pem"
162   # generate a new private key if we need or want one
163   if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
164     echo " + Generating private key..."
165     privkey="privkey-${timestamp}.pem"
166     openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
167   fi
168
169   # Generate signing request config and the actual signing request
170   SAN=""
171   for altname in $altnames; do
172     SAN+="DNS:${altname}, "
173   done
174   SAN="${SAN%%, }"
175   echo " + Generating signing request..."
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
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
181     echo " + Requesting challenge for ${altname}..."
182     response="$(signed_request "${CA}/acme/new-authz" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
183
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)"
188
189     if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
190       echo "  + Error: Can't retrieve challenges (${response})"
191       exit 1
192     fi
193
194     # Challenge response consists of the challenge token and the thumbprint of our public certificate
195     keyauth="${challenge_token}.${thumbprint}"
196
197     # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
198     printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
199     chmod a+r "${WELLKNOWN}/${challenge_token}"
200
201     # Wait for hook script to deploy the challenge if used
202     if [[ -n "${HOOK}" ]]; then
203         ${HOOK} "deploy_challenge" "${challenge_token}" "${keyauth}"
204     fi
205
206     # Ask the acme-server to verify our challenge and wait until it becomes valid
207     echo " + Responding to challenge for ${altname}..."
208     result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
209
210     status="$(printf '%s\n' "${result}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
211
212     # get status until a result is reached => not pending anymore
213     while [[ "${status}" = "pending" ]]; do
214       sleep 1
215       status="$(_request get "${challenge_uri}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
216     done
217
218     rm -f "${WELLKNOWN}/${challenge_token}"
219
220     if [[ "${status}" = "valid" ]]; then
221       echo " + Challenge is valid!"
222     else
223       echo " + Challenge is invalid! (returned: ${status})"
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
230       exit 1
231     fi
232
233   done
234
235   # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
236   echo " + Requesting certificate..."
237   csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
238   crt64="$(signed_request "${CA}/acme/new-cert" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
239   printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
240
241   # Create fullchain.pem
242   if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]] || [[ -e "${SCRIPTDIR}/certs/${ROOTCERT}" ]]; then
243     echo " + Creating fullchain.pem..."
244     cat "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
245     if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]]; then
246       cat "${BASEDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
247     else
248       cat "${SCRIPTDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
249     fi
250     ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
251   fi
252
253   # Update remaining symlinks
254   if [ ! "${privkey}" = "privkey.pem" ]; then
255     ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
256   fi
257
258   ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
259   ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
260
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
267   echo " + Done!"
268 }
269
270 # Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
271 register="0"
272 if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
273   echo "+ Generating account key..."
274   openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
275   register="1"
276 fi
277
278 # Get public components from private key and calculate thumbprint
279 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
280 pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
281
282 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
283
284 # If we generated a new private key in the step above we have to register it with the acme-server
285 if [[ "${register}" = "1" ]]; then
286   echo "+ Registering account key with letsencrypt..."
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
293 fi
294
295 if [[ -e "${BASEDIR}/domains.txt" ]]; then
296   DOMAINS_TXT="${BASEDIR}/domains.txt"
297 elif [[ -e "${SCRIPTDIR}/domains.txt" ]]; then
298   DOMAINS_TXT="${SCRIPTDIR}/domains.txt"
299 else
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
302 fi
303
304 if [[ ! -e "${WELLKNOWN}" ]]; then
305   mkdir -p "${WELLKNOWN}"
306 fi
307
308 # revoke certificate by user request
309 if [[ "${1:-}" = "revoke" ]]; then
310   if [[ -z "{2:-}" ]] || [[ ! -f "${2}" ]]; then
311     echo "Usage: ${0} revoke path/to/cert.pem"
312     exit 1
313   fi
314
315   echo "Revoking ${2}"
316   revoke_cert "${2}"
317
318   exit 0
319 fi
320
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
323   domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
324   cert="${BASEDIR}/certs/${domain}/cert.pem"
325
326   echo "Processing ${domain}"
327   if [[ -e "${cert}" ]]; then
328     echo " + Found existing cert..."
329
330     valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
331
332     echo -n " + Valid till ${valid} "
333     if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
334       echo "(Longer than ${RENEW_DAYS} days). Skipping!"
335       continue
336     fi
337     echo "(Less than ${RENEW_DAYS} days). Renewing!"
338   fi
339
340   # shellcheck disable=SC2086
341   sign_domain $line
342 done