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