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