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