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"
15 BASEDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
16 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
18 # If exists load config from same directory as this script
19 if [[ -e "${BASEDIR}/config.sh" ]]; then
20 # shellcheck disable=SC1090
21 . "${BASEDIR}/config.sh"
24 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
25 BASEDIR="${BASEDIR%%/}"
27 umask 077 # paranoid umask, we're creating private keys
34 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
35 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
39 # Store hex string from stdin
44 for ((i=0; i<${#tmphex}; i+=1)); do
45 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
49 test $((${#hex} & 1)) == 0 || hex="0${hex}"
51 # Convert to escaped string
53 for ((i=0; i<${#hex}; i+=2)); do
54 escapedhex=$escapedhex\\x${hex:$i:2}
57 # Convert to binary data
58 printf -- "${escapedhex}"
64 if [[ "${1}" = "head" ]]; then
65 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
66 elif [[ "${1}" = "get" ]]; then
67 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
68 elif [[ "${1}" = "post" ]]; then
69 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
72 if [[ ! "${statuscode:0:1}" = "2" ]]; then
73 echo " + ERROR: An error occured while sending ${1}-request to ${2} (Status ${statuscode})" >&2
76 echo "$(<"${tempcont}"))" >&2
86 # Encode payload as urlbase64
87 payload64="$(printf '%s' "${2}" | urlbase64)"
89 # Retrieve nonce from acme-server
90 nonce="$(_request head "${CA}/directory" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
92 # Build header with just our public key and algorithm information
93 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
95 # Build another header which also contains the previously received nonce and encode it as urlbase64
96 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
97 protected64="$(printf '%s' "${protected}" | urlbase64)"
99 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
100 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
102 # Send header + extended header + payload + signature to the acme-server
103 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
105 _request post "${1}" "${data}"
111 echo " + Signing domains..."
113 # If there is no existing certificate directory => make it
114 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
115 echo " + make directory ${BASEDIR}/certs/${domain} ..."
116 mkdir -p "${BASEDIR}/certs/${domain}"
119 # generate a new private key if we need or want one
120 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
121 echo " + Generating private key..."
122 timestamp="$(date +%s)"
123 openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
124 rm -f "${BASEDIR}/certs/${domain}/privkey.pem"
125 ln -s "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
128 # Generate signing request config and the actual signing request
130 for altname in $altnames; do
131 SAN+="DNS:${altname}, "
134 echo " + Generating signing request..."
135 openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/privkey.pem" -out "${BASEDIR}/certs/${domain}/cert.csr" -subj "/CN=${domain}/" -reqexts SAN -config <(cat "${OPENSSL_CNF}" <(printf "[SAN]\nsubjectAltName=%s" "${SAN}")) > /dev/null
137 # Request and respond to challenges
138 for altname in $altnames; do
139 # Ask the acme-server for new challenge token and extract them from the resulting json block
140 echo " + Requesting challenge for ${altname}..."
141 response="$(signed_request "${CA}/acme/new-authz" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
143 challenges="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]')"
144 challenge="$(printf "%s" "${challenges//\{/$'\n'{}" | grep 'http-01')"
145 challenge_token="$(printf '%s' "${challenge}" | grep -Eo '"token":\s*"[^"]*"' | cut -d'"' -f4 | sed 's/[^A-Za-z0-9_\-]/_/g')"
146 challenge_uri="$(printf '%s' "${challenge}" | grep -Eo '"uri":\s*"[^"]*"' | cut -d'"' -f4)"
148 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
149 echo " + Error: Can't retrieve challenges (${response})"
153 # Challenge response consists of the challenge token and the thumbprint of our public certificate
154 keyauth="${challenge_token}.${thumbprint}"
156 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
157 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
158 chmod a+r "${WELLKNOWN}/${challenge_token}"
160 # Wait for hook script to deploy the challenge if used
161 if [ -n "${HOOK_CHALLENGE}" ]; then
162 ${HOOK_CHALLENGE} "${WELLKNOWN}/${challenge_token}" "${keyauth}"
165 # Ask the acme-server to verify our challenge and wait until it becomes valid
166 echo " + Responding to challenge for ${altname}..."
167 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
169 status="$(printf '%s\n' "${result}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
171 # get status until it a result is reached => not pending anymore
172 while [[ "${status}" = "pending" ]]; do
174 status="$(_request get "${challenge_uri}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
177 rm -f "${WELLKNOWN}/${challenge_token}"
179 if [[ "${status}" = "valid" ]]; then
180 echo " + Challenge is valid!"
182 echo " + Challenge is invalid! (returned: ${status})"
188 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
189 echo " + Requesting certificate..."
190 timestamp="$(date +%s)"
191 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert.csr" -outform DER | urlbase64)"
192 crt64="$(signed_request "${CA}/acme/new-cert" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
193 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
194 rm -f "${BASEDIR}/certs/${domain}/cert.pem"
195 ln -s "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
199 # Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
201 if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
202 echo "+ Generating account key..."
203 openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
207 # Get public components from private key and calculate thumbprint
208 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
209 pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
211 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
213 # If we generated a new private key in the step above we have to register it with the acme-server
214 if [[ "${register}" = "1" ]]; then
215 echo "+ Registering account key with letsencrypt..."
216 signed_request "${CA}/acme/new-reg" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
219 if [[ ! -e "domains.txt" ]]; then
220 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
224 if [[ ! -e "${WELLKNOWN}" ]]; then
225 mkdir -p "${WELLKNOWN}"
228 # Generate certificates for all domains found in domain.txt. Check if existing certificate are about to expire
229 <domains.txt sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
230 domain="$(echo "${line}" | cut -d' ' -f1)"
231 cert="${BASEDIR}/certs/${domain}/cert.pem"
233 echo "Processing ${domain}"
234 if [[ -e "${cert}" ]]; then
235 echo " + Found existing cert..."
237 # Turning off exit on non-zero status for cert validation
238 set +e; openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; expiring=$?; set -e
239 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
241 echo -n " + Valid till ${valid} "
242 if [[ ${expiring} -eq 0 ]]; then
243 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
246 echo "(Less than ${RENEW_DAYS} days). Renewing!"
249 # shellcheck disable=SC2086