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