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/directory"
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 ${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}"
84 get_json_string_value() {
85 grep -Eo '"'"${1}"'":\s*"[^"]*"' | cut -d'"' -f4
89 grep -Eo '"'"${1}"'":[^\[]*\[[^]]*]'
95 if [[ "${1}" = "head" ]]; then
96 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
97 elif [[ "${1}" = "get" ]]; then
98 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
99 elif [[ "${1}" = "post" ]]; then
100 statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
103 if [[ ! "${statuscode:0:1}" = "2" ]]; then
104 echo " + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
107 echo "$(<"${tempcont}"))" >&2
110 # Wait for hook script to clean the challenge if used
111 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token:+set}" ]]; then
112 ${HOOK} "clean_challenge" '' "${challenge_token}" "${keyauth}"
122 # Only way to capture the output and exit code is to disable set -e.
127 if [[ $res -ne 0 ]]; then
128 echo " + ERROR: failed to run $* (Exitcode: $res)" >&2
135 # OpenSSL writes to stderr/stdout even when there are no errors. So just
136 # display the output if the exit code was != 0 to simplify debugging.
138 _output_on_error openssl "$@"
142 # Encode payload as urlbase64
143 payload64="$(printf '%s' "${2}" | urlbase64)"
145 # Retrieve nonce from acme-server
146 nonce="$(_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
148 # Build header with just our public key and algorithm information
149 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
151 # Build another header which also contains the previously received nonce and encode it as urlbase64
152 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
153 protected64="$(printf '%s' "${protected}" | urlbase64)"
155 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
156 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
158 # Send header + extended header + payload + signature to the acme-server
159 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
161 _request post "${1}" "${data}"
165 if [ -z "${CA_REVOKE_CERT}" ]; then
166 echo " + ERROR: Certificate authority doesn't allow certificate revocation."
170 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
171 response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
172 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
173 # so if we are here, it is safe to assume the request was successful
175 echo " + renaming certificate to ${cert}-revoked"
176 mv -f "${cert}" "${cert}-revoked"
182 echo " + Signing domains..."
183 if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
184 echo " + ERROR: Certificate authority doesn't allow certificate signing"
187 timestamp="$(date +%s)"
189 # If there is no existing certificate directory => make it
190 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
191 echo " + make directory ${BASEDIR}/certs/${domain} ..."
192 mkdir -p "${BASEDIR}/certs/${domain}"
195 privkey="privkey.pem"
196 # generate a new private key if we need or want one
197 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
198 echo " + Generating private key..."
199 privkey="privkey-${timestamp}.pem"
200 _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}"
203 # Generate signing request config and the actual signing request
205 for altname in $altnames; do
206 SAN+="DNS:${altname}, "
209 echo " + Generating signing request..."
210 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}"))
212 # Request and respond to challenges
213 for altname in $altnames; do
214 # Ask the acme-server for new challenge token and extract them from the resulting json block
215 echo " + Requesting challenge for ${altname}..."
216 response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
218 challenges="$(printf '%s\n' "${response}" | get_json_array challenges)"
219 repl=$'\n''{' # fix syntax highlighting in Vim
220 challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep 'http-01')"
221 challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | sed 's/[^A-Za-z0-9_\-]/_/g')"
222 challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
224 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
225 echo " + Error: Can't retrieve challenges (${response})"
229 # Challenge response consists of the challenge token and the thumbprint of our public certificate
230 keyauth="${challenge_token}.${thumbprint}"
232 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
233 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
234 chmod a+r "${WELLKNOWN}/${challenge_token}"
236 # Wait for hook script to deploy the challenge if used
237 if [[ -n "${HOOK}" ]]; then
238 ${HOOK} "deploy_challenge" "${altname}" "${challenge_token}" "${keyauth}"
241 # Ask the acme-server to verify our challenge and wait until it becomes valid
242 echo " + Responding to challenge for ${altname}..."
243 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
245 status="$(printf '%s\n' "${result}" | get_json_string_value status)"
247 # get status until a result is reached => not pending anymore
248 while [[ "${status}" = "pending" ]]; do
250 status="$(_request get "${challenge_uri}" | get_json_string_value status)"
253 rm -f "${WELLKNOWN}/${challenge_token}"
255 if [[ "${status}" = "valid" ]]; then
256 echo " + Challenge is valid!"
258 echo " + Challenge is invalid! (returned: ${status})"
260 # Wait for hook script to clean the challenge if used
261 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
262 ${HOOK} "clean_challenge" "${altname}" "${challenge_token}" "${keyauth}"
270 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
271 echo " + Requesting certificate..."
272 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
273 crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
274 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
275 # try to load the certificate to detect corruption
276 echo " + Checking certificate..." >&2
277 _openssl x509 -text < "${crt_path}"
279 # Create fullchain.pem
280 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]] || [[ -e "${SCRIPTDIR}/certs/${ROOTCERT}" ]]; then
281 echo " + Creating fullchain.pem..."
282 cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
283 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]]; then
284 cat "${BASEDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
286 cat "${SCRIPTDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
288 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
291 # Update remaining symlinks
292 if [ ! "${privkey}" = "privkey.pem" ]; then
293 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
296 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
297 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
299 # Wait for hook script to clean the challenge and to deploy cert if used
300 if [[ -n "${HOOK}" ]]; then
301 ${HOOK} "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
304 unset challenge_token
309 CA_DIRECTORY="$(_request get "${CA}")"
310 CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)"
311 CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)"
312 CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)"
313 CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)"
315 # Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
317 if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
318 echo "+ Generating account key..."
319 _openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}"
323 # Get public components from private key and calculate thumbprint
324 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
325 pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
327 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
329 # If we generated a new private key in the step above we have to register it with the acme-server
330 if [[ "${register}" = "1" ]]; then
331 echo "+ Registering account key with letsencrypt..."
332 if [ -z "${CA_NEW_REG}" ]; then
333 echo " + ERROR: Certificate authority doesn't allow registrations."
336 # if an email for the contact has been provided then adding it to the registration request
337 if [[ -n "${CONTACT_EMAIL}" ]]; then
338 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
340 signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
344 if [[ -e "${BASEDIR}/domains.txt" ]]; then
345 DOMAINS_TXT="${BASEDIR}/domains.txt"
346 elif [[ -e "${SCRIPTDIR}/domains.txt" ]]; then
347 DOMAINS_TXT="${SCRIPTDIR}/domains.txt"
349 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
353 if [[ ! -e "${WELLKNOWN}" ]]; then
354 mkdir -p "${WELLKNOWN}"
357 # revoke certificate by user request
358 if [[ "${1:-}" = "revoke" ]]; then
359 if [[ -z "{2:-}" ]] || [[ ! -f "${2}" ]]; then
360 echo "Usage: ${0} revoke path/to/cert.pem"
370 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
371 <"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
372 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
373 cert="${BASEDIR}/certs/${domain}/cert.pem"
375 echo "Processing ${domain}"
376 if [[ -e "${cert}" ]]; then
377 echo " + Found existing cert..."
379 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
381 echo -n " + Valid till ${valid} "
382 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
383 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
386 echo "(Less than ${RENEW_DAYS} days). Renewing!"
389 # shellcheck disable=SC2086