7 # Get the directory in which this script is stored
8 SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
10 # Default config values
11 CA="https://acme-v01.api.letsencrypt.org"
12 LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
16 WELLKNOWN="${SCRIPTDIR}/.acme-challenges"
17 PRIVATE_KEY_RENEW="no"
18 BASEDIR="${SCRIPTDIR}"
19 OPENSSL_CNF="$(openssl version -d | cut -d'"' -f2)/openssl.cnf"
20 ROOTCERT="lets-encrypt-x1-cross-signed.pem"
23 # Check for config in various locations
25 for check_config in "${SCRIPTDIR}" "${HOME}/.letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "/etc/letsencrypt.sh" "${PWD}"; do
26 if [[ -e "${check_config}/config.sh" ]]; then
27 BASEDIR="${check_config}"
28 CONFIG="${check_config}/config.sh"
33 if [[ -z "${CONFIG}" ]]; then
34 echo "WARNING: No config file found, using default config!"
37 echo "Using config file ${check_config}"
38 # shellcheck disable=SC1090
42 # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
43 BASEDIR="${BASEDIR%%/}"
45 umask 077 # paranoid umask, we're creating private keys
47 # Export some environment variables to be used in hook script
57 # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
58 openssl base64 -e | anti_newline | sed 's/=*$//g' | tr '+/' '-_'
62 # Store hex string from stdin
67 for ((i=0; i<${#tmphex}; i+=1)); do
68 test "${tmphex:$i:1}" == " " || hex="${hex}${tmphex:$i:1}"
72 test $((${#hex} & 1)) == 0 || hex="0${hex}"
74 # Convert to escaped string
76 for ((i=0; i<${#hex}; i+=2)); do
77 escapedhex=$escapedhex\\x${hex:$i:2}
80 # Convert to binary data
81 printf -- "${escapedhex}"
87 if [[ "${1}" = "head" ]]; then
88 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
89 elif [[ "${1}" = "get" ]]; then
90 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
91 elif [[ "${1}" = "post" ]]; then
92 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
95 if [[ ! "${statuscode:0:1}" = "2" ]]; then
96 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
99 echo "$(<"${tempcont}"))" >&2
102 # Wait for hook script to clean the challenge if used
103 if [[ -n "${HOOK}" ]]; then
104 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
114 # Only way to capture the output and exit code is to disable set -e.
119 if [[ $res -ne 0 ]]; then
120 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
127 # OpenSSL writes to stderr/stdout even when there are no errors. So just
128 # display the output if the exit code was != 0 to simplify debugging.
130 _output_on_error openssl "$@"
134 # Encode payload as urlbase64
135 payload64="$(printf '%s' "${2}" | urlbase64)"
137 # Retrieve nonce from acme-server
138 nonce="$(_request head "${CA}/directory" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
140 # Build header with just our public key and algorithm information
141 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
143 # Build another header which also contains the previously received nonce and encode it as urlbase64
144 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
145 protected64="$(printf '%s' "${protected}" | urlbase64)"
147 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
148 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
150 # Send header + extended header + payload + signature to the acme-server
151 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
153 _request post "${1}" "${data}"
158 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
159 response="$(signed_request "${CA}/acme/revoke-cert" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
160 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
161 # so if we are here, it is safe to assume the request was successful
163 echo " + renaming certificate to ${cert}-revoked"
164 mv -f "${cert}" "${cert}-revoked"
170 echo " + Signing domains..."
172 timestamp="$(date +%s)"
174 # If there is no existing certificate directory => make it
175 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
176 echo " + make directory ${BASEDIR}/certs/${domain} ..."
177 mkdir -p "${BASEDIR}/certs/${domain}"
180 privkey="privkey.pem"
181 # generate a new private key if we need or want one
182 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
183 echo " + Generating private key..."
184 privkey="privkey-${timestamp}.pem"
185 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
188 # Generate signing request config and the actual signing request
190 for altname in $altnames; do
191 SAN+="DNS:${altname}, "
194 echo " + Generating signing request..."
195 openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config <(cat "${OPENSSL_CNF}" <(printf "[SAN]\nsubjectAltName=%s" "${SAN}"))
197 # Request and respond to challenges
198 for altname in $altnames; do
199 # Ask the acme-server for new challenge token and extract them from the resulting json block
200 echo " + Requesting challenge for ${altname}..."
201 response="$(signed_request "${CA}/acme/new-authz" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
203 challenges="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]')"
204 repl=$'\n''{' # fix syntax highlighting in Vim
205 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
206 challenge_token="$(printf '%s' "${challenge}" | grep -Eo '"token":\s*"[^"]*"' | cut -d'"' -f4 | sed 's/[^A-Za-z0-9_\-]/_/g')"
207 challenge_uri="$(printf '%s' "${challenge}" | grep -Eo '"uri":\s*"[^"]*"' | cut -d'"' -f4)"
209 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
210 echo " + Error: Can't retrieve challenges (${response})"
214 # Challenge response consists of the challenge token and the thumbprint of our public certificate
215 keyauth="${challenge_token}.${thumbprint}"
217 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
218 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
219 chmod a+r "${WELLKNOWN}/${challenge_token}"
221 # Wait for hook script to deploy the challenge if used
222 if [[ -n "${HOOK}" ]]; then
223 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
226 # Ask the acme-server to verify our challenge and wait until it becomes valid
227 echo " + Responding to challenge for ${altname}..."
228 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
230 status="$(printf '%s\n' "${result}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
232 # get status until a result is reached => not pending anymore
233 while [[ "${status}" = "pending" ]]; do
235 status="$(_request get "${challenge_uri}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
238 rm -f "${WELLKNOWN}/${challenge_token}"
240 if [[ "${status}" = "valid" ]]; then
241 echo " + Challenge is valid!"
243 echo " + Challenge is invalid! (returned: ${status})"
245 # Wait for hook script to clean the challenge if used
246 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
247 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
255 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
256 echo " + Requesting certificate..."
257 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
258 crt64="$(signed_request "${CA}/acme/new-cert" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
259 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
261 # Create fullchain.pem
262 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]] || [[ -e "${SCRIPTDIR}/certs/${ROOTCERT}" ]]; then
263 echo " + Creating fullchain.pem..."
264 cat "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
265 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]]; then
266 cat "${BASEDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
268 cat "${SCRIPTDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
270 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
273 # Update remaining symlinks
274 if [ ! "${privkey}" = "privkey.pem" ]; then
275 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
278 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
279 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
281 # Wait for hook script to clean the challenge and to deploy cert if used
282 if [[ -n "${HOOK}" ]]; then
283 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
286 unset challenge_token
290 # Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
292 if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
293 echo "+ Generating account key..."
294 _openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}"
298 # Get public components from private key and calculate thumbprint
299 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
300 pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
302 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
304 # If we generated a new private key in the step above we have to register it with the acme-server
305 if [[ "${register}" = "1" ]]; then
306 echo "+ Registering account key with letsencrypt..."
307 # if an email for the contact has been provided then adding it to the registration request
308 if [ -n "${CONTACT_EMAIL}" ]; then
309 signed_request "${CA}/acme/new-reg" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
311 signed_request "${CA}/acme/new-reg" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
315 if [[ -e "${BASEDIR}/domains.txt" ]]; then
316 DOMAINS_TXT="${BASEDIR}/domains.txt"
317 elif [[ -e "${SCRIPTDIR}/domains.txt" ]]; then
318 DOMAINS_TXT="${SCRIPTDIR}/domains.txt"
320 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
324 if [[ ! -e "${WELLKNOWN}" ]]; then
325 mkdir -p "${WELLKNOWN}"
328 # revoke certificate by user request
329 if [[ "${1:-}" = "revoke" ]]; then
330 if [[ -z "{2:-}" ]] || [[ ! -f "${2}" ]]; then
331 echo "Usage: ${0} revoke path/to/cert.pem"
341 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
342 <"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
343 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
344 cert="${BASEDIR}/certs/${domain}/cert.pem"
346 echo "Processing ${domain}"
347 if [[ -e "${cert}" ]]; then
348 echo " + Found existing cert..."
350 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
352 echo -n " + Valid till ${valid} "
353 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
354 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
357 echo "(Less than ${RENEW_DAYS} days). Renewing!"
360 # shellcheck disable=SC2086