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