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