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