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