]> git.street.me.uk Git - andy/dehydrated.git/blob - letsencrypt.sh
delete challenge response after verification
[andy/dehydrated.git] / letsencrypt.sh
1 #!/usr/bin/env bash
2
3 set -e
4 set -u
5 set -o pipefail
6
7 # Default config values
8 CA="https://acme-v01.api.letsencrypt.org"
9 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
10 HOOK_CHALLENGE=
11 RENEW_DAYS="14"
12 KEYSIZE="4096"
13 WELLKNOWN=".acme-challenges"
14 PRIVATE_KEY_RENEW=no
15 BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
16 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
17
18 # If exists load config from same directory as this script
19 if [[ -e "${BASEDIR}/config.sh" ]]; then
20   # shellcheck disable=SC1090
21   . "${BASEDIR}/config.sh"
22 fi
23
24 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
25 BASEDIR="${BASEDIR%%/}"
26
27 umask 077 # paranoid umask, we're creating private keys
28
29 anti_newline() {
30   tr -d '\n\r'
31 }
32
33 urlbase64() {
34   # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
35   openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
36 }
37
38 hex2bin() {
39   # Store hex string from stdin
40   tmphex="$(cat)"
41
42   # Remove spaces
43   hex=''
44   for ((i=0; i<${#tmphex}; i+=1)); do
45     test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
46   done
47
48   # Add leading zero
49   test $((${#hex} & 1)) == 0 || hex="0${hex}"
50
51   # Convert to escaped string
52   escapedhex=''
53   for ((i=0; i<${#hex}; i+=2)); do
54     escapedhex=$escapedhex\\x${hex:$i:2}
55   done
56
57   # Convert to binary data
58   printf -- "${escapedhex}"
59 }
60
61 _request() {
62   tempcont="$(mktemp)"
63
64   if [[ "${1}" = "head" ]]; then
65     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
66   elif [[ "${1}" = "get" ]]; then
67     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
68   elif [[ "${1}" = "post" ]]; then
69     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
70   fi
71
72   if [[ ! "${statuscode:0:1}" = "2" ]]; then
73     echo "  + ERROR: An error occured while sending ${1}-request to ${2} (Status ${statuscode})" >&2
74     echo >&2
75     echo "Details:" >&2
76     echo "$(<"${tempcont}"))" >&2
77     rm -f "${tempcont}"
78     exit 1
79   fi
80
81   cat  "${tempcont}"
82   rm -f "${tempcont}"
83 }
84
85 signed_request() {
86   # Encode payload as urlbase64
87   payload64="$(printf '%s' "${2}" | urlbase64)"
88
89   # Retrieve nonce from acme-server
90   nonce="$(_request head "${CA}/directory" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
91
92   # Build header with just our public key and algorithm information
93   header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
94
95   # Build another header which also contains the previously received nonce and encode it as urlbase64
96   protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
97   protected64="$(printf '%s' "${protected}" | urlbase64)"
98
99   # Sign header with nonce and our payload with our private key and encode signature as urlbase64
100   signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
101
102   # Send header + extended header + payload + signature to the acme-server
103   data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
104
105   _request post "${1}" "${data}"
106 }
107
108 sign_domain() {
109   domain="${1}"
110   altnames="${*}"
111   echo " + Signing domains..."
112
113   # If there is no existing certificate directory => make it
114   if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
115     echo " + make directory ${BASEDIR}/certs/${domain} ..."
116     mkdir -p "${BASEDIR}/certs/${domain}"
117   fi
118
119   # generate a new private key if we need or want one
120   if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
121     echo " + Generating private key..."
122     timestamp="$(date +%s)"
123     openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
124     rm -f "${BASEDIR}/certs/${domain}/privkey.pem"
125     ln -s "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
126   fi
127
128   # Generate signing request config and the actual signing request
129   SAN=""
130   for altname in $altnames; do
131     SAN+="DNS:${altname}, "
132   done
133   SAN="${SAN%%, }"
134   echo " + Generating signing request..."
135   openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/privkey.pem" -out "${BASEDIR}/certs/${domain}/cert.csr" -subj "/CN=${domain}/" -reqexts SAN -config <(cat "${OPENSSL_CNF}" <(printf "[SAN]\nsubjectAltName=%s" "${SAN}")) > /dev/null
136
137   # Request and respond to challenges
138   for altname in $altnames; do
139     # Ask the acme-server for new challenge token and extract them from the resulting json block
140     echo " + Requesting challenge for ${altname}..."
141     response="$(signed_request "${CA}/acme/new-authz" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
142
143     challenges="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]')"
144     challenge="$(printf "%s" "${challenges//\{/$'\n'{}" | grep 'http-01')"
145     challenge_token="$(printf '%s' "${challenge}" | grep -Eo '"token":\s*"[^"]*"' | cut -d'"' -f4 | sed 's/[^A-Za-z0-9_\-]/_/g')"
146     challenge_uri="$(printf '%s' "${challenge}" | grep -Eo '"uri":\s*"[^"]*"' | cut -d'"' -f4)"
147
148     if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
149       echo "  + Error: Can't retrieve challenges (${response})"
150       exit 1
151     fi
152
153     # Challenge response consists of the challenge token and the thumbprint of our public certificate
154     keyauth="${challenge_token}.${thumbprint}"
155
156     # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
157     printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
158     chmod a+r "${WELLKNOWN}/${challenge_token}"
159
160     # Wait for hook script to deploy the challenge if used
161     if [ -n "${HOOK_CHALLENGE}" ]; then
162         ${HOOK_CHALLENGE} "${WELLKNOWN}/${challenge_token}" "${keyauth}"
163     fi
164
165     # Ask the acme-server to verify our challenge and wait until it becomes valid
166     echo " + Responding to challenge for ${altname}..."
167     result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
168
169     status="$(printf '%s\n' "${result}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
170
171     # get status until it a result is reached => not pending anymore    
172     while [[ "${status}" = "pending" ]]; do
173       sleep 1
174       status="$(_request get "${challenge_uri}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
175     done
176
177     rm -f "${WELLKNOWN}/${challenge_token}"
178
179     if [[ "${status}" = "valid" ]]; then
180       echo " + Challenge is valid!"
181     else
182       echo " + Challenge is invalid! (returned: ${status})"
183       exit 1
184     fi
185
186   done
187
188   # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
189   echo " + Requesting certificate..."
190   timestamp="$(date +%s)"
191   csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert.csr" -outform DER | urlbase64)"
192   crt64="$(signed_request "${CA}/acme/new-cert" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
193   printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
194   rm -f "${BASEDIR}/certs/${domain}/cert.pem"
195   ln -s "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
196   echo " + Done!"
197 }
198
199 # Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
200 register="0"
201 if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
202   echo "+ Generating account key..."
203   openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
204   register="1"
205 fi
206
207 # Get public components from private key and calculate thumbprint
208 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
209 pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
210
211 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
212
213 # If we generated a new private key in the step above we have to register it with the acme-server
214 if [[ "${register}" = "1" ]]; then
215   echo "+ Registering account key with letsencrypt..."
216   signed_request "${CA}/acme/new-reg" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
217 fi
218
219 if [[ ! -e "domains.txt" ]]; then
220   echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
221   exit 1
222 fi
223
224 if [[ ! -e "${WELLKNOWN}" ]]; then
225   mkdir -p "${WELLKNOWN}"
226 fi
227
228 # Generate certificates for all domains found in domain.txt. Check if existing certificate are about to expire
229 <domains.txt sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
230   domain="$(echo "${line}" | cut -d' ' -f1)"
231   cert="${BASEDIR}/certs/${domain}/cert.pem"
232
233   echo "Processing ${domain}"
234   if [[ -e "${cert}" ]]; then
235     echo " + Found existing cert..."
236
237     # Turning off exit on non-zero status for cert validation
238     set +e; openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; expiring=$?; set -e
239     valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
240
241     echo -n " + Valid till ${valid} "
242     if [[ ${expiring} -eq 0 ]]; then
243       echo "(Longer than ${RENEW_DAYS} days). Skipping!"
244       continue
245     fi
246     echo "(Less than ${RENEW_DAYS} days). Renewing!"
247   fi
248
249   # shellcheck disable=SC2086
250   sign_domain $line
251 done