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 occured 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}"
115 # Encode payload as urlbase64
116 payload64="$(printf '%s' "${2}" | urlbase64)"
118 # Retrieve nonce from acme-server
119 nonce="$(_request head "${CA}/directory" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | anti_newline)"
121 # Build header with just our public key and algorithm information
122 header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
124 # Build another header which also contains the previously received nonce and encode it as urlbase64
125 protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
126 protected64="$(printf '%s' "${protected}" | urlbase64)"
128 # Sign header with nonce and our payload with our private key and encode signature as urlbase64
129 signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${BASEDIR}/private_key.pem" | urlbase64)"
131 # Send header + extended header + payload + signature to the acme-server
132 data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
134 _request post "${1}" "${data}"
139 cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
140 response="$(signed_request "${CA}/acme/revoke-cert" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
141 # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
142 # so if we are here, it is safe to assume the request was successful
144 echo " + renaming certificate to ${cert}-revoked"
145 mv -f "${cert}" "${cert}-revoked"
151 echo " + Signing domains..."
153 timestamp="$(date +%s)"
155 # If there is no existing certificate directory => make it
156 if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
157 echo " + make directory ${BASEDIR}/certs/${domain} ..."
158 mkdir -p "${BASEDIR}/certs/${domain}"
161 privkey="privkey.pem"
162 # generate a new private key if we need or want one
163 if [[ ! -f "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
164 echo " + Generating private key..."
165 privkey="privkey-${timestamp}.pem"
166 openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
169 # Generate signing request config and the actual signing request
171 for altname in $altnames; do
172 SAN+="DNS:${altname}, "
175 echo " + Generating signing request..."
176 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}")) > /dev/null
178 # Request and respond to challenges
179 for altname in $altnames; do
180 # Ask the acme-server for new challenge token and extract them from the resulting json block
181 echo " + Requesting challenge for ${altname}..."
182 response="$(signed_request "${CA}/acme/new-authz" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
184 challenges="$(printf '%s\n' "${response}" | grep -Eo '"challenges":[^\[]*\[[^]]*]')"
185 challenge="$(printf "%s" "${challenges//\{/$'\n'{}" | grep 'http-01')"
186 challenge_token="$(printf '%s' "${challenge}" | grep -Eo '"token":\s*"[^"]*"' | cut -d'"' -f4 | sed 's/[^A-Za-z0-9_\-]/_/g')"
187 challenge_uri="$(printf '%s' "${challenge}" | grep -Eo '"uri":\s*"[^"]*"' | cut -d'"' -f4)"
189 if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
190 echo " + Error: Can't retrieve challenges (${response})"
194 # Challenge response consists of the challenge token and the thumbprint of our public certificate
195 keyauth="${challenge_token}.${thumbprint}"
197 # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
198 printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
199 chmod a+r "${WELLKNOWN}/${challenge_token}"
201 # Wait for hook script to deploy the challenge if used
202 if [[ -n "${HOOK}" ]]; then
203 ${HOOK} "deploy_challenge" "${challenge_token}" "${keyauth}"
206 # Ask the acme-server to verify our challenge and wait until it becomes valid
207 echo " + Responding to challenge for ${altname}..."
208 result="$(signed_request "${challenge_uri}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
210 status="$(printf '%s\n' "${result}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
212 # get status until a result is reached => not pending anymore
213 while [[ "${status}" = "pending" ]]; do
215 status="$(_request get "${challenge_uri}" | grep -Eo '"status":\s*"[^"]*"' | cut -d'"' -f4)"
218 rm -f "${WELLKNOWN}/${challenge_token}"
220 if [[ "${status}" = "valid" ]]; then
221 echo " + Challenge is valid!"
223 echo " + Challenge is invalid! (returned: ${status})"
225 # Wait for hook script to clean the challenge if used
226 if [[ -n "${HOOK}" ]] && [[ -n "${challenge_token}" ]]; then
227 ${HOOK} "clean_challenge" "${challenge_token}" "${keyauth}"
235 # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
236 echo " + Requesting certificate..."
237 csr64="$(openssl req -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -outform DER | urlbase64)"
238 crt64="$(signed_request "${CA}/acme/new-cert" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
239 printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" > "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
241 # Create fullchain.pem
242 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]] || [[ -e "${SCRIPTDIR}/certs/${ROOTCERT}" ]]; then
243 echo " + Creating fullchain.pem..."
244 cat "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
245 if [[ -e "${BASEDIR}/certs/${ROOTCERT}" ]]; then
246 cat "${BASEDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
248 cat "${SCRIPTDIR}/certs/${ROOTCERT}" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
250 ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
253 # Update remaining symlinks
254 if [ ! "${privkey}" = "privkey.pem" ]; then
255 ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
258 ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
259 ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
261 # Wait for hook script to clean the challenge and to deploy cert if used
262 if [[ -n "${HOOK}" ]]; then
263 ${HOOK} "deploy_cert" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
266 unset challenge_token
270 # Check if private key exists, if it doesn't exist yet generate a new one (rsa key)
272 if [[ ! -e "${BASEDIR}/private_key.pem" ]]; then
273 echo "+ Generating account key..."
274 openssl genrsa -out "${BASEDIR}/private_key.pem" "${KEYSIZE}" 2> /dev/null > /dev/null
278 # Get public components from private key and calculate thumbprint
279 pubExponent64="$(printf "%06x" "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -text | grep publicExponent | head -1 | cut -d' ' -f2)" | hex2bin | urlbase64)"
280 pubMod64="$(printf '%s' "$(openssl rsa -in "${BASEDIR}/private_key.pem" -noout -modulus | cut -d'=' -f2)" | hex2bin | urlbase64)"
282 thumbprint="$(printf '%s' "$(printf '%s' '{"e":"'"${pubExponent64}"'","kty":"RSA","n":"'"${pubMod64}"'"}' | shasum -a 256 | awk '{print $1}')" | hex2bin | urlbase64)"
284 # If we generated a new private key in the step above we have to register it with the acme-server
285 if [[ "${register}" = "1" ]]; then
286 echo "+ Registering account key with letsencrypt..."
287 # if an email for the contact has been provided then adding it to the registration request
288 if [ -n "${CONTACT_EMAIL}" ]; then
289 signed_request "${CA}/acme/new-reg" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > /dev/null
291 signed_request "${CA}/acme/new-reg" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > /dev/null
295 if [[ -e "${BASEDIR}/domains.txt" ]]; then
296 DOMAINS_TXT="${BASEDIR}/domains.txt"
297 elif [[ -e "${SCRIPTDIR}/domains.txt" ]]; then
298 DOMAINS_TXT="${SCRIPTDIR}/domains.txt"
300 echo "You have to create a domains.txt file listing the domains you want certificates for. Have a look at domains.txt.example."
304 if [[ ! -e "${WELLKNOWN}" ]]; then
305 mkdir -p "${WELLKNOWN}"
308 # revoke certificate by user request
309 if [[ "${1:-}" = "revoke" ]]; then
310 if [[ -z "{2:-}" ]] || [[ ! -f "${2}" ]]; then
311 echo "Usage: ${0} revoke path/to/cert.pem"
321 # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
322 <"${DOMAINS_TXT}" sed 's/^\s*//g;s/\s*$//g' | grep -v '^#' | grep -v '^$' | while read -r line; do
323 domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
324 cert="${BASEDIR}/certs/${domain}/cert.pem"
326 echo "Processing ${domain}"
327 if [[ -e "${cert}" ]]; then
328 echo " + Found existing cert..."
330 valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
332 echo -n " + Valid till ${valid} "
333 if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
334 echo "(Longer than ${RENEW_DAYS} days). Skipping!"
337 echo "(Less than ${RENEW_DAYS} days). Renewing!"
340 # shellcheck disable=SC2086