]> git.street.me.uk Git - andy/dehydrated.git/blob - letsencrypt.sh
added short license information to script
[andy/dehydrated.git] / letsencrypt.sh
1 #!/usr/bin/env bash
2
3 # letsencrypt.sh by lukas2511
4 # Source: https://github.com/lukas2511/letsencrypt.sh
5 #
6 # This script is licensed under The MIT License (see LICENSE for more information).
7
8 set -e
9 set -u
10 set -o pipefail
11 [[ -n "${ZSH_VERSION:-}" ]] && set -o SH_WORD_SPLIT && set +o FUNCTION_ARGZERO
12 umask 077 # paranoid umask, we're creating private keys
13
14 # Find directory in which this script is stored by traversing all symbolic links
15 SOURCE="${0}"
16 while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
17   DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
18   SOURCE="$(readlink "$SOURCE")"
19   [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
20 done
21 SCRIPTDIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
22
23 BASEDIR="${SCRIPTDIR}"
24
25 # Check for script dependencies
26 check_dependencies() {
27   # just execute some dummy and/or version commands to see if required tools exist and are actually usable
28   openssl version > /dev/null 2>&1 || _exiterr "This script requires an openssl binary."
29   _sed "" < /dev/null > /dev/null 2>&1 || _exiterr "This script requires sed with support for extended (modern) regular expressions."
30   command -v grep > /dev/null 2>&1 || _exiterr "This script requires grep."
31   mktemp -u -t XXXXXX > /dev/null 2>&1 || _exiterr "This script requires mktemp."
32
33   # curl returns with an error code in some ancient versions so we have to catch that
34   set +e
35   curl -V > /dev/null 2>&1
36   retcode="$?"
37   set -e
38   if [[ ! "${retcode}" = "0" ]] && [[ ! "${retcode}" = "2" ]]; then
39     _exiterr "This script requires curl."
40   fi
41 }
42
43 # Setup default config values, search for and load configuration files
44 load_config() {
45   # Check for config in various locations
46   if [[ -z "${CONFIG:-}" ]]; then
47     for check_config in "/etc/letsencrypt.sh" "/usr/local/etc/letsencrypt.sh" "${PWD}" "${SCRIPTDIR}"; do
48       if [[ -e "${check_config}/config.sh" ]]; then
49         BASEDIR="${check_config}"
50         CONFIG="${check_config}/config.sh"
51         break
52       fi
53     done
54   fi
55
56   # Default values
57   CA="https://acme-v01.api.letsencrypt.org/directory"
58   LICENSE="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
59   CHALLENGETYPE="http-01"
60   CONFIG_D=
61   HOOK=
62   HOOK_CHAIN="no"
63   RENEW_DAYS="30"
64   PRIVATE_KEY=
65   PRIVATE_KEY_JSON=
66   KEYSIZE="4096"
67   WELLKNOWN=
68   PRIVATE_KEY_RENEW="no"
69   KEY_ALGO=rsa
70   OPENSSL_CNF="$(openssl version -d | cut -d\" -f2)/openssl.cnf"
71   CONTACT_EMAIL=
72   LOCKFILE=
73
74   if [[ -z "${CONFIG:-}" ]]; then
75     echo "#" >&2
76     echo "# !! WARNING !! No main config file found, using default config!" >&2
77     echo "#" >&2
78   elif [[ -e "${CONFIG}" ]]; then
79     echo "# INFO: Using main config file ${CONFIG}"
80     BASEDIR="$(dirname "${CONFIG}")"
81     # shellcheck disable=SC1090
82     . "${CONFIG}"
83   else
84     _exiterr "Specified config file doesn't exist."
85   fi
86
87   if [[ -n "${CONFIG_D}" ]]; then
88     if [[ ! -d "${CONFIG_D}" ]]; then
89       _exiterr "The path ${CONFIG_D} specified for CONFIG_D does not point to a directory." >&2
90     fi
91
92     for check_config_d in "${CONFIG_D}"/*.sh; do
93       if [[ ! -e "${check_config_d}" ]]; then
94         echo "# !! WARNING !! Extra configuration directory ${CONFIG_D} exists, but no configuration found in it." >&2
95         break
96       elif [[ -f "${check_config_d}" ]] && [[ -r "${check_config_d}" ]]; then
97         echo "# INFO: Using additional config file ${check_config_d}"
98         # shellcheck disable=SC1090
99         . "${check_config_d}"
100       else
101         _exiterr "Specified additional config ${check_config_d} is not readable or not a file at all." >&2
102       fi
103    done
104   fi
105
106   # Remove slash from end of BASEDIR. Mostly for cleaner outputs, doesn't change functionality.
107   BASEDIR="${BASEDIR%%/}"
108
109   # Check BASEDIR and set default variables
110   [[ -d "${BASEDIR}" ]] || _exiterr "BASEDIR does not exist: ${BASEDIR}"
111
112   [[ -z "${PRIVATE_KEY}" ]] && PRIVATE_KEY="${BASEDIR}/private_key.pem"
113   [[ -z "${PRIVATE_KEY_JSON}" ]] && PRIVATE_KEY_JSON="${BASEDIR}/private_key.json"
114   [[ -z "${WELLKNOWN}" ]] && WELLKNOWN="${BASEDIR}/.acme-challenges"
115   [[ -z "${LOCKFILE}" ]] && LOCKFILE="${BASEDIR}/lock"
116
117   [[ -n "${PARAM_HOOK:-}" ]] && HOOK="${PARAM_HOOK}"
118   [[ -n "${PARAM_CHALLENGETYPE:-}" ]] && CHALLENGETYPE="${PARAM_CHALLENGETYPE}"
119   [[ -n "${PARAM_KEY_ALGO:-}" ]] && KEY_ALGO="${PARAM_KEY_ALGO}"
120
121   [[ "${CHALLENGETYPE}" =~ (http-01|dns-01) ]] || _exiterr "Unknown challenge type ${CHALLENGETYPE}... can not continue."
122   if [[ "${CHALLENGETYPE}" = "dns-01" ]] && [[ -z "${HOOK}" ]]; then
123    _exiterr "Challenge type dns-01 needs a hook script for deployment... can not continue."
124   fi
125   [[ "${KEY_ALGO}" =~ ^(rsa|prime256v1|secp384r1)$ ]] || _exiterr "Unknown public key algorithm ${KEY_ALGO}... can not continue."
126 }
127
128 # Initialize system
129 init_system() {
130   load_config
131
132   # Lockfile handling (prevents concurrent access)
133   LOCKDIR="$(dirname "${LOCKFILE}")"
134   [[ -w "${LOCKDIR}" ]] || _exiterr "Directory ${LOCKDIR} for LOCKFILE ${LOCKFILE} is not writable, aborting."
135   ( set -C; date > "${LOCKFILE}" ) 2>/dev/null || _exiterr "Lock file '${LOCKFILE}' present, aborting."
136   remove_lock() { rm -f "${LOCKFILE}"; }
137   trap 'remove_lock' EXIT
138
139   # Get CA URLs
140   CA_DIRECTORY="$(http_request get "${CA}")"
141   CA_NEW_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-cert)" &&
142   CA_NEW_AUTHZ="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-authz)" &&
143   CA_NEW_REG="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value new-reg)" &&
144   # shellcheck disable=SC2015
145   CA_REVOKE_CERT="$(printf "%s" "${CA_DIRECTORY}" | get_json_string_value revoke-cert)" ||
146   _exiterr "Problem retrieving ACME/CA-URLs, check if your configured CA points to the directory entrypoint."
147
148   # Export some environment variables to be used in hook script
149   export WELLKNOWN BASEDIR CONFIG
150
151   # Checking for private key ...
152   register_new_key="no"
153   if [[ -n "${PARAM_PRIVATE_KEY:-}" ]]; then
154     # a private key was specified from the command line so use it for this run
155     echo "Using private key ${PARAM_PRIVATE_KEY} instead of account key"
156     PRIVATE_KEY="${PARAM_PRIVATE_KEY}"
157   else
158     # Check if private account key exists, if it doesn't exist yet generate a new one (rsa key)
159     if [[ ! -e "${PRIVATE_KEY}" ]]; then
160       echo "+ Generating account key..."
161       _openssl genrsa -out "${PRIVATE_KEY}" "${KEYSIZE}"
162       register_new_key="yes"
163     fi
164   fi
165   openssl rsa -in "${PRIVATE_KEY}" -check 2>/dev/null > /dev/null || _exiterr "Private key is not valid, can not continue."
166
167   # Get public components from private key and calculate thumbprint
168   pubExponent64="$(printf '%x' "$(openssl rsa -in "${PRIVATE_KEY}" -noout -text | awk '/publicExponent/ {print $2}')" | hex2bin | urlbase64)"
169   pubMod64="$(openssl rsa -in "${PRIVATE_KEY}" -noout -modulus | cut -d'=' -f2 | hex2bin | urlbase64)"
170
171   thumbprint="$(printf '{"e":"%s","kty":"RSA","n":"%s"}' "${pubExponent64}" "${pubMod64}" | openssl dgst -sha256 -binary | urlbase64)"
172
173   # If we generated a new private key in the step above we have to register it with the acme-server
174   if [[ "${register_new_key}" = "yes" ]]; then
175     echo "+ Registering account key with letsencrypt..."
176     [[ ! -z "${CA_NEW_REG}" ]] || _exiterr "Certificate authority doesn't allow registrations."
177     # If an email for the contact has been provided then adding it to the registration request
178     if [[ -n "${CONTACT_EMAIL}" ]]; then
179       signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "contact":["mailto:'"${CONTACT_EMAIL}"'"], "agreement": "'"$LICENSE"'"}' > "${PRIVATE_KEY_JSON}"
180     else
181       signed_request "${CA_NEW_REG}" '{"resource": "new-reg", "agreement": "'"$LICENSE"'"}' > "${PRIVATE_KEY_JSON}"
182     fi
183   fi
184
185   if [[ "${CHALLENGETYPE}" = "http-01" && ! -d "${WELLKNOWN}" ]]; then
186       _exiterr "WELLKNOWN directory doesn't exist, please create ${WELLKNOWN} and set appropriate permissions."
187   fi
188 }
189
190 # Different sed version for different os types...
191 _sed() {
192   if [[ "${OSTYPE}" = "Linux" ]]; then
193     sed -r "${@}"
194   else
195     sed -E "${@}"
196   fi
197 }
198
199 # Print error message and exit with error
200 _exiterr() {
201   echo "ERROR: ${1}" >&2
202   exit 1
203 }
204
205 # Encode data as url-safe formatted base64
206 urlbase64() {
207   # urlbase64: base64 encoded string with '+' replaced with '-' and '/' replaced with '_'
208   openssl base64 -e | tr -d '\n\r' | _sed -e 's:=*$::g' -e 'y:+/:-_:'
209 }
210
211 # Convert hex string to binary data
212 hex2bin() {
213   # Remove spaces, add leading zero, escape as hex string and parse with printf
214   printf -- "$(cat | _sed -e 's/[[:space:]]//g' -e 's/^(.(.{2})*)$/0\1/' -e 's/(.{2})/\\x\1/g')"
215 }
216
217 # Get string value from json dictionary
218 get_json_string_value() {
219   local filter
220   filter=$(printf 's/.*"%s": *"\([^"]*\)".*/\\1/p' "$1")
221   sed -n "${filter}"
222 }
223
224 # OpenSSL writes to stderr/stdout even when there are no errors. So just
225 # display the output if the exit code was != 0 to simplify debugging.
226 _openssl() {
227   set +e
228   out="$(openssl "${@}" 2>&1)"
229   res=$?
230   set -e
231   if [[ ${res} -ne 0 ]]; then
232     echo "  + ERROR: failed to run $* (Exitcode: ${res})" >&2
233     echo >&2
234     echo "Details:" >&2
235     echo "${out}" >&2
236     echo >&2
237     exit ${res}
238   fi
239 }
240
241 # Send http(s) request with specified method
242 http_request() {
243   tempcont="$(mktemp -t XXXXXX)"
244
245   set +e
246   if [[ "${1}" = "head" ]]; then
247     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -I)"
248     curlret="${?}"
249   elif [[ "${1}" = "get" ]]; then
250     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}")"
251     curlret="${?}"
252   elif [[ "${1}" = "post" ]]; then
253     statuscode="$(curl -s -w "%{http_code}" -o "${tempcont}" "${2}" -d "${3}")"
254     curlret="${?}"
255   else
256     set -e
257     _exiterr "Unknown request method: ${1}"
258   fi
259   set -e
260
261   if [[ ! "${curlret}" = "0" ]]; then
262     _exiterr "Problem connecting to server (curl returned with ${curlret})"
263   fi
264
265   if [[ ! "${statuscode:0:1}" = "2" ]]; then
266     echo "  + ERROR: An error occurred while sending ${1}-request to ${2} (Status ${statuscode})" >&2
267     echo >&2
268     echo "Details:" >&2
269     cat "${tempcont}" >&2
270     rm -f "${tempcont}"
271
272     # Wait for hook script to clean the challenge if used
273     if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token:+set}" ]]; then
274       "${HOOK}" "clean_challenge" '' "${challenge_token}" "${keyauth}"
275     fi
276
277     # remove temporary domains.txt file if used
278     [[ -n "${PARAM_DOMAIN:-}" && -n "${DOMAINS_TXT:-}" ]] && rm "${DOMAINS_TXT}"
279     exit 1
280   fi
281
282   cat "${tempcont}"
283   rm -f "${tempcont}"
284 }
285
286 # Send signed request
287 signed_request() {
288   # Encode payload as urlbase64
289   payload64="$(printf '%s' "${2}" | urlbase64)"
290
291   # Retrieve nonce from acme-server
292   nonce="$(http_request head "${CA}" | grep Replay-Nonce: | awk -F ': ' '{print $2}' | tr -d '\n\r')"
293
294   # Build header with just our public key and algorithm information
295   header='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}}'
296
297   # Build another header which also contains the previously received nonce and encode it as urlbase64
298   protected='{"alg": "RS256", "jwk": {"e": "'"${pubExponent64}"'", "kty": "RSA", "n": "'"${pubMod64}"'"}, "nonce": "'"${nonce}"'"}'
299   protected64="$(printf '%s' "${protected}" | urlbase64)"
300
301   # Sign header with nonce and our payload with our private key and encode signature as urlbase64
302   signed64="$(printf '%s' "${protected64}.${payload64}" | openssl dgst -sha256 -sign "${PRIVATE_KEY}" | urlbase64)"
303
304   # Send header + extended header + payload + signature to the acme-server
305   data='{"header": '"${header}"', "protected": "'"${protected64}"'", "payload": "'"${payload64}"'", "signature": "'"${signed64}"'"}'
306
307   http_request post "${1}" "${data}"
308 }
309
310 # Extracts all subject names from a CSR
311 # Outputs either the CN, or the SANs, one per line
312 extract_altnames() {
313   csr="${1}" # the CSR itself (not a file)
314
315   if ! <<<"${csr}" openssl req -verify -noout 2>/dev/null; then
316     _exiterr "Certificate signing request isn't valid"
317   fi
318
319   reqtext="$( <<<"${csr}" openssl req -noout -text )"
320   if <<<"${reqtext}" grep -q '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$'; then
321     # SANs used, extract these
322     altnames="$( <<<"${reqtext}" grep -A1 '^[[:space:]]*X509v3 Subject Alternative Name:[[:space:]]*$' | tail -n1 )"
323     # split to one per line:
324     # shellcheck disable=SC1003
325     altnames="$( <<<"${altnames}" _sed -e 's/^[[:space:]]*//; s/, /\'$'\n''/g' )"
326     # we can only get DNS: ones signed
327     if grep -qv '^DNS:' <<<"${altnames}"; then
328       _exiterr "Certificate signing request contains non-DNS Subject Alternative Names"
329     fi
330     # strip away the DNS: prefix
331     altnames="$( <<<"${altnames}" _sed -e 's/^DNS://' )"
332     echo "${altnames}"
333
334   else
335     # No SANs, extract CN
336     altnames="$( <<<"${reqtext}" grep '^[[:space:]]*Subject:' | _sed -e 's/.* CN=([^ /,]*).*/\1/' )"
337     echo "${altnames}"
338   fi
339 }
340
341 # Create certificate for domain(s) and outputs it FD 3
342 sign_csr() {
343   csr="${1}" # the CSR itself (not a file)
344
345   if { true >&3; } 2>/dev/null; then
346     : # fd 3 looks OK
347   else
348     _exiterr "sign_csr: FD 3 not open"
349   fi
350
351   shift 1 || true
352   altnames="${*:-}"
353   if [ -z "${altnames}" ]; then
354     altnames="$( extract_altnames "${csr}" )"
355   fi
356
357   if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
358     _exiterr "Certificate authority doesn't allow certificate signing"
359   fi
360
361   local idx=0
362   if [[ -n "${ZSH_VERSION:-}" ]]; then
363     local -A challenge_uris challenge_tokens keyauths deploy_args
364   else
365     local -a challenge_uris challenge_tokens keyauths deploy_args
366   fi
367
368   # Request challenges
369   for altname in ${altnames}; do
370     # Ask the acme-server for new challenge token and extract them from the resulting json block
371     echo " + Requesting challenge for ${altname}..."
372     response="$(signed_request "${CA_NEW_AUTHZ}" '{"resource": "new-authz", "identifier": {"type": "dns", "value": "'"${altname}"'"}}')"
373
374     challenges="$(printf '%s\n' "${response}" | sed -n 's/.*\("challenges":[^\[]*\[[^]]*]\).*/\1/p')"
375     repl=$'\n''{' # fix syntax highlighting in Vim
376     challenge="$(printf "%s" "${challenges//\{/${repl}}" | grep \""${CHALLENGETYPE}"\")"
377     challenge_token="$(printf '%s' "${challenge}" | get_json_string_value token | _sed 's/[^A-Za-z0-9_\-]/_/g')"
378     challenge_uri="$(printf '%s' "${challenge}" | get_json_string_value uri)"
379
380     if [[ -z "${challenge_token}" ]] || [[ -z "${challenge_uri}" ]]; then
381       _exiterr "Can't retrieve challenges (${response})"
382     fi
383
384     # Challenge response consists of the challenge token and the thumbprint of our public certificate
385     keyauth="${challenge_token}.${thumbprint}"
386
387     case "${CHALLENGETYPE}" in
388       "http-01")
389         # Store challenge response in well-known location and make world-readable (so that a webserver can access it)
390         printf '%s' "${keyauth}" > "${WELLKNOWN}/${challenge_token}"
391         chmod a+r "${WELLKNOWN}/${challenge_token}"
392         keyauth_hook="${keyauth}"
393         ;;
394       "dns-01")
395         # Generate DNS entry content for dns-01 validation
396         keyauth_hook="$(printf '%s' "${keyauth}" | openssl dgst -sha256 -binary | urlbase64)"
397         ;;
398     esac
399
400     challenge_uris[${idx}]="${challenge_uri}"
401     keyauths[${idx}]="${keyauth}"
402     challenge_tokens[${idx}]="${challenge_token}"
403     # Note: assumes args will never have spaces!
404     deploy_args[${idx}]="${altname} ${challenge_token} ${keyauth_hook}"
405     idx=$((idx+1))
406   done
407
408   # Wait for hook script to deploy the challenges if used
409   # shellcheck disable=SC2068
410   [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[@]}
411
412   # Respond to challenges
413   idx=0
414   for altname in ${altnames}; do
415     challenge_token="${challenge_tokens[${idx}]}"
416     keyauth="${keyauths[${idx}]}"
417
418     # Wait for hook script to deploy the challenge if used
419     # shellcheck disable=SC2086
420     [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && "${HOOK}" "deploy_challenge" ${deploy_args[${idx}]}
421
422     # Ask the acme-server to verify our challenge and wait until it is no longer pending
423     echo " + Responding to challenge for ${altname}..."
424     result="$(signed_request "${challenge_uris[${idx}]}" '{"resource": "challenge", "keyAuthorization": "'"${keyauth}"'"}')"
425
426     reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
427
428     while [[ "${reqstatus}" = "pending" ]]; do
429       sleep 1
430       result="$(http_request get "${challenge_uris[${idx}]}")"
431       reqstatus="$(printf '%s\n' "${result}" | get_json_string_value status)"
432     done
433
434     [[ "${CHALLENGETYPE}" = "http-01" ]] && rm -f "${WELLKNOWN}/${challenge_token}"
435
436     # Wait for hook script to clean the challenge if used
437     if [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" != "yes" ]] && [[ -n "${challenge_token}" ]]; then
438       # shellcheck disable=SC2086
439       "${HOOK}" "clean_challenge" ${deploy_args[${idx}]}
440     fi
441     idx=$((idx+1))
442
443     if [[ "${reqstatus}" = "valid" ]]; then
444       echo " + Challenge is valid!"
445     else
446       break
447     fi
448   done
449
450   # Wait for hook script to clean the challenges if used
451   # shellcheck disable=SC2068
452   [[ -n "${HOOK}" ]] && [[ "${HOOK_CHAIN}" = "yes" ]] && "${HOOK}" "clean_challenge" ${deploy_args[@]}
453
454   if [[ "${reqstatus}" != "valid" ]]; then
455     # Clean up any remaining challenge_tokens if we stopped early
456     if [[ "${CHALLENGETYPE}" = "http-01" ]]; then
457       while [ ${idx} -lt ${#challenge_tokens[@]} ]; do
458         rm -f "${WELLKNOWN}/${challenge_tokens[${idx}]}"
459         idx=$((idx+1))
460       done
461     fi
462
463     _exiterr "Challenge is invalid! (returned: ${reqstatus}) (result: ${result})"
464   fi
465
466   # Finally request certificate from the acme-server and store it in cert-${timestamp}.pem and link from cert.pem
467   echo " + Requesting certificate..."
468   csr64="$( <<<"${csr}" openssl req -outform DER | urlbase64)"
469   crt64="$(signed_request "${CA_NEW_CERT}" '{"resource": "new-cert", "csr": "'"${csr64}"'"}' | openssl base64 -e)"
470   crt="$( printf -- '-----BEGIN CERTIFICATE-----\n%s\n-----END CERTIFICATE-----\n' "${crt64}" )"
471
472   # Try to load the certificate to detect corruption
473   echo " + Checking certificate..."
474   _openssl x509 -text <<<"${crt}"
475
476   echo "${crt}" >&3
477
478   unset challenge_token
479   echo " + Done!"
480 }
481
482 # Create certificate for domain(s)
483 sign_domain() {
484   domain="${1}"
485   altnames="${*}"
486   timestamp="$(date +%s)"
487
488   echo " + Signing domains..."
489   if [[ -z "${CA_NEW_AUTHZ}" ]] || [[ -z "${CA_NEW_CERT}" ]]; then
490     _exiterr "Certificate authority doesn't allow certificate signing"
491   fi
492
493   # If there is no existing certificate directory => make it
494   if [[ ! -e "${BASEDIR}/certs/${domain}" ]]; then
495     echo " + Creating new directory ${BASEDIR}/certs/${domain} ..."
496     mkdir -p "${BASEDIR}/certs/${domain}"
497   fi
498
499   privkey="privkey.pem"
500   # generate a new private key if we need or want one
501   if [[ ! -r "${BASEDIR}/certs/${domain}/privkey.pem" ]] || [[ "${PRIVATE_KEY_RENEW}" = "yes" ]]; then
502     echo " + Generating private key..."
503     privkey="privkey-${timestamp}.pem"
504     case "${KEY_ALGO}" in
505       rsa) _openssl genrsa -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem" "${KEYSIZE}";;
506       prime256v1|secp384r1) _openssl ecparam -genkey -name "${KEY_ALGO}" -out "${BASEDIR}/certs/${domain}/privkey-${timestamp}.pem";;
507     esac
508   fi
509
510   # Generate signing request config and the actual signing request
511   echo " + Generating signing request..."
512   SAN=""
513   for altname in ${altnames}; do
514     SAN+="DNS:${altname}, "
515   done
516   SAN="${SAN%%, }"
517   local tmp_openssl_cnf
518   tmp_openssl_cnf="$(mktemp -t XXXXXX)"
519   cat "${OPENSSL_CNF}" > "${tmp_openssl_cnf}"
520   printf "[SAN]\nsubjectAltName=%s" "${SAN}" >> "${tmp_openssl_cnf}"
521   openssl req -new -sha256 -key "${BASEDIR}/certs/${domain}/${privkey}" -out "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" -subj "/CN=${domain}/" -reqexts SAN -config "${tmp_openssl_cnf}"
522   rm -f "${tmp_openssl_cnf}"
523
524   crt_path="${BASEDIR}/certs/${domain}/cert-${timestamp}.pem"
525   # shellcheck disable=SC2086
526   sign_csr "$(< "${BASEDIR}/certs/${domain}/cert-${timestamp}.csr" )" ${altnames} 3>"${crt_path}"
527
528   # Create fullchain.pem
529   echo " + Creating fullchain.pem..."
530   cat "${crt_path}" > "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
531   http_request get "$(openssl x509 -in "${BASEDIR}/certs/${domain}/cert-${timestamp}.pem" -noout -text | grep 'CA Issuers - URI:' | cut -d':' -f2-)" > "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"
532   if ! grep -q "BEGIN CERTIFICATE" "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem"; then
533     openssl x509 -in "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -inform DER -out "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" -outform PEM
534   fi
535   cat "${BASEDIR}/certs/${domain}/chain-${timestamp}.pem" >> "${BASEDIR}/certs/${domain}/fullchain-${timestamp}.pem"
536
537   # Update symlinks
538   [[ "${privkey}" = "privkey.pem" ]] || ln -sf "privkey-${timestamp}.pem" "${BASEDIR}/certs/${domain}/privkey.pem"
539
540   ln -sf "chain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/chain.pem"
541   ln -sf "fullchain-${timestamp}.pem" "${BASEDIR}/certs/${domain}/fullchain.pem"
542   ln -sf "cert-${timestamp}.csr" "${BASEDIR}/certs/${domain}/cert.csr"
543   ln -sf "cert-${timestamp}.pem" "${BASEDIR}/certs/${domain}/cert.pem"
544
545   # Wait for hook script to clean the challenge and to deploy cert if used
546   [[ -n "${HOOK}" ]] && "${HOOK}" "deploy_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem" "${BASEDIR}/certs/${domain}/chain.pem"
547
548   unset challenge_token
549   echo " + Done!"
550 }
551
552 # Usage: --cron (-c)
553 # Description: Sign/renew non-existant/changed/expiring certificates.
554 command_sign_domains() {
555   init_system
556
557   if [[ -n "${PARAM_DOMAIN:-}" ]]; then
558     DOMAINS_TXT="$(mktemp -t XXXXXX)"
559     printf -- "${PARAM_DOMAIN}" > "${DOMAINS_TXT}"
560   elif [[ -e "${BASEDIR}/domains.txt" ]]; then
561     DOMAINS_TXT="${BASEDIR}/domains.txt"
562   else
563     _exiterr "domains.txt not found and --domain not given"
564   fi
565
566   # Generate certificates for all domains found in domains.txt. Check if existing certificate are about to expire
567   ORIGIFS="${IFS}"
568   IFS=$'\n'
569   for line in $(<"${DOMAINS_TXT}" tr -d '\r' | _sed -e 's/^[[:space:]]*//g' -e 's/[[:space:]]*$//g' -e 's/[[:space:]]+/ /g' | (grep -vE '^(#|$)' || true)); do
570     IFS="${ORIGIFS}"
571     domain="$(printf '%s\n' "${line}" | cut -d' ' -f1)"
572     morenames="$(printf '%s\n' "${line}" | cut -s -d' ' -f2-)"
573     cert="${BASEDIR}/certs/${domain}/cert.pem"
574
575     force_renew="${PARAM_FORCE:-no}"
576
577     if [[ -z "${morenames}" ]];then
578       echo "Processing ${domain}"
579     else
580       echo "Processing ${domain} with alternative names: ${morenames}"
581     fi
582
583     if [[ -e "${cert}" ]]; then
584       printf " + Checking domain name(s) of existing cert..."
585
586       certnames="$(openssl x509 -in "${cert}" -text -noout | grep DNS: | _sed 's/DNS://g' | tr -d ' ' | tr ',' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//')"
587       givennames="$(echo "${domain}" "${morenames}"| tr ' ' '\n' | sort -u | tr '\n' ' ' | _sed 's/ $//' | _sed 's/^ //')"
588
589       if [[ "${certnames}" = "${givennames}" ]]; then
590         echo " unchanged."
591       else
592         echo " changed!"
593         echo " + Domain name(s) are not matching!"
594         echo " + Names in old certificate: ${certnames}"
595         echo " + Configured names: ${givennames}"
596         echo " + Forcing renew."
597         force_renew="yes"
598       fi
599     fi
600
601     if [[ -e "${cert}" ]]; then
602       echo " + Checking expire date of existing cert..."
603       valid="$(openssl x509 -enddate -noout -in "${cert}" | cut -d= -f2- )"
604
605       printf " + Valid till %s " "${valid}"
606       if openssl x509 -checkend $((RENEW_DAYS * 86400)) -noout -in "${cert}"; then
607         printf "(Longer than %d days). " "${RENEW_DAYS}"
608         if [[ "${force_renew}" = "yes" ]]; then
609           echo "Ignoring because renew was forced!"
610         else
611           # Certificate-Names unchanged and cert is still valid
612           echo "Skipping renew!"
613           [[ -n "${HOOK}" ]] && "${HOOK}" "unchanged_cert" "${domain}" "${BASEDIR}/certs/${domain}/privkey.pem" "${BASEDIR}/certs/${domain}/cert.pem" "${BASEDIR}/certs/${domain}/fullchain.pem" "${BASEDIR}/certs/${domain}/chain.pem"
614           continue
615         fi
616       else
617         echo "(Less than ${RENEW_DAYS} days). Renewing!"
618       fi
619     fi
620
621     # shellcheck disable=SC2086
622     sign_domain ${line}
623   done
624
625   # remove temporary domains.txt file if used
626   [[ -n "${PARAM_DOMAIN:-}" ]] && rm -f "${DOMAINS_TXT}"
627
628   exit 0
629 }
630
631 # Usage: --signcsr (-s) path/to/csr.pem
632 # Description: Sign a given CSR, output CRT on stdout (advanced usage)
633 command_sign_csr() {
634   # redirect stdout to stderr
635   # leave stdout over at fd 3 to output the cert
636   exec 3>&1 1>&2
637
638   init_system
639
640   csrfile="${1}"
641   if [ ! -r "${csrfile}" ]; then
642     _exiterr "Could not read certificate signing request ${csrfile}"
643   fi
644
645   sign_csr "$(< "${csrfile}" )"
646
647   exit 0
648 }
649
650 # Usage: --revoke (-r) path/to/cert.pem
651 # Description: Revoke specified certificate
652 command_revoke() {
653   init_system
654
655   [[ -n "${CA_REVOKE_CERT}" ]] || _exiterr "Certificate authority doesn't allow certificate revocation."
656
657   cert="${1}"
658   if [[ -L "${cert}" ]]; then
659     # follow symlink and use real certificate name (so we move the real file and not the symlink at the end)
660     local link_target
661     link_target="$(readlink -n "${cert}")"
662     if [[ "${link_target}" =~ ^/ ]]; then
663       cert="${link_target}"
664     else
665       cert="$(dirname "${cert}")/${link_target}"
666     fi
667   fi
668   [[ -f "${cert}" ]] || _exiterr "Could not find certificate ${cert}"
669
670   echo "Revoking ${cert}"
671
672   cert64="$(openssl x509 -in "${cert}" -inform PEM -outform DER | urlbase64)"
673   response="$(signed_request "${CA_REVOKE_CERT}" '{"resource": "revoke-cert", "certificate": "'"${cert64}"'"}')"
674   # if there is a problem with our revoke request _request (via signed_request) will report this and "exit 1" out
675   # so if we are here, it is safe to assume the request was successful
676   echo " + Done."
677   echo " + Renaming certificate to ${cert}-revoked"
678   mv -f "${cert}" "${cert}-revoked"
679 }
680
681 # Usage: --cleanup (-gc)
682 # Description: Move unused certificate files to archive directory
683 command_cleanup() {
684   load_config
685
686   # Create global archive directory if not existant
687   if [[ ! -e "${BASEDIR}/archive" ]]; then
688     mkdir "${BASEDIR}/archive"
689   fi
690
691   # Loop over all certificate directories
692   for certdir in "${BASEDIR}/certs/"*; do
693     # Skip if entry is not a folder
694     [[ -d "${certdir}" ]] || continue
695
696     # Get certificate name
697     certname="$(basename "${certdir}")"
698
699     # Create certitifaces archive directory if not existant
700     archivedir="${BASEDIR}/archive/${certname}"
701     if [[ ! -e "${archivedir}" ]]; then
702       mkdir "${archivedir}"
703     fi
704
705     # Loop over file-types (certificates, keys, signing-requests, ...)
706     for filetype in cert.csr cert.pem chain.pem fullchain.pem privkey.pem; do
707       # Skip if symlink is broken
708       [[ -r "${certdir}/${filetype}" ]] || continue
709
710       # Look up current file in use
711       current="$(basename "$(readlink "${certdir}/${filetype}")")"
712
713       # Split filetype into name and extension
714       filebase="$(echo "${filetype}" | cut -d. -f1)"
715       fileext="$(echo "${filetype}" | cut -d. -f2)"
716
717       # Loop over all files of this type
718       for file in "${certdir}/${filebase}-"*".${fileext}"; do
719         # Handle case where no files match the wildcard
720         [[ -f "${file}" ]] || break
721
722         # Check if current file is in use, if unused move to archive directory
723         filename="$(basename "${file}")"
724         if [[ ! "${filename}" = "${current}" ]]; then
725           echo "Moving unused file to archive directory: ${certname}/${filename}"
726           mv "${certdir}/${filename}" "${archivedir}/${filename}"
727         fi
728       done
729     done
730   done
731
732   exit 0
733 }
734
735 # Usage: --help (-h)
736 # Description: Show help text
737 command_help() {
738   printf "Usage: %s [-h] [command [argument]] [parameter [argument]] [parameter [argument]] ...\n\n" "${0}"
739   printf "Default command: help\n\n"
740   echo "Commands:"
741   grep -e '^[[:space:]]*# Usage:' -e '^[[:space:]]*# Description:' -e '^command_.*()[[:space:]]*{' "${0}" | while read -r usage; read -r description; read -r command; do
742     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]] || [[ ! "${command}" =~ ^command_ ]]; then
743       _exiterr "Error generating help text."
744     fi
745     printf " %-32s %s\n" "${usage##"# Usage: "}" "${description##"# Description: "}"
746   done
747   printf -- "\nParameters:\n"
748   grep -E -e '^[[:space:]]*# PARAM_Usage:' -e '^[[:space:]]*# PARAM_Description:' "${0}" | while read -r usage; read -r description; do
749     if [[ ! "${usage}" =~ Usage ]] || [[ ! "${description}" =~ Description ]]; then
750       _exiterr "Error generating help text."
751     fi
752     printf " %-32s %s\n" "${usage##"# PARAM_Usage: "}" "${description##"# PARAM_Description: "}"
753   done
754 }
755
756 # Usage: --env (-e)
757 # Description: Output configuration variables for use in other scripts
758 command_env() {
759   echo "# letsencrypt.sh configuration"
760   load_config
761   typeset -p CA LICENSE CHALLENGETYPE HOOK HOOK_CHAIN RENEW_DAYS PRIVATE_KEY KEYSIZE WELLKNOWN PRIVATE_KEY_RENEW OPENSSL_CNF CONTACT_EMAIL LOCKFILE
762 }
763
764 # Main method (parses script arguments and calls command_* methods)
765 main() {
766   COMMAND=""
767   set_command() {
768     [[ -z "${COMMAND}" ]] || _exiterr "Only one command can be executed at a time. See help (-h) for more information."
769     COMMAND="${1}"
770   }
771
772   check_parameters() {
773     if [[ -z "${1:-}" ]]; then
774       echo "The specified command requires additional parameters. See help:" >&2
775       echo >&2
776       command_help >&2
777       exit 1
778     elif [[ "${1:0:1}" = "-" ]]; then
779       _exiterr "Invalid argument: ${1}"
780     fi
781   }
782
783   [[ -z "${@}" ]] && eval set -- "--help"
784
785   while (( ${#} )); do
786     case "${1}" in
787       --help|-h)
788         command_help
789         exit 0
790         ;;
791
792       --env|-e)
793         set_command env
794         ;;
795
796       --cron|-c)
797         set_command sign_domains
798         ;;
799
800       --signcsr|-s)
801         shift 1
802         set_command sign_csr
803         check_parameters "${1:-}"
804         PARAM_CSR="${1}"
805         ;;
806
807       --revoke|-r)
808         shift 1
809         set_command revoke
810         check_parameters "${1:-}"
811         PARAM_REVOKECERT="${1}"
812         ;;
813
814       --cleanup|-gc)
815         set_command cleanup
816         ;;
817
818       # PARAM_Usage: --domain (-d) domain.tld
819       # PARAM_Description: Use specified domain name(s) instead of domains.txt entry (one certificate!)
820       --domain|-d)
821         shift 1
822         check_parameters "${1:-}"
823         if [[ -z "${PARAM_DOMAIN:-}" ]]; then
824           PARAM_DOMAIN="${1}"
825         else
826           PARAM_DOMAIN="${PARAM_DOMAIN} ${1}"
827          fi
828         ;;
829
830
831       # PARAM_Usage: --force (-x)
832       # PARAM_Description: Force renew of certificate even if it is longer valid than value in RENEW_DAYS
833       --force|-x)
834         PARAM_FORCE="yes"
835         ;;
836
837       # PARAM_Usage: --privkey (-p) path/to/key.pem
838       # PARAM_Description: Use specified private key instead of account key (useful for revocation)
839       --privkey|-p)
840         shift 1
841         check_parameters "${1:-}"
842         PARAM_PRIVATE_KEY="${1}"
843         ;;
844
845       # PARAM_Usage: --config (-f) path/to/config.sh
846       # PARAM_Description: Use specified config file
847       --config|-f)
848         shift 1
849         check_parameters "${1:-}"
850         CONFIG="${1}"
851         ;;
852
853       # PARAM_Usage: --hook (-k) path/to/hook.sh
854       # PARAM_Description: Use specified script for hooks
855       --hook|-k)
856         shift 1
857         check_parameters "${1:-}"
858         PARAM_HOOK="${1}"
859         ;;
860
861       # PARAM_Usage: --challenge (-t) http-01|dns-01
862       # PARAM_Description: Which challenge should be used? Currently http-01 and dns-01 are supported
863       --challenge|-t)
864         shift 1
865         check_parameters "${1:-}"
866         PARAM_CHALLENGETYPE="${1}"
867         ;;
868
869       # PARAM_Usage: --algo (-a) rsa|prime256v1|secp384r1
870       # PARAM_Description: Which public key algorithm should be used? Supported: rsa, prime256v1 and secp384r1
871       --algo|-a)
872         shift 1
873         check_parameters "${1:-}"
874         PARAM_KEY_ALGO="${1}"
875         ;;
876
877       *)
878         echo "Unknown parameter detected: ${1}" >&2
879         echo >&2
880         command_help >&2
881         exit 1
882         ;;
883     esac
884
885     shift 1
886   done
887
888   case "${COMMAND}" in
889     env) command_env;;
890     sign_domains) command_sign_domains;;
891     sign_csr) command_sign_csr "${PARAM_CSR}";;
892     revoke) command_revoke "${PARAM_REVOKECERT}";;
893     cleanup) command_cleanup;;
894     *) command_help; exit 1;;
895   esac
896 }
897
898 # Determine OS type
899 OSTYPE="$(uname)"
900
901 # Check for missing dependencies
902 check_dependencies
903
904 # Run script
905 main "${@:-}"