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