]> git.proxmox.com Git - mirror_acme.sh.git/blob - acme.sh
Merge pull request #2606 from ianw/no-exit-manual-dns
[mirror_acme.sh.git] / acme.sh
1 #!/usr/bin/env sh
2
3 VER=3.0.5
4
5 PROJECT_NAME="acme.sh"
6
7 PROJECT_ENTRY="acme.sh"
8
9 PROJECT="https://github.com/acmesh-official/$PROJECT_NAME"
10
11 DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
12
13 _WINDOWS_SCHEDULER_NAME="$PROJECT_NAME.cron"
14
15 _SCRIPT_="$0"
16
17 _SUB_FOLDER_NOTIFY="notify"
18 _SUB_FOLDER_DNSAPI="dnsapi"
19 _SUB_FOLDER_DEPLOY="deploy"
20
21 _SUB_FOLDERS="$_SUB_FOLDER_DNSAPI $_SUB_FOLDER_DEPLOY $_SUB_FOLDER_NOTIFY"
22
23 CA_LETSENCRYPT_V2="https://acme-v02.api.letsencrypt.org/directory"
24 CA_LETSENCRYPT_V2_TEST="https://acme-staging-v02.api.letsencrypt.org/directory"
25
26 CA_BUYPASS="https://api.buypass.com/acme/directory"
27 CA_BUYPASS_TEST="https://api.test4.buypass.no/acme/directory"
28
29 CA_ZEROSSL="https://acme.zerossl.com/v2/DV90"
30 _ZERO_EAB_ENDPOINT="https://api.zerossl.com/acme/eab-credentials-email"
31
32 CA_SSLCOM_RSA="https://acme.ssl.com/sslcom-dv-rsa"
33 CA_SSLCOM_ECC="https://acme.ssl.com/sslcom-dv-ecc"
34
35 CA_GOOGLE="https://dv.acme-v02.api.pki.goog/directory"
36 CA_GOOGLE_TEST="https://dv.acme-v02.test-api.pki.goog/directory"
37
38 DEFAULT_CA=$CA_ZEROSSL
39 DEFAULT_STAGING_CA=$CA_LETSENCRYPT_V2_TEST
40
41 CA_NAMES="
42 ZeroSSL.com,zerossl
43 LetsEncrypt.org,letsencrypt
44 LetsEncrypt.org_test,letsencrypt_test,letsencrypttest
45 BuyPass.com,buypass
46 BuyPass.com_test,buypass_test,buypasstest
47 SSL.com,sslcom
48 Google.com,google
49 Google.com_test,googletest,google_test
50 "
51
52 CA_SERVERS="$CA_ZEROSSL,$CA_LETSENCRYPT_V2,$CA_LETSENCRYPT_V2_TEST,$CA_BUYPASS,$CA_BUYPASS_TEST,$CA_SSLCOM_RSA,$CA_GOOGLE,$CA_GOOGLE_TEST"
53
54 DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
55
56 DEFAULT_ACCOUNT_KEY_LENGTH=2048
57 DEFAULT_DOMAIN_KEY_LENGTH=2048
58
59 DEFAULT_OPENSSL_BIN="openssl"
60
61 VTYPE_HTTP="http-01"
62 VTYPE_DNS="dns-01"
63 VTYPE_ALPN="tls-alpn-01"
64
65 ID_TYPE_DNS="dns"
66 ID_TYPE_IP="ip"
67
68 LOCAL_ANY_ADDRESS="0.0.0.0"
69
70 DEFAULT_RENEW=60
71
72 NO_VALUE="no"
73
74 W_DNS="dns"
75 W_ALPN="alpn"
76 DNS_ALIAS_PREFIX="="
77
78 MODE_STATELESS="stateless"
79
80 STATE_VERIFIED="verified_ok"
81
82 NGINX="nginx:"
83 NGINX_START="#ACME_NGINX_START"
84 NGINX_END="#ACME_NGINX_END"
85
86 BEGIN_CSR="-----BEGIN [NEW ]\{0,4\}CERTIFICATE REQUEST-----"
87 END_CSR="-----END [NEW ]\{0,4\}CERTIFICATE REQUEST-----"
88
89 BEGIN_CERT="-----BEGIN CERTIFICATE-----"
90 END_CERT="-----END CERTIFICATE-----"
91
92 CONTENT_TYPE_JSON="application/jose+json"
93 RENEW_SKIP=2
94 CODE_DNS_MANUAL=3
95
96 B64CONF_START="__ACME_BASE64__START_"
97 B64CONF_END="__ACME_BASE64__END_"
98
99 ECC_SEP="_"
100 ECC_SUFFIX="${ECC_SEP}ecc"
101
102 LOG_LEVEL_1=1
103 LOG_LEVEL_2=2
104 LOG_LEVEL_3=3
105 DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
106
107 DEBUG_LEVEL_1=1
108 DEBUG_LEVEL_2=2
109 DEBUG_LEVEL_3=3
110 DEBUG_LEVEL_DEFAULT=$DEBUG_LEVEL_1
111 DEBUG_LEVEL_NONE=0
112
113 DOH_CLOUDFLARE=1
114 DOH_GOOGLE=2
115 DOH_ALI=3
116 DOH_DP=4
117
118 HIDDEN_VALUE="[hidden](please add '--output-insecure' to see this value)"
119
120 SYSLOG_ERROR="user.error"
121 SYSLOG_INFO="user.info"
122 SYSLOG_DEBUG="user.debug"
123
124 #error
125 SYSLOG_LEVEL_ERROR=3
126 #info
127 SYSLOG_LEVEL_INFO=6
128 #debug
129 SYSLOG_LEVEL_DEBUG=7
130 #debug2
131 SYSLOG_LEVEL_DEBUG_2=8
132 #debug3
133 SYSLOG_LEVEL_DEBUG_3=9
134
135 SYSLOG_LEVEL_DEFAULT=$SYSLOG_LEVEL_ERROR
136 #none
137 SYSLOG_LEVEL_NONE=0
138
139 NOTIFY_LEVEL_DISABLE=0
140 NOTIFY_LEVEL_ERROR=1
141 NOTIFY_LEVEL_RENEW=2
142 NOTIFY_LEVEL_SKIP=3
143
144 NOTIFY_LEVEL_DEFAULT=$NOTIFY_LEVEL_RENEW
145
146 NOTIFY_MODE_BULK=0
147 NOTIFY_MODE_CERT=1
148
149 NOTIFY_MODE_DEFAULT=$NOTIFY_MODE_BULK
150
151 _BASE64_ENCODED_CFGS="Le_PreHook Le_PostHook Le_RenewHook Le_Preferred_Chain Le_ReloadCmd"
152
153 _DEBUG_WIKI="https://github.com/acmesh-official/acme.sh/wiki/How-to-debug-acme.sh"
154
155 _PREPARE_LINK="https://github.com/acmesh-official/acme.sh/wiki/Install-preparations"
156
157 _STATELESS_WIKI="https://github.com/acmesh-official/acme.sh/wiki/Stateless-Mode"
158
159 _DNS_ALIAS_WIKI="https://github.com/acmesh-official/acme.sh/wiki/DNS-alias-mode"
160
161 _DNS_MANUAL_WIKI="https://github.com/acmesh-official/acme.sh/wiki/dns-manual-mode"
162
163 _DNS_API_WIKI="https://github.com/acmesh-official/acme.sh/wiki/dnsapi"
164
165 _NOTIFY_WIKI="https://github.com/acmesh-official/acme.sh/wiki/notify"
166
167 _SUDO_WIKI="https://github.com/acmesh-official/acme.sh/wiki/sudo"
168
169 _REVOKE_WIKI="https://github.com/acmesh-official/acme.sh/wiki/revokecert"
170
171 _ZEROSSL_WIKI="https://github.com/acmesh-official/acme.sh/wiki/ZeroSSL.com-CA"
172
173 _SSLCOM_WIKI="https://github.com/acmesh-official/acme.sh/wiki/SSL.com-CA"
174
175 _SERVER_WIKI="https://github.com/acmesh-official/acme.sh/wiki/Server"
176
177 _PREFERRED_CHAIN_WIKI="https://github.com/acmesh-official/acme.sh/wiki/Preferred-Chain"
178
179 _VALIDITY_WIKI="https://github.com/acmesh-official/acme.sh/wiki/Validity"
180
181 _DNSCHECK_WIKI="https://github.com/acmesh-official/acme.sh/wiki/dnscheck"
182
183 _DNS_MANUAL_ERR="The dns manual mode can not renew automatically, you must issue it again manually. You'd better use the other modes instead."
184
185 _DNS_MANUAL_WARN="It seems that you are using dns manual mode. please take care: $_DNS_MANUAL_ERR"
186
187 _DNS_MANUAL_ERROR="It seems that you are using dns manual mode. Read this link first: $_DNS_MANUAL_WIKI"
188
189 __INTERACTIVE=""
190 if [ -t 1 ]; then
191 __INTERACTIVE="1"
192 fi
193
194 __green() {
195 if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
196 printf '\33[1;32m%b\33[0m' "$1"
197 return
198 fi
199 printf -- "%b" "$1"
200 }
201
202 __red() {
203 if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
204 printf '\33[1;31m%b\33[0m' "$1"
205 return
206 fi
207 printf -- "%b" "$1"
208 }
209
210 _printargs() {
211 _exitstatus="$?"
212 if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
213 printf -- "%s" "[$(date)] "
214 fi
215 if [ -z "$2" ]; then
216 printf -- "%s" "$1"
217 else
218 printf -- "%s" "$1='$2'"
219 fi
220 printf "\n"
221 # return the saved exit status
222 return "$_exitstatus"
223 }
224
225 _dlg_versions() {
226 echo "Diagnosis versions: "
227 echo "openssl:$ACME_OPENSSL_BIN"
228 if _exists "${ACME_OPENSSL_BIN:-openssl}"; then
229 ${ACME_OPENSSL_BIN:-openssl} version 2>&1
230 else
231 echo "$ACME_OPENSSL_BIN doesn't exist."
232 fi
233
234 echo "apache:"
235 if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
236 $_APACHECTL -V 2>&1
237 else
238 echo "apache doesn't exist."
239 fi
240
241 echo "nginx:"
242 if _exists "nginx"; then
243 nginx -V 2>&1
244 else
245 echo "nginx doesn't exist."
246 fi
247
248 echo "socat:"
249 if _exists "socat"; then
250 socat -V 2>&1
251 else
252 _debug "socat doesn't exist."
253 fi
254 }
255
256 #class
257 _syslog() {
258 _exitstatus="$?"
259 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" = "$SYSLOG_LEVEL_NONE" ]; then
260 return
261 fi
262 _logclass="$1"
263 shift
264 if [ -z "$__logger_i" ]; then
265 if _contains "$(logger --help 2>&1)" "-i"; then
266 __logger_i="logger -i"
267 else
268 __logger_i="logger"
269 fi
270 fi
271 $__logger_i -t "$PROJECT_NAME" -p "$_logclass" "$(_printargs "$@")" >/dev/null 2>&1
272 return "$_exitstatus"
273 }
274
275 _log() {
276 [ -z "$LOG_FILE" ] && return
277 _printargs "$@" >>"$LOG_FILE"
278 }
279
280 _info() {
281 _log "$@"
282 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_INFO" ]; then
283 _syslog "$SYSLOG_INFO" "$@"
284 fi
285 _printargs "$@"
286 }
287
288 _err() {
289 _syslog "$SYSLOG_ERROR" "$@"
290 _log "$@"
291 if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
292 printf -- "%s" "[$(date)] " >&2
293 fi
294 if [ -z "$2" ]; then
295 __red "$1" >&2
296 else
297 __red "$1='$2'" >&2
298 fi
299 printf "\n" >&2
300 return 1
301 }
302
303 _usage() {
304 __red "$@" >&2
305 printf "\n" >&2
306 }
307
308 __debug_bash_helper() {
309 # At this point only do for --debug 3
310 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -lt "$DEBUG_LEVEL_3" ]; then
311 return
312 fi
313 # Return extra debug info when running with bash, otherwise return empty
314 # string.
315 if [ -z "${BASH_VERSION}" ]; then
316 return
317 fi
318 # We are a bash shell at this point, return the filename, function name, and
319 # line number as a string
320 _dbh_saveIFS=$IFS
321 IFS=" "
322 # Must use eval or syntax error happens under dash. The eval should use
323 # single quotes as older versions of busybox had a bug with double quotes and
324 # eval.
325 # Use 'caller 1' as we want one level up the stack as we should be called
326 # by one of the _debug* functions
327 eval '_dbh_called=($(caller 1))'
328 IFS=$_dbh_saveIFS
329 eval '_dbh_file=${_dbh_called[2]}'
330 if [ -n "${_script_home}" ]; then
331 # Trim off the _script_home directory name
332 eval '_dbh_file=${_dbh_file#$_script_home/}'
333 fi
334 eval '_dbh_function=${_dbh_called[1]}'
335 eval '_dbh_lineno=${_dbh_called[0]}'
336 printf "%-40s " "$_dbh_file:${_dbh_function}:${_dbh_lineno}"
337 }
338
339 _debug() {
340 if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
341 _log "$@"
342 fi
343 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
344 _syslog "$SYSLOG_DEBUG" "$@"
345 fi
346 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
347 _bash_debug=$(__debug_bash_helper)
348 _printargs "${_bash_debug}$@" >&2
349 fi
350 }
351
352 #output the sensitive messages
353 _secure_debug() {
354 if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
355 if [ "$OUTPUT_INSECURE" = "1" ]; then
356 _log "$@"
357 else
358 _log "$1" "$HIDDEN_VALUE"
359 fi
360 fi
361 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
362 _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
363 fi
364 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
365 if [ "$OUTPUT_INSECURE" = "1" ]; then
366 _printargs "$@" >&2
367 else
368 _printargs "$1" "$HIDDEN_VALUE" >&2
369 fi
370 fi
371 }
372
373 _debug2() {
374 if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
375 _log "$@"
376 fi
377 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
378 _syslog "$SYSLOG_DEBUG" "$@"
379 fi
380 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
381 _bash_debug=$(__debug_bash_helper)
382 _printargs "${_bash_debug}$@" >&2
383 fi
384 }
385
386 _secure_debug2() {
387 if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
388 if [ "$OUTPUT_INSECURE" = "1" ]; then
389 _log "$@"
390 else
391 _log "$1" "$HIDDEN_VALUE"
392 fi
393 fi
394 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
395 _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
396 fi
397 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
398 if [ "$OUTPUT_INSECURE" = "1" ]; then
399 _printargs "$@" >&2
400 else
401 _printargs "$1" "$HIDDEN_VALUE" >&2
402 fi
403 fi
404 }
405
406 _debug3() {
407 if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
408 _log "$@"
409 fi
410 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
411 _syslog "$SYSLOG_DEBUG" "$@"
412 fi
413 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
414 _bash_debug=$(__debug_bash_helper)
415 _printargs "${_bash_debug}$@" >&2
416 fi
417 }
418
419 _secure_debug3() {
420 if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
421 if [ "$OUTPUT_INSECURE" = "1" ]; then
422 _log "$@"
423 else
424 _log "$1" "$HIDDEN_VALUE"
425 fi
426 fi
427 if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
428 _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
429 fi
430 if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
431 if [ "$OUTPUT_INSECURE" = "1" ]; then
432 _printargs "$@" >&2
433 else
434 _printargs "$1" "$HIDDEN_VALUE" >&2
435 fi
436 fi
437 }
438
439 __USE_TR_RAW="$([ "$(echo "abc" | tr a-z A-Z 2>/dev/null)" = "ABC" ] && echo 1 || echo 0)"
440
441 _upper_case() {
442 if [ "$__USE_TR_RAW" = "0" ]; then
443 tr '[:lower:]' '[:upper:]'
444 else
445 # shellcheck disable=SC2018,SC2019
446 tr 'a-z' 'A-Z'
447 fi
448 }
449
450 _lower_case() {
451 if [ "$__USE_TR_RAW" = "0" ]; then
452 tr '[:upper:]' '[:lower:]'
453 else
454 # shellcheck disable=SC2018,SC2019
455 tr 'A-Z' 'a-z'
456 fi
457 }
458
459 _startswith() {
460 _str="$1"
461 _sub="$2"
462 echo "$_str" | grep -- "^$_sub" >/dev/null 2>&1
463 }
464
465 _endswith() {
466 _str="$1"
467 _sub="$2"
468 echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
469 }
470
471 _contains() {
472 _str="$1"
473 _sub="$2"
474 echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
475 }
476
477 _hasfield() {
478 _str="$1"
479 _field="$2"
480 _sep="$3"
481 if [ -z "$_field" ]; then
482 _usage "Usage: str field [sep]"
483 return 1
484 fi
485
486 if [ -z "$_sep" ]; then
487 _sep=","
488 fi
489
490 for f in $(echo "$_str" | tr "$_sep" ' '); do
491 if [ "$f" = "$_field" ]; then
492 _debug2 "'$_str' contains '$_field'"
493 return 0 #contains ok
494 fi
495 done
496 _debug2 "'$_str' does not contain '$_field'"
497 return 1 #not contains
498 }
499
500 # str index [sep]
501 _getfield() {
502 _str="$1"
503 _findex="$2"
504 _sep="$3"
505
506 if [ -z "$_findex" ]; then
507 _usage "Usage: str field [sep]"
508 return 1
509 fi
510
511 if [ -z "$_sep" ]; then
512 _sep=","
513 fi
514
515 _ffi="$_findex"
516 while [ "$_ffi" -gt "0" ]; do
517 _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
518 if [ "$_fv" ]; then
519 printf -- "%s" "$_fv"
520 return 0
521 fi
522 _ffi="$(_math "$_ffi" - 1)"
523 done
524
525 printf -- "%s" "$_str"
526
527 }
528
529 _exists() {
530 cmd="$1"
531 if [ -z "$cmd" ]; then
532 _usage "Usage: _exists cmd"
533 return 1
534 fi
535
536 if eval type type >/dev/null 2>&1; then
537 eval type "$cmd" >/dev/null 2>&1
538 elif command >/dev/null 2>&1; then
539 command -v "$cmd" >/dev/null 2>&1
540 else
541 which "$cmd" >/dev/null 2>&1
542 fi
543 ret="$?"
544 _debug3 "$cmd exists=$ret"
545 return $ret
546 }
547
548 #a + b
549 _math() {
550 _m_opts="$@"
551 printf "%s" "$(($_m_opts))"
552 }
553
554 _h_char_2_dec() {
555 _ch=$1
556 case "${_ch}" in
557 a | A)
558 printf "10"
559 ;;
560 b | B)
561 printf "11"
562 ;;
563 c | C)
564 printf "12"
565 ;;
566 d | D)
567 printf "13"
568 ;;
569 e | E)
570 printf "14"
571 ;;
572 f | F)
573 printf "15"
574 ;;
575 *)
576 printf "%s" "$_ch"
577 ;;
578 esac
579
580 }
581
582 _URGLY_PRINTF=""
583 if [ "$(printf '\x41')" != 'A' ]; then
584 _URGLY_PRINTF=1
585 fi
586
587 _ESCAPE_XARGS=""
588 if _exists xargs && [ "$(printf %s '\\x41' | xargs printf)" = 'A' ]; then
589 _ESCAPE_XARGS=1
590 fi
591
592 _h2b() {
593 if _exists xxd; then
594 if _contains "$(xxd --help 2>&1)" "assumes -c30"; then
595 if xxd -r -p -c 9999 2>/dev/null; then
596 return
597 fi
598 else
599 if xxd -r -p 2>/dev/null; then
600 return
601 fi
602 fi
603 fi
604
605 hex=$(cat)
606 ic=""
607 jc=""
608 _debug2 _URGLY_PRINTF "$_URGLY_PRINTF"
609 if [ -z "$_URGLY_PRINTF" ]; then
610 if [ "$_ESCAPE_XARGS" ] && _exists xargs; then
611 _debug2 "xargs"
612 echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/g' | xargs printf
613 else
614 for h in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/ \1/g'); do
615 if [ -z "$h" ]; then
616 break
617 fi
618 printf "\x$h%s"
619 done
620 fi
621 else
622 for c in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\)/ \1/g'); do
623 if [ -z "$ic" ]; then
624 ic=$c
625 continue
626 fi
627 jc=$c
628 ic="$(_h_char_2_dec "$ic")"
629 jc="$(_h_char_2_dec "$jc")"
630 printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
631 ic=""
632 jc=""
633 done
634 fi
635
636 }
637
638 _is_solaris() {
639 _contains "${__OS__:=$(uname -a)}" "solaris" || _contains "${__OS__:=$(uname -a)}" "SunOS"
640 }
641
642 #_ascii_hex str
643 #this can only process ascii chars, should only be used when od command is missing as a backup way.
644 _ascii_hex() {
645 _debug2 "Using _ascii_hex"
646 _str="$1"
647 _str_len=${#_str}
648 _h_i=1
649 while [ "$_h_i" -le "$_str_len" ]; do
650 _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
651 printf " %02x" "'$_str_c"
652 _h_i="$(_math "$_h_i" + 1)"
653 done
654 }
655
656 #stdin output hexstr splited by one space
657 #input:"abc"
658 #output: " 61 62 63"
659 _hex_dump() {
660 if _exists od; then
661 od -A n -v -t x1 | tr -s " " | sed 's/ $//' | tr -d "\r\t\n"
662 elif _exists hexdump; then
663 _debug3 "using hexdump"
664 hexdump -v -e '/1 ""' -e '/1 " %02x" ""'
665 elif _exists xxd; then
666 _debug3 "using xxd"
667 xxd -ps -c 20 -i | sed "s/ 0x/ /g" | tr -d ",\n" | tr -s " "
668 else
669 _debug3 "using _ascii_hex"
670 str=$(cat)
671 _ascii_hex "$str"
672 fi
673 }
674
675 #url encode, no-preserved chars
676 #A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
677 #41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a
678
679 #a b c d e f g h i j k l m n o p q r s t u v w x y z
680 #61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79 7a
681
682 #0 1 2 3 4 5 6 7 8 9 - _ . ~
683 #30 31 32 33 34 35 36 37 38 39 2d 5f 2e 7e
684
685 #stdin stdout
686 _url_encode() {
687 _hex_str=$(_hex_dump)
688 _debug3 "_url_encode"
689 _debug3 "_hex_str" "$_hex_str"
690 for _hex_code in $_hex_str; do
691 #upper case
692 case "${_hex_code}" in
693 "41")
694 printf "%s" "A"
695 ;;
696 "42")
697 printf "%s" "B"
698 ;;
699 "43")
700 printf "%s" "C"
701 ;;
702 "44")
703 printf "%s" "D"
704 ;;
705 "45")
706 printf "%s" "E"
707 ;;
708 "46")
709 printf "%s" "F"
710 ;;
711 "47")
712 printf "%s" "G"
713 ;;
714 "48")
715 printf "%s" "H"
716 ;;
717 "49")
718 printf "%s" "I"
719 ;;
720 "4a")
721 printf "%s" "J"
722 ;;
723 "4b")
724 printf "%s" "K"
725 ;;
726 "4c")
727 printf "%s" "L"
728 ;;
729 "4d")
730 printf "%s" "M"
731 ;;
732 "4e")
733 printf "%s" "N"
734 ;;
735 "4f")
736 printf "%s" "O"
737 ;;
738 "50")
739 printf "%s" "P"
740 ;;
741 "51")
742 printf "%s" "Q"
743 ;;
744 "52")
745 printf "%s" "R"
746 ;;
747 "53")
748 printf "%s" "S"
749 ;;
750 "54")
751 printf "%s" "T"
752 ;;
753 "55")
754 printf "%s" "U"
755 ;;
756 "56")
757 printf "%s" "V"
758 ;;
759 "57")
760 printf "%s" "W"
761 ;;
762 "58")
763 printf "%s" "X"
764 ;;
765 "59")
766 printf "%s" "Y"
767 ;;
768 "5a")
769 printf "%s" "Z"
770 ;;
771
772 #lower case
773 "61")
774 printf "%s" "a"
775 ;;
776 "62")
777 printf "%s" "b"
778 ;;
779 "63")
780 printf "%s" "c"
781 ;;
782 "64")
783 printf "%s" "d"
784 ;;
785 "65")
786 printf "%s" "e"
787 ;;
788 "66")
789 printf "%s" "f"
790 ;;
791 "67")
792 printf "%s" "g"
793 ;;
794 "68")
795 printf "%s" "h"
796 ;;
797 "69")
798 printf "%s" "i"
799 ;;
800 "6a")
801 printf "%s" "j"
802 ;;
803 "6b")
804 printf "%s" "k"
805 ;;
806 "6c")
807 printf "%s" "l"
808 ;;
809 "6d")
810 printf "%s" "m"
811 ;;
812 "6e")
813 printf "%s" "n"
814 ;;
815 "6f")
816 printf "%s" "o"
817 ;;
818 "70")
819 printf "%s" "p"
820 ;;
821 "71")
822 printf "%s" "q"
823 ;;
824 "72")
825 printf "%s" "r"
826 ;;
827 "73")
828 printf "%s" "s"
829 ;;
830 "74")
831 printf "%s" "t"
832 ;;
833 "75")
834 printf "%s" "u"
835 ;;
836 "76")
837 printf "%s" "v"
838 ;;
839 "77")
840 printf "%s" "w"
841 ;;
842 "78")
843 printf "%s" "x"
844 ;;
845 "79")
846 printf "%s" "y"
847 ;;
848 "7a")
849 printf "%s" "z"
850 ;;
851 #numbers
852 "30")
853 printf "%s" "0"
854 ;;
855 "31")
856 printf "%s" "1"
857 ;;
858 "32")
859 printf "%s" "2"
860 ;;
861 "33")
862 printf "%s" "3"
863 ;;
864 "34")
865 printf "%s" "4"
866 ;;
867 "35")
868 printf "%s" "5"
869 ;;
870 "36")
871 printf "%s" "6"
872 ;;
873 "37")
874 printf "%s" "7"
875 ;;
876 "38")
877 printf "%s" "8"
878 ;;
879 "39")
880 printf "%s" "9"
881 ;;
882 "2d")
883 printf "%s" "-"
884 ;;
885 "5f")
886 printf "%s" "_"
887 ;;
888 "2e")
889 printf "%s" "."
890 ;;
891 "7e")
892 printf "%s" "~"
893 ;;
894 #other hex
895 *)
896 printf '%%%s' "$_hex_code"
897 ;;
898 esac
899 done
900 }
901
902 _json_encode() {
903 _j_str="$(sed 's/"/\\"/g' | sed "s/\r/\\r/g")"
904 _debug3 "_json_encode"
905 _debug3 "_j_str" "$_j_str"
906 echo "$_j_str" | _hex_dump | _lower_case | sed 's/0a/5c 6e/g' | tr -d ' ' | _h2b | tr -d "\r\n"
907 }
908
909 #from: http:\/\/ to http://
910 _json_decode() {
911 _j_str="$(sed 's#\\/#/#g')"
912 _debug3 "_json_decode"
913 _debug3 "_j_str" "$_j_str"
914 echo "$_j_str"
915 }
916
917 #options file
918 _sed_i() {
919 options="$1"
920 filename="$2"
921 if [ -z "$filename" ]; then
922 _usage "Usage:_sed_i options filename"
923 return 1
924 fi
925 _debug2 options "$options"
926 if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
927 _debug "Using sed -i"
928 sed -i "$options" "$filename"
929 else
930 _debug "No -i support in sed"
931 text="$(cat "$filename")"
932 echo "$text" | sed "$options" >"$filename"
933 fi
934 }
935
936 _egrep_o() {
937 if ! egrep -o "$1" 2>/dev/null; then
938 sed -n 's/.*\('"$1"'\).*/\1/p'
939 fi
940 }
941
942 #Usage: file startline endline
943 _getfile() {
944 filename="$1"
945 startline="$2"
946 endline="$3"
947 if [ -z "$endline" ]; then
948 _usage "Usage: file startline endline"
949 return 1
950 fi
951
952 i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
953 if [ -z "$i" ]; then
954 _err "Can not find start line: $startline"
955 return 1
956 fi
957 i="$(_math "$i" + 1)"
958 _debug i "$i"
959
960 j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
961 if [ -z "$j" ]; then
962 _err "Can not find end line: $endline"
963 return 1
964 fi
965 j="$(_math "$j" - 1)"
966 _debug j "$j"
967
968 sed -n "$i,${j}p" "$filename"
969
970 }
971
972 #Usage: multiline
973 _base64() {
974 [ "" ] #urgly
975 if [ "$1" ]; then
976 _debug3 "base64 multiline:'$1'"
977 ${ACME_OPENSSL_BIN:-openssl} base64 -e
978 else
979 _debug3 "base64 single line."
980 ${ACME_OPENSSL_BIN:-openssl} base64 -e | tr -d '\r\n'
981 fi
982 }
983
984 #Usage: multiline
985 _dbase64() {
986 if [ "$1" ]; then
987 ${ACME_OPENSSL_BIN:-openssl} base64 -d
988 else
989 ${ACME_OPENSSL_BIN:-openssl} base64 -d -A
990 fi
991 }
992
993 #file
994 _checkcert() {
995 _cf="$1"
996 if [ "$DEBUG" ]; then
997 ${ACME_OPENSSL_BIN:-openssl} x509 -noout -text -in "$_cf"
998 else
999 ${ACME_OPENSSL_BIN:-openssl} x509 -noout -text -in "$_cf" >/dev/null 2>&1
1000 fi
1001 }
1002
1003 #Usage: hashalg [outputhex]
1004 #Output Base64-encoded digest
1005 _digest() {
1006 alg="$1"
1007 if [ -z "$alg" ]; then
1008 _usage "Usage: _digest hashalg"
1009 return 1
1010 fi
1011
1012 outputhex="$2"
1013
1014 if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
1015 if [ "$outputhex" ]; then
1016 ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
1017 else
1018 ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -binary | _base64
1019 fi
1020 else
1021 _err "$alg is not supported yet"
1022 return 1
1023 fi
1024
1025 }
1026
1027 #Usage: hashalg secret_hex [outputhex]
1028 #Output binary hmac
1029 _hmac() {
1030 alg="$1"
1031 secret_hex="$2"
1032 outputhex="$3"
1033
1034 if [ -z "$secret_hex" ]; then
1035 _usage "Usage: _hmac hashalg secret [outputhex]"
1036 return 1
1037 fi
1038
1039 if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
1040 if [ "$outputhex" ]; then
1041 (${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)") | cut -d = -f 2 | tr -d ' '
1042 else
1043 ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)" -binary
1044 fi
1045 else
1046 _err "$alg is not supported yet"
1047 return 1
1048 fi
1049
1050 }
1051
1052 #Usage: keyfile hashalg
1053 #Output: Base64-encoded signature value
1054 _sign() {
1055 keyfile="$1"
1056 alg="$2"
1057 if [ -z "$alg" ]; then
1058 _usage "Usage: _sign keyfile hashalg"
1059 return 1
1060 fi
1061
1062 _sign_openssl="${ACME_OPENSSL_BIN:-openssl} dgst -sign $keyfile "
1063
1064 if _isRSA "$keyfile" >/dev/null 2>&1; then
1065 $_sign_openssl -$alg | _base64
1066 elif _isEcc "$keyfile" >/dev/null 2>&1; then
1067 if ! _signedECText="$($_sign_openssl -sha$__ECC_KEY_LEN | ${ACME_OPENSSL_BIN:-openssl} asn1parse -inform DER)"; then
1068 _err "Sign failed: $_sign_openssl"
1069 _err "Key file: $keyfile"
1070 _err "Key content:$(wc -l <"$keyfile") lines"
1071 return 1
1072 fi
1073 _debug3 "_signedECText" "$_signedECText"
1074 _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
1075 _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
1076 if [ "$__ECC_KEY_LEN" -eq "256" ]; then
1077 while [ "${#_ec_r}" -lt "64" ]; do
1078 _ec_r="0${_ec_r}"
1079 done
1080 while [ "${#_ec_s}" -lt "64" ]; do
1081 _ec_s="0${_ec_s}"
1082 done
1083 fi
1084 if [ "$__ECC_KEY_LEN" -eq "384" ]; then
1085 while [ "${#_ec_r}" -lt "96" ]; do
1086 _ec_r="0${_ec_r}"
1087 done
1088 while [ "${#_ec_s}" -lt "96" ]; do
1089 _ec_s="0${_ec_s}"
1090 done
1091 fi
1092 if [ "$__ECC_KEY_LEN" -eq "512" ]; then
1093 while [ "${#_ec_r}" -lt "132" ]; do
1094 _ec_r="0${_ec_r}"
1095 done
1096 while [ "${#_ec_s}" -lt "132" ]; do
1097 _ec_s="0${_ec_s}"
1098 done
1099 fi
1100 _debug3 "_ec_r" "$_ec_r"
1101 _debug3 "_ec_s" "$_ec_s"
1102 printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
1103 else
1104 _err "Unknown key file format."
1105 return 1
1106 fi
1107
1108 }
1109
1110 #keylength or isEcc flag (empty str => not ecc)
1111 _isEccKey() {
1112 _length="$1"
1113
1114 if [ -z "$_length" ]; then
1115 return 1
1116 fi
1117
1118 [ "$_length" != "1024" ] &&
1119 [ "$_length" != "2048" ] &&
1120 [ "$_length" != "3072" ] &&
1121 [ "$_length" != "4096" ] &&
1122 [ "$_length" != "8192" ]
1123 }
1124
1125 # _createkey 2048|ec-256 file
1126 _createkey() {
1127 length="$1"
1128 f="$2"
1129 _debug2 "_createkey for file:$f"
1130 eccname="$length"
1131 if _startswith "$length" "ec-"; then
1132 length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
1133
1134 if [ "$length" = "256" ]; then
1135 eccname="prime256v1"
1136 fi
1137 if [ "$length" = "384" ]; then
1138 eccname="secp384r1"
1139 fi
1140 if [ "$length" = "521" ]; then
1141 eccname="secp521r1"
1142 fi
1143
1144 fi
1145
1146 if [ -z "$length" ]; then
1147 length=2048
1148 fi
1149
1150 _debug "Use length $length"
1151
1152 if ! [ -e "$f" ]; then
1153 if ! touch "$f" >/dev/null 2>&1; then
1154 _f_path="$(dirname "$f")"
1155 _debug _f_path "$_f_path"
1156 if ! mkdir -p "$_f_path"; then
1157 _err "Can not create path: $_f_path"
1158 return 1
1159 fi
1160 fi
1161 if ! touch "$f" >/dev/null 2>&1; then
1162 return 1
1163 fi
1164 chmod 600 "$f"
1165 fi
1166
1167 if _isEccKey "$length"; then
1168 _debug "Using ec name: $eccname"
1169 if _opkey="$(${ACME_OPENSSL_BIN:-openssl} ecparam -name "$eccname" -noout -genkey 2>/dev/null)"; then
1170 echo "$_opkey" >"$f"
1171 else
1172 _err "error ecc key name: $eccname"
1173 return 1
1174 fi
1175 else
1176 _debug "Using RSA: $length"
1177 __traditional=""
1178 if _contains "$(${ACME_OPENSSL_BIN:-openssl} help genrsa 2>&1)" "-traditional"; then
1179 __traditional="-traditional"
1180 fi
1181 if _opkey="$(${ACME_OPENSSL_BIN:-openssl} genrsa $__traditional "$length" 2>/dev/null)"; then
1182 echo "$_opkey" >"$f"
1183 else
1184 _err "error rsa key: $length"
1185 return 1
1186 fi
1187 fi
1188
1189 if [ "$?" != "0" ]; then
1190 _err "Create key error."
1191 return 1
1192 fi
1193 }
1194
1195 #domain
1196 _is_idn() {
1197 _is_idn_d="$1"
1198 _debug2 _is_idn_d "$_is_idn_d"
1199 _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '0-9' | tr -d 'a-z' | tr -d 'A-Z' | tr -d '*.,-_')
1200 _debug2 _idn_temp "$_idn_temp"
1201 [ "$_idn_temp" ]
1202 }
1203
1204 #aa.com
1205 #aa.com,bb.com,cc.com
1206 _idn() {
1207 __idn_d="$1"
1208 if ! _is_idn "$__idn_d"; then
1209 printf "%s" "$__idn_d"
1210 return 0
1211 fi
1212
1213 if _exists idn; then
1214 if _contains "$__idn_d" ','; then
1215 _i_first="1"
1216 for f in $(echo "$__idn_d" | tr ',' ' '); do
1217 [ -z "$f" ] && continue
1218 if [ -z "$_i_first" ]; then
1219 printf "%s" ","
1220 else
1221 _i_first=""
1222 fi
1223 idn --quiet "$f" | tr -d "\r\n"
1224 done
1225 else
1226 idn "$__idn_d" | tr -d "\r\n"
1227 fi
1228 else
1229 _err "Please install idn to process IDN names."
1230 fi
1231 }
1232
1233 #_createcsr cn san_list keyfile csrfile conf acmeValidationv1
1234 _createcsr() {
1235 _debug _createcsr
1236 domain="$1"
1237 domainlist="$2"
1238 csrkey="$3"
1239 csr="$4"
1240 csrconf="$5"
1241 acmeValidationv1="$6"
1242 _debug2 domain "$domain"
1243 _debug2 domainlist "$domainlist"
1244 _debug2 csrkey "$csrkey"
1245 _debug2 csr "$csr"
1246 _debug2 csrconf "$csrconf"
1247
1248 printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\n" >"$csrconf"
1249
1250 if [ "$acmeValidationv1" ]; then
1251 domainlist="$(_idn "$domainlist")"
1252 _debug2 domainlist "$domainlist"
1253 alt=""
1254 for dl in $(echo "$domainlist" | tr "," ' '); do
1255 if [ "$alt" ]; then
1256 alt="$alt,$(_getIdType "$dl" | _upper_case):$dl"
1257 else
1258 alt="$(_getIdType "$dl" | _upper_case):$dl"
1259 fi
1260 done
1261 printf -- "\nsubjectAltName=$alt" >>"$csrconf"
1262 elif [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
1263 #single domain
1264 _info "Single domain" "$domain"
1265 printf -- "\nsubjectAltName=$(_getIdType "$domain" | _upper_case):$(_idn "$domain")" >>"$csrconf"
1266 else
1267 domainlist="$(_idn "$domainlist")"
1268 _debug2 domainlist "$domainlist"
1269 alt="$(_getIdType "$domain" | _upper_case):$(_idn "$domain")"
1270 for dl in $(echo "'$domainlist'" | sed "s/,/' '/g"); do
1271 dl=$(echo "$dl" | tr -d "'")
1272 alt="$alt,$(_getIdType "$dl" | _upper_case):$dl"
1273 done
1274 #multi
1275 _info "Multi domain" "$alt"
1276 printf -- "\nsubjectAltName=$alt" >>"$csrconf"
1277 fi
1278 if [ "$Le_OCSP_Staple" = "1" ]; then
1279 _savedomainconf Le_OCSP_Staple "$Le_OCSP_Staple"
1280 printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
1281 fi
1282
1283 if [ "$acmeValidationv1" ]; then
1284 printf "\n1.3.6.1.5.5.7.1.31=critical,DER:04:20:${acmeValidationv1}" >>"${csrconf}"
1285 fi
1286
1287 _csr_cn="$(_idn "$domain")"
1288 _debug2 _csr_cn "$_csr_cn"
1289 if _contains "$(uname -a)" "MINGW"; then
1290 if _isIP "$_csr_cn"; then
1291 ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "//O=$PROJECT_NAME" -config "$csrconf" -out "$csr"
1292 else
1293 ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "//CN=$_csr_cn" -config "$csrconf" -out "$csr"
1294 fi
1295 else
1296 if _isIP "$_csr_cn"; then
1297 ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "/O=$PROJECT_NAME" -config "$csrconf" -out "$csr"
1298 else
1299 ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
1300 fi
1301 fi
1302 }
1303
1304 #_signcsr key csr conf cert
1305 _signcsr() {
1306 key="$1"
1307 csr="$2"
1308 conf="$3"
1309 cert="$4"
1310 _debug "_signcsr"
1311
1312 _msg="$(${ACME_OPENSSL_BIN:-openssl} x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
1313 _ret="$?"
1314 _debug "$_msg"
1315 return $_ret
1316 }
1317
1318 #_csrfile
1319 _readSubjectFromCSR() {
1320 _csrfile="$1"
1321 if [ -z "$_csrfile" ]; then
1322 _usage "_readSubjectFromCSR mycsr.csr"
1323 return 1
1324 fi
1325 ${ACME_OPENSSL_BIN:-openssl} req -noout -in "$_csrfile" -subject | tr ',' "\n" | _egrep_o "CN *=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d ' \n'
1326 }
1327
1328 #_csrfile
1329 #echo comma separated domain list
1330 _readSubjectAltNamesFromCSR() {
1331 _csrfile="$1"
1332 if [ -z "$_csrfile" ]; then
1333 _usage "_readSubjectAltNamesFromCSR mycsr.csr"
1334 return 1
1335 fi
1336
1337 _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
1338 _debug _csrsubj "$_csrsubj"
1339
1340 _dnsAltnames="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
1341 _debug _dnsAltnames "$_dnsAltnames"
1342
1343 if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
1344 _debug "AltNames contains subject"
1345 _excapedAlgnames="$(echo "$_dnsAltnames" | tr '*' '#')"
1346 _debug _excapedAlgnames "$_excapedAlgnames"
1347 _escapedSubject="$(echo "$_csrsubj" | tr '*' '#')"
1348 _debug _escapedSubject "$_escapedSubject"
1349 _dnsAltnames="$(echo "$_excapedAlgnames," | sed "s/DNS:$_escapedSubject,//g" | tr '#' '*' | sed "s/,\$//g")"
1350 _debug _dnsAltnames "$_dnsAltnames"
1351 else
1352 _debug "AltNames doesn't contain subject"
1353 fi
1354
1355 echo "$_dnsAltnames" | sed "s/DNS://g"
1356 }
1357
1358 #_csrfile
1359 _readKeyLengthFromCSR() {
1360 _csrfile="$1"
1361 if [ -z "$_csrfile" ]; then
1362 _usage "_readKeyLengthFromCSR mycsr.csr"
1363 return 1
1364 fi
1365
1366 _outcsr="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile")"
1367 _debug2 _outcsr "$_outcsr"
1368 if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
1369 _debug "ECC CSR"
1370 echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
1371 else
1372 _debug "RSA CSR"
1373 _rkl="$(echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1)"
1374 if [ "$_rkl" ]; then
1375 echo "$_rkl"
1376 else
1377 echo "$_outcsr" | tr "\t" " " | _egrep_o "RSA Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
1378 fi
1379 fi
1380 }
1381
1382 _ss() {
1383 _port="$1"
1384
1385 if _exists "ss"; then
1386 _debug "Using: ss"
1387 ss -ntpl 2>/dev/null | grep ":$_port "
1388 return 0
1389 fi
1390
1391 if _exists "netstat"; then
1392 _debug "Using: netstat"
1393 if netstat -help 2>&1 | grep "\-p proto" >/dev/null; then
1394 #for windows version netstat tool
1395 netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
1396 else
1397 if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
1398 netstat -an -p tcp | grep LISTEN | grep ":$_port "
1399 elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
1400 #for solaris
1401 netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
1402 elif netstat -help 2>&1 | grep "\-p" >/dev/null; then
1403 #for full linux
1404 netstat -ntpl | grep ":$_port "
1405 else
1406 #for busybox (embedded linux; no pid support)
1407 netstat -ntl 2>/dev/null | grep ":$_port "
1408 fi
1409 fi
1410 return 0
1411 fi
1412
1413 return 1
1414 }
1415
1416 #outfile key cert cacert [password [name [caname]]]
1417 _toPkcs() {
1418 _cpfx="$1"
1419 _ckey="$2"
1420 _ccert="$3"
1421 _cca="$4"
1422 pfxPassword="$5"
1423 pfxName="$6"
1424 pfxCaname="$7"
1425
1426 if [ "$pfxCaname" ]; then
1427 ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName" -caname "$pfxCaname"
1428 elif [ "$pfxName" ]; then
1429 ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName"
1430 elif [ "$pfxPassword" ]; then
1431 ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword"
1432 else
1433 ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca"
1434 fi
1435
1436 }
1437
1438 #domain [password] [isEcc]
1439 toPkcs() {
1440 domain="$1"
1441 pfxPassword="$2"
1442 if [ -z "$domain" ]; then
1443 _usage "Usage: $PROJECT_ENTRY --to-pkcs12 --domain <domain.tld> [--password <password>] [--ecc]"
1444 return 1
1445 fi
1446
1447 _isEcc="$3"
1448
1449 _initpath "$domain" "$_isEcc"
1450
1451 _toPkcs "$CERT_PFX_PATH" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$pfxPassword"
1452
1453 if [ "$?" = "0" ]; then
1454 _info "Success, Pfx is exported to: $CERT_PFX_PATH"
1455 fi
1456
1457 }
1458
1459 #domain [isEcc]
1460 toPkcs8() {
1461 domain="$1"
1462
1463 if [ -z "$domain" ]; then
1464 _usage "Usage: $PROJECT_ENTRY --to-pkcs8 --domain <domain.tld> [--ecc]"
1465 return 1
1466 fi
1467
1468 _isEcc="$2"
1469
1470 _initpath "$domain" "$_isEcc"
1471
1472 ${ACME_OPENSSL_BIN:-openssl} pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in "$CERT_KEY_PATH" -out "$CERT_PKCS8_PATH"
1473
1474 if [ "$?" = "0" ]; then
1475 _info "Success, $CERT_PKCS8_PATH"
1476 fi
1477
1478 }
1479
1480 #[2048]
1481 createAccountKey() {
1482 _info "Creating account key"
1483 if [ -z "$1" ]; then
1484 _usage "Usage: $PROJECT_ENTRY --create-account-key [--accountkeylength <bits>]"
1485 return
1486 fi
1487
1488 length=$1
1489 _create_account_key "$length"
1490
1491 }
1492
1493 _create_account_key() {
1494
1495 length=$1
1496
1497 if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
1498 _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
1499 length="$DEFAULT_ACCOUNT_KEY_LENGTH"
1500 fi
1501
1502 _debug length "$length"
1503 _initpath
1504
1505 mkdir -p "$CA_DIR"
1506 if [ -s "$ACCOUNT_KEY_PATH" ]; then
1507 _info "Account key exists, skip"
1508 return 0
1509 else
1510 #generate account key
1511 if _createkey "$length" "$ACCOUNT_KEY_PATH"; then
1512 _info "Create account key ok."
1513 return 0
1514 else
1515 _err "Create account key error."
1516 return 1
1517 fi
1518 fi
1519
1520 }
1521
1522 #domain [length]
1523 createDomainKey() {
1524 _info "Creating domain key"
1525 if [ -z "$1" ]; then
1526 _usage "Usage: $PROJECT_ENTRY --create-domain-key --domain <domain.tld> [--keylength <bits>]"
1527 return
1528 fi
1529
1530 domain=$1
1531 _cdl=$2
1532
1533 if [ -z "$_cdl" ]; then
1534 _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
1535 _cdl="$DEFAULT_DOMAIN_KEY_LENGTH"
1536 fi
1537
1538 _initpath "$domain" "$_cdl"
1539
1540 if [ ! -f "$CERT_KEY_PATH" ] || [ ! -s "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$_ACME_IS_RENEW" ]) || [ "$Le_ForceNewDomainKey" = "1" ]; then
1541 if _createkey "$_cdl" "$CERT_KEY_PATH"; then
1542 _savedomainconf Le_Keylength "$_cdl"
1543 _info "The domain key is here: $(__green $CERT_KEY_PATH)"
1544 return 0
1545 else
1546 _err "Can not create domain key"
1547 return 1
1548 fi
1549 else
1550 if [ "$_ACME_IS_RENEW" ]; then
1551 _info "Domain key exists, skip"
1552 return 0
1553 else
1554 _err "Domain key exists, do you want to overwrite the key?"
1555 _err "Add '--force', and try again."
1556 return 1
1557 fi
1558 fi
1559
1560 }
1561
1562 # domain domainlist isEcc
1563 createCSR() {
1564 _info "Creating csr"
1565 if [ -z "$1" ]; then
1566 _usage "Usage: $PROJECT_ENTRY --create-csr --domain <domain.tld> [--domain <domain2.tld> ...]"
1567 return
1568 fi
1569
1570 domain="$1"
1571 domainlist="$2"
1572 _isEcc="$3"
1573
1574 _initpath "$domain" "$_isEcc"
1575
1576 if [ -f "$CSR_PATH" ] && [ "$_ACME_IS_RENEW" ] && [ -z "$FORCE" ]; then
1577 _info "CSR exists, skip"
1578 return
1579 fi
1580
1581 if [ ! -f "$CERT_KEY_PATH" ]; then
1582 _err "The key file is not found: $CERT_KEY_PATH"
1583 _err "Please create the key file first."
1584 return 1
1585 fi
1586 _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
1587
1588 }
1589
1590 _url_replace() {
1591 tr '/+' '_-' | tr -d '= '
1592 }
1593
1594 #base64 string
1595 _durl_replace_base64() {
1596 _l=$((${#1} % 4))
1597 if [ $_l -eq 2 ]; then
1598 _s="$1"'=='
1599 elif [ $_l -eq 3 ]; then
1600 _s="$1"'='
1601 else
1602 _s="$1"
1603 fi
1604 echo "$_s" | tr '_-' '/+'
1605 }
1606
1607 _time2str() {
1608 #BSD
1609 if date -u -r "$1" -j "+%Y-%m-%dT%H:%M:%SZ" 2>/dev/null; then
1610 return
1611 fi
1612
1613 #Linux
1614 if date -u --date=@"$1" "+%Y-%m-%dT%H:%M:%SZ" 2>/dev/null; then
1615 return
1616 fi
1617
1618 #Solaris
1619 if printf "%(%Y-%m-%dT%H:%M:%SZ)T\n" $1 2>/dev/null; then
1620 return
1621 fi
1622
1623 #Busybox
1624 if echo "$1" | awk '{ print strftime("%Y-%m-%dT%H:%M:%SZ", $0); }' 2>/dev/null; then
1625 return
1626 fi
1627 }
1628
1629 _normalizeJson() {
1630 sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
1631 }
1632
1633 _stat() {
1634 #Linux
1635 if stat -c '%U:%G' "$1" 2>/dev/null; then
1636 return
1637 fi
1638
1639 #BSD
1640 if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
1641 return
1642 fi
1643
1644 return 1 #error, 'stat' not found
1645 }
1646
1647 #keyfile
1648 _isRSA() {
1649 keyfile=$1
1650 if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1 || ${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -noout -text | grep "^publicExponent:" >/dev/null 2>&1; then
1651 return 0
1652 fi
1653 return 1
1654 }
1655
1656 #keyfile
1657 _isEcc() {
1658 keyfile=$1
1659 if grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1 || ${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" >/dev/null 2>&1; then
1660 return 0
1661 fi
1662 return 1
1663 }
1664
1665 #keyfile
1666 _calcjwk() {
1667 keyfile="$1"
1668 if [ -z "$keyfile" ]; then
1669 _usage "Usage: _calcjwk keyfile"
1670 return 1
1671 fi
1672
1673 if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
1674 _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
1675 return 0
1676 fi
1677
1678 if _isRSA "$keyfile"; then
1679 _debug "RSA key"
1680 pub_exp=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
1681 if [ "${#pub_exp}" = "5" ]; then
1682 pub_exp=0$pub_exp
1683 fi
1684 _debug3 pub_exp "$pub_exp"
1685
1686 e=$(echo "$pub_exp" | _h2b | _base64)
1687 _debug3 e "$e"
1688
1689 modulus=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
1690 _debug3 modulus "$modulus"
1691 n="$(printf "%s" "$modulus" | _h2b | _base64 | _url_replace)"
1692 _debug3 n "$n"
1693
1694 jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
1695 _debug3 jwk "$jwk"
1696
1697 JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
1698 JWK_HEADERPLACE_PART1='{"nonce": "'
1699 JWK_HEADERPLACE_PART2='", "alg": "RS256"'
1700 elif _isEcc "$keyfile"; then
1701 _debug "EC key"
1702 crv="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
1703 _debug3 crv "$crv"
1704 __ECC_KEY_LEN=$(echo "$crv" | cut -d "-" -f 2)
1705 if [ "$__ECC_KEY_LEN" = "521" ]; then
1706 __ECC_KEY_LEN=512
1707 fi
1708 _debug3 __ECC_KEY_LEN "$__ECC_KEY_LEN"
1709 if [ -z "$crv" ]; then
1710 _debug "Let's try ASN1 OID"
1711 crv_oid="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
1712 _debug3 crv_oid "$crv_oid"
1713 case "${crv_oid}" in
1714 "prime256v1")
1715 crv="P-256"
1716 __ECC_KEY_LEN=256
1717 ;;
1718 "secp384r1")
1719 crv="P-384"
1720 __ECC_KEY_LEN=384
1721 ;;
1722 "secp521r1")
1723 crv="P-521"
1724 __ECC_KEY_LEN=512
1725 ;;
1726 *)
1727 _err "ECC oid : $crv_oid"
1728 return 1
1729 ;;
1730 esac
1731 _debug3 crv "$crv"
1732 fi
1733
1734 pubi="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
1735 pubi=$(_math "$pubi" + 1)
1736 _debug3 pubi "$pubi"
1737
1738 pubj="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
1739 pubj=$(_math "$pubj" - 1)
1740 _debug3 pubj "$pubj"
1741
1742 pubtext="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
1743 _debug3 pubtext "$pubtext"
1744
1745 xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
1746 xlen=$(_math "$xlen" / 4)
1747 _debug3 xlen "$xlen"
1748
1749 xend=$(_math "$xlen" + 1)
1750 x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
1751 _debug3 x "$x"
1752
1753 x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _url_replace)"
1754 _debug3 x64 "$x64"
1755
1756 xend=$(_math "$xend" + 1)
1757 y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
1758 _debug3 y "$y"
1759
1760 y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _url_replace)"
1761 _debug3 y64 "$y64"
1762
1763 jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
1764 _debug3 jwk "$jwk"
1765
1766 JWK_HEADER='{"alg": "ES'$__ECC_KEY_LEN'", "jwk": '$jwk'}'
1767 JWK_HEADERPLACE_PART1='{"nonce": "'
1768 JWK_HEADERPLACE_PART2='", "alg": "ES'$__ECC_KEY_LEN'"'
1769 else
1770 _err "Only RSA or EC key is supported. keyfile=$keyfile"
1771 _debug2 "$(cat "$keyfile")"
1772 return 1
1773 fi
1774
1775 _debug3 JWK_HEADER "$JWK_HEADER"
1776 __CACHED_JWK_KEY_FILE="$keyfile"
1777 }
1778
1779 _time() {
1780 date -u "+%s"
1781 }
1782
1783 #support 2 formats:
1784 # 2022-04-01 08:10:33 to 1648800633
1785 #or 2022-04-01T08:10:33Z to 1648800633
1786 _date2time() {
1787 #Linux
1788 if date -u -d "$(echo "$1" | tr -d "Z" | tr "T" ' ')" +"%s" 2>/dev/null; then
1789 return
1790 fi
1791
1792 #Solaris
1793 if gdate -u -d "$(echo "$1" | tr -d "Z" | tr "T" ' ')" +"%s" 2>/dev/null; then
1794 return
1795 fi
1796 #Mac/BSD
1797 if date -u -j -f "%Y-%m-%d %H:%M:%S" "$(echo "$1" | tr -d "Z" | tr "T" ' ')" +"%s" 2>/dev/null; then
1798 return
1799 fi
1800 _err "Can not parse _date2time $1"
1801 return 1
1802 }
1803
1804 _utc_date() {
1805 date -u "+%Y-%m-%d %H:%M:%S"
1806 }
1807
1808 _mktemp() {
1809 if _exists mktemp; then
1810 if mktemp 2>/dev/null; then
1811 return 0
1812 elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
1813 #for Mac osx
1814 return 0
1815 fi
1816 fi
1817 if [ -d "/tmp" ]; then
1818 echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
1819 return 0
1820 elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
1821 echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
1822 return 0
1823 fi
1824 _err "Can not create temp file."
1825 }
1826
1827 #clear all the https envs to cause _inithttp() to run next time.
1828 _resethttp() {
1829 __HTTP_INITIALIZED=""
1830 _ACME_CURL=""
1831 _ACME_WGET=""
1832 ACME_HTTP_NO_REDIRECTS=""
1833 }
1834
1835 _inithttp() {
1836
1837 if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
1838 HTTP_HEADER="$(_mktemp)"
1839 _debug2 HTTP_HEADER "$HTTP_HEADER"
1840 fi
1841
1842 if [ "$__HTTP_INITIALIZED" ]; then
1843 if [ "$_ACME_CURL$_ACME_WGET" ]; then
1844 _debug2 "Http already initialized."
1845 return 0
1846 fi
1847 fi
1848
1849 if [ -z "$_ACME_CURL" ] && _exists "curl"; then
1850 _ACME_CURL="curl --silent --dump-header $HTTP_HEADER "
1851 if [ -z "$ACME_HTTP_NO_REDIRECTS" ]; then
1852 _ACME_CURL="$_ACME_CURL -L "
1853 fi
1854 if [ "$DEBUG" ] && [ "$DEBUG" -ge 2 ]; then
1855 _CURL_DUMP="$(_mktemp)"
1856 _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
1857 fi
1858
1859 if [ "$CA_PATH" ]; then
1860 _ACME_CURL="$_ACME_CURL --capath $CA_PATH "
1861 elif [ "$CA_BUNDLE" ]; then
1862 _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
1863 fi
1864
1865 if _contains "$(curl --help 2>&1)" "--globoff"; then
1866 _ACME_CURL="$_ACME_CURL -g "
1867 fi
1868 fi
1869
1870 if [ -z "$_ACME_WGET" ] && _exists "wget"; then
1871 _ACME_WGET="wget -q"
1872 if [ "$ACME_HTTP_NO_REDIRECTS" ]; then
1873 _ACME_WGET="$_ACME_WGET --max-redirect 0 "
1874 fi
1875 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1876 if [ "$_ACME_WGET" ] && _contains "$($_ACME_WGET --help 2>&1)" "--debug"; then
1877 _ACME_WGET="$_ACME_WGET -d "
1878 fi
1879 fi
1880 if [ "$CA_PATH" ]; then
1881 _ACME_WGET="$_ACME_WGET --ca-directory=$CA_PATH "
1882 elif [ "$CA_BUNDLE" ]; then
1883 _ACME_WGET="$_ACME_WGET --ca-certificate=$CA_BUNDLE "
1884 fi
1885 fi
1886
1887 #from wget 1.14: do not skip body on 404 error
1888 if [ "$_ACME_WGET" ] && _contains "$($_ACME_WGET --help 2>&1)" "--content-on-error"; then
1889 _ACME_WGET="$_ACME_WGET --content-on-error "
1890 fi
1891
1892 __HTTP_INITIALIZED=1
1893
1894 }
1895
1896 # body url [needbase64] [POST|PUT|DELETE] [ContentType]
1897 _post() {
1898 body="$1"
1899 _post_url="$2"
1900 needbase64="$3"
1901 httpmethod="$4"
1902 _postContentType="$5"
1903
1904 if [ -z "$httpmethod" ]; then
1905 httpmethod="POST"
1906 fi
1907 _debug $httpmethod
1908 _debug "_post_url" "$_post_url"
1909 _debug2 "body" "$body"
1910 _debug2 "_postContentType" "$_postContentType"
1911
1912 _inithttp
1913
1914 if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
1915 _CURL="$_ACME_CURL"
1916 if [ "$HTTPS_INSECURE" ]; then
1917 _CURL="$_CURL --insecure "
1918 fi
1919 if [ "$httpmethod" = "HEAD" ]; then
1920 _CURL="$_CURL -I "
1921 fi
1922 _debug "_CURL" "$_CURL"
1923 if [ "$needbase64" ]; then
1924 if [ "$body" ]; then
1925 if [ "$_postContentType" ]; then
1926 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
1927 else
1928 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
1929 fi
1930 else
1931 if [ "$_postContentType" ]; then
1932 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url" | _base64)"
1933 else
1934 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url" | _base64)"
1935 fi
1936 fi
1937 else
1938 if [ "$body" ]; then
1939 if [ "$_postContentType" ]; then
1940 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
1941 else
1942 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
1943 fi
1944 else
1945 if [ "$_postContentType" ]; then
1946 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url")"
1947 else
1948 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$_post_url")"
1949 fi
1950 fi
1951 fi
1952 _ret="$?"
1953 if [ "$_ret" != "0" ]; then
1954 _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
1955 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1956 _err "Here is the curl dump log:"
1957 _err "$(cat "$_CURL_DUMP")"
1958 fi
1959 fi
1960 elif [ "$_ACME_WGET" ]; then
1961 _WGET="$_ACME_WGET"
1962 if [ "$HTTPS_INSECURE" ]; then
1963 _WGET="$_WGET --no-check-certificate "
1964 fi
1965 if [ "$httpmethod" = "HEAD" ]; then
1966 _WGET="$_WGET --read-timeout=3.0 --tries=2 "
1967 fi
1968 _debug "_WGET" "$_WGET"
1969 if [ "$needbase64" ]; then
1970 if [ "$httpmethod" = "POST" ]; then
1971 if [ "$_postContentType" ]; then
1972 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
1973 else
1974 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
1975 fi
1976 else
1977 if [ "$_postContentType" ]; then
1978 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
1979 else
1980 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
1981 fi
1982 fi
1983 else
1984 if [ "$httpmethod" = "POST" ]; then
1985 if [ "$_postContentType" ]; then
1986 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
1987 else
1988 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
1989 fi
1990 elif [ "$httpmethod" = "HEAD" ]; then
1991 if [ "$_postContentType" ]; then
1992 response="$($_WGET --spider -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
1993 else
1994 response="$($_WGET --spider -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
1995 fi
1996 else
1997 if [ "$_postContentType" ]; then
1998 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
1999 else
2000 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
2001 fi
2002 fi
2003 fi
2004 _ret="$?"
2005 if [ "$_ret" = "8" ]; then
2006 _ret=0
2007 _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
2008 fi
2009 if [ "$_ret" != "0" ]; then
2010 _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
2011 fi
2012 _sed_i "s/^ *//g" "$HTTP_HEADER"
2013 else
2014 _ret="$?"
2015 _err "Neither curl nor wget is found, can not do $httpmethod."
2016 fi
2017 _debug "_ret" "$_ret"
2018 printf "%s" "$response"
2019 return $_ret
2020 }
2021
2022 # url getheader timeout
2023 _get() {
2024 _debug GET
2025 url="$1"
2026 onlyheader="$2"
2027 t="$3"
2028 _debug url "$url"
2029 _debug "timeout=$t"
2030
2031 _inithttp
2032
2033 if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
2034 _CURL="$_ACME_CURL"
2035 if [ "$HTTPS_INSECURE" ]; then
2036 _CURL="$_CURL --insecure "
2037 fi
2038 if [ "$t" ]; then
2039 _CURL="$_CURL --connect-timeout $t"
2040 fi
2041 _debug "_CURL" "$_CURL"
2042 if [ "$onlyheader" ]; then
2043 $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
2044 else
2045 $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
2046 fi
2047 ret=$?
2048 if [ "$ret" != "0" ]; then
2049 _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
2050 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
2051 _err "Here is the curl dump log:"
2052 _err "$(cat "$_CURL_DUMP")"
2053 fi
2054 fi
2055 elif [ "$_ACME_WGET" ]; then
2056 _WGET="$_ACME_WGET"
2057 if [ "$HTTPS_INSECURE" ]; then
2058 _WGET="$_WGET --no-check-certificate "
2059 fi
2060 if [ "$t" ]; then
2061 _WGET="$_WGET --timeout=$t"
2062 fi
2063 _debug "_WGET" "$_WGET"
2064 if [ "$onlyheader" ]; then
2065 $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null "$url" 2>&1 | sed 's/^[ ]*//g'
2066 else
2067 $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
2068 fi
2069 ret=$?
2070 if [ "$ret" = "8" ]; then
2071 ret=0
2072 _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
2073 fi
2074 if [ "$ret" != "0" ]; then
2075 _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
2076 fi
2077 else
2078 ret=$?
2079 _err "Neither curl nor wget is found, can not do GET."
2080 fi
2081 _debug "ret" "$ret"
2082 return $ret
2083 }
2084
2085 _head_n() {
2086 head -n "$1"
2087 }
2088
2089 _tail_n() {
2090 if ! tail -n "$1" 2>/dev/null; then
2091 #fix for solaris
2092 tail -"$1"
2093 fi
2094 }
2095
2096 # url payload needbase64 keyfile
2097 _send_signed_request() {
2098 url=$1
2099 payload=$2
2100 needbase64=$3
2101 keyfile=$4
2102 if [ -z "$keyfile" ]; then
2103 keyfile="$ACCOUNT_KEY_PATH"
2104 fi
2105 _debug url "$url"
2106 _debug payload "$payload"
2107
2108 if ! _calcjwk "$keyfile"; then
2109 return 1
2110 fi
2111
2112 __request_conent_type="$CONTENT_TYPE_JSON"
2113
2114 payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
2115 _debug3 payload64 "$payload64"
2116
2117 MAX_REQUEST_RETRY_TIMES=20
2118 _sleep_retry_sec=1
2119 _request_retry_times=0
2120 while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
2121 _request_retry_times=$(_math "$_request_retry_times" + 1)
2122 _debug3 _request_retry_times "$_request_retry_times"
2123 if [ -z "$_CACHED_NONCE" ]; then
2124 _headers=""
2125 if [ "$ACME_NEW_NONCE" ]; then
2126 _debug2 "Get nonce with HEAD. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
2127 nonceurl="$ACME_NEW_NONCE"
2128 if _post "" "$nonceurl" "" "HEAD" "$__request_conent_type" >/dev/null; then
2129 _headers="$(cat "$HTTP_HEADER")"
2130 _debug2 _headers "$_headers"
2131 _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2 | cut -d , -f 1)"
2132 fi
2133 fi
2134 if [ -z "$_CACHED_NONCE" ]; then
2135 _debug2 "Get nonce with GET. ACME_DIRECTORY" "$ACME_DIRECTORY"
2136 nonceurl="$ACME_DIRECTORY"
2137 _headers="$(_get "$nonceurl" "onlyheader")"
2138 _debug2 _headers "$_headers"
2139 _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
2140 fi
2141 if [ -z "$_CACHED_NONCE" ] && [ "$ACME_NEW_NONCE" ]; then
2142 _debug2 "Get nonce with GET. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
2143 nonceurl="$ACME_NEW_NONCE"
2144 _headers="$(_get "$nonceurl" "onlyheader")"
2145 _debug2 _headers "$_headers"
2146 _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
2147 fi
2148 _debug2 _CACHED_NONCE "$_CACHED_NONCE"
2149 if [ "$?" != "0" ]; then
2150 _err "Can not connect to $nonceurl to get nonce."
2151 return 1
2152 fi
2153 else
2154 _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
2155 fi
2156 nonce="$_CACHED_NONCE"
2157 _debug2 nonce "$nonce"
2158 if [ -z "$nonce" ]; then
2159 _info "Could not get nonce, let's try again."
2160 _sleep 2
2161 continue
2162 fi
2163
2164 if [ "$url" = "$ACME_NEW_ACCOUNT" ]; then
2165 protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
2166 elif [ "$url" = "$ACME_REVOKE_CERT" ] && [ "$keyfile" != "$ACCOUNT_KEY_PATH" ]; then
2167 protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
2168 else
2169 protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"kid\": \"${ACCOUNT_URL}\""'}'
2170 fi
2171
2172 _debug3 protected "$protected"
2173
2174 protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
2175 _debug3 protected64 "$protected64"
2176
2177 if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
2178 _err "Sign request failed."
2179 return 1
2180 fi
2181 _debug3 _sig_t "$_sig_t"
2182
2183 sig="$(printf "%s" "$_sig_t" | _url_replace)"
2184 _debug3 sig "$sig"
2185
2186 body="{\"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
2187 _debug3 body "$body"
2188
2189 response="$(_post "$body" "$url" "$needbase64" "POST" "$__request_conent_type")"
2190 _CACHED_NONCE=""
2191
2192 if [ "$?" != "0" ]; then
2193 _err "Can not post to $url"
2194 return 1
2195 fi
2196
2197 responseHeaders="$(cat "$HTTP_HEADER")"
2198 _debug2 responseHeaders "$responseHeaders"
2199
2200 code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
2201 _debug code "$code"
2202
2203 _debug2 original "$response"
2204 if echo "$responseHeaders" | grep -i "Content-Type: *application/json" >/dev/null 2>&1; then
2205 response="$(echo "$response" | _json_decode | _normalizeJson)"
2206 fi
2207 _debug2 response "$response"
2208
2209 _CACHED_NONCE="$(echo "$responseHeaders" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2 | cut -d , -f 1)"
2210
2211 if ! _startswith "$code" "2"; then
2212 _body="$response"
2213 if [ "$needbase64" ]; then
2214 _body="$(echo "$_body" | _dbase64 multiline)"
2215 _debug3 _body "$_body"
2216 fi
2217
2218 if _contains "$_body" "JWS has invalid anti-replay nonce" || _contains "$_body" "JWS has an invalid anti-replay nonce"; then
2219 _info "It seems the CA server is busy now, let's wait and retry. Sleeping $_sleep_retry_sec seconds."
2220 _CACHED_NONCE=""
2221 _sleep $_sleep_retry_sec
2222 continue
2223 fi
2224 if _contains "$_body" "The Replay Nonce is not recognized"; then
2225 _info "The replay Nonce is not valid, let's get a new one, Sleeping $_sleep_retry_sec seconds."
2226 _CACHED_NONCE=""
2227 _sleep $_sleep_retry_sec
2228 continue
2229 fi
2230 fi
2231 return 0
2232 done
2233 _info "Giving up sending to CA server after $MAX_REQUEST_RETRY_TIMES retries."
2234 return 1
2235
2236 }
2237
2238 #setopt "file" "opt" "=" "value" [";"]
2239 _setopt() {
2240 __conf="$1"
2241 __opt="$2"
2242 __sep="$3"
2243 __val="$4"
2244 __end="$5"
2245 if [ -z "$__opt" ]; then
2246 _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
2247 return
2248 fi
2249 if [ ! -f "$__conf" ]; then
2250 touch "$__conf"
2251 fi
2252
2253 if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
2254 _debug3 OK
2255 if _contains "$__val" "&"; then
2256 __val="$(echo "$__val" | sed 's/&/\\&/g')"
2257 fi
2258 text="$(cat "$__conf")"
2259 printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
2260
2261 elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
2262 if _contains "$__val" "&"; then
2263 __val="$(echo "$__val" | sed 's/&/\\&/g')"
2264 fi
2265 text="$(cat "$__conf")"
2266 printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
2267
2268 else
2269 _debug3 APP
2270 echo "$__opt$__sep$__val$__end" >>"$__conf"
2271 fi
2272 _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
2273 }
2274
2275 #_save_conf file key value base64encode
2276 #save to conf
2277 _save_conf() {
2278 _s_c_f="$1"
2279 _sdkey="$2"
2280 _sdvalue="$3"
2281 _b64encode="$4"
2282 if [ "$_sdvalue" ] && [ "$_b64encode" ]; then
2283 _sdvalue="${B64CONF_START}$(printf "%s" "${_sdvalue}" | _base64)${B64CONF_END}"
2284 fi
2285 if [ "$_s_c_f" ]; then
2286 _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
2287 else
2288 _err "config file is empty, can not save $_sdkey=$_sdvalue"
2289 fi
2290 }
2291
2292 #_clear_conf file key
2293 _clear_conf() {
2294 _c_c_f="$1"
2295 _sdkey="$2"
2296 if [ "$_c_c_f" ]; then
2297 _conf_data="$(cat "$_c_c_f")"
2298 echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
2299 else
2300 _err "config file is empty, can not clear"
2301 fi
2302 }
2303
2304 #_read_conf file key
2305 _read_conf() {
2306 _r_c_f="$1"
2307 _sdkey="$2"
2308 if [ -f "$_r_c_f" ]; then
2309 _sdv="$(
2310 eval "$(grep "^$_sdkey *=" "$_r_c_f")"
2311 eval "printf \"%s\" \"\$$_sdkey\""
2312 )"
2313 if _startswith "$_sdv" "${B64CONF_START}" && _endswith "$_sdv" "${B64CONF_END}"; then
2314 _sdv="$(echo "$_sdv" | sed "s/${B64CONF_START}//" | sed "s/${B64CONF_END}//" | _dbase64)"
2315 fi
2316 printf "%s" "$_sdv"
2317 else
2318 _debug "config file is empty, can not read $_sdkey"
2319 fi
2320 }
2321
2322 #_savedomainconf key value base64encode
2323 #save to domain.conf
2324 _savedomainconf() {
2325 _save_conf "$DOMAIN_CONF" "$@"
2326 }
2327
2328 #_cleardomainconf key
2329 _cleardomainconf() {
2330 _clear_conf "$DOMAIN_CONF" "$1"
2331 }
2332
2333 #_readdomainconf key
2334 _readdomainconf() {
2335 _read_conf "$DOMAIN_CONF" "$1"
2336 }
2337
2338 #key value base64encode
2339 _savedeployconf() {
2340 _savedomainconf "SAVED_$1" "$2" "$3"
2341 #remove later
2342 _cleardomainconf "$1"
2343 }
2344
2345 #key
2346 _getdeployconf() {
2347 _rac_key="$1"
2348 _rac_value="$(eval echo \$"$_rac_key")"
2349 if [ "$_rac_value" ]; then
2350 if _startswith "$_rac_value" '"' && _endswith "$_rac_value" '"'; then
2351 _debug2 "trim quotation marks"
2352 eval "export $_rac_key=$_rac_value"
2353 fi
2354 return 0 # do nothing
2355 fi
2356 _saved=$(_readdomainconf "SAVED_$_rac_key")
2357 eval "export $_rac_key=\"\$_saved\""
2358 }
2359
2360 #_saveaccountconf key value base64encode
2361 _saveaccountconf() {
2362 _save_conf "$ACCOUNT_CONF_PATH" "$@"
2363 }
2364
2365 #key value base64encode
2366 _saveaccountconf_mutable() {
2367 _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2" "$3"
2368 #remove later
2369 _clearaccountconf "$1"
2370 }
2371
2372 #key
2373 _readaccountconf() {
2374 _read_conf "$ACCOUNT_CONF_PATH" "$1"
2375 }
2376
2377 #key
2378 _readaccountconf_mutable() {
2379 _rac_key="$1"
2380 _readaccountconf "SAVED_$_rac_key"
2381 }
2382
2383 #_clearaccountconf key
2384 _clearaccountconf() {
2385 _clear_conf "$ACCOUNT_CONF_PATH" "$1"
2386 }
2387
2388 #key
2389 _clearaccountconf_mutable() {
2390 _clearaccountconf "SAVED_$1"
2391 #remove later
2392 _clearaccountconf "$1"
2393 }
2394
2395 #_savecaconf key value
2396 _savecaconf() {
2397 _save_conf "$CA_CONF" "$1" "$2"
2398 }
2399
2400 #_readcaconf key
2401 _readcaconf() {
2402 _read_conf "$CA_CONF" "$1"
2403 }
2404
2405 #_clearaccountconf key
2406 _clearcaconf() {
2407 _clear_conf "$CA_CONF" "$1"
2408 }
2409
2410 # content localaddress
2411 _startserver() {
2412 content="$1"
2413 ncaddr="$2"
2414 _debug "content" "$content"
2415 _debug "ncaddr" "$ncaddr"
2416
2417 _debug "startserver: $$"
2418
2419 _debug Le_HTTPPort "$Le_HTTPPort"
2420 _debug Le_Listen_V4 "$Le_Listen_V4"
2421 _debug Le_Listen_V6 "$Le_Listen_V6"
2422
2423 _NC="socat"
2424 if [ "$Le_Listen_V4" ]; then
2425 _NC="$_NC -4"
2426 elif [ "$Le_Listen_V6" ]; then
2427 _NC="$_NC -6"
2428 fi
2429
2430 if [ "$DEBUG" ] && [ "$DEBUG" -gt "1" ]; then
2431 _NC="$_NC -d -d -v"
2432 fi
2433
2434 SOCAT_OPTIONS=TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork
2435
2436 #Adding bind to local-address
2437 if [ "$ncaddr" ]; then
2438 SOCAT_OPTIONS="$SOCAT_OPTIONS,bind=${ncaddr}"
2439 fi
2440
2441 _content_len="$(printf "%s" "$content" | wc -c)"
2442 _debug _content_len "$_content_len"
2443 _debug "_NC" "$_NC $SOCAT_OPTIONS"
2444 $_NC $SOCAT_OPTIONS SYSTEM:"sleep 1; \
2445 echo 'HTTP/1.0 200 OK'; \
2446 echo 'Content-Length\: $_content_len'; \
2447 echo ''; \
2448 printf '%s' '$content';" &
2449 serverproc="$!"
2450 }
2451
2452 _stopserver() {
2453 pid="$1"
2454 _debug "pid" "$pid"
2455 if [ -z "$pid" ]; then
2456 return
2457 fi
2458
2459 kill $pid
2460
2461 }
2462
2463 # sleep sec
2464 _sleep() {
2465 _sleep_sec="$1"
2466 if [ "$__INTERACTIVE" ]; then
2467 _sleep_c="$_sleep_sec"
2468 while [ "$_sleep_c" -ge "0" ]; do
2469 printf "\r \r"
2470 __green "$_sleep_c"
2471 _sleep_c="$(_math "$_sleep_c" - 1)"
2472 sleep 1
2473 done
2474 printf "\r"
2475 else
2476 sleep "$_sleep_sec"
2477 fi
2478 }
2479
2480 # _starttlsserver san_a san_b port content _ncaddr acmeValidationv1
2481 _starttlsserver() {
2482 _info "Starting tls server."
2483 san_a="$1"
2484 san_b="$2"
2485 port="$3"
2486 content="$4"
2487 opaddr="$5"
2488 acmeValidationv1="$6"
2489
2490 _debug san_a "$san_a"
2491 _debug san_b "$san_b"
2492 _debug port "$port"
2493 _debug acmeValidationv1 "$acmeValidationv1"
2494
2495 #create key TLS_KEY
2496 if ! _createkey "2048" "$TLS_KEY"; then
2497 _err "Create tls validation key error."
2498 return 1
2499 fi
2500
2501 #create csr
2502 alt="$san_a"
2503 if [ "$san_b" ]; then
2504 alt="$alt,$san_b"
2505 fi
2506 if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$acmeValidationv1"; then
2507 _err "Create tls validation csr error."
2508 return 1
2509 fi
2510
2511 #self signed
2512 if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
2513 _err "Create tls validation cert error."
2514 return 1
2515 fi
2516
2517 __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
2518 if [ "$opaddr" ]; then
2519 __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
2520 else
2521 __S_OPENSSL="$__S_OPENSSL -accept $port"
2522 fi
2523
2524 _debug Le_Listen_V4 "$Le_Listen_V4"
2525 _debug Le_Listen_V6 "$Le_Listen_V6"
2526 if [ "$Le_Listen_V4" ]; then
2527 __S_OPENSSL="$__S_OPENSSL -4"
2528 elif [ "$Le_Listen_V6" ]; then
2529 __S_OPENSSL="$__S_OPENSSL -6"
2530 fi
2531
2532 if [ "$acmeValidationv1" ]; then
2533 __S_OPENSSL="$__S_OPENSSL -alpn acme-tls/1"
2534 fi
2535
2536 _debug "$__S_OPENSSL"
2537 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
2538 $__S_OPENSSL -tlsextdebug &
2539 else
2540 $__S_OPENSSL >/dev/null 2>&1 &
2541 fi
2542
2543 serverproc="$!"
2544 sleep 1
2545 _debug serverproc "$serverproc"
2546 }
2547
2548 #file
2549 _readlink() {
2550 _rf="$1"
2551 if ! readlink -f "$_rf" 2>/dev/null; then
2552 if _startswith "$_rf" "/"; then
2553 echo "$_rf"
2554 return 0
2555 fi
2556 echo "$(pwd)/$_rf" | _conapath
2557 fi
2558 }
2559
2560 _conapath() {
2561 sed "s#/\./#/#g"
2562 }
2563
2564 __initHome() {
2565 if [ -z "$_SCRIPT_HOME" ]; then
2566 if _exists readlink && _exists dirname; then
2567 _debug "Lets find script dir."
2568 _debug "_SCRIPT_" "$_SCRIPT_"
2569 _script="$(_readlink "$_SCRIPT_")"
2570 _debug "_script" "$_script"
2571 _script_home="$(dirname "$_script")"
2572 _debug "_script_home" "$_script_home"
2573 if [ -d "$_script_home" ]; then
2574 _SCRIPT_HOME="$_script_home"
2575 else
2576 _err "It seems the script home is not correct:$_script_home"
2577 fi
2578 fi
2579 fi
2580
2581 # if [ -z "$LE_WORKING_DIR" ]; then
2582 # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
2583 # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
2584 # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
2585 # else
2586 # LE_WORKING_DIR="$_SCRIPT_HOME"
2587 # fi
2588 # fi
2589
2590 if [ -z "$LE_WORKING_DIR" ]; then
2591 _debug "Using default home:$DEFAULT_INSTALL_HOME"
2592 LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
2593 fi
2594 export LE_WORKING_DIR
2595
2596 if [ -z "$LE_CONFIG_HOME" ]; then
2597 LE_CONFIG_HOME="$LE_WORKING_DIR"
2598 fi
2599 _debug "Using config home:$LE_CONFIG_HOME"
2600 export LE_CONFIG_HOME
2601
2602 _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
2603
2604 if [ -z "$ACCOUNT_CONF_PATH" ]; then
2605 if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
2606 . "$_DEFAULT_ACCOUNT_CONF_PATH"
2607 fi
2608 fi
2609
2610 if [ -z "$ACCOUNT_CONF_PATH" ]; then
2611 ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
2612 fi
2613 _debug3 ACCOUNT_CONF_PATH "$ACCOUNT_CONF_PATH"
2614 DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
2615
2616 DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
2617
2618 if [ -z "$LE_TEMP_DIR" ]; then
2619 LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
2620 fi
2621 }
2622
2623 _clearAPI() {
2624 ACME_NEW_ACCOUNT=""
2625 ACME_KEY_CHANGE=""
2626 ACME_NEW_AUTHZ=""
2627 ACME_NEW_ORDER=""
2628 ACME_REVOKE_CERT=""
2629 ACME_NEW_NONCE=""
2630 ACME_AGREEMENT=""
2631 }
2632
2633 #server
2634 _initAPI() {
2635 _api_server="${1:-$ACME_DIRECTORY}"
2636 _debug "_init api for server: $_api_server"
2637
2638 MAX_API_RETRY_TIMES=10
2639 _sleep_retry_sec=10
2640 _request_retry_times=0
2641 while [ -z "$ACME_NEW_ACCOUNT" ] && [ "${_request_retry_times}" -lt "$MAX_API_RETRY_TIMES" ]; do
2642 _request_retry_times=$(_math "$_request_retry_times" + 1)
2643 response=$(_get "$_api_server")
2644 if [ "$?" != "0" ]; then
2645 _debug2 "response" "$response"
2646 _info "Can not init api for: $_api_server."
2647 _info "Sleep $_sleep_retry_sec and retry."
2648 _sleep "$_sleep_retry_sec"
2649 continue
2650 fi
2651 response=$(echo "$response" | _json_decode)
2652 _debug2 "response" "$response"
2653
2654 ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
2655 export ACME_KEY_CHANGE
2656
2657 ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
2658 export ACME_NEW_AUTHZ
2659
2660 ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
2661 export ACME_NEW_ORDER
2662
2663 ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
2664 export ACME_NEW_ACCOUNT
2665
2666 ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
2667 export ACME_REVOKE_CERT
2668
2669 ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
2670 export ACME_NEW_NONCE
2671
2672 ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
2673 export ACME_AGREEMENT
2674
2675 _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
2676 _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
2677 _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
2678 _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
2679 _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
2680 _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
2681 _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
2682 if [ "$ACME_NEW_ACCOUNT" ] && [ "$ACME_NEW_ORDER" ]; then
2683 return 0
2684 fi
2685 _info "Sleep $_sleep_retry_sec and retry."
2686 _sleep "$_sleep_retry_sec"
2687 done
2688 if [ "$ACME_NEW_ACCOUNT" ] && [ "$ACME_NEW_ORDER" ]; then
2689 return 0
2690 fi
2691 _err "Can not init api, for $_api_server"
2692 return 1
2693 }
2694
2695 _clearCA() {
2696 export CA_CONF=
2697 export ACCOUNT_KEY_PATH=
2698 export ACCOUNT_JSON_PATH=
2699 }
2700
2701 #[domain] [keylength or isEcc flag]
2702 _initpath() {
2703 domain="$1"
2704 _ilength="$2"
2705
2706 __initHome
2707
2708 if [ -f "$ACCOUNT_CONF_PATH" ]; then
2709 . "$ACCOUNT_CONF_PATH"
2710 fi
2711
2712 if [ "$_ACME_IN_CRON" ]; then
2713 if [ ! "$_USER_PATH_EXPORTED" ]; then
2714 _USER_PATH_EXPORTED=1
2715 export PATH="$USER_PATH:$PATH"
2716 fi
2717 fi
2718
2719 if [ -z "$CA_HOME" ]; then
2720 CA_HOME="$DEFAULT_CA_HOME"
2721 fi
2722
2723 if [ -z "$ACME_DIRECTORY" ]; then
2724 if [ "$STAGE" ]; then
2725 ACME_DIRECTORY="$DEFAULT_STAGING_CA"
2726 _info "Using ACME_DIRECTORY: $ACME_DIRECTORY"
2727 else
2728 default_acme_server=$(_readaccountconf "DEFAULT_ACME_SERVER")
2729 _debug default_acme_server "$default_acme_server"
2730 if [ "$default_acme_server" ]; then
2731 ACME_DIRECTORY="$default_acme_server"
2732 else
2733 ACME_DIRECTORY="$DEFAULT_CA"
2734 fi
2735 fi
2736 fi
2737
2738 _debug ACME_DIRECTORY "$ACME_DIRECTORY"
2739 _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
2740 _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
2741
2742 _ACME_SERVER_PATH="$(echo "$ACME_DIRECTORY" | cut -d : -f 2- | tr -s / | cut -d / -f 3-)"
2743 _debug2 "_ACME_SERVER_PATH" "$_ACME_SERVER_PATH"
2744
2745 CA_DIR="$CA_HOME/$_ACME_SERVER_HOST/$_ACME_SERVER_PATH"
2746 _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
2747 if [ -z "$CA_CONF" ]; then
2748 CA_CONF="$_DEFAULT_CA_CONF"
2749 fi
2750 _debug3 CA_CONF "$CA_CONF"
2751
2752 _OLD_CADIR="$CA_HOME/$_ACME_SERVER_HOST"
2753 _OLD_ACCOUNT_KEY="$_OLD_CADIR/account.key"
2754 _OLD_ACCOUNT_JSON="$_OLD_CADIR/account.json"
2755 _OLD_CA_CONF="$_OLD_CADIR/ca.conf"
2756
2757 _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
2758 _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
2759 if [ -z "$ACCOUNT_KEY_PATH" ]; then
2760 ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
2761 if [ -f "$_OLD_ACCOUNT_KEY" ] && ! [ -f "$ACCOUNT_KEY_PATH" ]; then
2762 mkdir -p "$CA_DIR"
2763 mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
2764 fi
2765 fi
2766
2767 if [ -z "$ACCOUNT_JSON_PATH" ]; then
2768 ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
2769 if [ -f "$_OLD_ACCOUNT_JSON" ] && ! [ -f "$ACCOUNT_JSON_PATH" ]; then
2770 mkdir -p "$CA_DIR"
2771 mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
2772 fi
2773 fi
2774
2775 if [ -f "$_OLD_CA_CONF" ] && ! [ -f "$CA_CONF" ]; then
2776 mkdir -p "$CA_DIR"
2777 mv "$_OLD_CA_CONF" "$CA_CONF"
2778 fi
2779
2780 if [ -f "$CA_CONF" ]; then
2781 . "$CA_CONF"
2782 fi
2783
2784 if [ -z "$ACME_DIR" ]; then
2785 ACME_DIR="/home/.acme"
2786 fi
2787
2788 if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
2789 APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
2790 fi
2791
2792 if [ -z "$USER_AGENT" ]; then
2793 USER_AGENT="$DEFAULT_USER_AGENT"
2794 fi
2795
2796 if [ -z "$HTTP_HEADER" ]; then
2797 HTTP_HEADER="$LE_CONFIG_HOME/http.header"
2798 fi
2799
2800 _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
2801 if [ -z "$CERT_HOME" ]; then
2802 CERT_HOME="$_DEFAULT_CERT_HOME"
2803 fi
2804
2805 if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
2806 ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
2807 fi
2808
2809 if [ -z "$domain" ]; then
2810 return 0
2811 fi
2812
2813 if [ -z "$DOMAIN_PATH" ]; then
2814 domainhome="$CERT_HOME/$domain"
2815 domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
2816
2817 DOMAIN_PATH="$domainhome"
2818
2819 if _isEccKey "$_ilength"; then
2820 DOMAIN_PATH="$domainhomeecc"
2821 else
2822 if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
2823 _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
2824 fi
2825 fi
2826 _debug DOMAIN_PATH "$DOMAIN_PATH"
2827 fi
2828
2829 if [ -z "$DOMAIN_BACKUP_PATH" ]; then
2830 DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
2831 fi
2832
2833 if [ -z "$DOMAIN_CONF" ]; then
2834 DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
2835 fi
2836
2837 if [ -z "$DOMAIN_SSL_CONF" ]; then
2838 DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
2839 fi
2840
2841 if [ -z "$CSR_PATH" ]; then
2842 CSR_PATH="$DOMAIN_PATH/$domain.csr"
2843 fi
2844 if [ -z "$CERT_KEY_PATH" ]; then
2845 CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
2846 fi
2847 if [ -z "$CERT_PATH" ]; then
2848 CERT_PATH="$DOMAIN_PATH/$domain.cer"
2849 fi
2850 if [ -z "$CA_CERT_PATH" ]; then
2851 CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
2852 fi
2853 if [ -z "$CERT_FULLCHAIN_PATH" ]; then
2854 CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
2855 fi
2856 if [ -z "$CERT_PFX_PATH" ]; then
2857 CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
2858 fi
2859 if [ -z "$CERT_PKCS8_PATH" ]; then
2860 CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
2861 fi
2862
2863 if [ -z "$TLS_CONF" ]; then
2864 TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
2865 fi
2866 if [ -z "$TLS_CERT" ]; then
2867 TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
2868 fi
2869 if [ -z "$TLS_KEY" ]; then
2870 TLS_KEY="$DOMAIN_PATH/tls.validation.key"
2871 fi
2872 if [ -z "$TLS_CSR" ]; then
2873 TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
2874 fi
2875
2876 }
2877
2878 _exec() {
2879 if [ -z "$_EXEC_TEMP_ERR" ]; then
2880 _EXEC_TEMP_ERR="$(_mktemp)"
2881 fi
2882
2883 if [ "$_EXEC_TEMP_ERR" ]; then
2884 eval "$@ 2>>$_EXEC_TEMP_ERR"
2885 else
2886 eval "$@"
2887 fi
2888 }
2889
2890 _exec_err() {
2891 [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
2892 }
2893
2894 _apachePath() {
2895 _APACHECTL="apachectl"
2896 if ! _exists apachectl; then
2897 if _exists apache2ctl; then
2898 _APACHECTL="apache2ctl"
2899 else
2900 _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
2901 _err "Please use webroot mode to try again."
2902 return 1
2903 fi
2904 fi
2905
2906 if ! _exec $_APACHECTL -V >/dev/null; then
2907 _exec_err
2908 return 1
2909 fi
2910
2911 if [ "$APACHE_HTTPD_CONF" ]; then
2912 _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
2913 httpdconf="$APACHE_HTTPD_CONF"
2914 httpdconfname="$(basename "$httpdconfname")"
2915 else
2916 httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
2917 _debug httpdconfname "$httpdconfname"
2918
2919 if [ -z "$httpdconfname" ]; then
2920 _err "Can not read apache config file."
2921 return 1
2922 fi
2923
2924 if _startswith "$httpdconfname" '/'; then
2925 httpdconf="$httpdconfname"
2926 httpdconfname="$(basename "$httpdconfname")"
2927 else
2928 httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
2929 _debug httpdroot "$httpdroot"
2930 httpdconf="$httpdroot/$httpdconfname"
2931 httpdconfname="$(basename "$httpdconfname")"
2932 fi
2933 fi
2934 _debug httpdconf "$httpdconf"
2935 _debug httpdconfname "$httpdconfname"
2936 if [ ! -f "$httpdconf" ]; then
2937 _err "Apache Config file not found" "$httpdconf"
2938 return 1
2939 fi
2940 return 0
2941 }
2942
2943 _restoreApache() {
2944 if [ -z "$usingApache" ]; then
2945 return 0
2946 fi
2947 _initpath
2948 if ! _apachePath; then
2949 return 1
2950 fi
2951
2952 if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
2953 _debug "No config file to restore."
2954 return 0
2955 fi
2956
2957 cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
2958 _debug "Restored: $httpdconf."
2959 if ! _exec $_APACHECTL -t; then
2960 _exec_err
2961 _err "Sorry, restore apache config error, please contact me."
2962 return 1
2963 fi
2964 _debug "Restored successfully."
2965 rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
2966 return 0
2967 }
2968
2969 _setApache() {
2970 _initpath
2971 if ! _apachePath; then
2972 return 1
2973 fi
2974
2975 #test the conf first
2976 _info "Checking if there is an error in the apache config file before starting."
2977
2978 if ! _exec "$_APACHECTL" -t >/dev/null; then
2979 _exec_err
2980 _err "The apache config file has error, please fix it first, then try again."
2981 _err "Don't worry, there is nothing changed to your system."
2982 return 1
2983 else
2984 _info "OK"
2985 fi
2986
2987 #backup the conf
2988 _debug "Backup apache config file" "$httpdconf"
2989 if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
2990 _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
2991 _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
2992 return 1
2993 fi
2994 _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
2995 _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
2996 _info "The backup file will be deleted on success, just forget it."
2997
2998 #add alias
2999
3000 apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
3001 _debug "apacheVer" "$apacheVer"
3002 apacheMajor="$(echo "$apacheVer" | cut -d . -f 1)"
3003 apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
3004
3005 if [ "$apacheVer" ] && [ "$apacheMajor$apacheMinor" -ge "24" ]; then
3006 echo "
3007 Alias /.well-known/acme-challenge $ACME_DIR
3008
3009 <Directory $ACME_DIR >
3010 Require all granted
3011 </Directory>
3012 " >>"$httpdconf"
3013 else
3014 echo "
3015 Alias /.well-known/acme-challenge $ACME_DIR
3016
3017 <Directory $ACME_DIR >
3018 Order allow,deny
3019 Allow from all
3020 </Directory>
3021 " >>"$httpdconf"
3022 fi
3023
3024 _msg="$($_APACHECTL -t 2>&1)"
3025 if [ "$?" != "0" ]; then
3026 _err "Sorry, apache config error"
3027 if _restoreApache; then
3028 _err "The apache config file is restored."
3029 else
3030 _err "Sorry, the apache config file can not be restored, please report bug."
3031 fi
3032 return 1
3033 fi
3034
3035 if [ ! -d "$ACME_DIR" ]; then
3036 mkdir -p "$ACME_DIR"
3037 chmod 755 "$ACME_DIR"
3038 fi
3039
3040 if ! _exec "$_APACHECTL" graceful; then
3041 _exec_err
3042 _err "$_APACHECTL graceful error, please contact me."
3043 _restoreApache
3044 return 1
3045 fi
3046 usingApache="1"
3047 return 0
3048 }
3049
3050 #find the real nginx conf file
3051 #backup
3052 #set the nginx conf
3053 #returns the real nginx conf file
3054 _setNginx() {
3055 _d="$1"
3056 _croot="$2"
3057 _thumbpt="$3"
3058
3059 FOUND_REAL_NGINX_CONF=""
3060 FOUND_REAL_NGINX_CONF_LN=""
3061 BACKUP_NGINX_CONF=""
3062 _debug _croot "$_croot"
3063 _start_f="$(echo "$_croot" | cut -d : -f 2)"
3064 _debug _start_f "$_start_f"
3065 if [ -z "$_start_f" ]; then
3066 _debug "find start conf from nginx command"
3067 if [ -z "$NGINX_CONF" ]; then
3068 if ! _exists "nginx"; then
3069 _err "nginx command is not found."
3070 return 1
3071 fi
3072 NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
3073 _debug NGINX_CONF "$NGINX_CONF"
3074 NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
3075 _debug NGINX_CONF "$NGINX_CONF"
3076 if [ -z "$NGINX_CONF" ]; then
3077 _err "Can not find nginx conf."
3078 NGINX_CONF=""
3079 return 1
3080 fi
3081 if [ ! -f "$NGINX_CONF" ]; then
3082 _err "'$NGINX_CONF' doesn't exist."
3083 NGINX_CONF=""
3084 return 1
3085 fi
3086 _debug "Found nginx conf file:$NGINX_CONF"
3087 fi
3088 _start_f="$NGINX_CONF"
3089 fi
3090 _debug "Start detect nginx conf for $_d from:$_start_f"
3091 if ! _checkConf "$_d" "$_start_f"; then
3092 _err "Can not find conf file for domain $d"
3093 return 1
3094 fi
3095 _info "Found conf file: $FOUND_REAL_NGINX_CONF"
3096
3097 _ln=$FOUND_REAL_NGINX_CONF_LN
3098 _debug "_ln" "$_ln"
3099
3100 _lnn=$(_math $_ln + 1)
3101 _debug _lnn "$_lnn"
3102 _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
3103 _debug "_start_tag" "$_start_tag"
3104 if [ "$_start_tag" = "$NGINX_START" ]; then
3105 _info "The domain $_d is already configured, skip"
3106 FOUND_REAL_NGINX_CONF=""
3107 return 0
3108 fi
3109
3110 mkdir -p "$DOMAIN_BACKUP_PATH"
3111 _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
3112 _debug _backup_conf "$_backup_conf"
3113 BACKUP_NGINX_CONF="$_backup_conf"
3114 _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
3115 if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
3116 _err "backup error."
3117 FOUND_REAL_NGINX_CONF=""
3118 return 1
3119 fi
3120
3121 if ! _exists "nginx"; then
3122 _err "nginx command is not found."
3123 return 1
3124 fi
3125 _info "Check the nginx conf before setting up."
3126 if ! _exec "nginx -t" >/dev/null; then
3127 _exec_err
3128 return 1
3129 fi
3130
3131 _info "OK, Set up nginx config file"
3132
3133 if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
3134 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
3135 _err "write nginx conf error, but don't worry, the file is restored to the original version."
3136 return 1
3137 fi
3138
3139 echo "$NGINX_START
3140 location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
3141 default_type text/plain;
3142 return 200 \"\$1.$_thumbpt\";
3143 }
3144 #NGINX_START
3145 " >>"$FOUND_REAL_NGINX_CONF"
3146
3147 if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
3148 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
3149 _err "write nginx conf error, but don't worry, the file is restored."
3150 return 1
3151 fi
3152 _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
3153 _info "nginx conf is done, let's check it again."
3154 if ! _exec "nginx -t" >/dev/null; then
3155 _exec_err
3156 _err "It seems that nginx conf was broken, let's restore."
3157 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
3158 return 1
3159 fi
3160
3161 _info "Reload nginx"
3162 if ! _exec "nginx -s reload" >/dev/null; then
3163 _exec_err
3164 _err "It seems that nginx reload error, let's restore."
3165 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
3166 return 1
3167 fi
3168
3169 return 0
3170 }
3171
3172 #d , conf
3173 _checkConf() {
3174 _d="$1"
3175 _c_file="$2"
3176 _debug "Start _checkConf from:$_c_file"
3177 if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
3178 _debug "wildcard"
3179 for _w_f in $2; do
3180 if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
3181 return 0
3182 fi
3183 done
3184 #not found
3185 return 1
3186 elif [ -f "$2" ]; then
3187 _debug "single"
3188 if _isRealNginxConf "$1" "$2"; then
3189 _debug "$2 is found."
3190 FOUND_REAL_NGINX_CONF="$2"
3191 return 0
3192 fi
3193 if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
3194 _debug "Try include files"
3195 for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
3196 _debug "check included $included"
3197 if ! _startswith "$included" "/" && _exists dirname; then
3198 _relpath="$(dirname "$2")"
3199 _debug "_relpath" "$_relpath"
3200 included="$_relpath/$included"
3201 fi
3202 if _checkConf "$1" "$included"; then
3203 return 0
3204 fi
3205 done
3206 fi
3207 return 1
3208 else
3209 _debug "$2 not found."
3210 return 1
3211 fi
3212 return 1
3213 }
3214
3215 #d , conf
3216 _isRealNginxConf() {
3217 _debug "_isRealNginxConf $1 $2"
3218 if [ -f "$2" ]; then
3219 for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
3220 _debug _fln "$_fln"
3221 if [ "$_fln" ]; then
3222 _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *" | grep -v server_name | _tail_n 1)
3223 _debug "_start" "$_start"
3224 _start_n=$(echo "$_start" | cut -d : -f 1)
3225 _start_nn=$(_math $_start_n + 1)
3226 _debug "_start_n" "$_start_n"
3227 _debug "_start_nn" "$_start_nn"
3228
3229 _left="$(sed -n "${_start_nn},99999p" "$2")"
3230 _debug2 _left "$_left"
3231 _end="$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *" | grep -v server_name | _head_n 1)"
3232 _debug "_end" "$_end"
3233 if [ "$_end" ]; then
3234 _end_n=$(echo "$_end" | cut -d : -f 1)
3235 _debug "_end_n" "$_end_n"
3236 _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
3237 else
3238 _seg_n="$_left"
3239 fi
3240
3241 _debug "_seg_n" "$_seg_n"
3242
3243 _skip_ssl=1
3244 for _listen_i in $(echo "$_seg_n" | tr "\t" ' ' | grep "^ *listen" | tr -d " "); do
3245 if [ "$_listen_i" ]; then
3246 if [ "$(echo "$_listen_i" | _egrep_o "listen.*ssl")" ]; then
3247 _debug2 "$_listen_i is ssl"
3248 else
3249 _debug2 "$_listen_i is plain text"
3250 _skip_ssl=""
3251 break
3252 fi
3253 fi
3254 done
3255
3256 if [ "$_skip_ssl" = "1" ]; then
3257 _debug "ssl on, skip"
3258 else
3259 FOUND_REAL_NGINX_CONF_LN=$_fln
3260 _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
3261 return 0
3262 fi
3263 fi
3264 done
3265 fi
3266 return 1
3267 }
3268
3269 #restore all the nginx conf
3270 _restoreNginx() {
3271 if [ -z "$NGINX_RESTORE_VLIST" ]; then
3272 _debug "No need to restore nginx, skip."
3273 return
3274 fi
3275 _debug "_restoreNginx"
3276 _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
3277
3278 for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
3279 _debug "ng_entry" "$ng_entry"
3280 _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
3281 _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
3282 _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
3283 _info "Restoring from $_ngbackupconf to $_ngconf"
3284 cat "$_ngbackupconf" >"$_ngconf"
3285 done
3286
3287 _info "Reload nginx"
3288 if ! _exec "nginx -s reload" >/dev/null; then
3289 _exec_err
3290 _err "It seems that nginx reload error, please report bug."
3291 return 1
3292 fi
3293 return 0
3294 }
3295
3296 _clearup() {
3297 _stopserver "$serverproc"
3298 serverproc=""
3299 _restoreApache
3300 _restoreNginx
3301 _clearupdns
3302 if [ -z "$DEBUG" ]; then
3303 rm -f "$TLS_CONF"
3304 rm -f "$TLS_CERT"
3305 rm -f "$TLS_KEY"
3306 rm -f "$TLS_CSR"
3307 fi
3308 }
3309
3310 _clearupdns() {
3311 _debug "_clearupdns"
3312 _debug "dns_entries" "$dns_entries"
3313
3314 if [ -z "$dns_entries" ]; then
3315 _debug "skip dns."
3316 return
3317 fi
3318 _info "Removing DNS records."
3319
3320 for entry in $dns_entries; do
3321 d=$(_getfield "$entry" 1)
3322 txtdomain=$(_getfield "$entry" 2)
3323 aliasDomain=$(_getfield "$entry" 3)
3324 _currentRoot=$(_getfield "$entry" 4)
3325 txt=$(_getfield "$entry" 5)
3326 d_api=$(_getfield "$entry" 6)
3327 _debug "d" "$d"
3328 _debug "txtdomain" "$txtdomain"
3329 _debug "aliasDomain" "$aliasDomain"
3330 _debug "_currentRoot" "$_currentRoot"
3331 _debug "txt" "$txt"
3332 _debug "d_api" "$d_api"
3333 if [ "$d_api" = "$txt" ]; then
3334 d_api=""
3335 fi
3336
3337 if [ -z "$d_api" ]; then
3338 _info "Not Found domain api file: $d_api"
3339 continue
3340 fi
3341
3342 if [ "$aliasDomain" ]; then
3343 txtdomain="$aliasDomain"
3344 fi
3345
3346 (
3347 if ! . "$d_api"; then
3348 _err "Load file $d_api error. Please check your api file and try again."
3349 return 1
3350 fi
3351
3352 rmcommand="${_currentRoot}_rm"
3353 if ! _exists "$rmcommand"; then
3354 _err "It seems that your api file doesn't define $rmcommand"
3355 return 1
3356 fi
3357 _info "Removing txt: $txt for domain: $txtdomain"
3358 if ! $rmcommand "$txtdomain" "$txt"; then
3359 _err "Error removing txt for domain:$txtdomain"
3360 return 1
3361 fi
3362 _info "Removed: Success"
3363 )
3364
3365 done
3366 }
3367
3368 # webroot removelevel tokenfile
3369 _clearupwebbroot() {
3370 __webroot="$1"
3371 if [ -z "$__webroot" ]; then
3372 _debug "no webroot specified, skip"
3373 return 0
3374 fi
3375
3376 _rmpath=""
3377 if [ "$2" = '1' ]; then
3378 _rmpath="$__webroot/.well-known"
3379 elif [ "$2" = '2' ]; then
3380 _rmpath="$__webroot/.well-known/acme-challenge"
3381 elif [ "$2" = '3' ]; then
3382 _rmpath="$__webroot/.well-known/acme-challenge/$3"
3383 else
3384 _debug "Skip for removelevel:$2"
3385 fi
3386
3387 if [ "$_rmpath" ]; then
3388 if [ "$DEBUG" ]; then
3389 _debug "Debugging, skip removing: $_rmpath"
3390 else
3391 rm -rf "$_rmpath"
3392 fi
3393 fi
3394
3395 return 0
3396
3397 }
3398
3399 _on_before_issue() {
3400 _chk_web_roots="$1"
3401 _chk_main_domain="$2"
3402 _chk_alt_domains="$3"
3403 _chk_pre_hook="$4"
3404 _chk_local_addr="$5"
3405 _debug _on_before_issue
3406 _debug _chk_main_domain "$_chk_main_domain"
3407 _debug _chk_alt_domains "$_chk_alt_domains"
3408 #run pre hook
3409 if [ "$_chk_pre_hook" ]; then
3410 _info "Run pre hook:'$_chk_pre_hook'"
3411 if ! (
3412 export Le_Domain="$_chk_main_domain"
3413 export Le_Alt="$_chk_alt_domains"
3414 cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
3415 ); then
3416 _err "Error when run pre hook."
3417 return 1
3418 fi
3419 fi
3420
3421 if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
3422 if ! _exists "socat"; then
3423 _err "Please install socat tools first."
3424 return 1
3425 fi
3426 fi
3427
3428 _debug Le_LocalAddress "$_chk_local_addr"
3429
3430 _index=1
3431 _currentRoot=""
3432 _addrIndex=1
3433 _w_index=1
3434 while true; do
3435 d="$(echo "$_chk_main_domain,$_chk_alt_domains," | cut -d , -f "$_w_index")"
3436 _w_index="$(_math "$_w_index" + 1)"
3437 _debug d "$d"
3438 if [ -z "$d" ]; then
3439 break
3440 fi
3441 _debug "Check for domain" "$d"
3442 _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
3443 _debug "_currentRoot" "$_currentRoot"
3444 _index=$(_math $_index + 1)
3445 _checkport=""
3446 if [ "$_currentRoot" = "$NO_VALUE" ]; then
3447 _info "Standalone mode."
3448 if [ -z "$Le_HTTPPort" ]; then
3449 Le_HTTPPort=80
3450 _cleardomainconf "Le_HTTPPort"
3451 else
3452 _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
3453 fi
3454 _checkport="$Le_HTTPPort"
3455 elif [ "$_currentRoot" = "$W_ALPN" ]; then
3456 _info "Standalone alpn mode."
3457 if [ -z "$Le_TLSPort" ]; then
3458 Le_TLSPort=443
3459 else
3460 _savedomainconf "Le_TLSPort" "$Le_TLSPort"
3461 fi
3462 _checkport="$Le_TLSPort"
3463 fi
3464
3465 if [ "$_checkport" ]; then
3466 _debug _checkport "$_checkport"
3467 _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
3468 _debug _checkaddr "$_checkaddr"
3469
3470 _addrIndex="$(_math $_addrIndex + 1)"
3471
3472 _netprc="$(_ss "$_checkport" | grep "$_checkport")"
3473 netprc="$(echo "$_netprc" | grep "$_checkaddr")"
3474 if [ -z "$netprc" ]; then
3475 netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS:$_checkport")"
3476 fi
3477 if [ "$netprc" ]; then
3478 _err "$netprc"
3479 _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
3480 _err "Please stop it first"
3481 return 1
3482 fi
3483 fi
3484 done
3485
3486 if _hasfield "$_chk_web_roots" "apache"; then
3487 if ! _setApache; then
3488 _err "set up apache error. Report error to me."
3489 return 1
3490 fi
3491 else
3492 usingApache=""
3493 fi
3494
3495 }
3496
3497 _on_issue_err() {
3498 _chk_post_hook="$1"
3499 _chk_vlist="$2"
3500 _debug _on_issue_err
3501
3502 if [ "$LOG_FILE" ]; then
3503 _err "Please check log file for more details: $LOG_FILE"
3504 else
3505 _err "Please add '--debug' or '--log' to check more details."
3506 _err "See: $_DEBUG_WIKI"
3507 fi
3508
3509 #run the post hook
3510 if [ "$_chk_post_hook" ]; then
3511 _info "Run post hook:'$_chk_post_hook'"
3512 if ! (
3513 cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
3514 ); then
3515 _err "Error when run post hook."
3516 return 1
3517 fi
3518 fi
3519
3520 #trigger the validation to flush the pending authz
3521 _debug2 "_chk_vlist" "$_chk_vlist"
3522 if [ "$_chk_vlist" ]; then
3523 (
3524 _debug2 "start to deactivate authz"
3525 ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
3526 for ventry in $ventries; do
3527 d=$(echo "$ventry" | cut -d "$sep" -f 1)
3528 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
3529 uri=$(echo "$ventry" | cut -d "$sep" -f 3)
3530 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
3531 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
3532 __trigger_validation "$uri" "$keyauthorization"
3533 done
3534 )
3535 fi
3536
3537 if [ "$_ACME_IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "$W_DNS"; then
3538 _err "$_DNS_MANUAL_ERR"
3539 fi
3540
3541 if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
3542 _debug "$(_dlg_versions)"
3543 fi
3544
3545 }
3546
3547 _on_issue_success() {
3548 _chk_post_hook="$1"
3549 _chk_renew_hook="$2"
3550 _debug _on_issue_success
3551
3552 #run the post hook
3553 if [ "$_chk_post_hook" ]; then
3554 _info "Run post hook:'$_chk_post_hook'"
3555 if ! (
3556 export CERT_PATH
3557 export CERT_KEY_PATH
3558 export CA_CERT_PATH
3559 export CERT_FULLCHAIN_PATH
3560 export Le_Domain="$_main_domain"
3561 cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
3562 ); then
3563 _err "Error when run post hook."
3564 return 1
3565 fi
3566 fi
3567
3568 #run renew hook
3569 if [ "$_ACME_IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
3570 _info "Run renew hook:'$_chk_renew_hook'"
3571 if ! (
3572 export CERT_PATH
3573 export CERT_KEY_PATH
3574 export CA_CERT_PATH
3575 export CERT_FULLCHAIN_PATH
3576 export Le_Domain="$_main_domain"
3577 cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
3578 ); then
3579 _err "Error when run renew hook."
3580 return 1
3581 fi
3582 fi
3583
3584 if _hasfield "$Le_Webroot" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
3585 _err "$_DNS_MANUAL_WARN"
3586 fi
3587
3588 }
3589
3590 #account_key_length eab-kid eab-hmac-key
3591 registeraccount() {
3592 _account_key_length="$1"
3593 _eab_id="$2"
3594 _eab_hmac_key="$3"
3595 _initpath
3596 _regAccount "$_account_key_length" "$_eab_id" "$_eab_hmac_key"
3597 }
3598
3599 __calcAccountKeyHash() {
3600 [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
3601 }
3602
3603 __calc_account_thumbprint() {
3604 printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
3605 }
3606
3607 _getAccountEmail() {
3608 if [ "$ACCOUNT_EMAIL" ]; then
3609 echo "$ACCOUNT_EMAIL"
3610 return 0
3611 fi
3612 if [ -z "$CA_EMAIL" ]; then
3613 CA_EMAIL="$(_readcaconf CA_EMAIL)"
3614 fi
3615 if [ "$CA_EMAIL" ]; then
3616 echo "$CA_EMAIL"
3617 return 0
3618 fi
3619 _readaccountconf "ACCOUNT_EMAIL"
3620 }
3621
3622 #keylength
3623 _regAccount() {
3624 _initpath
3625 _reg_length="$1"
3626 _eab_id="$2"
3627 _eab_hmac_key="$3"
3628 _debug3 _regAccount "$_regAccount"
3629 _initAPI
3630
3631 mkdir -p "$CA_DIR"
3632
3633 if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
3634 if ! _create_account_key "$_reg_length"; then
3635 _err "Create account key error."
3636 return 1
3637 fi
3638 fi
3639
3640 if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
3641 return 1
3642 fi
3643 if [ "$_eab_id" ] && [ "$_eab_hmac_key" ]; then
3644 _savecaconf CA_EAB_KEY_ID "$_eab_id"
3645 _savecaconf CA_EAB_HMAC_KEY "$_eab_hmac_key"
3646 fi
3647 _eab_id=$(_readcaconf "CA_EAB_KEY_ID")
3648 _eab_hmac_key=$(_readcaconf "CA_EAB_HMAC_KEY")
3649 _secure_debug3 _eab_id "$_eab_id"
3650 _secure_debug3 _eab_hmac_key "$_eab_hmac_key"
3651 _email="$(_getAccountEmail)"
3652 if [ "$_email" ]; then
3653 _savecaconf "CA_EMAIL" "$_email"
3654 fi
3655
3656 if [ "$ACME_DIRECTORY" = "$CA_ZEROSSL" ]; then
3657 if [ -z "$_eab_id" ] || [ -z "$_eab_hmac_key" ]; then
3658 _info "No EAB credentials found for ZeroSSL, let's get one"
3659 if [ -z "$_email" ]; then
3660 _info "$(__green "$PROJECT_NAME is using ZeroSSL as default CA now.")"
3661 _info "$(__green "Please update your account with an email address first.")"
3662 _info "$(__green "$PROJECT_ENTRY --register-account -m my@example.com")"
3663 _info "See: $(__green "$_ZEROSSL_WIKI")"
3664 return 1
3665 fi
3666 _eabresp=$(_post "email=$_email" $_ZERO_EAB_ENDPOINT)
3667 if [ "$?" != "0" ]; then
3668 _debug2 "$_eabresp"
3669 _err "Can not get EAB credentials from ZeroSSL."
3670 return 1
3671 fi
3672 _secure_debug2 _eabresp "$_eabresp"
3673 _eab_id="$(echo "$_eabresp" | tr ',}' '\n\n' | grep '"eab_kid"' | cut -d : -f 2 | tr -d '"')"
3674 _secure_debug2 _eab_id "$_eab_id"
3675 if [ -z "$_eab_id" ]; then
3676 _err "Can not resolve _eab_id"
3677 return 1
3678 fi
3679 _eab_hmac_key="$(echo "$_eabresp" | tr ',}' '\n\n' | grep '"eab_hmac_key"' | cut -d : -f 2 | tr -d '"')"
3680 _secure_debug2 _eab_hmac_key "$_eab_hmac_key"
3681 if [ -z "$_eab_hmac_key" ]; then
3682 _err "Can not resolve _eab_hmac_key"
3683 return 1
3684 fi
3685 _savecaconf CA_EAB_KEY_ID "$_eab_id"
3686 _savecaconf CA_EAB_HMAC_KEY "$_eab_hmac_key"
3687 fi
3688 fi
3689 if [ "$_eab_id" ] && [ "$_eab_hmac_key" ]; then
3690 eab_protected="{\"alg\":\"HS256\",\"kid\":\"$_eab_id\",\"url\":\"${ACME_NEW_ACCOUNT}\"}"
3691 _debug3 eab_protected "$eab_protected"
3692
3693 eab_protected64=$(printf "%s" "$eab_protected" | _base64 | _url_replace)
3694 _debug3 eab_protected64 "$eab_protected64"
3695
3696 eab_payload64=$(printf "%s" "$jwk" | _base64 | _url_replace)
3697 _debug3 eab_payload64 "$eab_payload64"
3698
3699 eab_sign_t="$eab_protected64.$eab_payload64"
3700 _debug3 eab_sign_t "$eab_sign_t"
3701
3702 key_hex="$(_durl_replace_base64 "$_eab_hmac_key" | _dbase64 multi | _hex_dump | tr -d ' ')"
3703 _debug3 key_hex "$key_hex"
3704
3705 eab_signature=$(printf "%s" "$eab_sign_t" | _hmac sha256 $key_hex | _base64 | _url_replace)
3706 _debug3 eab_signature "$eab_signature"
3707
3708 externalBinding=",\"externalAccountBinding\":{\"protected\":\"$eab_protected64\", \"payload\":\"$eab_payload64\", \"signature\":\"$eab_signature\"}"
3709 _debug3 externalBinding "$externalBinding"
3710 fi
3711 if [ "$_email" ]; then
3712 email_sg="\"contact\": [\"mailto:$_email\"], "
3713 fi
3714 regjson="{$email_sg\"termsOfServiceAgreed\": true$externalBinding}"
3715
3716 _info "Registering account: $ACME_DIRECTORY"
3717
3718 if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
3719 _err "Register account Error: $response"
3720 return 1
3721 fi
3722
3723 _eabAlreadyBound=""
3724 if [ "$code" = "" ] || [ "$code" = '201' ]; then
3725 echo "$response" >"$ACCOUNT_JSON_PATH"
3726 _info "Registered"
3727 elif [ "$code" = '409' ] || [ "$code" = '200' ]; then
3728 _info "Already registered"
3729 elif [ "$code" = '400' ] && _contains "$response" 'The account is not awaiting external account binding'; then
3730 _info "Already register EAB."
3731 _eabAlreadyBound=1
3732 else
3733 _err "Register account Error: $response"
3734 return 1
3735 fi
3736
3737 if [ -z "$_eabAlreadyBound" ]; then
3738 _debug2 responseHeaders "$responseHeaders"
3739 _accUri="$(echo "$responseHeaders" | grep -i "^Location:" | _head_n 1 | cut -d ':' -f 2- | tr -d "\r\n ")"
3740 _debug "_accUri" "$_accUri"
3741 if [ -z "$_accUri" ]; then
3742 _err "Can not find account id url."
3743 _err "$responseHeaders"
3744 return 1
3745 fi
3746 _savecaconf "ACCOUNT_URL" "$_accUri"
3747 else
3748 ACCOUNT_URL="$(_readcaconf ACCOUNT_URL)"
3749 fi
3750 export ACCOUNT_URL="$_accUri"
3751
3752 CA_KEY_HASH="$(__calcAccountKeyHash)"
3753 _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
3754 _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
3755
3756 if [ "$code" = '403' ]; then
3757 _err "It seems that the account key is already deactivated, please use a new account key."
3758 return 1
3759 fi
3760
3761 ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
3762 _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
3763 }
3764
3765 #implement updateaccount
3766 updateaccount() {
3767 _initpath
3768
3769 if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
3770 _err "Account key is not found at: $ACCOUNT_KEY_PATH"
3771 return 1
3772 fi
3773
3774 _accUri=$(_readcaconf "ACCOUNT_URL")
3775 _debug _accUri "$_accUri"
3776
3777 if [ -z "$_accUri" ]; then
3778 _err "The account url is empty, please run '--update-account' first to update the account info first,"
3779 _err "Then try again."
3780 return 1
3781 fi
3782
3783 if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
3784 return 1
3785 fi
3786 _initAPI
3787
3788 _email="$(_getAccountEmail)"
3789
3790 if [ "$_email" ]; then
3791 updjson='{"contact": ["mailto:'$_email'"]}'
3792 else
3793 updjson='{"contact": []}'
3794 fi
3795
3796 _send_signed_request "$_accUri" "$updjson"
3797
3798 if [ "$code" = '200' ]; then
3799 echo "$response" >"$ACCOUNT_JSON_PATH"
3800 _info "Account update success for $_accUri."
3801 else
3802 _info "Error. The account was not updated."
3803 return 1
3804 fi
3805 }
3806
3807 #Implement deactivate account
3808 deactivateaccount() {
3809 _initpath
3810
3811 if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
3812 _err "Account key is not found at: $ACCOUNT_KEY_PATH"
3813 return 1
3814 fi
3815
3816 _accUri=$(_readcaconf "ACCOUNT_URL")
3817 _debug _accUri "$_accUri"
3818
3819 if [ -z "$_accUri" ]; then
3820 _err "The account url is empty, please run '--update-account' first to update the account info first,"
3821 _err "Then try again."
3822 return 1
3823 fi
3824
3825 if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
3826 return 1
3827 fi
3828 _initAPI
3829
3830 _djson="{\"status\":\"deactivated\"}"
3831
3832 if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
3833 _info "Deactivate account success for $_accUri."
3834 _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
3835 elif [ "$code" = "403" ]; then
3836 _info "The account is already deactivated."
3837 _accid=$(_getfield "$_accUri" "999" "/")
3838 else
3839 _err "Deactivate: account failed for $_accUri."
3840 return 1
3841 fi
3842
3843 _debug "Account id: $_accid"
3844 if [ "$_accid" ]; then
3845 _deactivated_account_path="$CA_DIR/deactivated/$_accid"
3846 _debug _deactivated_account_path "$_deactivated_account_path"
3847 if mkdir -p "$_deactivated_account_path"; then
3848 _info "Moving deactivated account info to $_deactivated_account_path/"
3849 mv "$CA_CONF" "$_deactivated_account_path/"
3850 mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
3851 mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
3852 else
3853 _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
3854 rm -f "$CA_CONF"
3855 rm -f "$ACCOUNT_JSON_PATH"
3856 rm -f "$ACCOUNT_KEY_PATH"
3857 fi
3858 fi
3859 }
3860
3861 # domain folder file
3862 _findHook() {
3863 _hookdomain="$1"
3864 _hookcat="$2"
3865 _hookname="$3"
3866
3867 if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
3868 d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
3869 elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
3870 d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
3871 elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
3872 d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
3873 elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
3874 d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
3875 elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
3876 d_api="$LE_WORKING_DIR/$_hookname"
3877 elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
3878 d_api="$LE_WORKING_DIR/$_hookname.sh"
3879 elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
3880 d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
3881 elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
3882 d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
3883 fi
3884
3885 printf "%s" "$d_api"
3886 }
3887
3888 #domain
3889 __get_domain_new_authz() {
3890 _gdnd="$1"
3891 _info "Getting new-authz for domain" "$_gdnd"
3892 _initAPI
3893 _Max_new_authz_retry_times=5
3894 _authz_i=0
3895 while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
3896 _debug "Try new-authz for the $_authz_i time."
3897 if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
3898 _err "Can not get domain new authz."
3899 return 1
3900 fi
3901 if _contains "$response" "No registration exists matching provided key"; then
3902 _err "It seems there is an error, but it's recovered now, please try again."
3903 _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
3904 _clearcaconf "CA_KEY_HASH"
3905 break
3906 fi
3907 if ! _contains "$response" "An error occurred while processing your request"; then
3908 _info "The new-authz request is ok."
3909 break
3910 fi
3911 _authz_i="$(_math "$_authz_i" + 1)"
3912 _info "The server is busy, Sleep $_authz_i to retry."
3913 _sleep "$_authz_i"
3914 done
3915
3916 if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
3917 _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
3918 fi
3919
3920 if [ "$code" ] && [ "$code" != '201' ]; then
3921 _err "new-authz error: $response"
3922 return 1
3923 fi
3924
3925 }
3926
3927 #uri keyAuthorization
3928 __trigger_validation() {
3929 _debug2 "Trigger domain validation."
3930 _t_url="$1"
3931 _debug2 _t_url "$_t_url"
3932 _t_key_authz="$2"
3933 _debug2 _t_key_authz "$_t_key_authz"
3934 _t_vtype="$3"
3935 _debug2 _t_vtype "$_t_vtype"
3936
3937 _send_signed_request "$_t_url" "{}"
3938
3939 }
3940
3941 #endpoint domain type
3942 _ns_lookup_impl() {
3943 _ns_ep="$1"
3944 _ns_domain="$2"
3945 _ns_type="$3"
3946 _debug2 "_ns_ep" "$_ns_ep"
3947 _debug2 "_ns_domain" "$_ns_domain"
3948 _debug2 "_ns_type" "$_ns_type"
3949
3950 response="$(_H1="accept: application/dns-json" _get "$_ns_ep?name=$_ns_domain&type=$_ns_type")"
3951 _ret=$?
3952 _debug2 "response" "$response"
3953 if [ "$_ret" != "0" ]; then
3954 return $_ret
3955 fi
3956 _answers="$(echo "$response" | tr '{}' '<>' | _egrep_o '"Answer":\[[^]]*]' | tr '<>' '\n\n')"
3957 _debug2 "_answers" "$_answers"
3958 echo "$_answers"
3959 }
3960
3961 #domain, type
3962 _ns_lookup_cf() {
3963 _cf_ld="$1"
3964 _cf_ld_type="$2"
3965 _cf_ep="https://cloudflare-dns.com/dns-query"
3966 _ns_lookup_impl "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
3967 }
3968
3969 #domain, type
3970 _ns_purge_cf() {
3971 _cf_d="$1"
3972 _cf_d_type="$2"
3973 _debug "Cloudflare purge $_cf_d_type record for domain $_cf_d"
3974 _cf_purl="https://cloudflare-dns.com/api/v1/purge?domain=$_cf_d&type=$_cf_d_type"
3975 response="$(_post "" "$_cf_purl")"
3976 _debug2 response "$response"
3977 }
3978
3979 #checks if cf server is available
3980 _ns_is_available_cf() {
3981 if _get "https://cloudflare-dns.com" "" 1 >/dev/null 2>&1; then
3982 return 0
3983 else
3984 return 1
3985 fi
3986 }
3987
3988 _ns_is_available_google() {
3989 if _get "https://dns.google" "" 1 >/dev/null 2>&1; then
3990 return 0
3991 else
3992 return 1
3993 fi
3994 }
3995
3996 #domain, type
3997 _ns_lookup_google() {
3998 _cf_ld="$1"
3999 _cf_ld_type="$2"
4000 _cf_ep="https://dns.google/resolve"
4001 _ns_lookup_impl "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
4002 }
4003
4004 _ns_is_available_ali() {
4005 if _get "https://dns.alidns.com" "" 1 >/dev/null 2>&1; then
4006 return 0
4007 else
4008 return 1
4009 fi
4010 }
4011
4012 #domain, type
4013 _ns_lookup_ali() {
4014 _cf_ld="$1"
4015 _cf_ld_type="$2"
4016 _cf_ep="https://dns.alidns.com/resolve"
4017 _ns_lookup_impl "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
4018 }
4019
4020 _ns_is_available_dp() {
4021 if _get "https://doh.pub" "" 1 >/dev/null 2>&1; then
4022 return 0
4023 else
4024 return 1
4025 fi
4026 }
4027
4028 #dnspod
4029 _ns_lookup_dp() {
4030 _cf_ld="$1"
4031 _cf_ld_type="$2"
4032 _cf_ep="https://doh.pub/dns-query"
4033 _ns_lookup_impl "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
4034 }
4035
4036 #domain, type
4037 _ns_lookup() {
4038 if [ -z "$DOH_USE" ]; then
4039 _debug "Detect dns server first."
4040 if _ns_is_available_cf; then
4041 _debug "Use cloudflare doh server"
4042 export DOH_USE=$DOH_CLOUDFLARE
4043 elif _ns_is_available_google; then
4044 _debug "Use google doh server"
4045 export DOH_USE=$DOH_GOOGLE
4046 elif _ns_is_available_ali; then
4047 _debug "Use aliyun doh server"
4048 export DOH_USE=$DOH_ALI
4049 elif _ns_is_available_dp; then
4050 _debug "Use dns pod doh server"
4051 export DOH_USE=$DOH_DP
4052 else
4053 _err "No doh"
4054 fi
4055 fi
4056
4057 if [ "$DOH_USE" = "$DOH_CLOUDFLARE" ] || [ -z "$DOH_USE" ]; then
4058 _ns_lookup_cf "$@"
4059 elif [ "$DOH_USE" = "$DOH_GOOGLE" ]; then
4060 _ns_lookup_google "$@"
4061 elif [ "$DOH_USE" = "$DOH_ALI" ]; then
4062 _ns_lookup_ali "$@"
4063 elif [ "$DOH_USE" = "$DOH_DP" ]; then
4064 _ns_lookup_dp "$@"
4065 else
4066 _err "Unknown doh provider: DOH_USE=$DOH_USE"
4067 fi
4068
4069 }
4070
4071 #txtdomain, alias, txt
4072 __check_txt() {
4073 _c_txtdomain="$1"
4074 _c_aliasdomain="$2"
4075 _c_txt="$3"
4076 _debug "_c_txtdomain" "$_c_txtdomain"
4077 _debug "_c_aliasdomain" "$_c_aliasdomain"
4078 _debug "_c_txt" "$_c_txt"
4079 _answers="$(_ns_lookup "$_c_aliasdomain" TXT)"
4080 _contains "$_answers" "$_c_txt"
4081
4082 }
4083
4084 #txtdomain
4085 __purge_txt() {
4086 _p_txtdomain="$1"
4087 _debug _p_txtdomain "$_p_txtdomain"
4088 if [ "$DOH_USE" = "$DOH_CLOUDFLARE" ] || [ -z "$DOH_USE" ]; then
4089 _ns_purge_cf "$_p_txtdomain" "TXT"
4090 else
4091 _debug "no purge api for this doh api, just sleep 5 secs"
4092 _sleep 5
4093 fi
4094
4095 }
4096
4097 #wait and check each dns entries
4098 _check_dns_entries() {
4099 _success_txt=","
4100 _end_time="$(_time)"
4101 _end_time="$(_math "$_end_time" + 1200)" #let's check no more than 20 minutes.
4102
4103 while [ "$(_time)" -le "$_end_time" ]; do
4104 _info "You can use '--dnssleep' to disable public dns checks."
4105 _info "See: $_DNSCHECK_WIKI"
4106 _left=""
4107 for entry in $dns_entries; do
4108 d=$(_getfield "$entry" 1)
4109 txtdomain=$(_getfield "$entry" 2)
4110 txtdomain=$(_idn "$txtdomain")
4111 aliasDomain=$(_getfield "$entry" 3)
4112 aliasDomain=$(_idn "$aliasDomain")
4113 txt=$(_getfield "$entry" 5)
4114 d_api=$(_getfield "$entry" 6)
4115 _debug "d" "$d"
4116 _debug "txtdomain" "$txtdomain"
4117 _debug "aliasDomain" "$aliasDomain"
4118 _debug "txt" "$txt"
4119 _debug "d_api" "$d_api"
4120 _info "Checking $d for $aliasDomain"
4121 if _contains "$_success_txt" ",$txt,"; then
4122 _info "Already success, continue next one."
4123 continue
4124 fi
4125
4126 if __check_txt "$txtdomain" "$aliasDomain" "$txt"; then
4127 _info "Domain $d '$aliasDomain' success."
4128 _success_txt="$_success_txt,$txt,"
4129 continue
4130 fi
4131 _left=1
4132 _info "Not valid yet, let's wait 10 seconds and check next one."
4133 __purge_txt "$txtdomain"
4134 if [ "$txtdomain" != "$aliasDomain" ]; then
4135 __purge_txt "$aliasDomain"
4136 fi
4137 _sleep 10
4138 done
4139 if [ "$_left" ]; then
4140 _info "Let's wait 10 seconds and check again".
4141 _sleep 10
4142 else
4143 _info "All success, let's return"
4144 return 0
4145 fi
4146 done
4147 _info "Timed out waiting for DNS."
4148 return 1
4149
4150 }
4151
4152 #file
4153 _get_chain_issuers() {
4154 _cfile="$1"
4155 if _contains "$(${ACME_OPENSSL_BIN:-openssl} help crl2pkcs7 2>&1)" "Usage: crl2pkcs7" || _contains "$(${ACME_OPENSSL_BIN:-openssl} crl2pkcs7 -help 2>&1)" "Usage: crl2pkcs7" || _contains "$(${ACME_OPENSSL_BIN:-openssl} crl2pkcs7 help 2>&1)" "unknown option help"; then
4156 ${ACME_OPENSSL_BIN:-openssl} crl2pkcs7 -nocrl -certfile $_cfile | ${ACME_OPENSSL_BIN:-openssl} pkcs7 -print_certs -text -noout | grep -i 'Issuer:' | _egrep_o "CN *=[^,]*" | cut -d = -f 2
4157 else
4158 _cindex=1
4159 for _startn in $(grep -n -- "$BEGIN_CERT" "$_cfile" | cut -d : -f 1); do
4160 _endn="$(grep -n -- "$END_CERT" "$_cfile" | cut -d : -f 1 | _head_n $_cindex | _tail_n 1)"
4161 _debug2 "_startn" "$_startn"
4162 _debug2 "_endn" "$_endn"
4163 if [ "$DEBUG" ]; then
4164 _debug2 "cert$_cindex" "$(sed -n "$_startn,${_endn}p" "$_cfile")"
4165 fi
4166 sed -n "$_startn,${_endn}p" "$_cfile" | ${ACME_OPENSSL_BIN:-openssl} x509 -text -noout | grep 'Issuer:' | _egrep_o "CN *=[^,]*" | cut -d = -f 2 | sed "s/ *\(.*\)/\1/"
4167 _cindex=$(_math $_cindex + 1)
4168 done
4169 fi
4170 }
4171
4172 #
4173 _get_chain_subjects() {
4174 _cfile="$1"
4175 if _contains "$(${ACME_OPENSSL_BIN:-openssl} help crl2pkcs7 2>&1)" "Usage: crl2pkcs7" || _contains "$(${ACME_OPENSSL_BIN:-openssl} crl2pkcs7 -help 2>&1)" "Usage: crl2pkcs7" || _contains "$(${ACME_OPENSSL_BIN:-openssl} crl2pkcs7 help 2>&1)" "unknown option help"; then
4176 ${ACME_OPENSSL_BIN:-openssl} crl2pkcs7 -nocrl -certfile $_cfile | ${ACME_OPENSSL_BIN:-openssl} pkcs7 -print_certs -text -noout | grep -i 'Subject:' | _egrep_o "CN *=[^,]*" | cut -d = -f 2
4177 else
4178 _cindex=1
4179 for _startn in $(grep -n -- "$BEGIN_CERT" "$_cfile" | cut -d : -f 1); do
4180 _endn="$(grep -n -- "$END_CERT" "$_cfile" | cut -d : -f 1 | _head_n $_cindex | _tail_n 1)"
4181 _debug2 "_startn" "$_startn"
4182 _debug2 "_endn" "$_endn"
4183 if [ "$DEBUG" ]; then
4184 _debug2 "cert$_cindex" "$(sed -n "$_startn,${_endn}p" "$_cfile")"
4185 fi
4186 sed -n "$_startn,${_endn}p" "$_cfile" | ${ACME_OPENSSL_BIN:-openssl} x509 -text -noout | grep -i 'Subject:' | _egrep_o "CN *=[^,]*" | cut -d = -f 2 | sed "s/ *\(.*\)/\1/"
4187 _cindex=$(_math $_cindex + 1)
4188 done
4189 fi
4190 }
4191
4192 #cert issuer
4193 _match_issuer() {
4194 _cfile="$1"
4195 _missuer="$2"
4196 _fissuers="$(_get_chain_issuers $_cfile)"
4197 _debug2 _fissuers "$_fissuers"
4198 _rootissuer="$(echo "$_fissuers" | _lower_case | _tail_n 1)"
4199 _debug2 _rootissuer "$_rootissuer"
4200 _missuer="$(echo "$_missuer" | _lower_case)"
4201 _contains "$_rootissuer" "$_missuer"
4202 }
4203
4204 #ip
4205 _isIPv4() {
4206 for seg in $(echo "$1" | tr '.' ' '); do
4207 _debug2 seg "$seg"
4208 if [ "$(echo "$seg" | tr -d [0-9])" ]; then
4209 #not all number
4210 return 1
4211 fi
4212 if [ $seg -ge 0 ] && [ $seg -lt 256 ]; then
4213 continue
4214 fi
4215 return 1
4216 done
4217 return 0
4218 }
4219
4220 #ip6
4221 _isIPv6() {
4222 _contains "$1" ":"
4223 }
4224
4225 #ip
4226 _isIP() {
4227 _isIPv4 "$1" || _isIPv6 "$1"
4228 }
4229
4230 #identifier
4231 _getIdType() {
4232 if _isIP "$1"; then
4233 echo "$ID_TYPE_IP"
4234 else
4235 echo "$ID_TYPE_DNS"
4236 fi
4237 }
4238
4239 # beginTime dateTo
4240 # beginTime is full string format("2022-04-01T08:10:33Z"), beginTime can be empty, to use current time
4241 # dateTo can be ether in full string format("2022-04-01T08:10:33Z") or in delta format(+5d or +20h)
4242 _convertValidaty() {
4243 _beginTime="$1"
4244 _dateTo="$2"
4245 _debug2 "_beginTime" "$_beginTime"
4246 _debug2 "_dateTo" "$_dateTo"
4247
4248 if _startswith "$_dateTo" "+"; then
4249 _v_begin=$(_time)
4250 if [ "$_beginTime" ]; then
4251 _v_begin="$(_date2time "$_beginTime")"
4252 fi
4253 _debug2 "_v_begin" "$_v_begin"
4254 if _endswith "$_dateTo" "h"; then
4255 _v_end=$(_math "$_v_begin + 60 * 60 * $(echo "$_dateTo" | tr -d '+h')")
4256 elif _endswith "$_dateTo" "d"; then
4257 _v_end=$(_math "$_v_begin + 60 * 60 * 24 * $(echo "$_dateTo" | tr -d '+d')")
4258 else
4259 _err "Not recognized format for _dateTo: $_dateTo"
4260 return 1
4261 fi
4262 _debug2 "_v_end" "$_v_end"
4263 _time2str "$_v_end"
4264 else
4265 if [ "$(_time)" -gt "$(_date2time "$_dateTo")" ]; then
4266 _err "The validaty to is in the past: _dateTo = $_dateTo"
4267 return 1
4268 fi
4269 echo "$_dateTo"
4270 fi
4271 }
4272
4273 #webroot, domain domainlist keylength
4274 issue() {
4275 if [ -z "$2" ]; then
4276 _usage "Usage: $PROJECT_ENTRY --issue --domain <domain.tld> --webroot <directory>"
4277 return 1
4278 fi
4279 if [ -z "$1" ]; then
4280 _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
4281 return 1
4282 fi
4283 _web_roots="$1"
4284 _main_domain="$2"
4285 _alt_domains="$3"
4286
4287 if _contains "$_main_domain" ","; then
4288 _main_domain=$(echo "$2,$3" | cut -d , -f 1)
4289 _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
4290 fi
4291 _debug _main_domain "$_main_domain"
4292 _debug _alt_domains "$_alt_domains"
4293
4294 _key_length="$4"
4295 _real_cert="$5"
4296 _real_key="$6"
4297 _real_ca="$7"
4298 _reload_cmd="$8"
4299 _real_fullchain="$9"
4300 _pre_hook="${10}"
4301 _post_hook="${11}"
4302 _renew_hook="${12}"
4303 _local_addr="${13}"
4304 _challenge_alias="${14}"
4305 _preferred_chain="${15}"
4306 _valid_from="${16}"
4307 _valid_to="${17}"
4308
4309 if [ -z "$_ACME_IS_RENEW" ]; then
4310 _initpath "$_main_domain" "$_key_length"
4311 mkdir -p "$DOMAIN_PATH"
4312 elif ! _hasfield "$_web_roots" "$W_DNS"; then
4313 Le_OrderFinalize=""
4314 Le_LinkOrder=""
4315 Le_LinkCert=""
4316 fi
4317
4318 if _hasfield "$_web_roots" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
4319 _err "$_DNS_MANUAL_ERROR"
4320 return 1
4321 fi
4322
4323 if [ -f "$DOMAIN_CONF" ]; then
4324 Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
4325 _debug Le_NextRenewTime "$Le_NextRenewTime"
4326 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
4327 _valid_to_saved=$(_readdomainconf Le_Valid_to)
4328 if [ "$_valid_to_saved" ] && ! _startswith "$_valid_to_saved" "+"; then
4329 _info "The domain is set to be valid to: $_valid_to_saved"
4330 _info "It can not be renewed automatically"
4331 _info "See: $_VALIDITY_WIKI"
4332 return $RENEW_SKIP
4333 fi
4334 _saved_domain=$(_readdomainconf Le_Domain)
4335 _debug _saved_domain "$_saved_domain"
4336 _saved_alt=$(_readdomainconf Le_Alt)
4337 _debug _saved_alt "$_saved_alt"
4338 _normized_saved_domains="$(echo "$_saved_domain,$_saved_alt" | tr "," "\n" | sort | tr '\n' ',')"
4339 _debug _normized_saved_domains "$_normized_saved_domains"
4340
4341 _normized_domains="$(echo "$_main_domain,$_alt_domains" | tr "," "\n" | sort | tr '\n' ',')"
4342 _debug _normized_domains "$_normized_domains"
4343
4344 if [ "$_normized_saved_domains" = "$_normized_domains" ]; then
4345 _info "Domains not changed."
4346 _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
4347 _info "Add '$(__red '--force')' to force to renew."
4348 return $RENEW_SKIP
4349 else
4350 _info "Domains have changed."
4351 fi
4352 fi
4353 fi
4354
4355 _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
4356 if ! _initAPI; then
4357 return 1
4358 fi
4359
4360 _savedomainconf "Le_Domain" "$_main_domain"
4361 _savedomainconf "Le_Alt" "$_alt_domains"
4362 _savedomainconf "Le_Webroot" "$_web_roots"
4363
4364 _savedomainconf "Le_PreHook" "$_pre_hook" "base64"
4365 _savedomainconf "Le_PostHook" "$_post_hook" "base64"
4366 _savedomainconf "Le_RenewHook" "$_renew_hook" "base64"
4367
4368 if [ "$_local_addr" ]; then
4369 _savedomainconf "Le_LocalAddress" "$_local_addr"
4370 else
4371 _cleardomainconf "Le_LocalAddress"
4372 fi
4373 if [ "$_challenge_alias" ]; then
4374 _savedomainconf "Le_ChallengeAlias" "$_challenge_alias"
4375 else
4376 _cleardomainconf "Le_ChallengeAlias"
4377 fi
4378 if [ "$_preferred_chain" ]; then
4379 _savedomainconf "Le_Preferred_Chain" "$_preferred_chain" "base64"
4380 else
4381 _cleardomainconf "Le_Preferred_Chain"
4382 fi
4383
4384 Le_API="$ACME_DIRECTORY"
4385 _savedomainconf "Le_API" "$Le_API"
4386
4387 _info "Using CA: $ACME_DIRECTORY"
4388 if [ "$_alt_domains" = "$NO_VALUE" ]; then
4389 _alt_domains=""
4390 fi
4391
4392 if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
4393 _err "_on_before_issue."
4394 return 1
4395 fi
4396
4397 _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
4398 _debug2 _saved_account_key_hash "$_saved_account_key_hash"
4399
4400 if [ -z "$ACCOUNT_URL" ] || [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
4401 if ! _regAccount "$_accountkeylength"; then
4402 _on_issue_err "$_post_hook"
4403 return 1
4404 fi
4405 else
4406 _debug "_saved_account_key_hash is not changed, skip register account."
4407 fi
4408
4409 if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
4410 _info "Signing from existing CSR."
4411 else
4412 # When renewing from an old version, the empty Le_Keylength means 2048.
4413 # Note, do not use DEFAULT_DOMAIN_KEY_LENGTH as that value may change over
4414 # time but an empty value implies 2048 specifically.
4415 _key=$(_readdomainconf Le_Keylength)
4416 if [ -z "$_key" ]; then
4417 _key=2048
4418 fi
4419 _debug "Read key length:$_key"
4420 if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
4421 if ! createDomainKey "$_main_domain" "$_key_length"; then
4422 _err "Create domain key error."
4423 _clearup
4424 _on_issue_err "$_post_hook"
4425 return 1
4426 fi
4427 fi
4428
4429 if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
4430 _err "Create CSR error."
4431 _clearup
4432 _on_issue_err "$_post_hook"
4433 return 1
4434 fi
4435 fi
4436
4437 _savedomainconf "Le_Keylength" "$_key_length"
4438
4439 vlist="$Le_Vlist"
4440 _cleardomainconf "Le_Vlist"
4441 _info "Getting domain auth token for each domain"
4442 sep='#'
4443 dvsep=','
4444 if [ -z "$vlist" ]; then
4445 #make new order request
4446 _identifiers="{\"type\":\"$(_getIdType "$_main_domain")\",\"value\":\"$(_idn "$_main_domain")\"}"
4447 _w_index=1
4448 while true; do
4449 d="$(echo "$_alt_domains," | cut -d , -f "$_w_index")"
4450 _w_index="$(_math "$_w_index" + 1)"
4451 _debug d "$d"
4452 if [ -z "$d" ]; then
4453 break
4454 fi
4455 _identifiers="$_identifiers,{\"type\":\"$(_getIdType "$d")\",\"value\":\"$(_idn "$d")\"}"
4456 done
4457 _debug2 _identifiers "$_identifiers"
4458 _notBefore=""
4459 _notAfter=""
4460
4461 if [ "$_valid_from" ]; then
4462 _savedomainconf "Le_Valid_From" "$_valid_from"
4463 _debug2 "_valid_from" "$_valid_from"
4464 _notBefore="$(_convertValidaty "" "$_valid_from")"
4465 if [ "$?" != "0" ]; then
4466 _err "Can not parse _valid_from: $_valid_from"
4467 return 1
4468 fi
4469 if [ "$(_time)" -gt "$(_date2time "$_notBefore")" ]; then
4470 _notBefore=""
4471 fi
4472 else
4473 _cleardomainconf "Le_Valid_From"
4474 fi
4475 _debug2 _notBefore "$_notBefore"
4476
4477 if [ "$_valid_to" ]; then
4478 _debug2 "_valid_to" "$_valid_to"
4479 _savedomainconf "Le_Valid_To" "$_valid_to"
4480 _notAfter="$(_convertValidaty "$_notBefore" "$_valid_to")"
4481 if [ "$?" != "0" ]; then
4482 _err "Can not parse _valid_to: $_valid_to"
4483 return 1
4484 fi
4485 else
4486 _cleardomainconf "Le_Valid_To"
4487 fi
4488 _debug2 "_notAfter" "$_notAfter"
4489
4490 _newOrderObj="{\"identifiers\": [$_identifiers]"
4491 if [ "$_notBefore" ]; then
4492 _newOrderObj="$_newOrderObj,\"notBefore\": \"$_notBefore\""
4493 fi
4494 if [ "$_notAfter" ]; then
4495 _newOrderObj="$_newOrderObj,\"notAfter\": \"$_notAfter\""
4496 fi
4497 if ! _send_signed_request "$ACME_NEW_ORDER" "$_newOrderObj}"; then
4498 _err "Create new order error."
4499 _clearup
4500 _on_issue_err "$_post_hook"
4501 return 1
4502 fi
4503
4504 Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n " | cut -d ":" -f 2-)"
4505 _debug Le_LinkOrder "$Le_LinkOrder"
4506 Le_OrderFinalize="$(echo "$response" | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
4507 _debug Le_OrderFinalize "$Le_OrderFinalize"
4508 if [ -z "$Le_OrderFinalize" ]; then
4509 _err "Create new order error. Le_OrderFinalize not found. $response"
4510 _clearup
4511 _on_issue_err "$_post_hook"
4512 return 1
4513 fi
4514
4515 #for dns manual mode
4516 _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
4517
4518 _authorizations_seg="$(echo "$response" | _json_decode | _egrep_o '"authorizations" *: *\[[^\[]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
4519 _debug2 _authorizations_seg "$_authorizations_seg"
4520 if [ -z "$_authorizations_seg" ]; then
4521 _err "_authorizations_seg not found."
4522 _clearup
4523 _on_issue_err "$_post_hook"
4524 return 1
4525 fi
4526
4527 #domain and authz map
4528 _authorizations_map=""
4529 for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
4530 _debug2 "_authz_url" "$_authz_url"
4531 if ! _send_signed_request "$_authz_url"; then
4532 _err "get to authz error."
4533 _err "_authorizations_seg" "$_authorizations_seg"
4534 _err "_authz_url" "$_authz_url"
4535 _clearup
4536 _on_issue_err "$_post_hook"
4537 return 1
4538 fi
4539
4540 response="$(echo "$response" | _normalizeJson)"
4541 _debug2 response "$response"
4542 _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2- | tr -d ' "')"
4543 if _contains "$response" "\"wildcard\" *: *true"; then
4544 _d="*.$_d"
4545 fi
4546 _debug2 _d "$_d"
4547 _authorizations_map="$_d,$response
4548 $_authorizations_map"
4549 done
4550 _debug2 _authorizations_map "$_authorizations_map"
4551
4552 _index=0
4553 _currentRoot=""
4554 _w_index=1
4555 while true; do
4556 d="$(echo "$_main_domain,$_alt_domains," | cut -d , -f "$_w_index")"
4557 _w_index="$(_math "$_w_index" + 1)"
4558 _debug d "$d"
4559 if [ -z "$d" ]; then
4560 break
4561 fi
4562 _info "Getting webroot for domain" "$d"
4563 _index=$(_math $_index + 1)
4564 _w="$(echo $_web_roots | cut -d , -f $_index)"
4565 _debug _w "$_w"
4566 if [ "$_w" ]; then
4567 _currentRoot="$_w"
4568 fi
4569 _debug "_currentRoot" "$_currentRoot"
4570
4571 vtype="$VTYPE_HTTP"
4572 #todo, v2 wildcard force to use dns
4573 if _startswith "$_currentRoot" "$W_DNS"; then
4574 vtype="$VTYPE_DNS"
4575 fi
4576
4577 if [ "$_currentRoot" = "$W_ALPN" ]; then
4578 vtype="$VTYPE_ALPN"
4579 fi
4580
4581 _idn_d="$(_idn "$d")"
4582 _candidates="$(echo "$_authorizations_map" | grep -i "^$_idn_d,")"
4583 _debug2 _candidates "$_candidates"
4584 if [ "$(echo "$_candidates" | wc -l)" -gt 1 ]; then
4585 for _can in $_candidates; do
4586 if _startswith "$(echo "$_can" | tr '.' '|')" "$(echo "$_idn_d" | tr '.' '|'),"; then
4587 _candidates="$_can"
4588 break
4589 fi
4590 done
4591 fi
4592 response="$(echo "$_candidates" | sed "s/$_idn_d,//")"
4593 _debug2 "response" "$response"
4594 if [ -z "$response" ]; then
4595 _err "get to authz error."
4596 _err "_authorizations_map" "$_authorizations_map"
4597 _clearup
4598 _on_issue_err "$_post_hook"
4599 return 1
4600 fi
4601
4602 if [ -z "$thumbprint" ]; then
4603 thumbprint="$(__calc_account_thumbprint)"
4604 fi
4605
4606 entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
4607 _debug entry "$entry"
4608 keyauthorization=""
4609 if [ -z "$entry" ]; then
4610 if ! _startswith "$d" '*.'; then
4611 _debug "Not a wildcard domain, lets check whether the validation is already valid."
4612 if echo "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
4613 _debug "$d is already valid."
4614 keyauthorization="$STATE_VERIFIED"
4615 _debug keyauthorization "$keyauthorization"
4616 fi
4617 fi
4618 if [ -z "$keyauthorization" ]; then
4619 _err "Error, can not get domain token entry $d for $vtype"
4620 _supported_vtypes="$(echo "$response" | _egrep_o "\"challenges\":\[[^]]*]" | tr '{' "\n" | grep type | cut -d '"' -f 4 | tr "\n" ' ')"
4621 if [ "$_supported_vtypes" ]; then
4622 _err "The supported validation types are: $_supported_vtypes, but you specified: $vtype"
4623 fi
4624 _clearup
4625 _on_issue_err "$_post_hook"
4626 return 1
4627 fi
4628 fi
4629
4630 if [ -z "$keyauthorization" ]; then
4631 token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
4632 _debug token "$token"
4633
4634 if [ -z "$token" ]; then
4635 _err "Error, can not get domain token $entry"
4636 _clearup
4637 _on_issue_err "$_post_hook"
4638 return 1
4639 fi
4640
4641 uri="$(echo "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
4642
4643 _debug uri "$uri"
4644
4645 if [ -z "$uri" ]; then
4646 _err "Error, can not get domain uri. $entry"
4647 _clearup
4648 _on_issue_err "$_post_hook"
4649 return 1
4650 fi
4651 keyauthorization="$token.$thumbprint"
4652 _debug keyauthorization "$keyauthorization"
4653
4654 if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
4655 _debug "$d is already verified."
4656 keyauthorization="$STATE_VERIFIED"
4657 _debug keyauthorization "$keyauthorization"
4658 fi
4659 fi
4660
4661 dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
4662 _debug dvlist "$dvlist"
4663
4664 vlist="$vlist$dvlist$dvsep"
4665
4666 done
4667 _debug vlist "$vlist"
4668 #add entry
4669 dns_entries=""
4670 dnsadded=""
4671 ventries=$(echo "$vlist" | tr "$dvsep" ' ')
4672 _alias_index=1
4673 for ventry in $ventries; do
4674 d=$(echo "$ventry" | cut -d "$sep" -f 1)
4675 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
4676 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
4677 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
4678 _debug d "$d"
4679 if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
4680 _debug "$d is already verified, skip $vtype."
4681 _alias_index="$(_math "$_alias_index" + 1)"
4682 continue
4683 fi
4684
4685 if [ "$vtype" = "$VTYPE_DNS" ]; then
4686 dnsadded='0'
4687 _dns_root_d="$d"
4688 if _startswith "$_dns_root_d" "*."; then
4689 _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
4690 fi
4691 _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
4692 test "$_d_alias" = "$NO_VALUE" && _d_alias=""
4693 _alias_index="$(_math "$_alias_index" + 1)"
4694 _debug "_d_alias" "$_d_alias"
4695 if [ "$_d_alias" ]; then
4696 if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
4697 txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
4698 else
4699 txtdomain="_acme-challenge.$_d_alias"
4700 fi
4701 dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$txtdomain$dvsep$_currentRoot"
4702 else
4703 txtdomain="_acme-challenge.$_dns_root_d"
4704 dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$dvsep$_currentRoot"
4705 fi
4706
4707 _debug txtdomain "$txtdomain"
4708 txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
4709 _debug txt "$txt"
4710
4711 d_api="$(_findHook "$_dns_root_d" $_SUB_FOLDER_DNSAPI "$_currentRoot")"
4712 _debug d_api "$d_api"
4713
4714 dns_entry="$dns_entry$dvsep$txt${dvsep}$d_api"
4715 _debug2 dns_entry "$dns_entry"
4716 if [ "$d_api" ]; then
4717 _debug "Found domain api file: $d_api"
4718 else
4719 if [ "$_currentRoot" != "$W_DNS" ]; then
4720 _err "Can not find dns api hook for: $_currentRoot"
4721 _info "You need to add the txt record manually."
4722 fi
4723 _info "$(__red "Add the following TXT record:")"
4724 _info "$(__red "Domain: '$(__green "$txtdomain")'")"
4725 _info "$(__red "TXT value: '$(__green "$txt")'")"
4726 _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
4727 _info "$(__red "so the resulting subdomain will be: $txtdomain")"
4728 continue
4729 fi
4730
4731 (
4732 if ! . "$d_api"; then
4733 _err "Load file $d_api error. Please check your api file and try again."
4734 return 1
4735 fi
4736
4737 addcommand="${_currentRoot}_add"
4738 if ! _exists "$addcommand"; then
4739 _err "It seems that your api file is not correct, it must have a function named: $addcommand"
4740 return 1
4741 fi
4742 _info "Adding txt value: $txt for domain: $txtdomain"
4743 if ! $addcommand "$txtdomain" "$txt"; then
4744 _err "Error add txt for domain:$txtdomain"
4745 return 1
4746 fi
4747 _info "The txt record is added: Success."
4748 )
4749
4750 if [ "$?" != "0" ]; then
4751 _on_issue_err "$_post_hook" "$vlist"
4752 _clearup
4753 return 1
4754 fi
4755 dns_entries="$dns_entries$dns_entry
4756 "
4757 _debug2 "$dns_entries"
4758 dnsadded='1'
4759 fi
4760 done
4761
4762 if [ "$dnsadded" = '0' ]; then
4763 _savedomainconf "Le_Vlist" "$vlist"
4764 _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
4765 _err "Please add the TXT records to the domains, and re-run with --renew."
4766 _on_issue_err "$_post_hook"
4767 _clearup
4768 # If asked to be in manual DNS mode, flag this exit with a separate
4769 # error so it can be distinguished from other failures.
4770 return $CODE_DNS_MANUAL
4771 fi
4772
4773 fi
4774
4775 if [ "$dns_entries" ]; then
4776 if [ -z "$Le_DNSSleep" ]; then
4777 _info "Let's check each DNS record now. Sleep 20 seconds first."
4778 _sleep 20
4779 if ! _check_dns_entries; then
4780 _err "check dns error."
4781 _on_issue_err "$_post_hook"
4782 _clearup
4783 return 1
4784 fi
4785 else
4786 _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
4787 _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
4788 _sleep "$Le_DNSSleep"
4789 fi
4790 fi
4791
4792 NGINX_RESTORE_VLIST=""
4793 _debug "ok, let's start to verify"
4794
4795 _ncIndex=1
4796 ventries=$(echo "$vlist" | tr "$dvsep" ' ')
4797 for ventry in $ventries; do
4798 d=$(echo "$ventry" | cut -d "$sep" -f 1)
4799 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
4800 uri=$(echo "$ventry" | cut -d "$sep" -f 3)
4801 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
4802 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
4803
4804 if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
4805 _info "$d is already verified, skip $vtype."
4806 continue
4807 fi
4808
4809 _info "Verifying: $d"
4810 _debug "d" "$d"
4811 _debug "keyauthorization" "$keyauthorization"
4812 _debug "uri" "$uri"
4813 removelevel=""
4814 token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
4815
4816 _debug "_currentRoot" "$_currentRoot"
4817
4818 if [ "$vtype" = "$VTYPE_HTTP" ]; then
4819 if [ "$_currentRoot" = "$NO_VALUE" ]; then
4820 _info "Standalone mode server"
4821 _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
4822 _ncIndex="$(_math $_ncIndex + 1)"
4823 _startserver "$keyauthorization" "$_ncaddr"
4824 if [ "$?" != "0" ]; then
4825 _clearup
4826 _on_issue_err "$_post_hook" "$vlist"
4827 return 1
4828 fi
4829 sleep 1
4830 _debug serverproc "$serverproc"
4831 elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
4832 _info "Stateless mode for domain:$d"
4833 _sleep 1
4834 elif _startswith "$_currentRoot" "$NGINX"; then
4835 _info "Nginx mode for domain:$d"
4836 #set up nginx server
4837 FOUND_REAL_NGINX_CONF=""
4838 BACKUP_NGINX_CONF=""
4839 if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
4840 _clearup
4841 _on_issue_err "$_post_hook" "$vlist"
4842 return 1
4843 fi
4844
4845 if [ "$FOUND_REAL_NGINX_CONF" ]; then
4846 _realConf="$FOUND_REAL_NGINX_CONF"
4847 _backup="$BACKUP_NGINX_CONF"
4848 _debug _realConf "$_realConf"
4849 NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
4850 fi
4851 _sleep 1
4852 else
4853 if [ "$_currentRoot" = "apache" ]; then
4854 wellknown_path="$ACME_DIR"
4855 else
4856 wellknown_path="$_currentRoot/.well-known/acme-challenge"
4857 if [ ! -d "$_currentRoot/.well-known" ]; then
4858 removelevel='1'
4859 elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
4860 removelevel='2'
4861 else
4862 removelevel='3'
4863 fi
4864 fi
4865
4866 _debug wellknown_path "$wellknown_path"
4867
4868 _debug "writing token:$token to $wellknown_path/$token"
4869
4870 mkdir -p "$wellknown_path"
4871
4872 if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
4873 _err "$d:Can not write token to file : $wellknown_path/$token"
4874 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4875 _clearup
4876 _on_issue_err "$_post_hook" "$vlist"
4877 return 1
4878 fi
4879
4880 if [ ! "$usingApache" ]; then
4881 if webroot_owner=$(_stat "$_currentRoot"); then
4882 _debug "Changing owner/group of .well-known to $webroot_owner"
4883 if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
4884 _debug "$(cat "$_EXEC_TEMP_ERR")"
4885 _exec_err >/dev/null 2>&1
4886 fi
4887 else
4888 _debug "not changing owner/group of webroot"
4889 fi
4890 fi
4891
4892 fi
4893 elif [ "$vtype" = "$VTYPE_ALPN" ]; then
4894 acmevalidationv1="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
4895 _debug acmevalidationv1 "$acmevalidationv1"
4896 if ! _starttlsserver "$d" "" "$Le_TLSPort" "$keyauthorization" "$_ncaddr" "$acmevalidationv1"; then
4897 _err "Start tls server error."
4898 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4899 _clearup
4900 _on_issue_err "$_post_hook" "$vlist"
4901 return 1
4902 fi
4903 fi
4904
4905 if ! __trigger_validation "$uri" "$keyauthorization" "$vtype"; then
4906 _err "$d:Can not get challenge: $response"
4907 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4908 _clearup
4909 _on_issue_err "$_post_hook" "$vlist"
4910 return 1
4911 fi
4912
4913 if [ "$code" ] && [ "$code" != '202' ]; then
4914 if [ "$code" = '200' ]; then
4915 _debug "trigger validation code: $code"
4916 else
4917 _err "$d:Challenge error: $response"
4918 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4919 _clearup
4920 _on_issue_err "$_post_hook" "$vlist"
4921 return 1
4922 fi
4923 fi
4924
4925 waittimes=0
4926 if [ -z "$MAX_RETRY_TIMES" ]; then
4927 MAX_RETRY_TIMES=30
4928 fi
4929
4930 while true; do
4931 waittimes=$(_math "$waittimes" + 1)
4932 if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
4933 _err "$d:Timeout"
4934 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4935 _clearup
4936 _on_issue_err "$_post_hook" "$vlist"
4937 return 1
4938 fi
4939
4940 _debug2 original "$response"
4941
4942 response="$(echo "$response" | _normalizeJson)"
4943 _debug2 response "$response"
4944
4945 status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
4946 _debug2 status "$status"
4947 if _contains "$status" "invalid"; then
4948 error="$(echo "$response" | _egrep_o '"error":\{[^\}]*')"
4949 _debug2 error "$error"
4950 errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
4951 _debug2 errordetail "$errordetail"
4952 if [ "$errordetail" ]; then
4953 _err "$d:Verify error:$errordetail"
4954 else
4955 _err "$d:Verify error:$error"
4956 fi
4957 if [ "$DEBUG" ]; then
4958 if [ "$vtype" = "$VTYPE_HTTP" ]; then
4959 _debug "Debug: get token url."
4960 _get "http://$d/.well-known/acme-challenge/$token" "" 1
4961 fi
4962 fi
4963 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4964 _clearup
4965 _on_issue_err "$_post_hook" "$vlist"
4966 return 1
4967 fi
4968
4969 if _contains "$status" "valid"; then
4970 _info "$(__green Success)"
4971 _stopserver "$serverproc"
4972 serverproc=""
4973 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4974 break
4975 fi
4976
4977 if [ "$status" = "pending" ]; then
4978 _info "Pending, The CA is processing your order, please just wait. ($waittimes/$MAX_RETRY_TIMES)"
4979 elif [ "$status" = "processing" ]; then
4980 _info "Processing, The CA is processing your order, please just wait. ($waittimes/$MAX_RETRY_TIMES)"
4981 else
4982 _err "$d:Verify error:$response"
4983 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4984 _clearup
4985 _on_issue_err "$_post_hook" "$vlist"
4986 return 1
4987 fi
4988 _debug "sleep 2 secs to verify again"
4989 _sleep 2
4990 _debug "checking"
4991
4992 _send_signed_request "$uri"
4993
4994 if [ "$?" != "0" ]; then
4995 _err "$d:Verify error:$response"
4996 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4997 _clearup
4998 _on_issue_err "$_post_hook" "$vlist"
4999 return 1
5000 fi
5001 done
5002
5003 done
5004
5005 _clearup
5006 _info "Verify finished, start to sign."
5007 der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
5008
5009 _info "Lets finalize the order."
5010 _info "Le_OrderFinalize" "$Le_OrderFinalize"
5011 if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
5012 _err "Sign failed."
5013 _on_issue_err "$_post_hook"
5014 return 1
5015 fi
5016 if [ "$code" != "200" ]; then
5017 _err "Sign failed, finalize code is not 200."
5018 _err "$response"
5019 _on_issue_err "$_post_hook"
5020 return 1
5021 fi
5022 if [ -z "$Le_LinkOrder" ]; then
5023 Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n \t" | cut -d ":" -f 2-)"
5024 fi
5025
5026 _savedomainconf "Le_LinkOrder" "$Le_LinkOrder"
5027
5028 _link_cert_retry=0
5029 _MAX_CERT_RETRY=30
5030 while [ "$_link_cert_retry" -lt "$_MAX_CERT_RETRY" ]; do
5031 if _contains "$response" "\"status\":\"valid\""; then
5032 _debug "Order status is valid."
5033 Le_LinkCert="$(echo "$response" | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
5034 _debug Le_LinkCert "$Le_LinkCert"
5035 if [ -z "$Le_LinkCert" ]; then
5036 _err "Sign error, can not find Le_LinkCert"
5037 _err "$response"
5038 _on_issue_err "$_post_hook"
5039 return 1
5040 fi
5041 break
5042 elif _contains "$response" "\"processing\""; then
5043 _info "Order status is processing, lets sleep and retry."
5044 _retryafter=$(echo "$responseHeaders" | grep -i "^Retry-After *:" | cut -d : -f 2 | tr -d ' ' | tr -d '\r')
5045 _debug "_retryafter" "$_retryafter"
5046 if [ "$_retryafter" ]; then
5047 _info "Retry after: $_retryafter"
5048 _sleep $_retryafter
5049 else
5050 _sleep 2
5051 fi
5052 else
5053 _err "Sign error, wrong status"
5054 _err "$response"
5055 _on_issue_err "$_post_hook"
5056 return 1
5057 fi
5058 #the order is processing, so we are going to poll order status
5059 if [ -z "$Le_LinkOrder" ]; then
5060 _err "Sign error, can not get order link location header"
5061 _err "responseHeaders" "$responseHeaders"
5062 _on_issue_err "$_post_hook"
5063 return 1
5064 fi
5065 _info "Polling order status: $Le_LinkOrder"
5066 if ! _send_signed_request "$Le_LinkOrder"; then
5067 _err "Sign failed, can not post to Le_LinkOrder cert:$Le_LinkOrder."
5068 _err "$response"
5069 _on_issue_err "$_post_hook"
5070 return 1
5071 fi
5072 _link_cert_retry="$(_math $_link_cert_retry + 1)"
5073 done
5074
5075 if [ -z "$Le_LinkCert" ]; then
5076 _err "Sign failed, can not get Le_LinkCert, retry time limit."
5077 _err "$response"
5078 _on_issue_err "$_post_hook"
5079 return 1
5080 fi
5081 _info "Downloading cert."
5082 _info "Le_LinkCert" "$Le_LinkCert"
5083 if ! _send_signed_request "$Le_LinkCert"; then
5084 _err "Sign failed, can not download cert:$Le_LinkCert."
5085 _err "$response"
5086 _on_issue_err "$_post_hook"
5087 return 1
5088 fi
5089
5090 echo "$response" >"$CERT_PATH"
5091 _split_cert_chain "$CERT_PATH" "$CERT_FULLCHAIN_PATH" "$CA_CERT_PATH"
5092 if [ -z "$_preferred_chain" ]; then
5093 _preferred_chain=$(_readcaconf DEFAULT_PREFERRED_CHAIN)
5094 fi
5095 if [ "$_preferred_chain" ] && [ -f "$CERT_FULLCHAIN_PATH" ]; then
5096 if [ "$DEBUG" ]; then
5097 _debug "default chain issuers: " "$(_get_chain_issuers "$CERT_FULLCHAIN_PATH")"
5098 fi
5099 if ! _match_issuer "$CERT_FULLCHAIN_PATH" "$_preferred_chain"; then
5100 rels="$(echo "$responseHeaders" | tr -d ' <>' | grep -i "^link:" | grep -i 'rel="alternate"' | cut -d : -f 2- | cut -d ';' -f 1)"
5101 _debug2 "rels" "$rels"
5102 for rel in $rels; do
5103 _info "Try rel: $rel"
5104 if ! _send_signed_request "$rel"; then
5105 _err "Sign failed, can not download cert:$rel"
5106 _err "$response"
5107 continue
5108 fi
5109 _relcert="$CERT_PATH.alt"
5110 _relfullchain="$CERT_FULLCHAIN_PATH.alt"
5111 _relca="$CA_CERT_PATH.alt"
5112 echo "$response" >"$_relcert"
5113 _split_cert_chain "$_relcert" "$_relfullchain" "$_relca"
5114 if [ "$DEBUG" ]; then
5115 _debug "rel chain issuers: " "$(_get_chain_issuers "$_relfullchain")"
5116 fi
5117 if _match_issuer "$_relfullchain" "$_preferred_chain"; then
5118 _info "Matched issuer in: $rel"
5119 cat $_relcert >"$CERT_PATH"
5120 cat $_relfullchain >"$CERT_FULLCHAIN_PATH"
5121 cat $_relca >"$CA_CERT_PATH"
5122 rm -f "$_relcert"
5123 rm -f "$_relfullchain"
5124 rm -f "$_relca"
5125 break
5126 fi
5127 rm -f "$_relcert"
5128 rm -f "$_relfullchain"
5129 rm -f "$_relca"
5130 done
5131 fi
5132 fi
5133
5134 _debug "Le_LinkCert" "$Le_LinkCert"
5135 _savedomainconf "Le_LinkCert" "$Le_LinkCert"
5136
5137 if [ -z "$Le_LinkCert" ] || ! _checkcert "$CERT_PATH"; then
5138 response="$(echo "$response" | _dbase64 "multiline" | tr -d '\0' | _normalizeJson)"
5139 _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
5140 _on_issue_err "$_post_hook"
5141 return 1
5142 fi
5143
5144 if [ "$Le_LinkCert" ]; then
5145 _info "$(__green "Cert success.")"
5146 cat "$CERT_PATH"
5147
5148 _info "Your cert is in: $(__green "$CERT_PATH")"
5149
5150 if [ -f "$CERT_KEY_PATH" ]; then
5151 _info "Your cert key is in: $(__green "$CERT_KEY_PATH")"
5152 fi
5153
5154 if [ ! "$USER_PATH" ] || [ ! "$_ACME_IN_CRON" ]; then
5155 USER_PATH="$PATH"
5156 _saveaccountconf "USER_PATH" "$USER_PATH"
5157 fi
5158 fi
5159
5160 [ -f "$CA_CERT_PATH" ] && _info "The intermediate CA cert is in: $(__green "$CA_CERT_PATH")"
5161 [ -f "$CERT_FULLCHAIN_PATH" ] && _info "And the full chain certs is there: $(__green "$CERT_FULLCHAIN_PATH")"
5162
5163 Le_CertCreateTime=$(_time)
5164 _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
5165
5166 Le_CertCreateTimeStr=$(_time2str "$Le_CertCreateTime")
5167 _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
5168
5169 if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ]; then
5170 Le_RenewalDays="$DEFAULT_RENEW"
5171 else
5172 _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
5173 fi
5174
5175 if [ "$CA_BUNDLE" ]; then
5176 _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
5177 else
5178 _clearaccountconf "CA_BUNDLE"
5179 fi
5180
5181 if [ "$CA_PATH" ]; then
5182 _saveaccountconf CA_PATH "$CA_PATH"
5183 else
5184 _clearaccountconf "CA_PATH"
5185 fi
5186
5187 if [ "$HTTPS_INSECURE" ]; then
5188 _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
5189 else
5190 _clearaccountconf "HTTPS_INSECURE"
5191 fi
5192
5193 if [ "$Le_Listen_V4" ]; then
5194 _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
5195 _cleardomainconf Le_Listen_V6
5196 elif [ "$Le_Listen_V6" ]; then
5197 _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
5198 _cleardomainconf Le_Listen_V4
5199 fi
5200
5201 if [ "$Le_ForceNewDomainKey" = "1" ]; then
5202 _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
5203 else
5204 _cleardomainconf Le_ForceNewDomainKey
5205 fi
5206 if [ "$_notAfter" ]; then
5207 Le_NextRenewTime=$(_date2time "$_notAfter")
5208 Le_NextRenewTimeStr="$_notAfter"
5209 if [ "$_valid_to" ] && ! _startswith "$_valid_to" "+"; then
5210 _info "The domain is set to be valid to: $_valid_to"
5211 _info "It can not be renewed automatically"
5212 _info "See: $_VALIDITY_WIKI"
5213 fi
5214 else
5215 Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
5216 Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
5217 Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
5218 fi
5219 _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
5220 _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
5221
5222 if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
5223 _savedomainconf "Le_RealCertPath" "$_real_cert"
5224 _savedomainconf "Le_RealCACertPath" "$_real_ca"
5225 _savedomainconf "Le_RealKeyPath" "$_real_key"
5226 _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
5227 _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
5228 if ! _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"; then
5229 return 1
5230 fi
5231 fi
5232
5233 if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
5234 _err "Call hook error."
5235 return 1
5236 fi
5237 }
5238
5239 #in_out_cert out_fullchain out_ca
5240 _split_cert_chain() {
5241 _certf="$1"
5242 _fullchainf="$2"
5243 _caf="$3"
5244 if [ "$(grep -- "$BEGIN_CERT" "$_certf" | wc -l)" -gt "1" ]; then
5245 _debug "Found cert chain"
5246 cat "$_certf" >"$_fullchainf"
5247 _end_n="$(grep -n -- "$END_CERT" "$_fullchainf" | _head_n 1 | cut -d : -f 1)"
5248 _debug _end_n "$_end_n"
5249 sed -n "1,${_end_n}p" "$_fullchainf" >"$_certf"
5250 _end_n="$(_math $_end_n + 1)"
5251 sed -n "${_end_n},9999p" "$_fullchainf" >"$_caf"
5252 fi
5253 }
5254
5255 #domain [isEcc] [server]
5256 renew() {
5257 Le_Domain="$1"
5258 if [ -z "$Le_Domain" ]; then
5259 _usage "Usage: $PROJECT_ENTRY --renew --domain <domain.tld> [--ecc] [--server server]"
5260 return 1
5261 fi
5262
5263 _isEcc="$2"
5264 _renewServer="$3"
5265 _debug "_renewServer" "$_renewServer"
5266
5267 _initpath "$Le_Domain" "$_isEcc"
5268
5269 _set_level=${NOTIFY_LEVEL:-$NOTIFY_LEVEL_DEFAULT}
5270 _info "$(__green "Renew: '$Le_Domain'")"
5271 if [ ! -f "$DOMAIN_CONF" ]; then
5272 _info "'$Le_Domain' is not an issued domain, skip."
5273 return $RENEW_SKIP
5274 fi
5275
5276 if [ "$Le_RenewalDays" ]; then
5277 _savedomainconf Le_RenewalDays "$Le_RenewalDays"
5278 fi
5279
5280 . "$DOMAIN_CONF"
5281 _debug Le_API "$Le_API"
5282
5283 case "$Le_API" in
5284 "$CA_LETSENCRYPT_V2_TEST")
5285 _info "Switching back to $CA_LETSENCRYPT_V2"
5286 Le_API="$CA_LETSENCRYPT_V2"
5287 ;;
5288 "$CA_BUYPASS_TEST")
5289 _info "Switching back to $CA_BUYPASS"
5290 Le_API="$CA_BUYPASS"
5291 ;;
5292 "$CA_GOOGLE_TEST")
5293 _info "Switching back to $CA_GOOGLE"
5294 Le_API="$CA_GOOGLE"
5295 ;;
5296 esac
5297
5298 if [ "$_server" ]; then
5299 Le_API="$_server"
5300 fi
5301 _info "Renew to Le_API=$Le_API"
5302
5303 _clearAPI
5304 _clearCA
5305 export ACME_DIRECTORY="$Le_API"
5306
5307 #reload ca configs
5308 _debug2 "initpath again."
5309 _initpath "$Le_Domain" "$_isEcc"
5310
5311 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
5312 _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
5313 _info "Add '$(__red '--force')' to force to renew."
5314 if [ -z "$_ACME_IN_RENEWALL" ]; then
5315 if [ $_set_level -ge $NOTIFY_LEVEL_SKIP ]; then
5316 _send_notify "Renew $Le_Domain skipped" "Good, the cert is skipped." "$NOTIFY_HOOK" "$RENEW_SKIP"
5317 fi
5318 fi
5319 return "$RENEW_SKIP"
5320 fi
5321
5322 if [ "$_ACME_IN_CRON" = "1" ] && [ -z "$Le_CertCreateTime" ]; then
5323 _info "Skip invalid cert for: $Le_Domain"
5324 return $RENEW_SKIP
5325 fi
5326
5327 _ACME_IS_RENEW="1"
5328 Le_ReloadCmd="$(_readdomainconf Le_ReloadCmd)"
5329 Le_PreHook="$(_readdomainconf Le_PreHook)"
5330 Le_PostHook="$(_readdomainconf Le_PostHook)"
5331 Le_RenewHook="$(_readdomainconf Le_RenewHook)"
5332 Le_Preferred_Chain="$(_readdomainconf Le_Preferred_Chain)"
5333 # When renewing from an old version, the empty Le_Keylength means 2048.
5334 # Note, do not use DEFAULT_DOMAIN_KEY_LENGTH as that value may change over
5335 # time but an empty value implies 2048 specifically.
5336 Le_Keylength="$(_readdomainconf Le_Keylength)"
5337 if [ -z "$Le_Keylength" ]; then
5338 Le_Keylength=2048
5339 fi
5340 issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress" "$Le_ChallengeAlias" "$Le_Preferred_Chain" "$Le_Valid_From" "$Le_Valid_To"
5341 res="$?"
5342 if [ "$res" != "0" ]; then
5343 return "$res"
5344 fi
5345
5346 if [ "$Le_DeployHook" ]; then
5347 _deploy "$Le_Domain" "$Le_DeployHook"
5348 res="$?"
5349 fi
5350
5351 _ACME_IS_RENEW=""
5352 if [ -z "$_ACME_IN_RENEWALL" ]; then
5353 if [ "$res" = "0" ]; then
5354 if [ $_set_level -ge $NOTIFY_LEVEL_RENEW ]; then
5355 _send_notify "Renew $d success" "Good, the cert is renewed." "$NOTIFY_HOOK" 0
5356 fi
5357 else
5358 if [ $_set_level -ge $NOTIFY_LEVEL_ERROR ]; then
5359 _send_notify "Renew $d error" "There is an error." "$NOTIFY_HOOK" 1
5360 fi
5361 fi
5362 fi
5363
5364 return "$res"
5365 }
5366
5367 #renewAll [stopRenewOnError] [server]
5368 renewAll() {
5369 _initpath
5370 _clearCA
5371 _stopRenewOnError="$1"
5372 _debug "_stopRenewOnError" "$_stopRenewOnError"
5373
5374 _server="$2"
5375 _debug "_server" "$_server"
5376
5377 _ret="0"
5378 _success_msg=""
5379 _error_msg=""
5380 _skipped_msg=""
5381 _error_level=$NOTIFY_LEVEL_SKIP
5382 _notify_code=$RENEW_SKIP
5383 _set_level=${NOTIFY_LEVEL:-$NOTIFY_LEVEL_DEFAULT}
5384 _debug "_set_level" "$_set_level"
5385 export _ACME_IN_RENEWALL=1
5386 for di in "${CERT_HOME}"/*.*/; do
5387 _debug di "$di"
5388 if ! [ -d "$di" ]; then
5389 _debug "Not a directory, skip: $di"
5390 continue
5391 fi
5392 d=$(basename "$di")
5393 _debug d "$d"
5394 (
5395 if _endswith "$d" "$ECC_SUFFIX"; then
5396 _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
5397 d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
5398 fi
5399 renew "$d" "$_isEcc" "$_server"
5400 )
5401 rc="$?"
5402 _debug "Return code: $rc"
5403 if [ "$rc" = "0" ]; then
5404 if [ $_error_level -gt $NOTIFY_LEVEL_RENEW ]; then
5405 _error_level="$NOTIFY_LEVEL_RENEW"
5406 _notify_code=0
5407 fi
5408
5409 if [ $_set_level -ge $NOTIFY_LEVEL_RENEW ]; then
5410 if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
5411 _send_notify "Renew $d success" "Good, the cert is renewed." "$NOTIFY_HOOK" 0
5412 fi
5413 fi
5414
5415 _success_msg="${_success_msg} $d
5416 "
5417 elif [ "$rc" = "$RENEW_SKIP" ]; then
5418 if [ $_error_level -gt $NOTIFY_LEVEL_SKIP ]; then
5419 _error_level="$NOTIFY_LEVEL_SKIP"
5420 _notify_code=$RENEW_SKIP
5421 fi
5422
5423 if [ $_set_level -ge $NOTIFY_LEVEL_SKIP ]; then
5424 if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
5425 _send_notify "Renew $d skipped" "Good, the cert is skipped." "$NOTIFY_HOOK" "$RENEW_SKIP"
5426 fi
5427 fi
5428
5429 _info "Skipped $d"
5430 _skipped_msg="${_skipped_msg} $d
5431 "
5432 else
5433 if [ $_error_level -gt $NOTIFY_LEVEL_ERROR ]; then
5434 _error_level="$NOTIFY_LEVEL_ERROR"
5435 _notify_code=1
5436 fi
5437
5438 if [ $_set_level -ge $NOTIFY_LEVEL_ERROR ]; then
5439 if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
5440 _send_notify "Renew $d error" "There is an error." "$NOTIFY_HOOK" 1
5441 fi
5442 fi
5443
5444 _error_msg="${_error_msg} $d
5445 "
5446 if [ "$_stopRenewOnError" ]; then
5447 _err "Error renew $d, stop now."
5448 _ret="$rc"
5449 break
5450 else
5451 _ret="$rc"
5452 _err "Error renew $d."
5453 fi
5454 fi
5455 done
5456 _debug _error_level "$_error_level"
5457 _debug _set_level "$_set_level"
5458 if [ $_error_level -le $_set_level ]; then
5459 if [ -z "$NOTIFY_MODE" ] || [ "$NOTIFY_MODE" = "$NOTIFY_MODE_BULK" ]; then
5460 _msg_subject="Renew"
5461 if [ "$_error_msg" ]; then
5462 _msg_subject="${_msg_subject} Error"
5463 _msg_data="Error certs:
5464 ${_error_msg}
5465 "
5466 fi
5467 if [ "$_success_msg" ]; then
5468 _msg_subject="${_msg_subject} Success"
5469 _msg_data="${_msg_data}Success certs:
5470 ${_success_msg}
5471 "
5472 fi
5473 if [ "$_skipped_msg" ]; then
5474 _msg_subject="${_msg_subject} Skipped"
5475 _msg_data="${_msg_data}Skipped certs:
5476 ${_skipped_msg}
5477 "
5478 fi
5479
5480 _send_notify "$_msg_subject" "$_msg_data" "$NOTIFY_HOOK" "$_notify_code"
5481 fi
5482 fi
5483
5484 return "$_ret"
5485 }
5486
5487 #csr webroot
5488 signcsr() {
5489 _csrfile="$1"
5490 _csrW="$2"
5491 if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
5492 _usage "Usage: $PROJECT_ENTRY --sign-csr --csr <csr-file> --webroot <directory>"
5493 return 1
5494 fi
5495
5496 _real_cert="$3"
5497 _real_key="$4"
5498 _real_ca="$5"
5499 _reload_cmd="$6"
5500 _real_fullchain="$7"
5501 _pre_hook="${8}"
5502 _post_hook="${9}"
5503 _renew_hook="${10}"
5504 _local_addr="${11}"
5505 _challenge_alias="${12}"
5506 _preferred_chain="${13}"
5507
5508 _csrsubj=$(_readSubjectFromCSR "$_csrfile")
5509 if [ "$?" != "0" ]; then
5510 _err "Can not read subject from csr: $_csrfile"
5511 return 1
5512 fi
5513 _debug _csrsubj "$_csrsubj"
5514 if _contains "$_csrsubj" ' ' || ! _contains "$_csrsubj" '.'; then
5515 _info "It seems that the subject: $_csrsubj is not a valid domain name. Drop it."
5516 _csrsubj=""
5517 fi
5518
5519 _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
5520 if [ "$?" != "0" ]; then
5521 _err "Can not read domain list from csr: $_csrfile"
5522 return 1
5523 fi
5524 _debug "_csrdomainlist" "$_csrdomainlist"
5525
5526 if [ -z "$_csrsubj" ]; then
5527 _csrsubj="$(_getfield "$_csrdomainlist" 1)"
5528 _debug _csrsubj "$_csrsubj"
5529 _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
5530 _debug "_csrdomainlist" "$_csrdomainlist"
5531 fi
5532
5533 if [ -z "$_csrsubj" ]; then
5534 _err "Can not read subject from csr: $_csrfile"
5535 return 1
5536 fi
5537
5538 _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
5539 if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
5540 _err "Can not read key length from csr: $_csrfile"
5541 return 1
5542 fi
5543
5544 _initpath "$_csrsubj" "$_csrkeylength"
5545 mkdir -p "$DOMAIN_PATH"
5546
5547 _info "Copy csr to: $CSR_PATH"
5548 cp "$_csrfile" "$CSR_PATH"
5549
5550 issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength" "$_real_cert" "$_real_key" "$_real_ca" "$_reload_cmd" "$_real_fullchain" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_addr" "$_challenge_alias" "$_preferred_chain"
5551
5552 }
5553
5554 showcsr() {
5555 _csrfile="$1"
5556 _csrd="$2"
5557 if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
5558 _usage "Usage: $PROJECT_ENTRY --show-csr --csr <csr-file>"
5559 return 1
5560 fi
5561
5562 _initpath
5563
5564 _csrsubj=$(_readSubjectFromCSR "$_csrfile")
5565 if [ "$?" != "0" ]; then
5566 _err "Can not read subject from csr: $_csrfile"
5567 return 1
5568 fi
5569 if [ -z "$_csrsubj" ]; then
5570 _info "The Subject is empty"
5571 fi
5572
5573 _info "Subject=$_csrsubj"
5574
5575 _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
5576 if [ "$?" != "0" ]; then
5577 _err "Can not read domain list from csr: $_csrfile"
5578 return 1
5579 fi
5580 _debug "_csrdomainlist" "$_csrdomainlist"
5581
5582 _info "SubjectAltNames=$_csrdomainlist"
5583
5584 _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
5585 if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
5586 _err "Can not read key length from csr: $_csrfile"
5587 return 1
5588 fi
5589 _info "KeyLength=$_csrkeylength"
5590 }
5591
5592 #listraw domain
5593 list() {
5594 _raw="$1"
5595 _domain="$2"
5596 _initpath
5597
5598 _sep="|"
5599 if [ "$_raw" ]; then
5600 if [ -z "$_domain" ]; then
5601 printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}CA${_sep}Created${_sep}Renew"
5602 fi
5603 for di in "${CERT_HOME}"/*.*/; do
5604 d=$(basename "$di")
5605 _debug d "$d"
5606 (
5607 if _endswith "$d" "$ECC_SUFFIX"; then
5608 _isEcc="ecc"
5609 d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
5610 fi
5611 DOMAIN_CONF="$di/$d.conf"
5612 if [ -f "$DOMAIN_CONF" ]; then
5613 . "$DOMAIN_CONF"
5614 _ca="$(_getCAShortName "$Le_API")"
5615 if [ -z "$_domain" ]; then
5616 printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$_ca${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
5617 else
5618 if [ "$_domain" = "$d" ]; then
5619 cat "$DOMAIN_CONF"
5620 fi
5621 fi
5622 fi
5623 )
5624 done
5625 else
5626 if _exists column; then
5627 list "raw" "$_domain" | column -t -s "$_sep"
5628 else
5629 list "raw" "$_domain" | tr "$_sep" '\t'
5630 fi
5631 fi
5632
5633 }
5634
5635 _deploy() {
5636 _d="$1"
5637 _hooks="$2"
5638
5639 for _d_api in $(echo "$_hooks" | tr ',' " "); do
5640 _deployApi="$(_findHook "$_d" $_SUB_FOLDER_DEPLOY "$_d_api")"
5641 if [ -z "$_deployApi" ]; then
5642 _err "The deploy hook $_d_api is not found."
5643 return 1
5644 fi
5645 _debug _deployApi "$_deployApi"
5646
5647 if ! (
5648 if ! . "$_deployApi"; then
5649 _err "Load file $_deployApi error. Please check your api file and try again."
5650 return 1
5651 fi
5652
5653 d_command="${_d_api}_deploy"
5654 if ! _exists "$d_command"; then
5655 _err "It seems that your api file is not correct, it must have a function named: $d_command"
5656 return 1
5657 fi
5658
5659 if ! $d_command "$_d" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
5660 _err "Error deploy for domain:$_d"
5661 return 1
5662 fi
5663 ); then
5664 _err "Deploy error."
5665 return 1
5666 else
5667 _info "$(__green Success)"
5668 fi
5669 done
5670 }
5671
5672 #domain hooks
5673 deploy() {
5674 _d="$1"
5675 _hooks="$2"
5676 _isEcc="$3"
5677 if [ -z "$_hooks" ]; then
5678 _usage "Usage: $PROJECT_ENTRY --deploy --domain <domain.tld> --deploy-hook <hookname> [--ecc] "
5679 return 1
5680 fi
5681
5682 _initpath "$_d" "$_isEcc"
5683 if [ ! -d "$DOMAIN_PATH" ]; then
5684 _err "The domain '$_d' is not a cert name. You must use the cert name to specify the cert to install."
5685 _err "Can not find path:'$DOMAIN_PATH'"
5686 return 1
5687 fi
5688
5689 . "$DOMAIN_CONF"
5690
5691 _savedomainconf Le_DeployHook "$_hooks"
5692
5693 _deploy "$_d" "$_hooks"
5694 }
5695
5696 installcert() {
5697 _main_domain="$1"
5698 if [ -z "$_main_domain" ]; then
5699 _usage "Usage: $PROJECT_ENTRY --install-cert --domain <domain.tld> [--ecc] [--cert-file <file>] [--key-file <file>] [--ca-file <file>] [ --reloadcmd <command>] [--fullchain-file <file>]"
5700 return 1
5701 fi
5702
5703 _real_cert="$2"
5704 _real_key="$3"
5705 _real_ca="$4"
5706 _reload_cmd="$5"
5707 _real_fullchain="$6"
5708 _isEcc="$7"
5709
5710 _initpath "$_main_domain" "$_isEcc"
5711 if [ ! -d "$DOMAIN_PATH" ]; then
5712 _err "The domain '$_main_domain' is not a cert name. You must use the cert name to specify the cert to install."
5713 _err "Can not find path:'$DOMAIN_PATH'"
5714 return 1
5715 fi
5716
5717 _savedomainconf "Le_RealCertPath" "$_real_cert"
5718 _savedomainconf "Le_RealCACertPath" "$_real_ca"
5719 _savedomainconf "Le_RealKeyPath" "$_real_key"
5720 _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
5721 _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
5722
5723 _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
5724 }
5725
5726 #domain cert key ca fullchain reloadcmd backup-prefix
5727 _installcert() {
5728 _main_domain="$1"
5729 _real_cert="$2"
5730 _real_key="$3"
5731 _real_ca="$4"
5732 _real_fullchain="$5"
5733 _reload_cmd="$6"
5734 _backup_prefix="$7"
5735
5736 if [ "$_real_cert" = "$NO_VALUE" ]; then
5737 _real_cert=""
5738 fi
5739 if [ "$_real_key" = "$NO_VALUE" ]; then
5740 _real_key=""
5741 fi
5742 if [ "$_real_ca" = "$NO_VALUE" ]; then
5743 _real_ca=""
5744 fi
5745 if [ "$_reload_cmd" = "$NO_VALUE" ]; then
5746 _reload_cmd=""
5747 fi
5748 if [ "$_real_fullchain" = "$NO_VALUE" ]; then
5749 _real_fullchain=""
5750 fi
5751
5752 _backup_path="$DOMAIN_BACKUP_PATH/$_backup_prefix"
5753 mkdir -p "$_backup_path"
5754
5755 if [ "$_real_cert" ]; then
5756 _info "Installing cert to: $_real_cert"
5757 if [ -f "$_real_cert" ] && [ ! "$_ACME_IS_RENEW" ]; then
5758 cp "$_real_cert" "$_backup_path/cert.bak"
5759 fi
5760 if [ "$CERT_PATH" != "$_real_cert" ]; then
5761 cat "$CERT_PATH" >"$_real_cert" || return 1
5762 fi
5763 fi
5764
5765 if [ "$_real_ca" ]; then
5766 _info "Installing CA to: $_real_ca"
5767 if [ "$_real_ca" = "$_real_cert" ]; then
5768 echo "" >>"$_real_ca"
5769 cat "$CA_CERT_PATH" >>"$_real_ca" || return 1
5770 else
5771 if [ -f "$_real_ca" ] && [ ! "$_ACME_IS_RENEW" ]; then
5772 cp "$_real_ca" "$_backup_path/ca.bak"
5773 fi
5774 if [ "$CA_CERT_PATH" != "$_real_ca" ]; then
5775 cat "$CA_CERT_PATH" >"$_real_ca" || return 1
5776 fi
5777 fi
5778 fi
5779
5780 if [ "$_real_key" ]; then
5781 _info "Installing key to: $_real_key"
5782 if [ -f "$_real_key" ] && [ ! "$_ACME_IS_RENEW" ]; then
5783 cp "$_real_key" "$_backup_path/key.bak"
5784 fi
5785 if [ "$CERT_KEY_PATH" != "$_real_key" ]; then
5786 if [ -f "$_real_key" ]; then
5787 cat "$CERT_KEY_PATH" >"$_real_key" || return 1
5788 else
5789 touch "$_real_key" || return 1
5790 chmod 600 "$_real_key"
5791 cat "$CERT_KEY_PATH" >"$_real_key" || return 1
5792 fi
5793 fi
5794 fi
5795
5796 if [ "$_real_fullchain" ]; then
5797 _info "Installing full chain to: $_real_fullchain"
5798 if [ -f "$_real_fullchain" ] && [ ! "$_ACME_IS_RENEW" ]; then
5799 cp "$_real_fullchain" "$_backup_path/fullchain.bak"
5800 fi
5801 if [ "$_real_fullchain" != "$CERT_FULLCHAIN_PATH" ]; then
5802 cat "$CERT_FULLCHAIN_PATH" >"$_real_fullchain" || return 1
5803 fi
5804 fi
5805
5806 if [ "$_reload_cmd" ]; then
5807 _info "Run reload cmd: $_reload_cmd"
5808 if (
5809 export CERT_PATH
5810 export CERT_KEY_PATH
5811 export CA_CERT_PATH
5812 export CERT_FULLCHAIN_PATH
5813 export Le_Domain="$_main_domain"
5814 cd "$DOMAIN_PATH" && eval "$_reload_cmd"
5815 ); then
5816 _info "$(__green "Reload success")"
5817 else
5818 _err "Reload error for :$Le_Domain"
5819 fi
5820 fi
5821
5822 }
5823
5824 __read_password() {
5825 unset _pp
5826 prompt="Enter Password:"
5827 while IFS= read -p "$prompt" -r -s -n 1 char; do
5828 if [ "$char" = $'\0' ]; then
5829 break
5830 fi
5831 prompt='*'
5832 _pp="$_pp$char"
5833 done
5834 echo "$_pp"
5835 }
5836
5837 _install_win_taskscheduler() {
5838 _lesh="$1"
5839 _centry="$2"
5840 _randomminute="$3"
5841 if ! _exists cygpath; then
5842 _err "cygpath not found"
5843 return 1
5844 fi
5845 if ! _exists schtasks; then
5846 _err "schtasks.exe is not found, are you on Windows?"
5847 return 1
5848 fi
5849 _winbash="$(cygpath -w $(which bash))"
5850 _debug _winbash "$_winbash"
5851 if [ -z "$_winbash" ]; then
5852 _err "can not find bash path"
5853 return 1
5854 fi
5855 _myname="$(whoami)"
5856 _debug "_myname" "$_myname"
5857 if [ -z "$_myname" ]; then
5858 _err "can not find my user name"
5859 return 1
5860 fi
5861 _debug "_lesh" "$_lesh"
5862
5863 _info "To install scheduler task in your Windows account, you must input your windows password."
5864 _info "$PROJECT_NAME doesn't save your password."
5865 _info "Please input your Windows password for: $(__green "$_myname")"
5866 _password="$(__read_password)"
5867 #SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'" >/dev/null
5868 echo SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "\"$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'\"" | cmd.exe >/dev/null
5869 echo
5870
5871 }
5872
5873 _uninstall_win_taskscheduler() {
5874 if ! _exists schtasks; then
5875 _err "schtasks.exe is not found, are you on Windows?"
5876 return 1
5877 fi
5878 if ! echo SCHTASKS /query /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null; then
5879 _debug "scheduler $_WINDOWS_SCHEDULER_NAME is not found."
5880 else
5881 _info "Removing $_WINDOWS_SCHEDULER_NAME"
5882 echo SCHTASKS /delete /f /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null
5883 fi
5884 }
5885
5886 #confighome
5887 installcronjob() {
5888 _c_home="$1"
5889 _initpath
5890 _CRONTAB="crontab"
5891 if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
5892 lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
5893 else
5894 _debug "_SCRIPT_" "$_SCRIPT_"
5895 _script="$(_readlink "$_SCRIPT_")"
5896 _debug _script "$_script"
5897 if [ -f "$_script" ]; then
5898 _info "Using the current script from: $_script"
5899 lesh="$_script"
5900 else
5901 _err "Can not install cronjob, $PROJECT_ENTRY not found."
5902 return 1
5903 fi
5904 fi
5905 if [ "$_c_home" ]; then
5906 _c_entry="--config-home \"$_c_home\" "
5907 fi
5908 _t=$(_time)
5909 random_minute=$(_math $_t % 60)
5910
5911 if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
5912 _CRONTAB="fcrontab"
5913 fi
5914
5915 if ! _exists "$_CRONTAB"; then
5916 if _exists cygpath && _exists schtasks.exe; then
5917 _info "It seems you are on Windows, let's install Windows scheduler task."
5918 if _install_win_taskscheduler "$lesh" "$_c_entry" "$random_minute"; then
5919 _info "Install Windows scheduler task success."
5920 return 0
5921 else
5922 _err "Install Windows scheduler task failed."
5923 return 1
5924 fi
5925 fi
5926 _err "crontab/fcrontab doesn't exist, so, we can not install cron jobs."
5927 _err "All your certs will not be renewed automatically."
5928 _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
5929 return 1
5930 fi
5931 _info "Installing cron job"
5932 if ! $_CRONTAB -l | grep "$PROJECT_ENTRY --cron"; then
5933 if _exists uname && uname -a | grep SunOS >/dev/null; then
5934 $_CRONTAB -l | {
5935 cat
5936 echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
5937 } | $_CRONTAB --
5938 else
5939 $_CRONTAB -l | {
5940 cat
5941 echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
5942 } | $_CRONTAB -
5943 fi
5944 fi
5945 if [ "$?" != "0" ]; then
5946 _err "Install cron job failed. You need to manually renew your certs."
5947 _err "Or you can add cronjob by yourself:"
5948 _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
5949 return 1
5950 fi
5951 }
5952
5953 uninstallcronjob() {
5954 _CRONTAB="crontab"
5955 if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
5956 _CRONTAB="fcrontab"
5957 fi
5958
5959 if ! _exists "$_CRONTAB"; then
5960 if _exists cygpath && _exists schtasks.exe; then
5961 _info "It seems you are on Windows, let's uninstall Windows scheduler task."
5962 if _uninstall_win_taskscheduler; then
5963 _info "Uninstall Windows scheduler task success."
5964 return 0
5965 else
5966 _err "Uninstall Windows scheduler task failed."
5967 return 1
5968 fi
5969 fi
5970 return
5971 fi
5972 _info "Removing cron job"
5973 cr="$($_CRONTAB -l | grep "$PROJECT_ENTRY --cron")"
5974 if [ "$cr" ]; then
5975 if _exists uname && uname -a | grep SunOS >/dev/null; then
5976 $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB --
5977 else
5978 $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB -
5979 fi
5980 LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
5981 _info LE_WORKING_DIR "$LE_WORKING_DIR"
5982 if _contains "$cr" "--config-home"; then
5983 LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
5984 _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
5985 fi
5986 fi
5987 _initpath
5988
5989 }
5990
5991 #domain isECC revokeReason
5992 revoke() {
5993 Le_Domain="$1"
5994 if [ -z "$Le_Domain" ]; then
5995 _usage "Usage: $PROJECT_ENTRY --revoke --domain <domain.tld> [--ecc]"
5996 return 1
5997 fi
5998
5999 _isEcc="$2"
6000 _reason="$3"
6001 if [ -z "$_reason" ]; then
6002 _reason="0"
6003 fi
6004 _initpath "$Le_Domain" "$_isEcc"
6005 if [ ! -f "$DOMAIN_CONF" ]; then
6006 _err "$Le_Domain is not a issued domain, skip."
6007 return 1
6008 fi
6009
6010 if [ ! -f "$CERT_PATH" ]; then
6011 _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
6012 return 1
6013 fi
6014
6015 . "$DOMAIN_CONF"
6016 _debug Le_API "$Le_API"
6017
6018 if [ "$Le_API" ]; then
6019 if [ "$Le_API" != "$ACME_DIRECTORY" ]; then
6020 _clearAPI
6021 fi
6022 export ACME_DIRECTORY="$Le_API"
6023 #reload ca configs
6024 ACCOUNT_KEY_PATH=""
6025 ACCOUNT_JSON_PATH=""
6026 CA_CONF=""
6027 _debug3 "initpath again."
6028 _initpath "$Le_Domain" "$_isEcc"
6029 _initAPI
6030 fi
6031
6032 cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
6033
6034 if [ -z "$cert" ]; then
6035 _err "Cert for $Le_Domain is empty found, skip."
6036 return 1
6037 fi
6038
6039 _initAPI
6040
6041 data="{\"certificate\": \"$cert\",\"reason\":$_reason}"
6042
6043 uri="${ACME_REVOKE_CERT}"
6044
6045 if [ -f "$CERT_KEY_PATH" ]; then
6046 _info "Try domain key first."
6047 if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
6048 if [ -z "$response" ]; then
6049 _info "Revoke success."
6050 rm -f "$CERT_PATH"
6051 return 0
6052 else
6053 _err "Revoke error by domain key."
6054 _err "$response"
6055 fi
6056 fi
6057 else
6058 _info "Domain key file doesn't exist."
6059 fi
6060
6061 _info "Try account key."
6062
6063 if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
6064 if [ -z "$response" ]; then
6065 _info "Revoke success."
6066 rm -f "$CERT_PATH"
6067 return 0
6068 else
6069 _err "Revoke error."
6070 _debug "$response"
6071 fi
6072 fi
6073 return 1
6074 }
6075
6076 #domain ecc
6077 remove() {
6078 Le_Domain="$1"
6079 if [ -z "$Le_Domain" ]; then
6080 _usage "Usage: $PROJECT_ENTRY --remove --domain <domain.tld> [--ecc]"
6081 return 1
6082 fi
6083
6084 _isEcc="$2"
6085
6086 _initpath "$Le_Domain" "$_isEcc"
6087 _removed_conf="$DOMAIN_CONF.removed"
6088 if [ ! -f "$DOMAIN_CONF" ]; then
6089 if [ -f "$_removed_conf" ]; then
6090 _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
6091 else
6092 _err "$Le_Domain is not a issued domain, skip."
6093 fi
6094 return 1
6095 fi
6096
6097 if mv "$DOMAIN_CONF" "$_removed_conf"; then
6098 _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
6099 _info "You can remove them by yourself."
6100 return 0
6101 else
6102 _err "Remove $Le_Domain failed."
6103 return 1
6104 fi
6105 }
6106
6107 #domain vtype
6108 _deactivate() {
6109 _d_domain="$1"
6110 _d_type="$2"
6111 _initpath "$_d_domain" "$_d_type"
6112
6113 . "$DOMAIN_CONF"
6114 _debug Le_API "$Le_API"
6115
6116 if [ "$Le_API" ]; then
6117 if [ "$Le_API" != "$ACME_DIRECTORY" ]; then
6118 _clearAPI
6119 fi
6120 export ACME_DIRECTORY="$Le_API"
6121 #reload ca configs
6122 ACCOUNT_KEY_PATH=""
6123 ACCOUNT_JSON_PATH=""
6124 CA_CONF=""
6125 _debug3 "initpath again."
6126 _initpath "$Le_Domain" "$_d_type"
6127 _initAPI
6128 fi
6129
6130 _identifiers="{\"type\":\"$(_getIdType "$_d_domain")\",\"value\":\"$_d_domain\"}"
6131 if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
6132 _err "Can not get domain new order."
6133 return 1
6134 fi
6135 _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
6136 _debug2 _authorizations_seg "$_authorizations_seg"
6137 if [ -z "$_authorizations_seg" ]; then
6138 _err "_authorizations_seg not found."
6139 _clearup
6140 _on_issue_err "$_post_hook"
6141 return 1
6142 fi
6143
6144 authzUri="$_authorizations_seg"
6145 _debug2 "authzUri" "$authzUri"
6146 if ! _send_signed_request "$authzUri"; then
6147 _err "get to authz error."
6148 _err "_authorizations_seg" "$_authorizations_seg"
6149 _err "authzUri" "$authzUri"
6150 _clearup
6151 _on_issue_err "$_post_hook"
6152 return 1
6153 fi
6154
6155 response="$(echo "$response" | _normalizeJson)"
6156 _debug2 response "$response"
6157 _URL_NAME="url"
6158
6159 entries="$(echo "$response" | tr '][' '==' | _egrep_o "challenges\": *=[^=]*=" | tr '}{' '\n\n' | grep "\"status\": *\"valid\"")"
6160 if [ -z "$entries" ]; then
6161 _info "No valid entries found."
6162 if [ -z "$thumbprint" ]; then
6163 thumbprint="$(__calc_account_thumbprint)"
6164 fi
6165 _debug "Trigger validation."
6166 vtype="$(_getIdType "$_d_domain")"
6167 entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
6168 _debug entry "$entry"
6169 if [ -z "$entry" ]; then
6170 _err "Error, can not get domain token $d"
6171 return 1
6172 fi
6173 token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
6174 _debug token "$token"
6175
6176 uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
6177 _debug uri "$uri"
6178
6179 keyauthorization="$token.$thumbprint"
6180 _debug keyauthorization "$keyauthorization"
6181 __trigger_validation "$uri" "$keyauthorization"
6182
6183 fi
6184
6185 _d_i=0
6186 _d_max_retry=$(echo "$entries" | wc -l)
6187 while [ "$_d_i" -lt "$_d_max_retry" ]; do
6188 _info "Deactivate: $_d_domain"
6189 _d_i="$(_math $_d_i + 1)"
6190 entry="$(echo "$entries" | sed -n "${_d_i}p")"
6191 _debug entry "$entry"
6192
6193 if [ -z "$entry" ]; then
6194 _info "No more valid entry found."
6195 break
6196 fi
6197
6198 _vtype="$(echo "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
6199 _debug _vtype "$_vtype"
6200 _info "Found $_vtype"
6201
6202 uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*\"" | tr -d '" ' | cut -d : -f 2-)"
6203 _debug uri "$uri"
6204
6205 if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
6206 _info "Skip $_vtype"
6207 continue
6208 fi
6209
6210 _info "Deactivate: $_vtype"
6211
6212 _djson="{\"status\":\"deactivated\"}"
6213
6214 if _send_signed_request "$authzUri" "$_djson" && _contains "$response" '"deactivated"'; then
6215 _info "Deactivate: $_vtype success."
6216 else
6217 _err "Can not deactivate $_vtype."
6218 break
6219 fi
6220
6221 done
6222 _debug "$_d_i"
6223 if [ "$_d_i" -eq "$_d_max_retry" ]; then
6224 _info "Deactivated success!"
6225 else
6226 _err "Deactivate failed."
6227 fi
6228
6229 }
6230
6231 deactivate() {
6232 _d_domain_list="$1"
6233 _d_type="$2"
6234 _initpath
6235 _initAPI
6236 _debug _d_domain_list "$_d_domain_list"
6237 if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
6238 _usage "Usage: $PROJECT_ENTRY --deactivate --domain <domain.tld> [--domain <domain2.tld> ...]"
6239 return 1
6240 fi
6241 for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
6242 if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
6243 continue
6244 fi
6245 if ! _deactivate "$_d_dm" "$_d_type"; then
6246 return 1
6247 fi
6248 done
6249 }
6250
6251 # Detect profile file if not specified as environment variable
6252 _detect_profile() {
6253 if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
6254 echo "$PROFILE"
6255 return
6256 fi
6257
6258 DETECTED_PROFILE=''
6259 SHELLTYPE="$(basename "/$SHELL")"
6260
6261 if [ "$SHELLTYPE" = "bash" ]; then
6262 if [ -f "$HOME/.bashrc" ]; then
6263 DETECTED_PROFILE="$HOME/.bashrc"
6264 elif [ -f "$HOME/.bash_profile" ]; then
6265 DETECTED_PROFILE="$HOME/.bash_profile"
6266 fi
6267 elif [ "$SHELLTYPE" = "zsh" ]; then
6268 DETECTED_PROFILE="$HOME/.zshrc"
6269 fi
6270
6271 if [ -z "$DETECTED_PROFILE" ]; then
6272 if [ -f "$HOME/.profile" ]; then
6273 DETECTED_PROFILE="$HOME/.profile"
6274 elif [ -f "$HOME/.bashrc" ]; then
6275 DETECTED_PROFILE="$HOME/.bashrc"
6276 elif [ -f "$HOME/.bash_profile" ]; then
6277 DETECTED_PROFILE="$HOME/.bash_profile"
6278 elif [ -f "$HOME/.zshrc" ]; then
6279 DETECTED_PROFILE="$HOME/.zshrc"
6280 fi
6281 fi
6282
6283 echo "$DETECTED_PROFILE"
6284 }
6285
6286 _initconf() {
6287 _initpath
6288 if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
6289 echo "
6290
6291 #LOG_FILE=\"$DEFAULT_LOG_FILE\"
6292 #LOG_LEVEL=1
6293
6294 #AUTO_UPGRADE=\"1\"
6295
6296 #NO_TIMESTAMP=1
6297
6298 " >"$ACCOUNT_CONF_PATH"
6299 fi
6300 }
6301
6302 # nocron
6303 _precheck() {
6304 _nocron="$1"
6305
6306 if ! _exists "curl" && ! _exists "wget"; then
6307 _err "Please install curl or wget first, we need to access http resources."
6308 return 1
6309 fi
6310
6311 if [ -z "$_nocron" ]; then
6312 if ! _exists "crontab" && ! _exists "fcrontab"; then
6313 if _exists cygpath && _exists schtasks.exe; then
6314 _info "It seems you are on Windows, we will install Windows scheduler task."
6315 else
6316 _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
6317 _err "We need to set cron job to renew the certs automatically."
6318 _err "Otherwise, your certs will not be able to be renewed automatically."
6319 if [ -z "$FORCE" ]; then
6320 _err "Please add '--force' and try install again to go without crontab."
6321 _err "./$PROJECT_ENTRY --install --force"
6322 return 1
6323 fi
6324 fi
6325 fi
6326 fi
6327
6328 if ! _exists "${ACME_OPENSSL_BIN:-openssl}"; then
6329 _err "Please install openssl first. ACME_OPENSSL_BIN=$ACME_OPENSSL_BIN"
6330 _err "We need openssl to generate keys."
6331 return 1
6332 fi
6333
6334 if ! _exists "socat"; then
6335 _err "It is recommended to install socat first."
6336 _err "We use socat for standalone server if you use standalone mode."
6337 _err "If you don't use standalone mode, just ignore this warning."
6338 fi
6339
6340 return 0
6341 }
6342
6343 _setShebang() {
6344 _file="$1"
6345 _shebang="$2"
6346 if [ -z "$_shebang" ]; then
6347 _usage "Usage: file shebang"
6348 return 1
6349 fi
6350 cp "$_file" "$_file.tmp"
6351 echo "$_shebang" >"$_file"
6352 sed -n 2,99999p "$_file.tmp" >>"$_file"
6353 rm -f "$_file.tmp"
6354 }
6355
6356 #confighome
6357 _installalias() {
6358 _c_home="$1"
6359 _initpath
6360
6361 _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
6362 if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
6363 echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
6364 echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
6365 echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
6366 fi
6367
6368 if [ "$_c_home" ]; then
6369 _c_entry=" --config-home '$_c_home'"
6370 fi
6371
6372 _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
6373 if [ "$_c_home" ]; then
6374 _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
6375 else
6376 _sed_i "/^export LE_CONFIG_HOME/d" "$_envfile"
6377 fi
6378 _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
6379
6380 _profile="$(_detect_profile)"
6381 if [ "$_profile" ]; then
6382 _debug "Found profile: $_profile"
6383 _info "Installing alias to '$_profile'"
6384 _setopt "$_profile" ". \"$_envfile\""
6385 _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
6386 else
6387 _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
6388 fi
6389
6390 #for csh
6391 _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
6392 _csh_profile="$HOME/.cshrc"
6393 if [ -f "$_csh_profile" ]; then
6394 _info "Installing alias to '$_csh_profile'"
6395 _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
6396 if [ "$_c_home" ]; then
6397 _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
6398 else
6399 _sed_i "/^setenv LE_CONFIG_HOME/d" "$_cshfile"
6400 fi
6401 _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
6402 _setopt "$_csh_profile" "source \"$_cshfile\""
6403 fi
6404
6405 #for tcsh
6406 _tcsh_profile="$HOME/.tcshrc"
6407 if [ -f "$_tcsh_profile" ]; then
6408 _info "Installing alias to '$_tcsh_profile'"
6409 _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
6410 if [ "$_c_home" ]; then
6411 _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
6412 fi
6413 _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
6414 _setopt "$_tcsh_profile" "source \"$_cshfile\""
6415 fi
6416
6417 }
6418
6419 # nocron confighome noprofile accountemail
6420 install() {
6421
6422 if [ -z "$LE_WORKING_DIR" ]; then
6423 LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
6424 fi
6425
6426 _nocron="$1"
6427 _c_home="$2"
6428 _noprofile="$3"
6429 _accountemail="$4"
6430
6431 if ! _initpath; then
6432 _err "Install failed."
6433 return 1
6434 fi
6435 if [ "$_nocron" ]; then
6436 _debug "Skip install cron job"
6437 fi
6438
6439 if [ "$_ACME_IN_CRON" != "1" ]; then
6440 if ! _precheck "$_nocron"; then
6441 _err "Pre-check failed, can not install."
6442 return 1
6443 fi
6444 fi
6445
6446 if [ -z "$_c_home" ] && [ "$LE_CONFIG_HOME" != "$LE_WORKING_DIR" ]; then
6447 _info "Using config home: $LE_CONFIG_HOME"
6448 _c_home="$LE_CONFIG_HOME"
6449 fi
6450
6451 #convert from le
6452 if [ -d "$HOME/.le" ]; then
6453 for envfile in "le.env" "le.sh.env"; do
6454 if [ -f "$HOME/.le/$envfile" ]; then
6455 if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
6456 _upgrading="1"
6457 _info "You are upgrading from le.sh"
6458 _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
6459 mv "$HOME/.le" "$LE_WORKING_DIR"
6460 mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
6461 break
6462 fi
6463 fi
6464 done
6465 fi
6466
6467 _info "Installing to $LE_WORKING_DIR"
6468
6469 if [ ! -d "$LE_WORKING_DIR" ]; then
6470 if ! mkdir -p "$LE_WORKING_DIR"; then
6471 _err "Can not create working dir: $LE_WORKING_DIR"
6472 return 1
6473 fi
6474
6475 chmod 700 "$LE_WORKING_DIR"
6476 fi
6477
6478 if [ ! -d "$LE_CONFIG_HOME" ]; then
6479 if ! mkdir -p "$LE_CONFIG_HOME"; then
6480 _err "Can not create config dir: $LE_CONFIG_HOME"
6481 return 1
6482 fi
6483
6484 chmod 700 "$LE_CONFIG_HOME"
6485 fi
6486
6487 cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
6488
6489 if [ "$?" != "0" ]; then
6490 _err "Install failed, can not copy $PROJECT_ENTRY"
6491 return 1
6492 fi
6493
6494 _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
6495
6496 if [ "$_ACME_IN_CRON" != "1" ] && [ -z "$_noprofile" ]; then
6497 _installalias "$_c_home"
6498 fi
6499
6500 for subf in $_SUB_FOLDERS; do
6501 if [ -d "$subf" ]; then
6502 mkdir -p "$LE_WORKING_DIR/$subf"
6503 cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
6504 fi
6505 done
6506
6507 if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
6508 _initconf
6509 fi
6510
6511 if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
6512 _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
6513 fi
6514
6515 if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
6516 _saveaccountconf "CERT_HOME" "$CERT_HOME"
6517 fi
6518
6519 if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
6520 _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
6521 fi
6522
6523 if [ -z "$_nocron" ]; then
6524 installcronjob "$_c_home"
6525 fi
6526
6527 if [ -z "$NO_DETECT_SH" ]; then
6528 #Modify shebang
6529 if _exists bash; then
6530 _bash_path="$(bash -c "command -v bash 2>/dev/null")"
6531 if [ -z "$_bash_path" ]; then
6532 _bash_path="$(bash -c 'echo $SHELL')"
6533 fi
6534 fi
6535 if [ "$_bash_path" ]; then
6536 _info "Good, bash is found, so change the shebang to use bash as preferred."
6537 _shebang='#!'"$_bash_path"
6538 _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
6539 for subf in $_SUB_FOLDERS; do
6540 if [ -d "$LE_WORKING_DIR/$subf" ]; then
6541 for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
6542 _setShebang "$_apifile" "$_shebang"
6543 done
6544 fi
6545 done
6546 fi
6547 fi
6548
6549 if [ "$_accountemail" ]; then
6550 _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
6551 fi
6552
6553 _info OK
6554 }
6555
6556 # nocron
6557 uninstall() {
6558 _nocron="$1"
6559 if [ -z "$_nocron" ]; then
6560 uninstallcronjob
6561 fi
6562 _initpath
6563
6564 _uninstallalias
6565
6566 rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
6567 _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
6568
6569 }
6570
6571 _uninstallalias() {
6572 _initpath
6573
6574 _profile="$(_detect_profile)"
6575 if [ "$_profile" ]; then
6576 _info "Uninstalling alias from: '$_profile'"
6577 text="$(cat "$_profile")"
6578 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
6579 fi
6580
6581 _csh_profile="$HOME/.cshrc"
6582 if [ -f "$_csh_profile" ]; then
6583 _info "Uninstalling alias from: '$_csh_profile'"
6584 text="$(cat "$_csh_profile")"
6585 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
6586 fi
6587
6588 _tcsh_profile="$HOME/.tcshrc"
6589 if [ -f "$_tcsh_profile" ]; then
6590 _info "Uninstalling alias from: '$_csh_profile'"
6591 text="$(cat "$_tcsh_profile")"
6592 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
6593 fi
6594
6595 }
6596
6597 cron() {
6598 export _ACME_IN_CRON=1
6599 _initpath
6600 _info "$(__green "===Starting cron===")"
6601 if [ "$AUTO_UPGRADE" = "1" ]; then
6602 export LE_WORKING_DIR
6603 (
6604 if ! upgrade; then
6605 _err "Cron:Upgrade failed!"
6606 return 1
6607 fi
6608 )
6609 . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
6610
6611 if [ -t 1 ]; then
6612 __INTERACTIVE="1"
6613 fi
6614
6615 _info "Auto upgraded to: $VER"
6616 fi
6617 renewAll
6618 _ret="$?"
6619 _ACME_IN_CRON=""
6620 _info "$(__green "===End cron===")"
6621 exit $_ret
6622 }
6623
6624 version() {
6625 echo "$PROJECT"
6626 echo "v$VER"
6627 }
6628
6629 # subject content hooks code
6630 _send_notify() {
6631 _nsubject="$1"
6632 _ncontent="$2"
6633 _nhooks="$3"
6634 _nerror="$4"
6635
6636 if [ "$NOTIFY_LEVEL" = "$NOTIFY_LEVEL_DISABLE" ]; then
6637 _debug "The NOTIFY_LEVEL is $NOTIFY_LEVEL, disabled, just return."
6638 return 0
6639 fi
6640
6641 if [ -z "$_nhooks" ]; then
6642 _debug "The NOTIFY_HOOK is empty, just return."
6643 return 0
6644 fi
6645
6646 _send_err=0
6647 for _n_hook in $(echo "$_nhooks" | tr ',' " "); do
6648 _n_hook_file="$(_findHook "" $_SUB_FOLDER_NOTIFY "$_n_hook")"
6649 _info "Sending via: $_n_hook"
6650 _debug "Found $_n_hook_file for $_n_hook"
6651 if [ -z "$_n_hook_file" ]; then
6652 _err "Can not find the hook file for $_n_hook"
6653 continue
6654 fi
6655 if ! (
6656 if ! . "$_n_hook_file"; then
6657 _err "Load file $_n_hook_file error. Please check your api file and try again."
6658 return 1
6659 fi
6660
6661 d_command="${_n_hook}_send"
6662 if ! _exists "$d_command"; then
6663 _err "It seems that your api file is not correct, it must have a function named: $d_command"
6664 return 1
6665 fi
6666
6667 if ! $d_command "$_nsubject" "$_ncontent" "$_nerror"; then
6668 _err "Error send message by $d_command"
6669 return 1
6670 fi
6671
6672 return 0
6673 ); then
6674 _err "Set $_n_hook_file error."
6675 _send_err=1
6676 else
6677 _info "$_n_hook $(__green Success)"
6678 fi
6679 done
6680 return $_send_err
6681
6682 }
6683
6684 # hook
6685 _set_notify_hook() {
6686 _nhooks="$1"
6687
6688 _test_subject="Hello, this is a notification from $PROJECT_NAME"
6689 _test_content="If you receive this message, your notification works."
6690
6691 _send_notify "$_test_subject" "$_test_content" "$_nhooks" 0
6692
6693 }
6694
6695 #[hook] [level] [mode]
6696 setnotify() {
6697 _nhook="$1"
6698 _nlevel="$2"
6699 _nmode="$3"
6700
6701 _initpath
6702
6703 if [ -z "$_nhook$_nlevel$_nmode" ]; then
6704 _usage "Usage: $PROJECT_ENTRY --set-notify [--notify-hook <hookname>] [--notify-level <0|1|2|3>] [--notify-mode <0|1>]"
6705 _usage "$_NOTIFY_WIKI"
6706 return 1
6707 fi
6708
6709 if [ "$_nlevel" ]; then
6710 _info "Set notify level to: $_nlevel"
6711 export "NOTIFY_LEVEL=$_nlevel"
6712 _saveaccountconf "NOTIFY_LEVEL" "$NOTIFY_LEVEL"
6713 fi
6714
6715 if [ "$_nmode" ]; then
6716 _info "Set notify mode to: $_nmode"
6717 export "NOTIFY_MODE=$_nmode"
6718 _saveaccountconf "NOTIFY_MODE" "$NOTIFY_MODE"
6719 fi
6720
6721 if [ "$_nhook" ]; then
6722 _info "Set notify hook to: $_nhook"
6723 if [ "$_nhook" = "$NO_VALUE" ]; then
6724 _info "Clear notify hook"
6725 _clearaccountconf "NOTIFY_HOOK"
6726 else
6727 if _set_notify_hook "$_nhook"; then
6728 export NOTIFY_HOOK="$_nhook"
6729 _saveaccountconf "NOTIFY_HOOK" "$NOTIFY_HOOK"
6730 return 0
6731 else
6732 _err "Can not set notify hook to: $_nhook"
6733 return 1
6734 fi
6735 fi
6736 fi
6737
6738 }
6739
6740 showhelp() {
6741 _initpath
6742 version
6743 echo "Usage: $PROJECT_ENTRY <command> ... [parameters ...]
6744 Commands:
6745 -h, --help Show this help message.
6746 -v, --version Show version info.
6747 --install Install $PROJECT_NAME to your system.
6748 --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
6749 --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT.
6750 --issue Issue a cert.
6751 --deploy Deploy the cert to your server.
6752 -i, --install-cert Install the issued cert to apache/nginx or any other server.
6753 -r, --renew Renew a cert.
6754 --renew-all Renew all the certs.
6755 --revoke Revoke a cert.
6756 --remove Remove the cert from list of certs known to $PROJECT_NAME.
6757 --list List all the certs.
6758 --info Show the $PROJECT_NAME configs, or the configs for a domain with [-d domain] parameter.
6759 --to-pkcs12 Export the certificate and key to a pfx file.
6760 --to-pkcs8 Convert to pkcs8 format.
6761 --sign-csr Issue a cert from an existing csr.
6762 --show-csr Show the content of a csr.
6763 -ccr, --create-csr Create CSR, professional use.
6764 --create-domain-key Create an domain private key, professional use.
6765 --update-account Update account info.
6766 --register-account Register account key.
6767 --deactivate-account Deactivate the account.
6768 --create-account-key Create an account private key, professional use.
6769 --install-cronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
6770 --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
6771 --cron Run cron job to renew all the certs.
6772 --set-notify Set the cron notification hook, level or mode.
6773 --deactivate Deactivate the domain authz, professional use.
6774 --set-default-ca Used with '--server', Set the default CA to use.
6775 See: $_SERVER_WIKI
6776 --set-default-chain Set the default preferred chain for a CA.
6777 See: $_PREFERRED_CHAIN_WIKI
6778
6779
6780 Parameters:
6781 -d, --domain <domain.tld> Specifies a domain, used to issue, renew or revoke etc.
6782 --challenge-alias <domain.tld> The challenge domain alias for DNS alias mode.
6783 See: $_DNS_ALIAS_WIKI
6784
6785 --domain-alias <domain.tld> The domain alias for DNS alias mode.
6786 See: $_DNS_ALIAS_WIKI
6787
6788 --preferred-chain <chain> If the CA offers multiple certificate chains, prefer the chain with an issuer matching this Subject Common Name.
6789 If no match, the default offered chain will be used. (default: empty)
6790 See: $_PREFERRED_CHAIN_WIKI
6791
6792 --valid-to <date-time> Request the NotAfter field of the cert.
6793 See: $_VALIDITY_WIKI
6794 --valid-from <date-time> Request the NotBefore field of the cert.
6795 See: $_VALIDITY_WIKI
6796
6797 -f, --force Force install, force cert renewal or override sudo restrictions.
6798 --staging, --test Use staging server, for testing.
6799 --debug [0|1|2|3] Output debug info. Defaults to 1 if argument is omitted.
6800 --output-insecure Output all the sensitive messages.
6801 By default all the credentials/sensitive messages are hidden from the output/debug/log for security.
6802 -w, --webroot <directory> Specifies the web root folder for web root mode.
6803 --standalone Use standalone mode.
6804 --alpn Use standalone alpn mode.
6805 --stateless Use stateless mode.
6806 See: $_STATELESS_WIKI
6807
6808 --apache Use apache mode.
6809 --dns [dns_hook] Use dns manual mode or dns api. Defaults to manual mode when argument is omitted.
6810 See: $_DNS_API_WIKI
6811
6812 --dnssleep <seconds> The time in seconds to wait for all the txt records to propagate in dns api mode.
6813 It's not necessary to use this by default, $PROJECT_NAME polls dns status by DOH automatically.
6814 -k, --keylength <bits> Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384, ec-521.
6815 -ak, --accountkeylength <bits> Specifies the account key length: 2048, 3072, 4096
6816 --log [file] Specifies the log file. Defaults to \"$DEFAULT_LOG_FILE\" if argument is omitted.
6817 --log-level <1|2> Specifies the log level, default is 1.
6818 --syslog <0|3|6|7> Syslog level, 0: disable syslog, 3: error, 6: info, 7: debug.
6819 --eab-kid <eab_key_id> Key Identifier for External Account Binding.
6820 --eab-hmac-key <eab_hmac_key> HMAC key for External Account Binding.
6821
6822
6823 These parameters are to install the cert to nginx/apache or any other server after issue/renew a cert:
6824
6825 --cert-file <file> Path to copy the cert file to after issue/renew..
6826 --key-file <file> Path to copy the key file to after issue/renew.
6827 --ca-file <file> Path to copy the intermediate cert file to after issue/renew.
6828 --fullchain-file <file> Path to copy the fullchain cert file to after issue/renew.
6829 --reloadcmd <command> Command to execute after issue/renew to reload the server.
6830
6831 --server <server_uri> ACME Directory Resource URI. (default: $DEFAULT_CA)
6832 See: $_SERVER_WIKI
6833
6834 --accountconf <file> Specifies a customized account config file.
6835 --home <directory> Specifies the home dir for $PROJECT_NAME.
6836 --cert-home <directory> Specifies the home dir to save all the certs, only valid for '--install' command.
6837 --config-home <directory> Specifies the home dir to save all the configurations.
6838 --useragent <string> Specifies the user agent string. it will be saved for future use too.
6839 -m, --email <email> Specifies the account email, only valid for the '--install' and '--update-account' command.
6840 --accountkey <file> Specifies the account key path, only valid for the '--install' command.
6841 --days <ndays> Specifies the days to renew the cert when using '--issue' command. The default value is $DEFAULT_RENEW days.
6842 --httpport <port> Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
6843 --tlsport <port> Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
6844 --local-address <ip> Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
6845 --listraw Only used for '--list' command, list the certs in raw format.
6846 -se, --stop-renew-on-error Only valid for '--renew-all' command. Stop if one cert has error in renewal.
6847 --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
6848 --ca-bundle <file> Specifies the path to the CA certificate bundle to verify api server's certificate.
6849 --ca-path <directory> Specifies directory containing CA certificates in PEM format, used by wget or curl.
6850 --no-cron Only valid for '--install' command, which means: do not install the default cron job.
6851 In this case, the certs will not be renewed automatically.
6852 --no-profile Only valid for '--install' command, which means: do not install aliases to user profile.
6853 --no-color Do not output color text.
6854 --force-color Force output of color text. Useful for non-interactive use with the aha tool for HTML E-Mails.
6855 --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--to-pkcs12' and '--create-csr'
6856 --csr <file> Specifies the input csr.
6857 --pre-hook <command> Command to be run before obtaining any certificates.
6858 --post-hook <command> Command to be run after attempting to obtain/renew certificates. Runs regardless of whether obtain/renew succeeded or failed.
6859 --renew-hook <command> Command to be run after each successfully renewed certificate.
6860 --deploy-hook <hookname> The hook file to deploy cert
6861 --ocsp, --ocsp-must-staple Generate OCSP-Must-Staple extension.
6862 --always-force-new-domain-key Generate new domain key on renewal. Otherwise, the domain key is not changed by default.
6863 --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future. Defaults to 1 if argument is omitted.
6864 --listen-v4 Force standalone/tls server to listen at ipv4.
6865 --listen-v6 Force standalone/tls server to listen at ipv6.
6866 --openssl-bin <file> Specifies a custom openssl bin location.
6867 --use-wget Force to use wget, if you have both curl and wget installed.
6868 --yes-I-know-dns-manual-mode-enough-go-ahead-please Force use of dns manual mode.
6869 See: $_DNS_MANUAL_WIKI
6870
6871 -b, --branch <branch> Only valid for '--upgrade' command, specifies the branch name to upgrade to.
6872 --notify-level <0|1|2|3> Set the notification level: Default value is $NOTIFY_LEVEL_DEFAULT.
6873 0: disabled, no notification will be sent.
6874 1: send notifications only when there is an error.
6875 2: send notifications when a cert is successfully renewed, or there is an error.
6876 3: send notifications when a cert is skipped, renewed, or error.
6877 --notify-mode <0|1> Set notification mode. Default value is $NOTIFY_MODE_DEFAULT.
6878 0: Bulk mode. Send all the domain's notifications in one message(mail).
6879 1: Cert mode. Send a message for every single cert.
6880 --notify-hook <hookname> Set the notify hook
6881 --revoke-reason <0-10> The reason for revocation, can be used in conjunction with the '--revoke' command.
6882 See: $_REVOKE_WIKI
6883
6884 --password <password> Add a password to exported pfx file. Use with --to-pkcs12.
6885
6886
6887 "
6888 }
6889
6890 installOnline() {
6891 _info "Installing from online archive."
6892
6893 _branch="$BRANCH"
6894 if [ -z "$_branch" ]; then
6895 _branch="master"
6896 fi
6897
6898 target="$PROJECT/archive/$_branch.tar.gz"
6899 _info "Downloading $target"
6900 localname="$_branch.tar.gz"
6901 if ! _get "$target" >$localname; then
6902 _err "Download error."
6903 return 1
6904 fi
6905 (
6906 _info "Extracting $localname"
6907 if ! (tar xzf $localname || gtar xzf $localname); then
6908 _err "Extraction error."
6909 exit 1
6910 fi
6911
6912 cd "$PROJECT_NAME-$_branch"
6913 chmod +x $PROJECT_ENTRY
6914 if ./$PROJECT_ENTRY --install "$@"; then
6915 _info "Install success!"
6916 _initpath
6917 _saveaccountconf "UPGRADE_HASH" "$(_getUpgradeHash)"
6918 fi
6919
6920 cd ..
6921
6922 rm -rf "$PROJECT_NAME-$_branch"
6923 rm -f "$localname"
6924 )
6925 }
6926
6927 _getRepoHash() {
6928 _hash_path=$1
6929 shift
6930 _hash_url="https://api.github.com/repos/acmesh-official/$PROJECT_NAME/git/refs/$_hash_path"
6931 _get $_hash_url | tr -d "\r\n" | tr '{},' '\n\n\n' | grep '"sha":' | cut -d '"' -f 4
6932 }
6933
6934 _getUpgradeHash() {
6935 _b="$BRANCH"
6936 if [ -z "$_b" ]; then
6937 _b="master"
6938 fi
6939 _hash=$(_getRepoHash "heads/$_b")
6940 if [ -z "$_hash" ]; then _hash=$(_getRepoHash "tags/$_b"); fi
6941 echo $_hash
6942 }
6943
6944 upgrade() {
6945 if (
6946 _initpath
6947 [ -z "$FORCE" ] && [ "$(_getUpgradeHash)" = "$(_readaccountconf "UPGRADE_HASH")" ] && _info "Already uptodate!" && exit 0
6948 export LE_WORKING_DIR
6949 cd "$LE_WORKING_DIR"
6950 installOnline "--nocron" "--noprofile"
6951 ); then
6952 _info "Upgrade success!"
6953 exit 0
6954 else
6955 _err "Upgrade failed!"
6956 exit 1
6957 fi
6958 }
6959
6960 _processAccountConf() {
6961 if [ "$_useragent" ]; then
6962 _saveaccountconf "USER_AGENT" "$_useragent"
6963 elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
6964 _saveaccountconf "USER_AGENT" "$USER_AGENT"
6965 fi
6966
6967 if [ "$_openssl_bin" ]; then
6968 _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
6969 elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
6970 _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
6971 fi
6972
6973 if [ "$_auto_upgrade" ]; then
6974 _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
6975 elif [ "$AUTO_UPGRADE" ]; then
6976 _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
6977 fi
6978
6979 if [ "$_use_wget" ]; then
6980 _saveaccountconf "ACME_USE_WGET" "$_use_wget"
6981 elif [ "$ACME_USE_WGET" ]; then
6982 _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
6983 fi
6984
6985 }
6986
6987 _checkSudo() {
6988 if [ -z "__INTERACTIVE" ]; then
6989 #don't check if it's not in an interactive shell
6990 return 0
6991 fi
6992 if [ "$SUDO_GID" ] && [ "$SUDO_COMMAND" ] && [ "$SUDO_USER" ] && [ "$SUDO_UID" ]; then
6993 if [ "$SUDO_USER" = "root" ] && [ "$SUDO_UID" = "0" ]; then
6994 #it's root using sudo, no matter it's using sudo or not, just fine
6995 return 0
6996 fi
6997 if [ -n "$SUDO_COMMAND" ]; then
6998 #it's a normal user doing "sudo su", or `sudo -i` or `sudo -s`, or `sudo su acmeuser1`
6999 _endswith "$SUDO_COMMAND" /bin/su || _contains "$SUDO_COMMAND" "/bin/su " || grep "^$SUDO_COMMAND\$" /etc/shells >/dev/null 2>&1
7000 return $?
7001 fi
7002 #otherwise
7003 return 1
7004 fi
7005 return 0
7006 }
7007
7008 #server #keylength
7009 _selectServer() {
7010 _server="$1"
7011 _skeylength="$2"
7012 _server_lower="$(echo "$_server" | _lower_case)"
7013 _sindex=0
7014 for snames in $CA_NAMES; do
7015 snames="$(echo "$snames" | _lower_case)"
7016 _sindex="$(_math $_sindex + 1)"
7017 _debug2 "_selectServer try snames" "$snames"
7018 for sname in $(echo "$snames" | tr ',' ' '); do
7019 if [ "$_server_lower" = "$sname" ]; then
7020 _debug2 "_selectServer match $sname"
7021 _serverdir="$(_getfield "$CA_SERVERS" $_sindex)"
7022 if [ "$_serverdir" = "$CA_SSLCOM_RSA" ] && _isEccKey "$_skeylength"; then
7023 _serverdir="$CA_SSLCOM_ECC"
7024 fi
7025 _debug "Selected server: $_serverdir"
7026 ACME_DIRECTORY="$_serverdir"
7027 export ACME_DIRECTORY
7028 return
7029 fi
7030 done
7031 done
7032 ACME_DIRECTORY="$_server"
7033 export ACME_DIRECTORY
7034 }
7035
7036 #url
7037 _getCAShortName() {
7038 caurl="$1"
7039 if [ -z "$caurl" ]; then
7040 caurl="$DEFAULT_CA"
7041 fi
7042 if [ "$CA_SSLCOM_ECC" = "$caurl" ]; then
7043 caurl="$CA_SSLCOM_RSA" #just hack to get the short name
7044 fi
7045 caurl_lower="$(echo $caurl | _lower_case)"
7046 _sindex=0
7047 for surl in $(echo "$CA_SERVERS" | _lower_case | tr , ' '); do
7048 _sindex="$(_math $_sindex + 1)"
7049 if [ "$caurl_lower" = "$surl" ]; then
7050 _nindex=0
7051 for snames in $CA_NAMES; do
7052 _nindex="$(_math $_nindex + 1)"
7053 if [ $_nindex -ge $_sindex ]; then
7054 _getfield "$snames" 1
7055 return
7056 fi
7057 done
7058 fi
7059 done
7060 echo "$caurl"
7061 }
7062
7063 #set default ca to $ACME_DIRECTORY
7064 setdefaultca() {
7065 if [ -z "$ACME_DIRECTORY" ]; then
7066 _err "Please give a --server parameter."
7067 return 1
7068 fi
7069 _saveaccountconf "DEFAULT_ACME_SERVER" "$ACME_DIRECTORY"
7070 _info "Changed default CA to: $(__green "$ACME_DIRECTORY")"
7071 }
7072
7073 #preferred-chain
7074 setdefaultchain() {
7075 _initpath
7076 _preferred_chain="$1"
7077 if [ -z "$_preferred_chain" ]; then
7078 _err "Please give a '--preferred-chain value' value."
7079 return 1
7080 fi
7081 mkdir -p "$CA_DIR"
7082 _savecaconf "DEFAULT_PREFERRED_CHAIN" "$_preferred_chain"
7083 }
7084
7085 #domain ecc
7086 info() {
7087 _domain="$1"
7088 _ecc="$2"
7089 _initpath
7090 if [ -z "$_domain" ]; then
7091 _debug "Show global configs"
7092 echo "LE_WORKING_DIR=$LE_WORKING_DIR"
7093 echo "LE_CONFIG_HOME=$LE_CONFIG_HOME"
7094 cat "$ACCOUNT_CONF_PATH"
7095 else
7096 _debug "Show domain configs"
7097 (
7098 _initpath "$_domain" "$_ecc"
7099 echo "DOMAIN_CONF=$DOMAIN_CONF"
7100 for seg in $(cat $DOMAIN_CONF | cut -d = -f 1); do
7101 echo "$seg=$(_readdomainconf "$seg")"
7102 done
7103 )
7104 fi
7105 }
7106
7107 _process() {
7108 _CMD=""
7109 _domain=""
7110 _altdomains="$NO_VALUE"
7111 _webroot=""
7112 _challenge_alias=""
7113 _keylength="$DEFAULT_DOMAIN_KEY_LENGTH"
7114 _accountkeylength="$DEFAULT_ACCOUNT_KEY_LENGTH"
7115 _cert_file=""
7116 _key_file=""
7117 _ca_file=""
7118 _fullchain_file=""
7119 _reloadcmd=""
7120 _password=""
7121 _accountconf=""
7122 _useragent=""
7123 _accountemail=""
7124 _accountkey=""
7125 _certhome=""
7126 _confighome=""
7127 _httpport=""
7128 _tlsport=""
7129 _dnssleep=""
7130 _listraw=""
7131 _stopRenewOnError=""
7132 #_insecure=""
7133 _ca_bundle=""
7134 _ca_path=""
7135 _nocron=""
7136 _noprofile=""
7137 _ecc=""
7138 _csr=""
7139 _pre_hook=""
7140 _post_hook=""
7141 _renew_hook=""
7142 _deploy_hook=""
7143 _logfile=""
7144 _log=""
7145 _local_address=""
7146 _log_level=""
7147 _auto_upgrade=""
7148 _listen_v4=""
7149 _listen_v6=""
7150 _openssl_bin=""
7151 _syslog=""
7152 _use_wget=""
7153 _server=""
7154 _notify_hook=""
7155 _notify_level=""
7156 _notify_mode=""
7157 _revoke_reason=""
7158 _eab_kid=""
7159 _eab_hmac_key=""
7160 _preferred_chain=""
7161 _valid_from=""
7162 _valid_to=""
7163 while [ ${#} -gt 0 ]; do
7164 case "${1}" in
7165
7166 --help | -h)
7167 showhelp
7168 return
7169 ;;
7170 --version | -v)
7171 version
7172 return
7173 ;;
7174 --install)
7175 _CMD="install"
7176 ;;
7177 --install-online)
7178 shift
7179 installOnline "$@"
7180 return
7181 ;;
7182 --uninstall)
7183 _CMD="uninstall"
7184 ;;
7185 --upgrade)
7186 _CMD="upgrade"
7187 ;;
7188 --issue)
7189 _CMD="issue"
7190 ;;
7191 --deploy)
7192 _CMD="deploy"
7193 ;;
7194 --sign-csr | --signcsr)
7195 _CMD="signcsr"
7196 ;;
7197 --show-csr | --showcsr)
7198 _CMD="showcsr"
7199 ;;
7200 -i | --install-cert | --installcert)
7201 _CMD="installcert"
7202 ;;
7203 --renew | -r)
7204 _CMD="renew"
7205 ;;
7206 --renew-all | --renewAll | --renewall)
7207 _CMD="renewAll"
7208 ;;
7209 --revoke)
7210 _CMD="revoke"
7211 ;;
7212 --remove)
7213 _CMD="remove"
7214 ;;
7215 --list)
7216 _CMD="list"
7217 ;;
7218 --info)
7219 _CMD="info"
7220 ;;
7221 --install-cronjob | --installcronjob)
7222 _CMD="installcronjob"
7223 ;;
7224 --uninstall-cronjob | --uninstallcronjob)
7225 _CMD="uninstallcronjob"
7226 ;;
7227 --cron)
7228 _CMD="cron"
7229 ;;
7230 --to-pkcs12 | --to-pkcs | --toPkcs)
7231 _CMD="toPkcs"
7232 ;;
7233 --to-pkcs8 | --toPkcs8)
7234 _CMD="toPkcs8"
7235 ;;
7236 --create-account-key | --createAccountKey | --createaccountkey | -cak)
7237 _CMD="createAccountKey"
7238 ;;
7239 --create-domain-key | --createDomainKey | --createdomainkey | -cdk)
7240 _CMD="createDomainKey"
7241 ;;
7242 -ccr | --create-csr | --createCSR | --createcsr)
7243 _CMD="createCSR"
7244 ;;
7245 --deactivate)
7246 _CMD="deactivate"
7247 ;;
7248 --update-account | --updateaccount)
7249 _CMD="updateaccount"
7250 ;;
7251 --register-account | --registeraccount)
7252 _CMD="registeraccount"
7253 ;;
7254 --deactivate-account)
7255 _CMD="deactivateaccount"
7256 ;;
7257 --set-notify)
7258 _CMD="setnotify"
7259 ;;
7260 --set-default-ca)
7261 _CMD="setdefaultca"
7262 ;;
7263 --set-default-chain)
7264 _CMD="setdefaultchain"
7265 ;;
7266 -d | --domain)
7267 _dvalue="$2"
7268
7269 if [ "$_dvalue" ]; then
7270 if _startswith "$_dvalue" "-"; then
7271 _err "'$_dvalue' is not a valid domain for parameter '$1'"
7272 return 1
7273 fi
7274 if _is_idn "$_dvalue" && ! _exists idn; then
7275 _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
7276 return 1
7277 fi
7278
7279 if [ -z "$_domain" ]; then
7280 _domain="$_dvalue"
7281 else
7282 if [ "$_altdomains" = "$NO_VALUE" ]; then
7283 _altdomains="$_dvalue"
7284 else
7285 _altdomains="$_altdomains,$_dvalue"
7286 fi
7287 fi
7288 fi
7289
7290 shift
7291 ;;
7292
7293 -f | --force)
7294 FORCE="1"
7295 ;;
7296 --staging | --test)
7297 STAGE="1"
7298 ;;
7299 --server)
7300 _server="$2"
7301 shift
7302 ;;
7303 --debug)
7304 if [ -z "$2" ] || _startswith "$2" "-"; then
7305 DEBUG="$DEBUG_LEVEL_DEFAULT"
7306 else
7307 DEBUG="$2"
7308 shift
7309 fi
7310 ;;
7311 --output-insecure)
7312 export OUTPUT_INSECURE=1
7313 ;;
7314 -w | --webroot)
7315 wvalue="$2"
7316 if [ -z "$_webroot" ]; then
7317 _webroot="$wvalue"
7318 else
7319 _webroot="$_webroot,$wvalue"
7320 fi
7321 shift
7322 ;;
7323 --challenge-alias)
7324 cvalue="$2"
7325 _challenge_alias="$_challenge_alias$cvalue,"
7326 shift
7327 ;;
7328 --domain-alias)
7329 cvalue="$DNS_ALIAS_PREFIX$2"
7330 _challenge_alias="$_challenge_alias$cvalue,"
7331 shift
7332 ;;
7333 --standalone)
7334 wvalue="$NO_VALUE"
7335 if [ -z "$_webroot" ]; then
7336 _webroot="$wvalue"
7337 else
7338 _webroot="$_webroot,$wvalue"
7339 fi
7340 ;;
7341 --alpn)
7342 wvalue="$W_ALPN"
7343 if [ -z "$_webroot" ]; then
7344 _webroot="$wvalue"
7345 else
7346 _webroot="$_webroot,$wvalue"
7347 fi
7348 ;;
7349 --stateless)
7350 wvalue="$MODE_STATELESS"
7351 if [ -z "$_webroot" ]; then
7352 _webroot="$wvalue"
7353 else
7354 _webroot="$_webroot,$wvalue"
7355 fi
7356 ;;
7357 --local-address)
7358 lvalue="$2"
7359 _local_address="$_local_address$lvalue,"
7360 shift
7361 ;;
7362 --apache)
7363 wvalue="apache"
7364 if [ -z "$_webroot" ]; then
7365 _webroot="$wvalue"
7366 else
7367 _webroot="$_webroot,$wvalue"
7368 fi
7369 ;;
7370 --nginx)
7371 wvalue="$NGINX"
7372 if [ "$2" ] && ! _startswith "$2" "-"; then
7373 wvalue="$NGINX$2"
7374 shift
7375 fi
7376 if [ -z "$_webroot" ]; then
7377 _webroot="$wvalue"
7378 else
7379 _webroot="$_webroot,$wvalue"
7380 fi
7381 ;;
7382 --dns)
7383 wvalue="$W_DNS"
7384 if [ "$2" ] && ! _startswith "$2" "-"; then
7385 wvalue="$2"
7386 shift
7387 fi
7388 if [ -z "$_webroot" ]; then
7389 _webroot="$wvalue"
7390 else
7391 _webroot="$_webroot,$wvalue"
7392 fi
7393 ;;
7394 --dnssleep)
7395 _dnssleep="$2"
7396 Le_DNSSleep="$_dnssleep"
7397 shift
7398 ;;
7399 --keylength | -k)
7400 _keylength="$2"
7401 shift
7402 ;;
7403 -ak | --accountkeylength)
7404 _accountkeylength="$2"
7405 shift
7406 ;;
7407 --cert-file | --certpath)
7408 _cert_file="$2"
7409 shift
7410 ;;
7411 --key-file | --keypath)
7412 _key_file="$2"
7413 shift
7414 ;;
7415 --ca-file | --capath)
7416 _ca_file="$2"
7417 shift
7418 ;;
7419 --fullchain-file | --fullchainpath)
7420 _fullchain_file="$2"
7421 shift
7422 ;;
7423 --reloadcmd | --reloadCmd)
7424 _reloadcmd="$2"
7425 shift
7426 ;;
7427 --password)
7428 _password="$2"
7429 shift
7430 ;;
7431 --accountconf)
7432 _accountconf="$2"
7433 ACCOUNT_CONF_PATH="$_accountconf"
7434 shift
7435 ;;
7436 --home)
7437 LE_WORKING_DIR="$2"
7438 shift
7439 ;;
7440 --cert-home | --certhome)
7441 _certhome="$2"
7442 CERT_HOME="$_certhome"
7443 shift
7444 ;;
7445 --config-home)
7446 _confighome="$2"
7447 LE_CONFIG_HOME="$_confighome"
7448 shift
7449 ;;
7450 --useragent)
7451 _useragent="$2"
7452 USER_AGENT="$_useragent"
7453 shift
7454 ;;
7455 -m | --email | --accountemail)
7456 _accountemail="$2"
7457 export ACCOUNT_EMAIL="$_accountemail"
7458 shift
7459 ;;
7460 --accountkey)
7461 _accountkey="$2"
7462 ACCOUNT_KEY_PATH="$_accountkey"
7463 shift
7464 ;;
7465 --days)
7466 _days="$2"
7467 Le_RenewalDays="$_days"
7468 shift
7469 ;;
7470 --valid-from)
7471 _valid_from="$2"
7472 shift
7473 ;;
7474 --valid-to)
7475 _valid_to="$2"
7476 shift
7477 ;;
7478 --httpport)
7479 _httpport="$2"
7480 Le_HTTPPort="$_httpport"
7481 shift
7482 ;;
7483 --tlsport)
7484 _tlsport="$2"
7485 Le_TLSPort="$_tlsport"
7486 shift
7487 ;;
7488 --listraw)
7489 _listraw="raw"
7490 ;;
7491 -se | --stop-renew-on-error | --stopRenewOnError | --stoprenewonerror)
7492 _stopRenewOnError="1"
7493 ;;
7494 --insecure)
7495 #_insecure="1"
7496 HTTPS_INSECURE="1"
7497 ;;
7498 --ca-bundle)
7499 _ca_bundle="$(_readlink "$2")"
7500 CA_BUNDLE="$_ca_bundle"
7501 shift
7502 ;;
7503 --ca-path)
7504 _ca_path="$2"
7505 CA_PATH="$_ca_path"
7506 shift
7507 ;;
7508 --no-cron | --nocron)
7509 _nocron="1"
7510 ;;
7511 --no-profile | --noprofile)
7512 _noprofile="1"
7513 ;;
7514 --no-color)
7515 export ACME_NO_COLOR=1
7516 ;;
7517 --force-color)
7518 export ACME_FORCE_COLOR=1
7519 ;;
7520 --ecc)
7521 _ecc="isEcc"
7522 ;;
7523 --csr)
7524 _csr="$2"
7525 shift
7526 ;;
7527 --pre-hook)
7528 _pre_hook="$2"
7529 shift
7530 ;;
7531 --post-hook)
7532 _post_hook="$2"
7533 shift
7534 ;;
7535 --renew-hook)
7536 _renew_hook="$2"
7537 shift
7538 ;;
7539 --deploy-hook)
7540 if [ -z "$2" ] || _startswith "$2" "-"; then
7541 _usage "Please specify a value for '--deploy-hook'"
7542 return 1
7543 fi
7544 _deploy_hook="$_deploy_hook$2,"
7545 shift
7546 ;;
7547 --ocsp-must-staple | --ocsp)
7548 Le_OCSP_Staple="1"
7549 ;;
7550 --always-force-new-domain-key)
7551 if [ -z "$2" ] || _startswith "$2" "-"; then
7552 Le_ForceNewDomainKey=1
7553 else
7554 Le_ForceNewDomainKey="$2"
7555 shift
7556 fi
7557 ;;
7558 --yes-I-know-dns-manual-mode-enough-go-ahead-please)
7559 export FORCE_DNS_MANUAL=1
7560 ;;
7561 --log | --logfile)
7562 _log="1"
7563 _logfile="$2"
7564 if _startswith "$_logfile" '-'; then
7565 _logfile=""
7566 else
7567 shift
7568 fi
7569 LOG_FILE="$_logfile"
7570 if [ -z "$LOG_LEVEL" ]; then
7571 LOG_LEVEL="$DEFAULT_LOG_LEVEL"
7572 fi
7573 ;;
7574 --log-level)
7575 _log_level="$2"
7576 LOG_LEVEL="$_log_level"
7577 shift
7578 ;;
7579 --syslog)
7580 if ! _startswith "$2" '-'; then
7581 _syslog="$2"
7582 shift
7583 fi
7584 if [ -z "$_syslog" ]; then
7585 _syslog="$SYSLOG_LEVEL_DEFAULT"
7586 fi
7587 ;;
7588 --auto-upgrade)
7589 _auto_upgrade="$2"
7590 if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
7591 _auto_upgrade="1"
7592 else
7593 shift
7594 fi
7595 AUTO_UPGRADE="$_auto_upgrade"
7596 ;;
7597 --listen-v4)
7598 _listen_v4="1"
7599 Le_Listen_V4="$_listen_v4"
7600 ;;
7601 --listen-v6)
7602 _listen_v6="1"
7603 Le_Listen_V6="$_listen_v6"
7604 ;;
7605 --openssl-bin)
7606 _openssl_bin="$2"
7607 ACME_OPENSSL_BIN="$_openssl_bin"
7608 shift
7609 ;;
7610 --use-wget)
7611 _use_wget="1"
7612 ACME_USE_WGET="1"
7613 ;;
7614 --branch | -b)
7615 export BRANCH="$2"
7616 shift
7617 ;;
7618 --notify-hook)
7619 _nhook="$2"
7620 if _startswith "$_nhook" "-"; then
7621 _err "'$_nhook' is not a hook name for '$1'"
7622 return 1
7623 fi
7624 if [ "$_notify_hook" ]; then
7625 _notify_hook="$_notify_hook,$_nhook"
7626 else
7627 _notify_hook="$_nhook"
7628 fi
7629 shift
7630 ;;
7631 --notify-level)
7632 _nlevel="$2"
7633 if _startswith "$_nlevel" "-"; then
7634 _err "'$_nlevel' is not a integer for '$1'"
7635 return 1
7636 fi
7637 _notify_level="$_nlevel"
7638 shift
7639 ;;
7640 --notify-mode)
7641 _nmode="$2"
7642 if _startswith "$_nmode" "-"; then
7643 _err "'$_nmode' is not a integer for '$1'"
7644 return 1
7645 fi
7646 _notify_mode="$_nmode"
7647 shift
7648 ;;
7649 --revoke-reason)
7650 _revoke_reason="$2"
7651 if _startswith "$_revoke_reason" "-"; then
7652 _err "'$_revoke_reason' is not a integer for '$1'"
7653 return 1
7654 fi
7655 shift
7656 ;;
7657 --eab-kid)
7658 _eab_kid="$2"
7659 shift
7660 ;;
7661 --eab-hmac-key)
7662 _eab_hmac_key="$2"
7663 shift
7664 ;;
7665 --preferred-chain)
7666 _preferred_chain="$2"
7667 shift
7668 ;;
7669 *)
7670 _err "Unknown parameter : $1"
7671 return 1
7672 ;;
7673 esac
7674
7675 shift 1
7676 done
7677
7678 if [ "$_server" ]; then
7679 _selectServer "$_server" "${_ecc:-$_keylength}"
7680 _server="$ACME_DIRECTORY"
7681 fi
7682
7683 if [ "${_CMD}" != "install" ]; then
7684 if [ "$__INTERACTIVE" ] && ! _checkSudo; then
7685 if [ -z "$FORCE" ]; then
7686 #Use "echo" here, instead of _info. it's too early
7687 echo "It seems that you are using sudo, please read this link first:"
7688 echo "$_SUDO_WIKI"
7689 return 1
7690 fi
7691 fi
7692 __initHome
7693 if [ "$_log" ]; then
7694 if [ -z "$_logfile" ]; then
7695 _logfile="$DEFAULT_LOG_FILE"
7696 fi
7697 fi
7698 if [ "$_logfile" ]; then
7699 _saveaccountconf "LOG_FILE" "$_logfile"
7700 LOG_FILE="$_logfile"
7701 fi
7702
7703 if [ "$_log_level" ]; then
7704 _saveaccountconf "LOG_LEVEL" "$_log_level"
7705 LOG_LEVEL="$_log_level"
7706 fi
7707
7708 if [ "$_syslog" ]; then
7709 if _exists logger; then
7710 if [ "$_syslog" = "0" ]; then
7711 _clearaccountconf "SYS_LOG"
7712 else
7713 _saveaccountconf "SYS_LOG" "$_syslog"
7714 fi
7715 SYS_LOG="$_syslog"
7716 else
7717 _err "The 'logger' command is not found, can not enable syslog."
7718 _clearaccountconf "SYS_LOG"
7719 SYS_LOG=""
7720 fi
7721 fi
7722
7723 _processAccountConf
7724 fi
7725
7726 _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
7727
7728 if [ "$DEBUG" ]; then
7729 version
7730 if [ "$_server" ]; then
7731 _debug "Using server: $_server"
7732 fi
7733 fi
7734 _debug "Running cmd: ${_CMD}"
7735 case "${_CMD}" in
7736 install) install "$_nocron" "$_confighome" "$_noprofile" "$_accountemail" ;;
7737 uninstall) uninstall "$_nocron" ;;
7738 upgrade) upgrade ;;
7739 issue)
7740 issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias" "$_preferred_chain" "$_valid_from" "$_valid_to"
7741 ;;
7742 deploy)
7743 deploy "$_domain" "$_deploy_hook" "$_ecc"
7744 ;;
7745 signcsr)
7746 signcsr "$_csr" "$_webroot" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias" "$_preferred_chain"
7747 ;;
7748 showcsr)
7749 showcsr "$_csr" "$_domain"
7750 ;;
7751 installcert)
7752 installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
7753 ;;
7754 renew)
7755 renew "$_domain" "$_ecc" "$_server"
7756 ;;
7757 renewAll)
7758 renewAll "$_stopRenewOnError" "$_server"
7759 ;;
7760 revoke)
7761 revoke "$_domain" "$_ecc" "$_revoke_reason"
7762 ;;
7763 remove)
7764 remove "$_domain" "$_ecc"
7765 ;;
7766 deactivate)
7767 deactivate "$_domain,$_altdomains"
7768 ;;
7769 registeraccount)
7770 registeraccount "$_accountkeylength" "$_eab_kid" "$_eab_hmac_key"
7771 ;;
7772 updateaccount)
7773 updateaccount
7774 ;;
7775 deactivateaccount)
7776 deactivateaccount
7777 ;;
7778 list)
7779 list "$_listraw" "$_domain"
7780 ;;
7781 info)
7782 info "$_domain" "$_ecc"
7783 ;;
7784 installcronjob) installcronjob "$_confighome" ;;
7785 uninstallcronjob) uninstallcronjob ;;
7786 cron) cron ;;
7787 toPkcs)
7788 toPkcs "$_domain" "$_password" "$_ecc"
7789 ;;
7790 toPkcs8)
7791 toPkcs8 "$_domain" "$_ecc"
7792 ;;
7793 createAccountKey)
7794 createAccountKey "$_accountkeylength"
7795 ;;
7796 createDomainKey)
7797 createDomainKey "$_domain" "$_keylength"
7798 ;;
7799 createCSR)
7800 createCSR "$_domain" "$_altdomains" "$_ecc"
7801 ;;
7802 setnotify)
7803 setnotify "$_notify_hook" "$_notify_level" "$_notify_mode"
7804 ;;
7805 setdefaultca)
7806 setdefaultca
7807 ;;
7808 setdefaultchain)
7809 setdefaultchain "$_preferred_chain"
7810 ;;
7811 *)
7812 if [ "$_CMD" ]; then
7813 _err "Invalid command: $_CMD"
7814 fi
7815 showhelp
7816 return 1
7817 ;;
7818 esac
7819 _ret="$?"
7820 if [ "$_ret" != "0" ]; then
7821 return $_ret
7822 fi
7823
7824 if [ "${_CMD}" = "install" ]; then
7825 if [ "$_log" ]; then
7826 if [ -z "$LOG_FILE" ]; then
7827 LOG_FILE="$DEFAULT_LOG_FILE"
7828 fi
7829 _saveaccountconf "LOG_FILE" "$LOG_FILE"
7830 fi
7831
7832 if [ "$_log_level" ]; then
7833 _saveaccountconf "LOG_LEVEL" "$_log_level"
7834 fi
7835
7836 if [ "$_syslog" ]; then
7837 if _exists logger; then
7838 if [ "$_syslog" = "0" ]; then
7839 _clearaccountconf "SYS_LOG"
7840 else
7841 _saveaccountconf "SYS_LOG" "$_syslog"
7842 fi
7843 else
7844 _err "The 'logger' command is not found, can not enable syslog."
7845 _clearaccountconf "SYS_LOG"
7846 SYS_LOG=""
7847 fi
7848 fi
7849
7850 _processAccountConf
7851 fi
7852
7853 }
7854
7855 main() {
7856 [ -z "$1" ] && showhelp && return
7857 if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
7858 }
7859
7860 main "$@"