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