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