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"
13 WELLKNOWN=".acme-challenges"
17 if [[ -e "config.sh" ]]; then
21 umask 077 # paranoid umask, we're creating private keys
28 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
29 openssl base64 -e | anti_newline | sed -r 's/=*$//g' | tr '+/' '-_'
33 # Store hex string from stdin
38 for ((i=0; i<${#tmphex}; i+=1)); do
39 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
43 test $((${#hex} & 1)) == 0 || hex="0${hex}"
45 # Convert to escaped string
47 for ((i=0; i<${#hex}; i+=2)); do
48 escapedhex=$escapedhex\\x${hex:$i:2}
51 # Convert to binary data
52 printf "${escapedhex}"
58 if [[ "${1}" = "head" ]]; then
59 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
60 elif [[ "${1}" = "get" ]]; then
61 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
62 elif [[ "${1}" = "post" ]]; then
63 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
66 if [[ ! "${statuscode:0:1}" = "2" ]]; then
67 echo " + ERROR: An error occured while sending ${1}-request to ${2} (Status ${statuscode})" >&2
70 echo "$(<"${tempcont}"))" >&2
80 # Encode payload as urlbase64
81 payload64="$(printf '%s' "${2}" | urlbase64)"
83 # Retrieve nonce from acme-server
84 nonce="$(_request head "${CA}/directory" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
86 # Build header with just our public key and algorithm information
87 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
89 # Build another header which also contains the previously received nonce and encode it as urlbase64
90 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
91 protected64="$(printf '%s' "${protected}" | urlbase64)"
93 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
94 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
96 # Send header + extended header + payload + signature to the acme-server
97 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
99 _request post "${1}" "${data}"
105 echo " + Signing domains..."
107 # If there is no existing certificate directory => make it
108 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
109 echo " + make directory ${BASEDIR}/certs/${domain} ..."
110 mkdir -p "${BASEDIR}/certs/${domain}"
113 # generate a new private key if we need or want one
114 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
115 echo " + Generating private key..."
116 timestamp="$(date +%s)"
117 openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
118 rm -f "${BASEDIR}/certs/${domain}/privkey.pem"
119 ln -s "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
122 # Generate signing request config and the actual signing request
124 for altname in $altnames; do
125 SAN+="DNS:${altname}, "
127 SAN="$(printf '%s' "${SAN}" | sed 's/,\s*$//g')"
128 echo " + Generating signing request..."
129 openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/privkey.pem" -out "${BASEDIR}/certs/${domain}/cert.csr" -subj "/CN=${domain}/" -reqexts SAN -config <(cat /etc/ssl/openssl.cnf <(printf "[SAN]\nsubjectAltName=%s" "${SAN}")) > /dev/null
131 # Request and respond to challenges
132 for altname in $altnames; do
133 # Ask the acme-server for new challenge token and extract them from the resulting json block
134 echo " + Requesting challenge for ${altname}..."
135 response="$(signed_request "${CA}/acme/new-authz" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
137 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')"
138 challenge_uri="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]' | sed 's/{/\n{/g' | grep 'http-01' | grep -Eo '"uri":\s*"[^"]*"' | cut -d'"' -f4)"
140 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
141 echo " + Error: Can't retrieve challenges (${response})"
145 # Challenge response consists of the challenge token and the thumbprint of our public certificate
146 keyauth="${challenge_token}.${thumbprint}"
148 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
149 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
150 chmod a+r "${WELLKNOWN}/${challenge_token}"
152 # Wait for hook script to deploy the challenge if used
153 if [ -n "${HOOK_CHALLENGE}" ]; then
154 ${HOOK_CHALLENGE} "${WELLKNOWN}/${challenge_token}" "${keyauth}"
157 # Ask the acme-server to verify our challenge and wait until it becomes valid
158 echo " + Responding to challenge for ${altname}..."
159 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
161 status="$(printf '%s\n' "${result}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
163 # get status until it a result is reached => not pending anymore
164 while [[ "${status}" = "pending" ]]; do
166 status="$(_request get "${challenge_uri}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
169 if [[ "${status}" = "valid" ]]; then
170 echo " + Challenge is valid!"
172 echo " + Challenge is invalid! (returned: ${status})"
178 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
179 echo " + Requesting certificate..."
180 timestamp="$(date +%s)"
181 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert.csr" -outform DER | urlbase64)"
182 crt64="$(signed_request "${CA}/acme/new-cert" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
183 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
184 rm -f "${BASEDIR}/certs/${domain}/cert.pem"
185 ln -s "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
189 # Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
191 if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
192 echo "+ Generating account key..."
193 openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
197 # Get public components from private key and calculate thumbprint
198 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
199 pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
201 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
203 # If we generated a new private key in the step above we have to register it with the acme-server
204 if [[ "${register}" = "1" ]]; then
205 echo "+ Registering account key with letsencrypt..."
206 signed_request "${CA}/acme/new-reg" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
209 if [[ ! -e "domains.txt" ]]; then
210 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
214 if [[ ! -e "${WELLKNOWN}" ]]; then
215 mkdir -p "${WELLKNOWN}"
218 # Generate certificates for all domains found in domain.txt. Check if existing certificate are about to expire
219 <domains.txt sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
220 domain="$(echo $line | cut -d' ' -f1)"
221 cert="${BASEDIR}/certs/${domain}/cert.pem"
223 echo "Processing ${domain}"
224 if [[ -e "${cert}" ]]; then
225 echo " + Found existing cert..."
227 # Turning off exit on non-zero status for cert validation
228 set +e; openssl x509 -checkend $((${RENEW_DAYS} * 86400)) -noout -in "${cert}"; expiring=$?; set -e
229 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
231 echo -n " + Valid till ${valid} "
232 if [[ ${expiring} -eq 0 ]]; then
233 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
236 echo "(Less than ${RENEW_DAYS} days). Renewing!"