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