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