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