]> git.proxmox.com Git - mirror_acme.sh.git/blob - acme.sh
support to specify the nginx or site conf for nginx mode.
[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 _debug "_CURL" "$_CURL"
1701 if [ "$needbase64" ]; then
1702 if [ "$_postContentType" ]; then
1703 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)"
1704 else
1705 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
1706 fi
1707 else
1708 if [ "$_postContentType" ]; then
1709 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")"
1710 else
1711 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
1712 fi
1713 fi
1714 _ret="$?"
1715 if [ "$_ret" != "0" ]; then
1716 _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
1717 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1718 _err "Here is the curl dump log:"
1719 _err "$(cat "$_CURL_DUMP")"
1720 fi
1721 fi
1722 elif [ "$_ACME_WGET" ]; then
1723 _WGET="$_ACME_WGET"
1724 if [ "$HTTPS_INSECURE" ]; then
1725 _WGET="$_WGET --no-check-certificate "
1726 fi
1727 _debug "_WGET" "$_WGET"
1728 if [ "$needbase64" ]; then
1729 if [ "$httpmethod" = "POST" ]; then
1730 if [ "$_postContentType" ]; then
1731 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)"
1732 else
1733 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)"
1734 fi
1735 else
1736 if [ "$_postContentType" ]; then
1737 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)"
1738 else
1739 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)"
1740 fi
1741 fi
1742 else
1743 if [ "$httpmethod" = "POST" ]; then
1744 if [ "$_postContentType" ]; then
1745 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")"
1746 else
1747 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")"
1748 fi
1749 else
1750 if [ "$_postContentType" ]; then
1751 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")"
1752 else
1753 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")"
1754 fi
1755 fi
1756 fi
1757 _ret="$?"
1758 if [ "$_ret" = "8" ]; then
1759 _ret=0
1760 _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
1761 fi
1762 if [ "$_ret" != "0" ]; then
1763 _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
1764 fi
1765 _sed_i "s/^ *//g" "$HTTP_HEADER"
1766 else
1767 _ret="$?"
1768 _err "Neither curl nor wget is found, can not do $httpmethod."
1769 fi
1770 _debug "_ret" "$_ret"
1771 printf "%s" "$response"
1772 return $_ret
1773 }
1774
1775 # url getheader timeout
1776 _get() {
1777 _debug GET
1778 url="$1"
1779 onlyheader="$2"
1780 t="$3"
1781 _debug url "$url"
1782 _debug "timeout=$t"
1783
1784 _inithttp
1785
1786 if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
1787 _CURL="$_ACME_CURL"
1788 if [ "$HTTPS_INSECURE" ]; then
1789 _CURL="$_CURL --insecure "
1790 fi
1791 if [ "$t" ]; then
1792 _CURL="$_CURL --connect-timeout $t"
1793 fi
1794 _debug "_CURL" "$_CURL"
1795 if [ "$onlyheader" ]; then
1796 $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
1797 else
1798 $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
1799 fi
1800 ret=$?
1801 if [ "$ret" != "0" ]; then
1802 _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
1803 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1804 _err "Here is the curl dump log:"
1805 _err "$(cat "$_CURL_DUMP")"
1806 fi
1807 fi
1808 elif [ "$_ACME_WGET" ]; then
1809 _WGET="$_ACME_WGET"
1810 if [ "$HTTPS_INSECURE" ]; then
1811 _WGET="$_WGET --no-check-certificate "
1812 fi
1813 if [ "$t" ]; then
1814 _WGET="$_WGET --timeout=$t"
1815 fi
1816 _debug "_WGET" "$_WGET"
1817 if [ "$onlyheader" ]; then
1818 $_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'
1819 else
1820 $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
1821 fi
1822 ret=$?
1823 if [ "$ret" = "8" ]; then
1824 ret=0
1825 _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
1826 fi
1827 if [ "$ret" != "0" ]; then
1828 _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
1829 fi
1830 else
1831 ret=$?
1832 _err "Neither curl nor wget is found, can not do GET."
1833 fi
1834 _debug "ret" "$ret"
1835 return $ret
1836 }
1837
1838 _head_n() {
1839 head -n "$1"
1840 }
1841
1842 _tail_n() {
1843 if ! tail -n "$1" 2>/dev/null; then
1844 #fix for solaris
1845 tail -"$1"
1846 fi
1847 }
1848
1849 # url payload needbase64 keyfile
1850 _send_signed_request() {
1851 url=$1
1852 payload=$2
1853 needbase64=$3
1854 keyfile=$4
1855 if [ -z "$keyfile" ]; then
1856 keyfile="$ACCOUNT_KEY_PATH"
1857 fi
1858 _debug url "$url"
1859 _debug payload "$payload"
1860
1861 if ! _calcjwk "$keyfile"; then
1862 return 1
1863 fi
1864
1865 __request_conent_type="$CONTENT_TYPE_JSON"
1866
1867 payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
1868 _debug3 payload64 "$payload64"
1869
1870 MAX_REQUEST_RETRY_TIMES=20
1871 _sleep_retry_sec=1
1872 _request_retry_times=0
1873 while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
1874 _request_retry_times=$(_math "$_request_retry_times" + 1)
1875 _debug3 _request_retry_times "$_request_retry_times"
1876 if [ -z "$_CACHED_NONCE" ]; then
1877 _headers=""
1878 if [ "$ACME_NEW_NONCE" ]; then
1879 _debug2 "Get nonce with HEAD. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
1880 nonceurl="$ACME_NEW_NONCE"
1881 if _post "" "$nonceurl" "" "HEAD" "$__request_conent_type"; then
1882 _headers="$(cat "$HTTP_HEADER")"
1883 _debug2 _headers "$_headers"
1884 _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
1885 fi
1886 fi
1887 if [ -z "$_CACHED_NONCE" ]; then
1888 _debug2 "Get nonce with GET. ACME_DIRECTORY" "$ACME_DIRECTORY"
1889 nonceurl="$ACME_DIRECTORY"
1890 _headers="$(_get "$nonceurl" "onlyheader")"
1891 _debug2 _headers "$_headers"
1892 _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
1893 fi
1894 if [ -z "$_CACHED_NONCE" ] && [ "$ACME_NEW_NONCE" ]; then
1895 _debug2 "Get nonce with GET. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
1896 nonceurl="$ACME_NEW_NONCE"
1897 _headers="$(_get "$nonceurl" "onlyheader")"
1898 _debug2 _headers "$_headers"
1899 _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
1900 fi
1901 _debug2 _CACHED_NONCE "$_CACHED_NONCE"
1902 if [ "$?" != "0" ]; then
1903 _err "Can not connect to $nonceurl to get nonce."
1904 return 1
1905 fi
1906 else
1907 _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
1908 fi
1909 nonce="$_CACHED_NONCE"
1910 _debug2 nonce "$nonce"
1911 if [ -z "$nonce" ]; then
1912 _info "Could not get nonce, let's try again."
1913 _sleep 2
1914 continue
1915 fi
1916 if [ "$ACME_VERSION" = "2" ]; then
1917 if [ "$url" = "$ACME_NEW_ACCOUNT" ] || [ "$url" = "$ACME_REVOKE_CERT" ]; then
1918 protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
1919 else
1920 protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"kid\": \"${ACCOUNT_URL}\""'}'
1921 fi
1922 else
1923 protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
1924 fi
1925 _debug3 protected "$protected"
1926
1927 protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
1928 _debug3 protected64 "$protected64"
1929
1930 if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
1931 _err "Sign request failed."
1932 return 1
1933 fi
1934 _debug3 _sig_t "$_sig_t"
1935
1936 sig="$(printf "%s" "$_sig_t" | _url_replace)"
1937 _debug3 sig "$sig"
1938
1939 body="{\"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
1940 _debug3 body "$body"
1941
1942 response="$(_post "$body" "$url" "$needbase64" "POST" "$__request_conent_type")"
1943 _CACHED_NONCE=""
1944
1945 if [ "$?" != "0" ]; then
1946 _err "Can not post to $url"
1947 return 1
1948 fi
1949
1950 responseHeaders="$(cat "$HTTP_HEADER")"
1951 _debug2 responseHeaders "$responseHeaders"
1952
1953 code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
1954 _debug code "$code"
1955
1956 _debug2 original "$response"
1957 if echo "$responseHeaders" | grep -i "Content-Type: application/json" >/dev/null 2>&1; then
1958 response="$(echo "$response" | _normalizeJson)"
1959 fi
1960 _debug2 response "$response"
1961
1962 _CACHED_NONCE="$(echo "$responseHeaders" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
1963
1964 if ! _startswith "$code" "2"; then
1965 _body="$response"
1966 if [ "$needbase64" ]; then
1967 _body="$(echo "$_body" | _dbase64 multiline)"
1968 _debug3 _body "$_body"
1969 fi
1970
1971 if _contains "$_body" "JWS has invalid anti-replay nonce" || _contains "$_body" "JWS has an invalid anti-replay nonce"; then
1972 _info "It seems the CA server is busy now, let's wait and retry. Sleeping $_sleep_retry_sec seconds."
1973 _CACHED_NONCE=""
1974 _sleep $_sleep_retry_sec
1975 continue
1976 fi
1977 fi
1978 break
1979 done
1980
1981 }
1982
1983 #setopt "file" "opt" "=" "value" [";"]
1984 _setopt() {
1985 __conf="$1"
1986 __opt="$2"
1987 __sep="$3"
1988 __val="$4"
1989 __end="$5"
1990 if [ -z "$__opt" ]; then
1991 _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
1992 return
1993 fi
1994 if [ ! -f "$__conf" ]; then
1995 touch "$__conf"
1996 fi
1997
1998 if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
1999 _debug3 OK
2000 if _contains "$__val" "&"; then
2001 __val="$(echo "$__val" | sed 's/&/\\&/g')"
2002 fi
2003 text="$(cat "$__conf")"
2004 printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
2005
2006 elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
2007 if _contains "$__val" "&"; then
2008 __val="$(echo "$__val" | sed 's/&/\\&/g')"
2009 fi
2010 text="$(cat "$__conf")"
2011 printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
2012
2013 else
2014 _debug3 APP
2015 echo "$__opt$__sep$__val$__end" >>"$__conf"
2016 fi
2017 _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
2018 }
2019
2020 #_save_conf file key value base64encode
2021 #save to conf
2022 _save_conf() {
2023 _s_c_f="$1"
2024 _sdkey="$2"
2025 _sdvalue="$3"
2026 _b64encode="$4"
2027 if [ "$_sdvalue" ] && [ "$_b64encode" ]; then
2028 _sdvalue="${B64CONF_START}$(printf "%s" "${_sdvalue}" | _base64)${B64CONF_END}"
2029 fi
2030 if [ "$_s_c_f" ]; then
2031 _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
2032 else
2033 _err "config file is empty, can not save $_sdkey=$_sdvalue"
2034 fi
2035 }
2036
2037 #_clear_conf file key
2038 _clear_conf() {
2039 _c_c_f="$1"
2040 _sdkey="$2"
2041 if [ "$_c_c_f" ]; then
2042 _conf_data="$(cat "$_c_c_f")"
2043 echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
2044 else
2045 _err "config file is empty, can not clear"
2046 fi
2047 }
2048
2049 #_read_conf file key
2050 _read_conf() {
2051 _r_c_f="$1"
2052 _sdkey="$2"
2053 if [ -f "$_r_c_f" ]; then
2054 _sdv="$(
2055 eval "$(grep "^$_sdkey *=" "$_r_c_f")"
2056 eval "printf \"%s\" \"\$$_sdkey\""
2057 )"
2058 if _startswith "$_sdv" "${B64CONF_START}" && _endswith "$_sdv" "${B64CONF_END}"; then
2059 _sdv="$(echo "$_sdv" | sed "s/${B64CONF_START}//" | sed "s/${B64CONF_END}//" | _dbase64)"
2060 fi
2061 printf "%s" "$_sdv"
2062 else
2063 _debug "config file is empty, can not read $_sdkey"
2064 fi
2065 }
2066
2067 #_savedomainconf key value base64encode
2068 #save to domain.conf
2069 _savedomainconf() {
2070 _save_conf "$DOMAIN_CONF" "$@"
2071 }
2072
2073 #_cleardomainconf key
2074 _cleardomainconf() {
2075 _clear_conf "$DOMAIN_CONF" "$1"
2076 }
2077
2078 #_readdomainconf key
2079 _readdomainconf() {
2080 _read_conf "$DOMAIN_CONF" "$1"
2081 }
2082
2083 #key value base64encode
2084 _savedeployconf() {
2085 _savedomainconf "SAVED_$1" "$2" "$3"
2086 #remove later
2087 _cleardomainconf "$1"
2088 }
2089
2090 #key
2091 _getdeployconf() {
2092 _rac_key="$1"
2093 _rac_value="$(eval echo \$"$_rac_key")"
2094 if [ "$_rac_value" ]; then
2095 if _startswith "$_rac_value" '"' && _endswith "$_rac_value" '"'; then
2096 _debug2 "trim quotation marks"
2097 eval "export $_rac_key=$_rac_value"
2098 fi
2099 return 0 # do nothing
2100 fi
2101 _saved=$(_readdomainconf "SAVED_$_rac_key")
2102 eval "export $_rac_key=$_saved"
2103 }
2104
2105 #_saveaccountconf key value base64encode
2106 _saveaccountconf() {
2107 _save_conf "$ACCOUNT_CONF_PATH" "$@"
2108 }
2109
2110 #key value base64encode
2111 _saveaccountconf_mutable() {
2112 _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2" "$3"
2113 #remove later
2114 _clearaccountconf "$1"
2115 }
2116
2117 #key
2118 _readaccountconf() {
2119 _read_conf "$ACCOUNT_CONF_PATH" "$1"
2120 }
2121
2122 #key
2123 _readaccountconf_mutable() {
2124 _rac_key="$1"
2125 _readaccountconf "SAVED_$_rac_key"
2126 }
2127
2128 #_clearaccountconf key
2129 _clearaccountconf() {
2130 _clear_conf "$ACCOUNT_CONF_PATH" "$1"
2131 }
2132
2133 #_savecaconf key value
2134 _savecaconf() {
2135 _save_conf "$CA_CONF" "$1" "$2"
2136 }
2137
2138 #_readcaconf key
2139 _readcaconf() {
2140 _read_conf "$CA_CONF" "$1"
2141 }
2142
2143 #_clearaccountconf key
2144 _clearcaconf() {
2145 _clear_conf "$CA_CONF" "$1"
2146 }
2147
2148 # content localaddress
2149 _startserver() {
2150 content="$1"
2151 ncaddr="$2"
2152 _debug "content" "$content"
2153 _debug "ncaddr" "$ncaddr"
2154
2155 _debug "startserver: $$"
2156
2157 _debug Le_HTTPPort "$Le_HTTPPort"
2158 _debug Le_Listen_V4 "$Le_Listen_V4"
2159 _debug Le_Listen_V6 "$Le_Listen_V6"
2160
2161 _NC="socat"
2162 if [ "$Le_Listen_V4" ]; then
2163 _NC="$_NC -4"
2164 elif [ "$Le_Listen_V6" ]; then
2165 _NC="$_NC -6"
2166 fi
2167
2168 if [ "$DEBUG" ] && [ "$DEBUG" -gt "1" ]; then
2169 _NC="$_NC -d -d -v"
2170 fi
2171
2172 SOCAT_OPTIONS=TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork
2173
2174 #Adding bind to local-address
2175 if [ "$ncaddr" ]; then
2176 SOCAT_OPTIONS="$SOCAT_OPTIONS,bind=${ncaddr}"
2177 fi
2178
2179 _content_len="$(printf "%s" "$content" | wc -c)"
2180 _debug _content_len "$_content_len"
2181 _debug "_NC" "$_NC $SOCAT_OPTIONS"
2182 $_NC $SOCAT_OPTIONS SYSTEM:"sleep 1; \
2183 echo 'HTTP/1.0 200 OK'; \
2184 echo 'Content-Length\: $_content_len'; \
2185 echo ''; \
2186 printf -- '$content';" &
2187 serverproc="$!"
2188 }
2189
2190 _stopserver() {
2191 pid="$1"
2192 _debug "pid" "$pid"
2193 if [ -z "$pid" ]; then
2194 return
2195 fi
2196
2197 kill $pid
2198
2199 }
2200
2201 # sleep sec
2202 _sleep() {
2203 _sleep_sec="$1"
2204 if [ "$__INTERACTIVE" ]; then
2205 _sleep_c="$_sleep_sec"
2206 while [ "$_sleep_c" -ge "0" ]; do
2207 printf "\r \r"
2208 __green "$_sleep_c"
2209 _sleep_c="$(_math "$_sleep_c" - 1)"
2210 sleep 1
2211 done
2212 printf "\r"
2213 else
2214 sleep "$_sleep_sec"
2215 fi
2216 }
2217
2218 # _starttlsserver san_a san_b port content _ncaddr acmeValidationv1
2219 _starttlsserver() {
2220 _info "Starting tls server."
2221 san_a="$1"
2222 san_b="$2"
2223 port="$3"
2224 content="$4"
2225 opaddr="$5"
2226 acmeValidationv1="$6"
2227
2228 _debug san_a "$san_a"
2229 _debug san_b "$san_b"
2230 _debug port "$port"
2231 _debug acmeValidationv1 "$acmeValidationv1"
2232
2233 #create key TLS_KEY
2234 if ! _createkey "2048" "$TLS_KEY"; then
2235 _err "Create tls validation key error."
2236 return 1
2237 fi
2238
2239 #create csr
2240 alt="$san_a"
2241 if [ "$san_b" ]; then
2242 alt="$alt,$san_b"
2243 fi
2244 if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$acmeValidationv1"; then
2245 _err "Create tls validation csr error."
2246 return 1
2247 fi
2248
2249 #self signed
2250 if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
2251 _err "Create tls validation cert error."
2252 return 1
2253 fi
2254
2255 __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
2256 if [ "$opaddr" ]; then
2257 __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
2258 else
2259 __S_OPENSSL="$__S_OPENSSL -accept $port"
2260 fi
2261
2262 _debug Le_Listen_V4 "$Le_Listen_V4"
2263 _debug Le_Listen_V6 "$Le_Listen_V6"
2264 if [ "$Le_Listen_V4" ]; then
2265 __S_OPENSSL="$__S_OPENSSL -4"
2266 elif [ "$Le_Listen_V6" ]; then
2267 __S_OPENSSL="$__S_OPENSSL -6"
2268 fi
2269
2270 if [ "$acmeValidationv1" ]; then
2271 __S_OPENSSL="$__S_OPENSSL -alpn acme-tls/1"
2272 fi
2273
2274 _debug "$__S_OPENSSL"
2275 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
2276 $__S_OPENSSL -tlsextdebug &
2277 else
2278 $__S_OPENSSL >/dev/null 2>&1 &
2279 fi
2280
2281 serverproc="$!"
2282 sleep 1
2283 _debug serverproc "$serverproc"
2284 }
2285
2286 #file
2287 _readlink() {
2288 _rf="$1"
2289 if ! readlink -f "$_rf" 2>/dev/null; then
2290 if _startswith "$_rf" "/"; then
2291 echo "$_rf"
2292 return 0
2293 fi
2294 echo "$(pwd)/$_rf" | _conapath
2295 fi
2296 }
2297
2298 _conapath() {
2299 sed "s#/\./#/#g"
2300 }
2301
2302 __initHome() {
2303 if [ -z "$_SCRIPT_HOME" ]; then
2304 if _exists readlink && _exists dirname; then
2305 _debug "Lets find script dir."
2306 _debug "_SCRIPT_" "$_SCRIPT_"
2307 _script="$(_readlink "$_SCRIPT_")"
2308 _debug "_script" "$_script"
2309 _script_home="$(dirname "$_script")"
2310 _debug "_script_home" "$_script_home"
2311 if [ -d "$_script_home" ]; then
2312 _SCRIPT_HOME="$_script_home"
2313 else
2314 _err "It seems the script home is not correct:$_script_home"
2315 fi
2316 fi
2317 fi
2318
2319 # if [ -z "$LE_WORKING_DIR" ]; then
2320 # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
2321 # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
2322 # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
2323 # else
2324 # LE_WORKING_DIR="$_SCRIPT_HOME"
2325 # fi
2326 # fi
2327
2328 if [ -z "$LE_WORKING_DIR" ]; then
2329 _debug "Using default home:$DEFAULT_INSTALL_HOME"
2330 LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
2331 fi
2332 export LE_WORKING_DIR
2333
2334 if [ -z "$LE_CONFIG_HOME" ]; then
2335 LE_CONFIG_HOME="$LE_WORKING_DIR"
2336 fi
2337 _debug "Using config home:$LE_CONFIG_HOME"
2338 export LE_CONFIG_HOME
2339
2340 _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
2341
2342 if [ -z "$ACCOUNT_CONF_PATH" ]; then
2343 if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
2344 . "$_DEFAULT_ACCOUNT_CONF_PATH"
2345 fi
2346 fi
2347
2348 if [ -z "$ACCOUNT_CONF_PATH" ]; then
2349 ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
2350 fi
2351
2352 DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
2353
2354 DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
2355
2356 if [ -z "$LE_TEMP_DIR" ]; then
2357 LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
2358 fi
2359 }
2360
2361 #server
2362 _initAPI() {
2363 _api_server="${1:-$ACME_DIRECTORY}"
2364 _debug "_init api for server: $_api_server"
2365
2366 if [ -z "$ACME_NEW_ACCOUNT" ]; then
2367 response=$(_get "$_api_server")
2368 if [ "$?" != "0" ]; then
2369 _debug2 "response" "$response"
2370 _err "Can not init api."
2371 return 1
2372 fi
2373 _debug2 "response" "$response"
2374
2375 ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'key-change" *: *"[^"]*"' | cut -d '"' -f 3)
2376 if [ -z "$ACME_KEY_CHANGE" ]; then
2377 ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
2378 fi
2379 export ACME_KEY_CHANGE
2380
2381 ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'new-authz" *: *"[^"]*"' | cut -d '"' -f 3)
2382 if [ -z "$ACME_NEW_AUTHZ" ]; then
2383 ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
2384 fi
2385 export ACME_NEW_AUTHZ
2386
2387 ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-cert" *: *"[^"]*"' | cut -d '"' -f 3)
2388 ACME_NEW_ORDER_RES="new-cert"
2389 if [ -z "$ACME_NEW_ORDER" ]; then
2390 ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-order" *: *"[^"]*"' | cut -d '"' -f 3)
2391 ACME_NEW_ORDER_RES="new-order"
2392 if [ -z "$ACME_NEW_ORDER" ]; then
2393 ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
2394 fi
2395 fi
2396 export ACME_NEW_ORDER
2397 export ACME_NEW_ORDER_RES
2398
2399 ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-reg" *: *"[^"]*"' | cut -d '"' -f 3)
2400 ACME_NEW_ACCOUNT_RES="new-reg"
2401 if [ -z "$ACME_NEW_ACCOUNT" ]; then
2402 ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-account" *: *"[^"]*"' | cut -d '"' -f 3)
2403 ACME_NEW_ACCOUNT_RES="new-account"
2404 if [ -z "$ACME_NEW_ACCOUNT" ]; then
2405 ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
2406 if [ "$ACME_NEW_ACCOUNT" ]; then
2407 export ACME_VERSION=2
2408 fi
2409 fi
2410 fi
2411 export ACME_NEW_ACCOUNT
2412 export ACME_NEW_ACCOUNT_RES
2413
2414 ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revoke-cert" *: *"[^"]*"' | cut -d '"' -f 3)
2415 if [ -z "$ACME_REVOKE_CERT" ]; then
2416 ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
2417 fi
2418 export ACME_REVOKE_CERT
2419
2420 ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'new-nonce" *: *"[^"]*"' | cut -d '"' -f 3)
2421 if [ -z "$ACME_NEW_NONCE" ]; then
2422 ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
2423 fi
2424 export ACME_NEW_NONCE
2425
2426 ACME_AGREEMENT=$(echo "$response" | _egrep_o 'terms-of-service" *: *"[^"]*"' | cut -d '"' -f 3)
2427 if [ -z "$ACME_AGREEMENT" ]; then
2428 ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
2429 fi
2430 export ACME_AGREEMENT
2431
2432 _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
2433 _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
2434 _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
2435 _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
2436 _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
2437 _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
2438 _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
2439 _debug "ACME_VERSION" "$ACME_VERSION"
2440
2441 fi
2442 }
2443
2444 #[domain] [keylength or isEcc flag]
2445 _initpath() {
2446 domain="$1"
2447 _ilength="$2"
2448
2449 __initHome
2450
2451 if [ -f "$ACCOUNT_CONF_PATH" ]; then
2452 . "$ACCOUNT_CONF_PATH"
2453 fi
2454
2455 if [ "$ACME_IN_CRON" ]; then
2456 if [ ! "$_USER_PATH_EXPORTED" ]; then
2457 _USER_PATH_EXPORTED=1
2458 export PATH="$USER_PATH:$PATH"
2459 fi
2460 fi
2461
2462 if [ -z "$CA_HOME" ]; then
2463 CA_HOME="$DEFAULT_CA_HOME"
2464 fi
2465
2466 if [ "$ACME_VERSION" = "2" ]; then
2467 DEFAULT_CA="$LETSENCRYPT_CA_V2"
2468 DEFAULT_STAGING_CA="$LETSENCRYPT_STAGING_CA_V2"
2469 fi
2470
2471 if [ -z "$ACME_DIRECTORY" ]; then
2472 if [ -z "$STAGE" ]; then
2473 ACME_DIRECTORY="$DEFAULT_CA"
2474 else
2475 ACME_DIRECTORY="$DEFAULT_STAGING_CA"
2476 _info "Using stage ACME_DIRECTORY: $ACME_DIRECTORY"
2477 fi
2478 fi
2479
2480 _debug ACME_DIRECTORY "$ACME_DIRECTORY"
2481 _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
2482 _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
2483
2484 CA_DIR="$CA_HOME/$_ACME_SERVER_HOST"
2485
2486 _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
2487
2488 if [ -z "$CA_CONF" ]; then
2489 CA_CONF="$_DEFAULT_CA_CONF"
2490 fi
2491 _debug3 CA_CONF "$CA_CONF"
2492
2493 if [ -f "$CA_CONF" ]; then
2494 . "$CA_CONF"
2495 fi
2496
2497 if [ -z "$ACME_DIR" ]; then
2498 ACME_DIR="/home/.acme"
2499 fi
2500
2501 if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
2502 APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
2503 fi
2504
2505 if [ -z "$USER_AGENT" ]; then
2506 USER_AGENT="$DEFAULT_USER_AGENT"
2507 fi
2508
2509 if [ -z "$HTTP_HEADER" ]; then
2510 HTTP_HEADER="$LE_CONFIG_HOME/http.header"
2511 fi
2512
2513 _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
2514 _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
2515
2516 _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
2517 _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
2518 if [ -z "$ACCOUNT_KEY_PATH" ]; then
2519 ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
2520 fi
2521
2522 if [ -z "$ACCOUNT_JSON_PATH" ]; then
2523 ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
2524 fi
2525
2526 _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
2527 if [ -z "$CERT_HOME" ]; then
2528 CERT_HOME="$_DEFAULT_CERT_HOME"
2529 fi
2530
2531 if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
2532 ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
2533 fi
2534
2535 if [ -z "$domain" ]; then
2536 return 0
2537 fi
2538
2539 if [ -z "$DOMAIN_PATH" ]; then
2540 domainhome="$CERT_HOME/$domain"
2541 domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
2542
2543 DOMAIN_PATH="$domainhome"
2544
2545 if _isEccKey "$_ilength"; then
2546 DOMAIN_PATH="$domainhomeecc"
2547 else
2548 if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
2549 _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
2550 fi
2551 fi
2552 _debug DOMAIN_PATH "$DOMAIN_PATH"
2553 fi
2554
2555 if [ -z "$DOMAIN_BACKUP_PATH" ]; then
2556 DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
2557 fi
2558
2559 if [ -z "$DOMAIN_CONF" ]; then
2560 DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
2561 fi
2562
2563 if [ -z "$DOMAIN_SSL_CONF" ]; then
2564 DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
2565 fi
2566
2567 if [ -z "$CSR_PATH" ]; then
2568 CSR_PATH="$DOMAIN_PATH/$domain.csr"
2569 fi
2570 if [ -z "$CERT_KEY_PATH" ]; then
2571 CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
2572 fi
2573 if [ -z "$CERT_PATH" ]; then
2574 CERT_PATH="$DOMAIN_PATH/$domain.cer"
2575 fi
2576 if [ -z "$CA_CERT_PATH" ]; then
2577 CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
2578 fi
2579 if [ -z "$CERT_FULLCHAIN_PATH" ]; then
2580 CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
2581 fi
2582 if [ -z "$CERT_PFX_PATH" ]; then
2583 CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
2584 fi
2585 if [ -z "$CERT_PKCS8_PATH" ]; then
2586 CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
2587 fi
2588
2589 if [ -z "$TLS_CONF" ]; then
2590 TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
2591 fi
2592 if [ -z "$TLS_CERT" ]; then
2593 TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
2594 fi
2595 if [ -z "$TLS_KEY" ]; then
2596 TLS_KEY="$DOMAIN_PATH/tls.validation.key"
2597 fi
2598 if [ -z "$TLS_CSR" ]; then
2599 TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
2600 fi
2601
2602 }
2603
2604 _exec() {
2605 if [ -z "$_EXEC_TEMP_ERR" ]; then
2606 _EXEC_TEMP_ERR="$(_mktemp)"
2607 fi
2608
2609 if [ "$_EXEC_TEMP_ERR" ]; then
2610 eval "$@ 2>>$_EXEC_TEMP_ERR"
2611 else
2612 eval "$@"
2613 fi
2614 }
2615
2616 _exec_err() {
2617 [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
2618 }
2619
2620 _apachePath() {
2621 _APACHECTL="apachectl"
2622 if ! _exists apachectl; then
2623 if _exists apache2ctl; then
2624 _APACHECTL="apache2ctl"
2625 else
2626 _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
2627 _err "Please use webroot mode to try again."
2628 return 1
2629 fi
2630 fi
2631
2632 if ! _exec $_APACHECTL -V >/dev/null; then
2633 _exec_err
2634 return 1
2635 fi
2636
2637 if [ "$APACHE_HTTPD_CONF" ]; then
2638 _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
2639 httpdconf="$APACHE_HTTPD_CONF"
2640 httpdconfname="$(basename "$httpdconfname")"
2641 else
2642 httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
2643 _debug httpdconfname "$httpdconfname"
2644
2645 if [ -z "$httpdconfname" ]; then
2646 _err "Can not read apache config file."
2647 return 1
2648 fi
2649
2650 if _startswith "$httpdconfname" '/'; then
2651 httpdconf="$httpdconfname"
2652 httpdconfname="$(basename "$httpdconfname")"
2653 else
2654 httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
2655 _debug httpdroot "$httpdroot"
2656 httpdconf="$httpdroot/$httpdconfname"
2657 httpdconfname="$(basename "$httpdconfname")"
2658 fi
2659 fi
2660 _debug httpdconf "$httpdconf"
2661 _debug httpdconfname "$httpdconfname"
2662 if [ ! -f "$httpdconf" ]; then
2663 _err "Apache Config file not found" "$httpdconf"
2664 return 1
2665 fi
2666 return 0
2667 }
2668
2669 _restoreApache() {
2670 if [ -z "$usingApache" ]; then
2671 return 0
2672 fi
2673 _initpath
2674 if ! _apachePath; then
2675 return 1
2676 fi
2677
2678 if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
2679 _debug "No config file to restore."
2680 return 0
2681 fi
2682
2683 cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
2684 _debug "Restored: $httpdconf."
2685 if ! _exec $_APACHECTL -t; then
2686 _exec_err
2687 _err "Sorry, restore apache config error, please contact me."
2688 return 1
2689 fi
2690 _debug "Restored successfully."
2691 rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
2692 return 0
2693 }
2694
2695 _setApache() {
2696 _initpath
2697 if ! _apachePath; then
2698 return 1
2699 fi
2700
2701 #test the conf first
2702 _info "Checking if there is an error in the apache config file before starting."
2703
2704 if ! _exec "$_APACHECTL" -t >/dev/null; then
2705 _exec_err
2706 _err "The apache config file has error, please fix it first, then try again."
2707 _err "Don't worry, there is nothing changed to your system."
2708 return 1
2709 else
2710 _info "OK"
2711 fi
2712
2713 #backup the conf
2714 _debug "Backup apache config file" "$httpdconf"
2715 if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
2716 _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
2717 _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
2718 return 1
2719 fi
2720 _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
2721 _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
2722 _info "The backup file will be deleted on success, just forget it."
2723
2724 #add alias
2725
2726 apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
2727 _debug "apacheVer" "$apacheVer"
2728 apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
2729 apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
2730
2731 if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
2732 echo "
2733 Alias /.well-known/acme-challenge $ACME_DIR
2734
2735 <Directory $ACME_DIR >
2736 Require all granted
2737 </Directory>
2738 " >>"$httpdconf"
2739 else
2740 echo "
2741 Alias /.well-known/acme-challenge $ACME_DIR
2742
2743 <Directory $ACME_DIR >
2744 Order allow,deny
2745 Allow from all
2746 </Directory>
2747 " >>"$httpdconf"
2748 fi
2749
2750 _msg="$($_APACHECTL -t 2>&1)"
2751 if [ "$?" != "0" ]; then
2752 _err "Sorry, apache config error"
2753 if _restoreApache; then
2754 _err "The apache config file is restored."
2755 else
2756 _err "Sorry, The apache config file can not be restored, please report bug."
2757 fi
2758 return 1
2759 fi
2760
2761 if [ ! -d "$ACME_DIR" ]; then
2762 mkdir -p "$ACME_DIR"
2763 chmod 755 "$ACME_DIR"
2764 fi
2765
2766 if ! _exec "$_APACHECTL" graceful; then
2767 _exec_err
2768 _err "$_APACHECTL graceful error, please contact me."
2769 _restoreApache
2770 return 1
2771 fi
2772 usingApache="1"
2773 return 0
2774 }
2775
2776 #find the real nginx conf file
2777 #backup
2778 #set the nginx conf
2779 #returns the real nginx conf file
2780 _setNginx() {
2781 _d="$1"
2782 _croot="$2"
2783 _thumbpt="$3"
2784
2785 FOUND_REAL_NGINX_CONF=""
2786 FOUND_REAL_NGINX_CONF_LN=""
2787 BACKUP_NGINX_CONF=""
2788 _debug _croot "$_croot"
2789 _start_f="$(echo "$_croot" | cut -d : -f 2)"
2790 _debug _start_f "$_start_f"
2791 if [ -z "$_start_f" ]; then
2792 _debug "find start conf from nginx command"
2793 if [ -z "$NGINX_CONF" ]; then
2794 if ! _exists "nginx"; then
2795 _err "nginx command is not found."
2796 return 1
2797 fi
2798 NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
2799 _debug NGINX_CONF "$NGINX_CONF"
2800 NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
2801 _debug NGINX_CONF "$NGINX_CONF"
2802 if [ -z "$NGINX_CONF" ]; then
2803 _err "Can not find nginx conf."
2804 NGINX_CONF=""
2805 return 1
2806 fi
2807 if [ ! -f "$NGINX_CONF" ]; then
2808 _err "'$NGINX_CONF' doesn't exist."
2809 NGINX_CONF=""
2810 return 1
2811 fi
2812 _debug "Found nginx conf file:$NGINX_CONF"
2813 fi
2814 _start_f="$NGINX_CONF"
2815 fi
2816 _debug "Start detect nginx conf for $_d from:$_start_f"
2817 if ! _checkConf "$_d" "$_start_f"; then
2818 _err "Can not find conf file for domain $d"
2819 return 1
2820 fi
2821 _info "Found conf file: $FOUND_REAL_NGINX_CONF"
2822
2823 _ln=$FOUND_REAL_NGINX_CONF_LN
2824 _debug "_ln" "$_ln"
2825
2826 _lnn=$(_math $_ln + 1)
2827 _debug _lnn "$_lnn"
2828 _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
2829 _debug "_start_tag" "$_start_tag"
2830 if [ "$_start_tag" = "$NGINX_START" ]; then
2831 _info "The domain $_d is already configured, skip"
2832 FOUND_REAL_NGINX_CONF=""
2833 return 0
2834 fi
2835
2836 mkdir -p "$DOMAIN_BACKUP_PATH"
2837 _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
2838 _debug _backup_conf "$_backup_conf"
2839 BACKUP_NGINX_CONF="$_backup_conf"
2840 _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
2841 if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
2842 _err "backup error."
2843 FOUND_REAL_NGINX_CONF=""
2844 return 1
2845 fi
2846
2847 if ! _exists "nginx"; then
2848 _err "nginx command is not found."
2849 return 1
2850 fi
2851 _info "Check the nginx conf before setting up."
2852 if ! _exec "nginx -t" >/dev/null; then
2853 _exec_err
2854 return 1
2855 fi
2856
2857 _info "OK, Set up nginx config file"
2858
2859 if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
2860 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
2861 _err "write nginx conf error, but don't worry, the file is restored to the original version."
2862 return 1
2863 fi
2864
2865 echo "$NGINX_START
2866 location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
2867 default_type text/plain;
2868 return 200 \"\$1.$_thumbpt\";
2869 }
2870 #NGINX_START
2871 " >>"$FOUND_REAL_NGINX_CONF"
2872
2873 if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
2874 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
2875 _err "write nginx conf error, but don't worry, the file is restored."
2876 return 1
2877 fi
2878 _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
2879 _info "nginx conf is done, let's check it again."
2880 if ! _exec "nginx -t" >/dev/null; then
2881 _exec_err
2882 _err "It seems that nginx conf was broken, let's restore."
2883 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
2884 return 1
2885 fi
2886
2887 _info "Reload nginx"
2888 if ! _exec "nginx -s reload" >/dev/null; then
2889 _exec_err
2890 _err "It seems that nginx reload error, let's restore."
2891 cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
2892 return 1
2893 fi
2894
2895 return 0
2896 }
2897
2898 #d , conf
2899 _checkConf() {
2900 _d="$1"
2901 _c_file="$2"
2902 _debug "Start _checkConf from:$_c_file"
2903 if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
2904 _debug "wildcard"
2905 for _w_f in $2; do
2906 if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
2907 return 0
2908 fi
2909 done
2910 #not found
2911 return 1
2912 elif [ -f "$2" ]; then
2913 _debug "single"
2914 if _isRealNginxConf "$1" "$2"; then
2915 _debug "$2 is found."
2916 FOUND_REAL_NGINX_CONF="$2"
2917 return 0
2918 fi
2919 if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
2920 _debug "Try include files"
2921 for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
2922 _debug "check included $included"
2923 if _checkConf "$1" "$included"; then
2924 return 0
2925 fi
2926 done
2927 fi
2928 return 1
2929 else
2930 _debug "$2 not found."
2931 return 1
2932 fi
2933 return 1
2934 }
2935
2936 #d , conf
2937 _isRealNginxConf() {
2938 _debug "_isRealNginxConf $1 $2"
2939 if [ -f "$2" ]; then
2940 for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
2941 _debug _fln "$_fln"
2942 if [ "$_fln" ]; then
2943 _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *" | grep -v server_name | _tail_n 1)
2944 _debug "_start" "$_start"
2945 _start_n=$(echo "$_start" | cut -d : -f 1)
2946 _start_nn=$(_math $_start_n + 1)
2947 _debug "_start_n" "$_start_n"
2948 _debug "_start_nn" "$_start_nn"
2949
2950 _left="$(sed -n "${_start_nn},99999p" "$2")"
2951 _debug2 _left "$_left"
2952 _end="$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *" | grep -v server_name | _head_n 1)"
2953 _debug "_end" "$_end"
2954 if [ "$_end" ]; then
2955 _end_n=$(echo "$_end" | cut -d : -f 1)
2956 _debug "_end_n" "$_end_n"
2957 _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
2958 else
2959 _seg_n="$_left"
2960 fi
2961
2962 _debug "_seg_n" "$_seg_n"
2963
2964 _skip_ssl=1
2965 for _listen_i in $(echo "$_seg_n" | tr "\t" ' ' | grep "^ *listen" | tr -d " "); do
2966 if [ "$_listen_i" ]; then
2967 if [ "$(echo "$_listen_i" | _egrep_o "listen.*ssl")" ]; then
2968 _debug2 "$_listen_i is ssl"
2969 else
2970 _debug2 "$_listen_i is plain text"
2971 _skip_ssl=""
2972 break
2973 fi
2974 fi
2975 done
2976
2977 if [ "$_skip_ssl" = "1" ]; then
2978 _debug "ssl on, skip"
2979 else
2980 FOUND_REAL_NGINX_CONF_LN=$_fln
2981 _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
2982 return 0
2983 fi
2984 fi
2985 done
2986 fi
2987 return 1
2988 }
2989
2990 #restore all the nginx conf
2991 _restoreNginx() {
2992 if [ -z "$NGINX_RESTORE_VLIST" ]; then
2993 _debug "No need to restore nginx, skip."
2994 return
2995 fi
2996 _debug "_restoreNginx"
2997 _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
2998
2999 for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
3000 _debug "ng_entry" "$ng_entry"
3001 _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
3002 _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
3003 _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
3004 _info "Restoring from $_ngbackupconf to $_ngconf"
3005 cat "$_ngbackupconf" >"$_ngconf"
3006 done
3007
3008 _info "Reload nginx"
3009 if ! _exec "nginx -s reload" >/dev/null; then
3010 _exec_err
3011 _err "It seems that nginx reload error, please report bug."
3012 return 1
3013 fi
3014 return 0
3015 }
3016
3017 _clearup() {
3018 _stopserver "$serverproc"
3019 serverproc=""
3020 _restoreApache
3021 _restoreNginx
3022 _clearupdns
3023 if [ -z "$DEBUG" ]; then
3024 rm -f "$TLS_CONF"
3025 rm -f "$TLS_CERT"
3026 rm -f "$TLS_KEY"
3027 rm -f "$TLS_CSR"
3028 fi
3029 }
3030
3031 _clearupdns() {
3032 _debug "_clearupdns"
3033 _debug "dns_entries" "$dns_entries"
3034
3035 if [ -z "$dns_entries" ]; then
3036 _debug "skip dns."
3037 return
3038 fi
3039 _info "Removing DNS records."
3040
3041 for entry in $dns_entries; do
3042 d=$(_getfield "$entry" 1)
3043 txtdomain=$(_getfield "$entry" 2)
3044 aliasDomain=$(_getfield "$entry" 3)
3045 _currentRoot=$(_getfield "$entry" 4)
3046 txt=$(_getfield "$entry" 5)
3047 d_api=$(_getfield "$entry" 6)
3048 _debug "d" "$d"
3049 _debug "txtdomain" "$txtdomain"
3050 _debug "aliasDomain" "$aliasDomain"
3051 _debug "_currentRoot" "$_currentRoot"
3052 _debug "txt" "$txt"
3053 _debug "d_api" "$d_api"
3054 if [ "$d_api" = "$txt" ]; then
3055 d_api=""
3056 fi
3057
3058 if [ -z "$d_api" ]; then
3059 _info "Not Found domain api file: $d_api"
3060 continue
3061 fi
3062
3063 if [ "$aliasDomain" ]; then
3064 txtdomain="$aliasDomain"
3065 fi
3066
3067 (
3068 if ! . "$d_api"; then
3069 _err "Load file $d_api error. Please check your api file and try again."
3070 return 1
3071 fi
3072
3073 rmcommand="${_currentRoot}_rm"
3074 if ! _exists "$rmcommand"; then
3075 _err "It seems that your api file doesn't define $rmcommand"
3076 return 1
3077 fi
3078 _info "Removing txt: $txt for domain: $txtdomain"
3079 if ! $rmcommand "$txtdomain" "$txt"; then
3080 _err "Error removing txt for domain:$txtdomain"
3081 return 1
3082 fi
3083 _info "Removed: Success"
3084 )
3085
3086 done
3087 }
3088
3089 # webroot removelevel tokenfile
3090 _clearupwebbroot() {
3091 __webroot="$1"
3092 if [ -z "$__webroot" ]; then
3093 _debug "no webroot specified, skip"
3094 return 0
3095 fi
3096
3097 _rmpath=""
3098 if [ "$2" = '1' ]; then
3099 _rmpath="$__webroot/.well-known"
3100 elif [ "$2" = '2' ]; then
3101 _rmpath="$__webroot/.well-known/acme-challenge"
3102 elif [ "$2" = '3' ]; then
3103 _rmpath="$__webroot/.well-known/acme-challenge/$3"
3104 else
3105 _debug "Skip for removelevel:$2"
3106 fi
3107
3108 if [ "$_rmpath" ]; then
3109 if [ "$DEBUG" ]; then
3110 _debug "Debugging, skip removing: $_rmpath"
3111 else
3112 rm -rf "$_rmpath"
3113 fi
3114 fi
3115
3116 return 0
3117
3118 }
3119
3120 _on_before_issue() {
3121 _chk_web_roots="$1"
3122 _chk_main_domain="$2"
3123 _chk_alt_domains="$3"
3124 _chk_pre_hook="$4"
3125 _chk_local_addr="$5"
3126 _debug _on_before_issue
3127 _debug _chk_main_domain "$_chk_main_domain"
3128 _debug _chk_alt_domains "$_chk_alt_domains"
3129 #run pre hook
3130 if [ "$_chk_pre_hook" ]; then
3131 _info "Run pre hook:'$_chk_pre_hook'"
3132 if ! (
3133 cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
3134 ); then
3135 _err "Error when run pre hook."
3136 return 1
3137 fi
3138 fi
3139
3140 if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
3141 if ! _exists "socat"; then
3142 _err "Please install socat tools first."
3143 return 1
3144 fi
3145 fi
3146
3147 _debug Le_LocalAddress "$_chk_local_addr"
3148
3149 _index=1
3150 _currentRoot=""
3151 _addrIndex=1
3152 _w_index=1
3153 while true; do
3154 d="$(echo "$_chk_main_domain,$_chk_alt_domains," | cut -d , -f "$_w_index")"
3155 _w_index="$(_math "$_w_index" + 1)"
3156 _debug d "$d"
3157 if [ -z "$d" ]; then
3158 break
3159 fi
3160 _debug "Check for domain" "$d"
3161 _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
3162 _debug "_currentRoot" "$_currentRoot"
3163 _index=$(_math $_index + 1)
3164 _checkport=""
3165 if [ "$_currentRoot" = "$NO_VALUE" ]; then
3166 _info "Standalone mode."
3167 if [ -z "$Le_HTTPPort" ]; then
3168 Le_HTTPPort=80
3169 _cleardomainconf "Le_HTTPPort"
3170 else
3171 _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
3172 fi
3173 _checkport="$Le_HTTPPort"
3174 elif [ "$_currentRoot" = "$W_ALPN" ]; then
3175 _info "Standalone alpn mode."
3176 if [ -z "$Le_TLSPort" ]; then
3177 Le_TLSPort=443
3178 else
3179 _savedomainconf "Le_TLSPort" "$Le_TLSPort"
3180 fi
3181 _checkport="$Le_TLSPort"
3182 fi
3183
3184 if [ "$_checkport" ]; then
3185 _debug _checkport "$_checkport"
3186 _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
3187 _debug _checkaddr "$_checkaddr"
3188
3189 _addrIndex="$(_math $_addrIndex + 1)"
3190
3191 _netprc="$(_ss "$_checkport" | grep "$_checkport")"
3192 netprc="$(echo "$_netprc" | grep "$_checkaddr")"
3193 if [ -z "$netprc" ]; then
3194 netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
3195 fi
3196 if [ "$netprc" ]; then
3197 _err "$netprc"
3198 _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
3199 _err "Please stop it first"
3200 return 1
3201 fi
3202 fi
3203 done
3204
3205 if _hasfield "$_chk_web_roots" "apache"; then
3206 if ! _setApache; then
3207 _err "set up apache error. Report error to me."
3208 return 1
3209 fi
3210 else
3211 usingApache=""
3212 fi
3213
3214 }
3215
3216 _on_issue_err() {
3217 _chk_post_hook="$1"
3218 _chk_vlist="$2"
3219 _debug _on_issue_err
3220
3221 if [ "$LOG_FILE" ]; then
3222 _err "Please check log file for more details: $LOG_FILE"
3223 else
3224 _err "Please add '--debug' or '--log' to check more details."
3225 _err "See: $_DEBUG_WIKI"
3226 fi
3227
3228 #run the post hook
3229 if [ "$_chk_post_hook" ]; then
3230 _info "Run post hook:'$_chk_post_hook'"
3231 if ! (
3232 cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
3233 ); then
3234 _err "Error when run post hook."
3235 return 1
3236 fi
3237 fi
3238
3239 #trigger the validation to flush the pending authz
3240 _debug2 "_chk_vlist" "$_chk_vlist"
3241 if [ "$_chk_vlist" ]; then
3242 (
3243 _debug2 "start to deactivate authz"
3244 ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
3245 for ventry in $ventries; do
3246 d=$(echo "$ventry" | cut -d "$sep" -f 1)
3247 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
3248 uri=$(echo "$ventry" | cut -d "$sep" -f 3)
3249 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
3250 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
3251 __trigger_validation "$uri" "$keyauthorization"
3252 done
3253 )
3254 fi
3255
3256 if [ "$IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "$W_DNS"; then
3257 _err "$_DNS_MANUAL_ERR"
3258 fi
3259
3260 if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
3261 _debug "$(_dlg_versions)"
3262 fi
3263
3264 }
3265
3266 _on_issue_success() {
3267 _chk_post_hook="$1"
3268 _chk_renew_hook="$2"
3269 _debug _on_issue_success
3270
3271 #run the post hook
3272 if [ "$_chk_post_hook" ]; then
3273 _info "Run post hook:'$_chk_post_hook'"
3274 if ! (
3275 export CERT_PATH
3276 export CERT_KEY_PATH
3277 export CA_CERT_PATH
3278 export CERT_FULLCHAIN_PATH
3279 export Le_Domain="$_main_domain"
3280 cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
3281 ); then
3282 _err "Error when run post hook."
3283 return 1
3284 fi
3285 fi
3286
3287 #run renew hook
3288 if [ "$IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
3289 _info "Run renew hook:'$_chk_renew_hook'"
3290 if ! (
3291 export CERT_PATH
3292 export CERT_KEY_PATH
3293 export CA_CERT_PATH
3294 export CERT_FULLCHAIN_PATH
3295 export Le_Domain="$_main_domain"
3296 cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
3297 ); then
3298 _err "Error when run renew hook."
3299 return 1
3300 fi
3301 fi
3302
3303 if _hasfield "$Le_Webroot" "$W_DNS"; then
3304 _err "$_DNS_MANUAL_WARN"
3305 fi
3306
3307 }
3308
3309 registeraccount() {
3310 _reg_length="$1"
3311 _initpath
3312 _regAccount "$_reg_length"
3313 }
3314
3315 __calcAccountKeyHash() {
3316 [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
3317 }
3318
3319 __calc_account_thumbprint() {
3320 printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
3321 }
3322
3323 #keylength
3324 _regAccount() {
3325 _initpath
3326 _reg_length="$1"
3327 _debug3 _regAccount "$_regAccount"
3328 _initAPI
3329
3330 mkdir -p "$CA_DIR"
3331 if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
3332 _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
3333 mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
3334 fi
3335
3336 if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
3337 _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
3338 mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
3339 fi
3340
3341 if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
3342 if ! _create_account_key "$_reg_length"; then
3343 _err "Create account key error."
3344 return 1
3345 fi
3346 fi
3347
3348 if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
3349 return 1
3350 fi
3351
3352 if [ "$ACME_VERSION" = "2" ]; then
3353 regjson='{"termsOfServiceAgreed": true}'
3354 if [ "$ACCOUNT_EMAIL" ]; then
3355 regjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"], "termsOfServiceAgreed": true}'
3356 fi
3357 else
3358 _reg_res="$ACME_NEW_ACCOUNT_RES"
3359 regjson='{"resource": "'$_reg_res'", "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
3360 if [ "$ACCOUNT_EMAIL" ]; then
3361 regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
3362 fi
3363 fi
3364
3365 _info "Registering account"
3366
3367 if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
3368 _err "Register account Error: $response"
3369 return 1
3370 fi
3371
3372 if [ "$code" = "" ] || [ "$code" = '201' ]; then
3373 echo "$response" >"$ACCOUNT_JSON_PATH"
3374 _info "Registered"
3375 elif [ "$code" = '409' ] || [ "$code" = '200' ]; then
3376 _info "Already registered"
3377 else
3378 _err "Register account Error: $response"
3379 return 1
3380 fi
3381
3382 _debug2 responseHeaders "$responseHeaders"
3383 _accUri="$(echo "$responseHeaders" | grep -i "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
3384 _debug "_accUri" "$_accUri"
3385 if [ -z "$_accUri" ]; then
3386 _err "Can not find account id url."
3387 _err "$responseHeaders"
3388 return 1
3389 fi
3390 _savecaconf "ACCOUNT_URL" "$_accUri"
3391 export ACCOUNT_URL="$_accUri"
3392
3393 CA_KEY_HASH="$(__calcAccountKeyHash)"
3394 _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
3395 _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
3396
3397 if [ "$code" = '403' ]; then
3398 _err "It seems that the account key is already deactivated, please use a new account key."
3399 return 1
3400 fi
3401
3402 ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
3403 _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
3404 }
3405
3406 #implement updateaccount
3407 updateaccount() {
3408 _initpath
3409
3410 if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
3411 _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
3412 mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
3413 fi
3414
3415 if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
3416 _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
3417 mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
3418 fi
3419
3420 if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
3421 _err "Account key is not found at: $ACCOUNT_KEY_PATH"
3422 return 1
3423 fi
3424
3425 _accUri=$(_readcaconf "ACCOUNT_URL")
3426 _debug _accUri "$_accUri"
3427
3428 if [ -z "$_accUri" ]; then
3429 _err "The account url is empty, please run '--update-account' first to update the account info first,"
3430 _err "Then try again."
3431 return 1
3432 fi
3433
3434 if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
3435 return 1
3436 fi
3437 _initAPI
3438
3439 if [ "$ACME_VERSION" = "2" ]; then
3440 if [ "$ACCOUNT_EMAIL" ]; then
3441 updjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"]}'
3442 fi
3443 else
3444 # ACMEv1: Updates happen the same way a registration is done.
3445 # https://tools.ietf.org/html/draft-ietf-acme-acme-01#section-6.3
3446 _regAccount
3447 return
3448 fi
3449
3450 # this part handles ACMEv2 account updates.
3451 _send_signed_request "$_accUri" "$updjson"
3452
3453 if [ "$code" = '200' ]; then
3454 _info "account update success for $_accUri."
3455 else
3456 _info "Error. The account was not updated."
3457 return 1
3458 fi
3459 }
3460
3461 #Implement deactivate account
3462 deactivateaccount() {
3463 _initpath
3464
3465 if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
3466 _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
3467 mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
3468 fi
3469
3470 if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
3471 _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
3472 mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
3473 fi
3474
3475 if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
3476 _err "Account key is not found at: $ACCOUNT_KEY_PATH"
3477 return 1
3478 fi
3479
3480 _accUri=$(_readcaconf "ACCOUNT_URL")
3481 _debug _accUri "$_accUri"
3482
3483 if [ -z "$_accUri" ]; then
3484 _err "The account url is empty, please run '--update-account' first to update the account info first,"
3485 _err "Then try again."
3486 return 1
3487 fi
3488
3489 if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
3490 return 1
3491 fi
3492 _initAPI
3493
3494 if [ "$ACME_VERSION" = "2" ]; then
3495 _djson="{\"status\":\"deactivated\"}"
3496 else
3497 _djson="{\"resource\": \"reg\", \"status\":\"deactivated\"}"
3498 fi
3499 if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
3500 _info "Deactivate account success for $_accUri."
3501 _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
3502 elif [ "$code" = "403" ]; then
3503 _info "The account is already deactivated."
3504 _accid=$(_getfield "$_accUri" "999" "/")
3505 else
3506 _err "Deactivate: account failed for $_accUri."
3507 return 1
3508 fi
3509
3510 _debug "Account id: $_accid"
3511 if [ "$_accid" ]; then
3512 _deactivated_account_path="$CA_DIR/deactivated/$_accid"
3513 _debug _deactivated_account_path "$_deactivated_account_path"
3514 if mkdir -p "$_deactivated_account_path"; then
3515 _info "Moving deactivated account info to $_deactivated_account_path/"
3516 mv "$CA_CONF" "$_deactivated_account_path/"
3517 mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
3518 mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
3519 else
3520 _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
3521 rm -f "$CA_CONF"
3522 rm -f "$ACCOUNT_JSON_PATH"
3523 rm -f "$ACCOUNT_KEY_PATH"
3524 fi
3525 fi
3526 }
3527
3528 # domain folder file
3529 _findHook() {
3530 _hookdomain="$1"
3531 _hookcat="$2"
3532 _hookname="$3"
3533
3534 if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
3535 d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
3536 elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
3537 d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
3538 elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
3539 d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
3540 elif [ "$_hookdomain" ] && [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
3541 d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
3542 elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
3543 d_api="$LE_WORKING_DIR/$_hookname"
3544 elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
3545 d_api="$LE_WORKING_DIR/$_hookname.sh"
3546 elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
3547 d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
3548 elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
3549 d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
3550 fi
3551
3552 printf "%s" "$d_api"
3553 }
3554
3555 #domain
3556 __get_domain_new_authz() {
3557 _gdnd="$1"
3558 _info "Getting new-authz for domain" "$_gdnd"
3559 _initAPI
3560 _Max_new_authz_retry_times=5
3561 _authz_i=0
3562 while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
3563 _debug "Try new-authz for the $_authz_i time."
3564 if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
3565 _err "Can not get domain new authz."
3566 return 1
3567 fi
3568 if _contains "$response" "No registration exists matching provided key"; then
3569 _err "It seems there is an error, but it's recovered now, please try again."
3570 _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
3571 _clearcaconf "CA_KEY_HASH"
3572 break
3573 fi
3574 if ! _contains "$response" "An error occurred while processing your request"; then
3575 _info "The new-authz request is ok."
3576 break
3577 fi
3578 _authz_i="$(_math "$_authz_i" + 1)"
3579 _info "The server is busy, Sleep $_authz_i to retry."
3580 _sleep "$_authz_i"
3581 done
3582
3583 if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
3584 _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
3585 fi
3586
3587 if [ "$code" ] && [ "$code" != '201' ]; then
3588 _err "new-authz error: $response"
3589 return 1
3590 fi
3591
3592 }
3593
3594 #uri keyAuthorization
3595 __trigger_validation() {
3596 _debug2 "Trigger domain validation."
3597 _t_url="$1"
3598 _debug2 _t_url "$_t_url"
3599 _t_key_authz="$2"
3600 _debug2 _t_key_authz "$_t_key_authz"
3601 _t_vtype="$3"
3602 _debug2 _t_vtype "$_t_vtype"
3603 if [ "$ACME_VERSION" = "2" ]; then
3604 _send_signed_request "$_t_url" "{}"
3605 else
3606 _send_signed_request "$_t_url" "{\"resource\": \"challenge\", \"type\": \"$_t_vtype\", \"keyAuthorization\": \"$_t_key_authz\"}"
3607 fi
3608 }
3609
3610 #endpoint domain type
3611 _ns_lookup() {
3612 _ns_ep="$1"
3613 _ns_domain="$2"
3614 _ns_type="$3"
3615 _debug2 "_ns_ep" "$_ns_ep"
3616 _debug2 "_ns_domain" "$_ns_domain"
3617 _debug2 "_ns_type" "$_ns_type"
3618
3619 response="$(_H1="accept: application/dns-json" _get "$_ns_ep?name=$_ns_domain&type=$_ns_type")"
3620 _ret=$?
3621 _debug2 "response" "$response"
3622 if [ "$_ret" != "0" ]; then
3623 return $_ret
3624 fi
3625 _answers="$(echo "$response" | tr '{}' '<>' | _egrep_o '"Answer":\[[^]]*]' | tr '<>' '\n\n')"
3626 _debug2 "_answers" "$_answers"
3627 echo "$_answers"
3628 }
3629
3630 #domain, type
3631 _ns_lookup_cf() {
3632 _cf_ld="$1"
3633 _cf_ld_type="$2"
3634 _cf_ep="https://cloudflare-dns.com/dns-query"
3635 _ns_lookup "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
3636 }
3637
3638 #domain, type
3639 _ns_purge_cf() {
3640 _cf_d="$1"
3641 _cf_d_type="$2"
3642 _debug "Cloudflare purge $_cf_d_type record for domain $_cf_d"
3643 _cf_purl="https://cloudflare-dns.com/api/v1/purge?domain=$_cf_d&type=$_cf_d_type"
3644 response="$(_post "" "$_cf_purl")"
3645 _debug2 response "$response"
3646 }
3647
3648 #txtdomain, alias, txt
3649 __check_txt() {
3650 _c_txtdomain="$1"
3651 _c_aliasdomain="$2"
3652 _c_txt="$3"
3653 _debug "_c_txtdomain" "$_c_txtdomain"
3654 _debug "_c_aliasdomain" "$_c_aliasdomain"
3655 _debug "_c_txt" "$_c_txt"
3656 _answers="$(_ns_lookup_cf "$_c_aliasdomain" TXT)"
3657 _contains "$_answers" "$_c_txt"
3658
3659 }
3660
3661 #txtdomain
3662 __purge_txt() {
3663 _p_txtdomain="$1"
3664 _debug _p_txtdomain "$_p_txtdomain"
3665 _ns_purge_cf "$_p_txtdomain" "TXT"
3666 }
3667
3668 #wait and check each dns entries
3669 _check_dns_entries() {
3670 _success_txt=","
3671 _end_time="$(_time)"
3672 _end_time="$(_math "$_end_time" + 1200)" #let's check no more than 20 minutes.
3673
3674 while [ "$(_time)" -le "$_end_time" ]; do
3675 _left=""
3676 for entry in $dns_entries; do
3677 d=$(_getfield "$entry" 1)
3678 txtdomain=$(_getfield "$entry" 2)
3679 txtdomain=$(_idn "$txtdomain")
3680 aliasDomain=$(_getfield "$entry" 3)
3681 aliasDomain=$(_idn "$aliasDomain")
3682 txt=$(_getfield "$entry" 5)
3683 d_api=$(_getfield "$entry" 6)
3684 _debug "d" "$d"
3685 _debug "txtdomain" "$txtdomain"
3686 _debug "aliasDomain" "$aliasDomain"
3687 _debug "txt" "$txt"
3688 _debug "d_api" "$d_api"
3689 _info "Checking $d for $aliasDomain"
3690 if _contains "$_success_txt" ",$txt,"; then
3691 _info "Already success, continue next one."
3692 continue
3693 fi
3694
3695 if __check_txt "$txtdomain" "$aliasDomain" "$txt"; then
3696 _info "Domain $d '$aliasDomain' success."
3697 _success_txt="$_success_txt,$txt,"
3698 continue
3699 fi
3700 _left=1
3701 _info "Not valid yet, let's wait 10 seconds and check next one."
3702 __purge_txt "$txtdomain"
3703 if [ "$txtdomain" != "$aliasDomain" ]; then
3704 __purge_txt "$aliasDomain"
3705 fi
3706 _sleep 10
3707 done
3708 if [ "$_left" ]; then
3709 _info "Let's wait 10 seconds and check again".
3710 _sleep 10
3711 else
3712 _info "All success, let's return"
3713 break
3714 fi
3715 done
3716
3717 }
3718
3719 #webroot, domain domainlist keylength
3720 issue() {
3721 if [ -z "$2" ]; then
3722 _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
3723 return 1
3724 fi
3725 if [ -z "$1" ]; then
3726 _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
3727 return 1
3728 fi
3729 _web_roots="$1"
3730 _main_domain="$2"
3731 _alt_domains="$3"
3732
3733 if _contains "$_main_domain" ","; then
3734 _main_domain=$(echo "$2,$3" | cut -d , -f 1)
3735 _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
3736 fi
3737 _debug _main_domain "$_main_domain"
3738 _debug _alt_domains "$_alt_domains"
3739
3740 _key_length="$4"
3741 _real_cert="$5"
3742 _real_key="$6"
3743 _real_ca="$7"
3744 _reload_cmd="$8"
3745 _real_fullchain="$9"
3746 _pre_hook="${10}"
3747 _post_hook="${11}"
3748 _renew_hook="${12}"
3749 _local_addr="${13}"
3750 _challenge_alias="${14}"
3751 #remove these later.
3752 if [ "$_web_roots" = "dns-cf" ]; then
3753 _web_roots="dns_cf"
3754 fi
3755 if [ "$_web_roots" = "dns-dp" ]; then
3756 _web_roots="dns_dp"
3757 fi
3758 if [ "$_web_roots" = "dns-cx" ]; then
3759 _web_roots="dns_cx"
3760 fi
3761
3762 if [ ! "$IS_RENEW" ]; then
3763 _initpath "$_main_domain" "$_key_length"
3764 mkdir -p "$DOMAIN_PATH"
3765 fi
3766
3767 if _hasfield "$_web_roots" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
3768 _err "$_DNS_MANUAL_ERROR"
3769 return 1
3770 fi
3771
3772 _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
3773
3774 _initAPI
3775
3776 if [ -f "$DOMAIN_CONF" ]; then
3777 Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
3778 _debug Le_NextRenewTime "$Le_NextRenewTime"
3779 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
3780 _saved_domain=$(_readdomainconf Le_Domain)
3781 _debug _saved_domain "$_saved_domain"
3782 _saved_alt=$(_readdomainconf Le_Alt)
3783 _debug _saved_alt "$_saved_alt"
3784 if [ "$_saved_domain,$_saved_alt" = "$_main_domain,$_alt_domains" ]; then
3785 _info "Domains not changed."
3786 _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
3787 _info "Add '$(__red '--force')' to force to renew."
3788 return $RENEW_SKIP
3789 else
3790 _info "Domains have changed."
3791 fi
3792 fi
3793 fi
3794
3795 _savedomainconf "Le_Domain" "$_main_domain"
3796 _savedomainconf "Le_Alt" "$_alt_domains"
3797 _savedomainconf "Le_Webroot" "$_web_roots"
3798
3799 _savedomainconf "Le_PreHook" "$_pre_hook" "base64"
3800 _savedomainconf "Le_PostHook" "$_post_hook" "base64"
3801 _savedomainconf "Le_RenewHook" "$_renew_hook" "base64"
3802
3803 if [ "$_local_addr" ]; then
3804 _savedomainconf "Le_LocalAddress" "$_local_addr"
3805 else
3806 _cleardomainconf "Le_LocalAddress"
3807 fi
3808 if [ "$_challenge_alias" ]; then
3809 _savedomainconf "Le_ChallengeAlias" "$_challenge_alias"
3810 else
3811 _cleardomainconf "Le_ChallengeAlias"
3812 fi
3813
3814 if [ "$ACME_DIRECTORY" != "$DEFAULT_CA" ]; then
3815 Le_API="$ACME_DIRECTORY"
3816 _savedomainconf "Le_API" "$Le_API"
3817 else
3818 _cleardomainconf Le_API
3819 fi
3820
3821 if [ "$_alt_domains" = "$NO_VALUE" ]; then
3822 _alt_domains=""
3823 fi
3824
3825 if [ "$_key_length" = "$NO_VALUE" ]; then
3826 _key_length=""
3827 fi
3828
3829 if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
3830 _err "_on_before_issue."
3831 return 1
3832 fi
3833
3834 _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
3835 _debug2 _saved_account_key_hash "$_saved_account_key_hash"
3836
3837 if [ -z "$ACCOUNT_URL" ] || [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
3838 if ! _regAccount "$_accountkeylength"; then
3839 _on_issue_err "$_post_hook"
3840 return 1
3841 fi
3842 else
3843 _debug "_saved_account_key_hash is not changed, skip register account."
3844 fi
3845
3846 if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
3847 _info "Signing from existing CSR."
3848 else
3849 _key=$(_readdomainconf Le_Keylength)
3850 _debug "Read key length:$_key"
3851 if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
3852 if ! createDomainKey "$_main_domain" "$_key_length"; then
3853 _err "Create domain key error."
3854 _clearup
3855 _on_issue_err "$_post_hook"
3856 return 1
3857 fi
3858 fi
3859
3860 if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
3861 _err "Create CSR error."
3862 _clearup
3863 _on_issue_err "$_post_hook"
3864 return 1
3865 fi
3866 fi
3867
3868 _savedomainconf "Le_Keylength" "$_key_length"
3869
3870 vlist="$Le_Vlist"
3871 _cleardomainconf "Le_Vlist"
3872 _info "Getting domain auth token for each domain"
3873 sep='#'
3874 dvsep=','
3875 if [ -z "$vlist" ]; then
3876 if [ "$ACME_VERSION" = "2" ]; then
3877 #make new order request
3878 _identifiers="{\"type\":\"dns\",\"value\":\"$(_idn "$_main_domain")\"}"
3879 _w_index=1
3880 while true; do
3881 d="$(echo "$_alt_domains," | cut -d , -f "$_w_index")"
3882 _w_index="$(_math "$_w_index" + 1)"
3883 _debug d "$d"
3884 if [ -z "$d" ]; then
3885 break
3886 fi
3887 _identifiers="$_identifiers,{\"type\":\"dns\",\"value\":\"$(_idn "$d")\"}"
3888 done
3889 _debug2 _identifiers "$_identifiers"
3890 if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
3891 _err "Create new order error."
3892 _clearup
3893 _on_issue_err "$_post_hook"
3894 return 1
3895 fi
3896 Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
3897 _debug Le_LinkOrder "$Le_LinkOrder"
3898 Le_OrderFinalize="$(echo "$response" | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
3899 _debug Le_OrderFinalize "$Le_OrderFinalize"
3900 if [ -z "$Le_OrderFinalize" ]; then
3901 _err "Create new order error. Le_OrderFinalize not found. $response"
3902 _clearup
3903 _on_issue_err "$_post_hook"
3904 return 1
3905 fi
3906
3907 #for dns manual mode
3908 _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
3909
3910 _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
3911 _debug2 _authorizations_seg "$_authorizations_seg"
3912 if [ -z "$_authorizations_seg" ]; then
3913 _err "_authorizations_seg not found."
3914 _clearup
3915 _on_issue_err "$_post_hook"
3916 return 1
3917 fi
3918
3919 #domain and authz map
3920 _authorizations_map=""
3921 for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
3922 _debug2 "_authz_url" "$_authz_url"
3923 if ! _send_signed_request "$_authz_url"; then
3924 _err "get to authz error."
3925 _err "_authorizations_seg" "$_authorizations_seg"
3926 _err "_authz_url" "$_authz_url"
3927 _clearup
3928 _on_issue_err "$_post_hook"
3929 return 1
3930 fi
3931
3932 response="$(echo "$response" | _normalizeJson)"
3933 _debug2 response "$response"
3934 _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2 | tr -d ' "')"
3935 if _contains "$response" "\"wildcard\" *: *true"; then
3936 _d="*.$_d"
3937 fi
3938 _debug2 _d "$_d"
3939 _authorizations_map="$_d,$response
3940 $_authorizations_map"
3941 done
3942 _debug2 _authorizations_map "$_authorizations_map"
3943 fi
3944
3945 _index=0
3946 _currentRoot=""
3947 _w_index=1
3948 while true; do
3949 d="$(echo "$_main_domain,$_alt_domains," | cut -d , -f "$_w_index")"
3950 _w_index="$(_math "$_w_index" + 1)"
3951 _debug d "$d"
3952 if [ -z "$d" ]; then
3953 break
3954 fi
3955 _info "Getting webroot for domain" "$d"
3956 _index=$(_math $_index + 1)
3957 _w="$(echo $_web_roots | cut -d , -f $_index)"
3958 _debug _w "$_w"
3959 if [ "$_w" ]; then
3960 _currentRoot="$_w"
3961 fi
3962 _debug "_currentRoot" "$_currentRoot"
3963
3964 vtype="$VTYPE_HTTP"
3965 #todo, v2 wildcard force to use dns
3966 if _startswith "$_currentRoot" "$W_DNS"; then
3967 vtype="$VTYPE_DNS"
3968 fi
3969
3970 if [ "$_currentRoot" = "$W_ALPN" ]; then
3971 vtype="$VTYPE_ALPN"
3972 fi
3973
3974 if [ "$ACME_VERSION" = "2" ]; then
3975 response="$(echo "$_authorizations_map" | grep "^$(_idn "$d")," | sed "s/$d,//")"
3976 _debug2 "response" "$response"
3977 if [ -z "$response" ]; then
3978 _err "get to authz error."
3979 _err "_authorizations_map" "$_authorizations_map"
3980 _clearup
3981 _on_issue_err "$_post_hook"
3982 return 1
3983 fi
3984 else
3985 if ! __get_domain_new_authz "$d"; then
3986 _clearup
3987 _on_issue_err "$_post_hook"
3988 return 1
3989 fi
3990 fi
3991
3992 if [ -z "$thumbprint" ]; then
3993 thumbprint="$(__calc_account_thumbprint)"
3994 fi
3995
3996 entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
3997 _debug entry "$entry"
3998 if [ -z "$entry" ]; then
3999 _err "Error, can not get domain token entry $d"
4000 _supported_vtypes="$(echo "$response" | _egrep_o "\"challenges\":\[[^]]*]" | tr '{' "\n" | grep type | cut -d '"' -f 4 | tr "\n" ' ')"
4001 if [ "$_supported_vtypes" ]; then
4002 _err "The supported validation types are: $_supported_vtypes, but you specified: $vtype"
4003 fi
4004 _clearup
4005 _on_issue_err "$_post_hook"
4006 return 1
4007 fi
4008 token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
4009 _debug token "$token"
4010
4011 if [ -z "$token" ]; then
4012 _err "Error, can not get domain token $entry"
4013 _clearup
4014 _on_issue_err "$_post_hook"
4015 return 1
4016 fi
4017 if [ "$ACME_VERSION" = "2" ]; then
4018 uri="$(echo "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
4019 else
4020 uri="$(echo "$entry" | _egrep_o '"uri":"[^"]*' | cut -d '"' -f 4)"
4021 fi
4022 _debug uri "$uri"
4023
4024 if [ -z "$uri" ]; then
4025 _err "Error, can not get domain uri. $entry"
4026 _clearup
4027 _on_issue_err "$_post_hook"
4028 return 1
4029 fi
4030 keyauthorization="$token.$thumbprint"
4031 _debug keyauthorization "$keyauthorization"
4032
4033 if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
4034 _debug "$d is already verified."
4035 keyauthorization="$STATE_VERIFIED"
4036 _debug keyauthorization "$keyauthorization"
4037 fi
4038
4039 dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
4040 _debug dvlist "$dvlist"
4041
4042 vlist="$vlist$dvlist$dvsep"
4043
4044 done
4045 _debug vlist "$vlist"
4046 #add entry
4047 dns_entries=""
4048 dnsadded=""
4049 ventries=$(echo "$vlist" | tr "$dvsep" ' ')
4050 _alias_index=1
4051 for ventry in $ventries; do
4052 d=$(echo "$ventry" | cut -d "$sep" -f 1)
4053 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
4054 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
4055 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
4056 _debug d "$d"
4057 if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
4058 _debug "$d is already verified, skip $vtype."
4059 _alias_index="$(_math "$_alias_index" + 1)"
4060 continue
4061 fi
4062
4063 if [ "$vtype" = "$VTYPE_DNS" ]; then
4064 dnsadded='0'
4065 _dns_root_d="$d"
4066 if _startswith "$_dns_root_d" "*."; then
4067 _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
4068 fi
4069 _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
4070 _alias_index="$(_math "$_alias_index" + 1)"
4071 _debug "_d_alias" "$_d_alias"
4072 if [ "$_d_alias" ]; then
4073 if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
4074 txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
4075 else
4076 txtdomain="_acme-challenge.$_d_alias"
4077 fi
4078 dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$txtdomain$dvsep$_currentRoot"
4079 else
4080 txtdomain="_acme-challenge.$_dns_root_d"
4081 dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$dvsep$_currentRoot"
4082 fi
4083
4084 _debug txtdomain "$txtdomain"
4085 txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
4086 _debug txt "$txt"
4087
4088 d_api="$(_findHook "$_dns_root_d" $_SUB_FOLDER_DNSAPI "$_currentRoot")"
4089 _debug d_api "$d_api"
4090
4091 dns_entry="$dns_entry$dvsep$txt${dvsep}$d_api"
4092 _debug2 dns_entry "$dns_entry"
4093 if [ "$d_api" ]; then
4094 _debug "Found domain api file: $d_api"
4095 else
4096 if [ "$_currentRoot" != "$W_DNS" ]; then
4097 _err "Can not find dns api hook for: $_currentRoot"
4098 _info "You need to add the txt record manually."
4099 fi
4100 _info "$(__red "Add the following TXT record:")"
4101 _info "$(__red "Domain: '$(__green "$txtdomain")'")"
4102 _info "$(__red "TXT value: '$(__green "$txt")'")"
4103 _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
4104 _info "$(__red "so the resulting subdomain will be: $txtdomain")"
4105 continue
4106 fi
4107
4108 (
4109 if ! . "$d_api"; then
4110 _err "Load file $d_api error. Please check your api file and try again."
4111 return 1
4112 fi
4113
4114 addcommand="${_currentRoot}_add"
4115 if ! _exists "$addcommand"; then
4116 _err "It seems that your api file is not correct, it must have a function named: $addcommand"
4117 return 1
4118 fi
4119 _info "Adding txt value: $txt for domain: $txtdomain"
4120 if ! $addcommand "$txtdomain" "$txt"; then
4121 _err "Error add txt for domain:$txtdomain"
4122 return 1
4123 fi
4124 _info "The txt record is added: Success."
4125 )
4126
4127 if [ "$?" != "0" ]; then
4128 _on_issue_err "$_post_hook" "$vlist"
4129 _clearup
4130 return 1
4131 fi
4132 dns_entries="$dns_entries$dns_entry
4133 "
4134 _debug2 "$dns_entries"
4135 dnsadded='1'
4136 fi
4137 done
4138
4139 if [ "$dnsadded" = '0' ]; then
4140 _savedomainconf "Le_Vlist" "$vlist"
4141 _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
4142 _err "Please add the TXT records to the domains, and re-run with --renew."
4143 _on_issue_err "$_post_hook"
4144 _clearup
4145 return 1
4146 fi
4147
4148 fi
4149
4150 if [ "$dns_entries" ]; then
4151 if [ -z "$Le_DNSSleep" ]; then
4152 _info "Let's check each dns records now. Sleep 20 seconds first."
4153 _sleep 20
4154 if ! _check_dns_entries; then
4155 _err "check dns error."
4156 _on_issue_err "$_post_hook"
4157 _clearup
4158 return 1
4159 fi
4160 else
4161 _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
4162 _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
4163 _sleep "$Le_DNSSleep"
4164 fi
4165 fi
4166
4167 NGINX_RESTORE_VLIST=""
4168 _debug "ok, let's start to verify"
4169
4170 _ncIndex=1
4171 ventries=$(echo "$vlist" | tr "$dvsep" ' ')
4172 for ventry in $ventries; do
4173 d=$(echo "$ventry" | cut -d "$sep" -f 1)
4174 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
4175 uri=$(echo "$ventry" | cut -d "$sep" -f 3)
4176 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
4177 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
4178
4179 if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
4180 _info "$d is already verified, skip $vtype."
4181 continue
4182 fi
4183
4184 _info "Verifying: $d"
4185 _debug "d" "$d"
4186 _debug "keyauthorization" "$keyauthorization"
4187 _debug "uri" "$uri"
4188 removelevel=""
4189 token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
4190
4191 _debug "_currentRoot" "$_currentRoot"
4192
4193 if [ "$vtype" = "$VTYPE_HTTP" ]; then
4194 if [ "$_currentRoot" = "$NO_VALUE" ]; then
4195 _info "Standalone mode server"
4196 _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
4197 _ncIndex="$(_math $_ncIndex + 1)"
4198 _startserver "$keyauthorization" "$_ncaddr"
4199 if [ "$?" != "0" ]; then
4200 _clearup
4201 _on_issue_err "$_post_hook" "$vlist"
4202 return 1
4203 fi
4204 sleep 1
4205 _debug serverproc "$serverproc"
4206 elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
4207 _info "Stateless mode for domain:$d"
4208 _sleep 1
4209 elif _startswith "$_currentRoot" "$NGINX"; then
4210 _info "Nginx mode for domain:$d"
4211 #set up nginx server
4212 FOUND_REAL_NGINX_CONF=""
4213 BACKUP_NGINX_CONF=""
4214 if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
4215 _clearup
4216 _on_issue_err "$_post_hook" "$vlist"
4217 return 1
4218 fi
4219
4220 if [ "$FOUND_REAL_NGINX_CONF" ]; then
4221 _realConf="$FOUND_REAL_NGINX_CONF"
4222 _backup="$BACKUP_NGINX_CONF"
4223 _debug _realConf "$_realConf"
4224 NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
4225 fi
4226 _sleep 1
4227 else
4228 if [ "$_currentRoot" = "apache" ]; then
4229 wellknown_path="$ACME_DIR"
4230 else
4231 wellknown_path="$_currentRoot/.well-known/acme-challenge"
4232 if [ ! -d "$_currentRoot/.well-known" ]; then
4233 removelevel='1'
4234 elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
4235 removelevel='2'
4236 else
4237 removelevel='3'
4238 fi
4239 fi
4240
4241 _debug wellknown_path "$wellknown_path"
4242
4243 _debug "writing token:$token to $wellknown_path/$token"
4244
4245 mkdir -p "$wellknown_path"
4246
4247 if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
4248 _err "$d:Can not write token to file : $wellknown_path/$token"
4249 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4250 _clearup
4251 _on_issue_err "$_post_hook" "$vlist"
4252 return 1
4253 fi
4254
4255 if [ ! "$usingApache" ]; then
4256 if webroot_owner=$(_stat "$_currentRoot"); then
4257 _debug "Changing owner/group of .well-known to $webroot_owner"
4258 if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
4259 _debug "$(cat "$_EXEC_TEMP_ERR")"
4260 _exec_err >/dev/null 2>&1
4261 fi
4262 else
4263 _debug "not changing owner/group of webroot"
4264 fi
4265 fi
4266
4267 fi
4268 elif [ "$vtype" = "$VTYPE_ALPN" ]; then
4269 acmevalidationv1="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
4270 _debug acmevalidationv1 "$acmevalidationv1"
4271 if ! _starttlsserver "$d" "" "$Le_TLSPort" "$keyauthorization" "$_ncaddr" "$acmevalidationv1"; then
4272 _err "Start tls server error."
4273 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4274 _clearup
4275 _on_issue_err "$_post_hook" "$vlist"
4276 return 1
4277 fi
4278 fi
4279
4280 if ! __trigger_validation "$uri" "$keyauthorization" "$vtype"; then
4281 _err "$d:Can not get challenge: $response"
4282 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4283 _clearup
4284 _on_issue_err "$_post_hook" "$vlist"
4285 return 1
4286 fi
4287
4288 if [ "$code" ] && [ "$code" != '202' ]; then
4289 if [ "$code" = '200' ]; then
4290 _debug "trigger validation code: $code"
4291 else
4292 _err "$d:Challenge error: $response"
4293 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4294 _clearup
4295 _on_issue_err "$_post_hook" "$vlist"
4296 return 1
4297 fi
4298 fi
4299
4300 waittimes=0
4301 if [ -z "$MAX_RETRY_TIMES" ]; then
4302 MAX_RETRY_TIMES=30
4303 fi
4304
4305 while true; do
4306 waittimes=$(_math "$waittimes" + 1)
4307 if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
4308 _err "$d:Timeout"
4309 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4310 _clearup
4311 _on_issue_err "$_post_hook" "$vlist"
4312 return 1
4313 fi
4314
4315 _debug "sleep 2 secs to verify"
4316 sleep 2
4317 _debug "checking"
4318 if [ "$ACME_VERSION" = "2" ]; then
4319 _send_signed_request "$uri"
4320 else
4321 response="$(_get "$uri")"
4322 fi
4323 if [ "$?" != "0" ]; then
4324 _err "$d:Verify error:$response"
4325 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4326 _clearup
4327 _on_issue_err "$_post_hook" "$vlist"
4328 return 1
4329 fi
4330 _debug2 original "$response"
4331
4332 response="$(echo "$response" | _normalizeJson)"
4333 _debug2 response "$response"
4334
4335 status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
4336 if [ "$status" = "valid" ]; then
4337 _info "$(__green Success)"
4338 _stopserver "$serverproc"
4339 serverproc=""
4340 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4341 break
4342 fi
4343
4344 if [ "$status" = "invalid" ]; then
4345 error="$(echo "$response" | _egrep_o '"error":\{[^\}]*')"
4346 _debug2 error "$error"
4347 errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
4348 _debug2 errordetail "$errordetail"
4349 if [ "$errordetail" ]; then
4350 _err "$d:Verify error:$errordetail"
4351 else
4352 _err "$d:Verify error:$error"
4353 fi
4354 if [ "$DEBUG" ]; then
4355 if [ "$vtype" = "$VTYPE_HTTP" ]; then
4356 _debug "Debug: get token url."
4357 _get "http://$d/.well-known/acme-challenge/$token" "" 1
4358 fi
4359 fi
4360 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4361 _clearup
4362 _on_issue_err "$_post_hook" "$vlist"
4363 return 1
4364 fi
4365
4366 if [ "$status" = "pending" ]; then
4367 _info "Pending"
4368 elif [ "$status" = "processing" ]; then
4369 _info "Processing"
4370 else
4371 _err "$d:Verify error:$response"
4372 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
4373 _clearup
4374 _on_issue_err "$_post_hook" "$vlist"
4375 return 1
4376 fi
4377
4378 done
4379
4380 done
4381
4382 _clearup
4383 _info "Verify finished, start to sign."
4384 der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
4385
4386 if [ "$ACME_VERSION" = "2" ]; then
4387 _info "Lets finalize the order, Le_OrderFinalize: $Le_OrderFinalize"
4388 if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
4389 _err "Sign failed."
4390 _on_issue_err "$_post_hook"
4391 return 1
4392 fi
4393 if [ "$code" != "200" ]; then
4394 _err "Sign failed, finalize code is not 200."
4395 _err "$response"
4396 _on_issue_err "$_post_hook"
4397 return 1
4398 fi
4399 if [ -z "$Le_LinkOrder" ]; then
4400 Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
4401 fi
4402
4403 _savedomainconf "Le_LinkOrder" "$Le_LinkOrder"
4404
4405 _link_cert_retry=0
4406 _MAX_CERT_RETRY=5
4407 while [ "$_link_cert_retry" -lt "$_MAX_CERT_RETRY" ]; do
4408 if _contains "$response" "\"status\":\"valid\""; then
4409 _debug "Order status is valid."
4410 Le_LinkCert="$(echo "$response" | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
4411 _debug Le_LinkCert "$Le_LinkCert"
4412 if [ -z "$Le_LinkCert" ]; then
4413 _err "Sign error, can not find Le_LinkCert"
4414 _err "$response"
4415 _on_issue_err "$_post_hook"
4416 return 1
4417 fi
4418 break
4419 elif _contains "$response" "\"processing\""; then
4420 _info "Order status is processing, lets sleep and retry."
4421 _sleep 2
4422 else
4423 _err "Sign error, wrong status"
4424 _err "$response"
4425 _on_issue_err "$_post_hook"
4426 return 1
4427 fi
4428 #the order is processing, so we are going to poll order status
4429 if [ -z "$Le_LinkOrder" ]; then
4430 _err "Sign error, can not get order link location header"
4431 _err "responseHeaders" "$responseHeaders"
4432 _on_issue_err "$_post_hook"
4433 return 1
4434 fi
4435 _info "Polling order status: $Le_LinkOrder"
4436 if ! _send_signed_request "$Le_LinkOrder"; then
4437 _err "Sign failed, can not post to Le_LinkOrder cert:$Le_LinkOrder."
4438 _err "$response"
4439 _on_issue_err "$_post_hook"
4440 return 1
4441 fi
4442 _link_cert_retry="$(_math $_link_cert_retry + 1)"
4443 done
4444
4445 if [ -z "$Le_LinkCert" ]; then
4446 _err "Sign failed, can not get Le_LinkCert, retry time limit."
4447 _err "$response"
4448 _on_issue_err "$_post_hook"
4449 return 1
4450 fi
4451 _info "Download cert, Le_LinkCert: $Le_LinkCert"
4452 if ! _send_signed_request "$Le_LinkCert"; then
4453 _err "Sign failed, can not download cert:$Le_LinkCert."
4454 _err "$response"
4455 _on_issue_err "$_post_hook"
4456 return 1
4457 fi
4458
4459 echo "$response" >"$CERT_PATH"
4460
4461 if [ "$(grep -- "$BEGIN_CERT" "$CERT_PATH" | wc -l)" -gt "1" ]; then
4462 _debug "Found cert chain"
4463 cat "$CERT_PATH" >"$CERT_FULLCHAIN_PATH"
4464 _end_n="$(grep -n -- "$END_CERT" "$CERT_FULLCHAIN_PATH" | _head_n 1 | cut -d : -f 1)"
4465 _debug _end_n "$_end_n"
4466 sed -n "1,${_end_n}p" "$CERT_FULLCHAIN_PATH" >"$CERT_PATH"
4467 _end_n="$(_math $_end_n + 1)"
4468 sed -n "${_end_n},9999p" "$CERT_FULLCHAIN_PATH" >"$CA_CERT_PATH"
4469 fi
4470
4471 else
4472 if ! _send_signed_request "${ACME_NEW_ORDER}" "{\"resource\": \"$ACME_NEW_ORDER_RES\", \"csr\": \"$der\"}" "needbase64"; then
4473 _err "Sign failed. $response"
4474 _on_issue_err "$_post_hook"
4475 return 1
4476 fi
4477 _rcert="$response"
4478 Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
4479 echo "$BEGIN_CERT" >"$CERT_PATH"
4480
4481 #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
4482 # _debug "Get cert failed. Let's try last response."
4483 # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
4484 #fi
4485
4486 if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
4487 _debug "Try cert link."
4488 _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
4489 fi
4490
4491 echo "$END_CERT" >>"$CERT_PATH"
4492 fi
4493
4494 _debug "Le_LinkCert" "$Le_LinkCert"
4495 _savedomainconf "Le_LinkCert" "$Le_LinkCert"
4496
4497 if [ -z "$Le_LinkCert" ] || ! _checkcert "$CERT_PATH"; then
4498 response="$(echo "$response" | _dbase64 "multiline" | tr -d '\0' | _normalizeJson)"
4499 _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
4500 _on_issue_err "$_post_hook"
4501 return 1
4502 fi
4503
4504 if [ "$Le_LinkCert" ]; then
4505 _info "$(__green "Cert success.")"
4506 cat "$CERT_PATH"
4507
4508 _info "Your cert is in $(__green " $CERT_PATH ")"
4509
4510 if [ -f "$CERT_KEY_PATH" ]; then
4511 _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
4512 fi
4513
4514 if [ ! "$USER_PATH" ] || [ ! "$ACME_IN_CRON" ]; then
4515 USER_PATH="$PATH"
4516 _saveaccountconf "USER_PATH" "$USER_PATH"
4517 fi
4518 fi
4519
4520 if [ "$ACME_VERSION" = "2" ]; then
4521 _debug "v2 chain."
4522 else
4523 cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
4524 Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
4525
4526 if [ "$Le_LinkIssuer" ]; then
4527 if ! _contains "$Le_LinkIssuer" ":"; then
4528 _info "$(__red "Relative issuer link found.")"
4529 Le_LinkIssuer="$_ACME_SERVER_HOST$Le_LinkIssuer"
4530 fi
4531 _debug Le_LinkIssuer "$Le_LinkIssuer"
4532 _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
4533
4534 _link_issuer_retry=0
4535 _MAX_ISSUER_RETRY=5
4536 while [ "$_link_issuer_retry" -lt "$_MAX_ISSUER_RETRY" ]; do
4537 _debug _link_issuer_retry "$_link_issuer_retry"
4538 if [ "$ACME_VERSION" = "2" ]; then
4539 if _send_signed_request "$Le_LinkIssuer"; then
4540 echo "$response" >"$CA_CERT_PATH"
4541 break
4542 fi
4543 else
4544 if _get "$Le_LinkIssuer" >"$CA_CERT_PATH.der"; then
4545 echo "$BEGIN_CERT" >"$CA_CERT_PATH"
4546 _base64 "multiline" <"$CA_CERT_PATH.der" >>"$CA_CERT_PATH"
4547 echo "$END_CERT" >>"$CA_CERT_PATH"
4548 if ! _checkcert "$CA_CERT_PATH"; then
4549 _err "Can not get the ca cert."
4550 break
4551 fi
4552 cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
4553 rm -f "$CA_CERT_PATH.der"
4554 break
4555 fi
4556 fi
4557 _link_issuer_retry=$(_math $_link_issuer_retry + 1)
4558 _sleep "$_link_issuer_retry"
4559 done
4560 if [ "$_link_issuer_retry" = "$_MAX_ISSUER_RETRY" ]; then
4561 _err "Max retry for issuer ca cert is reached."
4562 fi
4563 else
4564 _debug "No Le_LinkIssuer header found."
4565 fi
4566 fi
4567 [ -f "$CA_CERT_PATH" ] && _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
4568 [ -f "$CERT_FULLCHAIN_PATH" ] && _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
4569
4570 Le_CertCreateTime=$(_time)
4571 _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
4572
4573 Le_CertCreateTimeStr=$(date -u)
4574 _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
4575
4576 if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ]; then
4577 Le_RenewalDays="$DEFAULT_RENEW"
4578 else
4579 _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
4580 fi
4581
4582 if [ "$CA_BUNDLE" ]; then
4583 _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
4584 else
4585 _clearaccountconf "CA_BUNDLE"
4586 fi
4587
4588 if [ "$CA_PATH" ]; then
4589 _saveaccountconf CA_PATH "$CA_PATH"
4590 else
4591 _clearaccountconf "CA_PATH"
4592 fi
4593
4594 if [ "$HTTPS_INSECURE" ]; then
4595 _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
4596 else
4597 _clearaccountconf "HTTPS_INSECURE"
4598 fi
4599
4600 if [ "$Le_Listen_V4" ]; then
4601 _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
4602 _cleardomainconf Le_Listen_V6
4603 elif [ "$Le_Listen_V6" ]; then
4604 _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
4605 _cleardomainconf Le_Listen_V4
4606 fi
4607
4608 if [ "$Le_ForceNewDomainKey" = "1" ]; then
4609 _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
4610 else
4611 _cleardomainconf Le_ForceNewDomainKey
4612 fi
4613
4614 Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
4615
4616 Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
4617 _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
4618
4619 Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
4620 _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
4621
4622 if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
4623 _savedomainconf "Le_RealCertPath" "$_real_cert"
4624 _savedomainconf "Le_RealCACertPath" "$_real_ca"
4625 _savedomainconf "Le_RealKeyPath" "$_real_key"
4626 _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
4627 _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
4628 if ! _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"; then
4629 return 1
4630 fi
4631 fi
4632
4633 if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
4634 _err "Call hook error."
4635 return 1
4636 fi
4637 }
4638
4639 #domain [isEcc]
4640 renew() {
4641 Le_Domain="$1"
4642 if [ -z "$Le_Domain" ]; then
4643 _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
4644 return 1
4645 fi
4646
4647 _isEcc="$2"
4648
4649 _initpath "$Le_Domain" "$_isEcc"
4650
4651 _info "$(__green "Renew: '$Le_Domain'")"
4652 if [ ! -f "$DOMAIN_CONF" ]; then
4653 _info "'$Le_Domain' is not a issued domain, skip."
4654 return $RENEW_SKIP
4655 fi
4656
4657 if [ "$Le_RenewalDays" ]; then
4658 _savedomainconf Le_RenewalDays "$Le_RenewalDays"
4659 fi
4660
4661 . "$DOMAIN_CONF"
4662 _debug Le_API "$Le_API"
4663
4664 if [ "$Le_API" = "$LETSENCRYPT_CA_V1" ]; then
4665 _cleardomainconf Le_API
4666 Le_API="$DEFAULT_CA"
4667 fi
4668 if [ "$Le_API" = "$LETSENCRYPT_STAGING_CA_V1" ]; then
4669 _cleardomainconf Le_API
4670 Le_API="$DEFAULT_STAGING_CA"
4671 fi
4672
4673 if [ "$Le_API" ]; then
4674 if [ "$_OLD_CA_HOST" = "$Le_API" ]; then
4675 export Le_API="$DEFAULT_CA"
4676 _savedomainconf Le_API "$Le_API"
4677 fi
4678 if [ "$_OLD_STAGE_CA_HOST" = "$Le_API" ]; then
4679 export Le_API="$DEFAULT_STAGING_CA"
4680 _savedomainconf Le_API "$Le_API"
4681 fi
4682 export ACME_DIRECTORY="$Le_API"
4683 #reload ca configs
4684 ACCOUNT_KEY_PATH=""
4685 ACCOUNT_JSON_PATH=""
4686 CA_CONF=""
4687 _debug3 "initpath again."
4688 _initpath "$Le_Domain" "$_isEcc"
4689 fi
4690
4691 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
4692 _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
4693 _info "Add '$(__red '--force')' to force to renew."
4694 return "$RENEW_SKIP"
4695 fi
4696
4697 if [ "$ACME_IN_CRON" = "1" ] && [ -z "$Le_CertCreateTime" ]; then
4698 _info "Skip invalid cert for: $Le_Domain"
4699 return $RENEW_SKIP
4700 fi
4701
4702 IS_RENEW="1"
4703 Le_ReloadCmd="$(_readdomainconf Le_ReloadCmd)"
4704 Le_PreHook="$(_readdomainconf Le_PreHook)"
4705 Le_PostHook="$(_readdomainconf Le_PostHook)"
4706 Le_RenewHook="$(_readdomainconf Le_RenewHook)"
4707 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"
4708 res="$?"
4709 if [ "$res" != "0" ]; then
4710 return "$res"
4711 fi
4712
4713 if [ "$Le_DeployHook" ]; then
4714 _deploy "$Le_Domain" "$Le_DeployHook"
4715 res="$?"
4716 fi
4717
4718 IS_RENEW=""
4719
4720 return "$res"
4721 }
4722
4723 #renewAll [stopRenewOnError]
4724 renewAll() {
4725 _initpath
4726 _stopRenewOnError="$1"
4727 _debug "_stopRenewOnError" "$_stopRenewOnError"
4728 _ret="0"
4729 _success_msg=""
4730 _error_msg=""
4731 _skipped_msg=""
4732 _error_level=$NOTIFY_LEVEL_SKIP
4733 _notify_code=$RENEW_SKIP
4734 _set_level=${NOTIFY_LEVEL:-$NOTIFY_LEVEL_DEFAULT}
4735 _debug "_set_level" "$_set_level"
4736 for di in "${CERT_HOME}"/*.*/; do
4737 _debug di "$di"
4738 if ! [ -d "$di" ]; then
4739 _debug "Not directory, skip: $di"
4740 continue
4741 fi
4742 d=$(basename "$di")
4743 _debug d "$d"
4744 (
4745 if _endswith "$d" "$ECC_SUFFIX"; then
4746 _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
4747 d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
4748 fi
4749 renew "$d" "$_isEcc"
4750 )
4751 rc="$?"
4752 _debug "Return code: $rc"
4753 if [ "$rc" = "0" ]; then
4754 if [ $_error_level -gt $NOTIFY_LEVEL_RENEW ]; then
4755 _error_level="$NOTIFY_LEVEL_RENEW"
4756 _notify_code=0
4757 fi
4758 if [ "$ACME_IN_CRON" ]; then
4759 if [ $_set_level -ge $NOTIFY_LEVEL_RENEW ]; then
4760 if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
4761 _send_notify "Renew $d success" "Good, the cert is renewed." "$NOTIFY_HOOK" 0
4762 fi
4763 fi
4764 fi
4765 _success_msg="${_success_msg} $d
4766 "
4767 elif [ "$rc" = "$RENEW_SKIP" ]; then
4768 if [ $_error_level -gt $NOTIFY_LEVEL_SKIP ]; then
4769 _error_level="$NOTIFY_LEVEL_SKIP"
4770 _notify_code=$RENEW_SKIP
4771 fi
4772 if [ "$ACME_IN_CRON" ]; then
4773 if [ $_set_level -ge $NOTIFY_LEVEL_SKIP ]; then
4774 if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
4775 _send_notify "Renew $d skipped" "Good, the cert is skipped." "$NOTIFY_HOOK" "$RENEW_SKIP"
4776 fi
4777 fi
4778 fi
4779 _info "Skipped $d"
4780 _skipped_msg="${_skipped_msg} $d
4781 "
4782 else
4783 if [ $_error_level -gt $NOTIFY_LEVEL_ERROR ]; then
4784 _error_level="$NOTIFY_LEVEL_ERROR"
4785 _notify_code=1
4786 fi
4787 if [ "$ACME_IN_CRON" ]; then
4788 if [ $_set_level -ge $NOTIFY_LEVEL_ERROR ]; then
4789 if [ "$NOTIFY_MODE" = "$NOTIFY_MODE_CERT" ]; then
4790 _send_notify "Renew $d error" "There is an error." "$NOTIFY_HOOK" 1
4791 fi
4792 fi
4793 fi
4794 _error_msg="${_error_msg} $d
4795 "
4796 if [ "$_stopRenewOnError" ]; then
4797 _err "Error renew $d, stop now."
4798 _ret="$rc"
4799 break
4800 else
4801 _ret="$rc"
4802 _err "Error renew $d."
4803 fi
4804 fi
4805 done
4806 _debug _error_level "$_error_level"
4807 _debug _set_level "$_set_level"
4808 if [ "$ACME_IN_CRON" ] && [ $_error_level -le $_set_level ]; then
4809 if [ -z "$NOTIFY_MODE" ] || [ "$NOTIFY_MODE" = "$NOTIFY_MODE_BULK" ]; then
4810 _msg_subject="Renew"
4811 if [ "$_error_msg" ]; then
4812 _msg_subject="${_msg_subject} Error"
4813 _msg_data="Error certs:
4814 ${_error_msg}
4815 "
4816 fi
4817 if [ "$_success_msg" ]; then
4818 _msg_subject="${_msg_subject} Success"
4819 _msg_data="${_msg_data}Success certs:
4820 ${_success_msg}
4821 "
4822 fi
4823 if [ "$_skipped_msg" ]; then
4824 _msg_subject="${_msg_subject} Skipped"
4825 _msg_data="${_msg_data}Skipped certs:
4826 ${_skipped_msg}
4827 "
4828 fi
4829
4830 _send_notify "$_msg_subject" "$_msg_data" "$NOTIFY_HOOK" "$_notify_code"
4831 fi
4832 fi
4833
4834 return "$_ret"
4835 }
4836
4837 #csr webroot
4838 signcsr() {
4839 _csrfile="$1"
4840 _csrW="$2"
4841 if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
4842 _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
4843 return 1
4844 fi
4845
4846 _real_cert="$3"
4847 _real_key="$4"
4848 _real_ca="$5"
4849 _reload_cmd="$6"
4850 _real_fullchain="$7"
4851 _pre_hook="${8}"
4852 _post_hook="${9}"
4853 _renew_hook="${10}"
4854 _local_addr="${11}"
4855 _challenge_alias="${12}"
4856
4857 _csrsubj=$(_readSubjectFromCSR "$_csrfile")
4858 if [ "$?" != "0" ]; then
4859 _err "Can not read subject from csr: $_csrfile"
4860 return 1
4861 fi
4862 _debug _csrsubj "$_csrsubj"
4863 if _contains "$_csrsubj" ' ' || ! _contains "$_csrsubj" '.'; then
4864 _info "It seems that the subject: $_csrsubj is not a valid domain name. Drop it."
4865 _csrsubj=""
4866 fi
4867
4868 _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
4869 if [ "$?" != "0" ]; then
4870 _err "Can not read domain list from csr: $_csrfile"
4871 return 1
4872 fi
4873 _debug "_csrdomainlist" "$_csrdomainlist"
4874
4875 if [ -z "$_csrsubj" ]; then
4876 _csrsubj="$(_getfield "$_csrdomainlist" 1)"
4877 _debug _csrsubj "$_csrsubj"
4878 _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
4879 _debug "_csrdomainlist" "$_csrdomainlist"
4880 fi
4881
4882 if [ -z "$_csrsubj" ]; then
4883 _err "Can not read subject from csr: $_csrfile"
4884 return 1
4885 fi
4886
4887 _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
4888 if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
4889 _err "Can not read key length from csr: $_csrfile"
4890 return 1
4891 fi
4892
4893 if [ -z "$ACME_VERSION" ] && _contains "$_csrsubj,$_csrdomainlist" "*."; then
4894 export ACME_VERSION=2
4895 fi
4896 _initpath "$_csrsubj" "$_csrkeylength"
4897 mkdir -p "$DOMAIN_PATH"
4898
4899 _info "Copy csr to: $CSR_PATH"
4900 cp "$_csrfile" "$CSR_PATH"
4901
4902 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"
4903
4904 }
4905
4906 showcsr() {
4907 _csrfile="$1"
4908 _csrd="$2"
4909 if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
4910 _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
4911 return 1
4912 fi
4913
4914 _initpath
4915
4916 _csrsubj=$(_readSubjectFromCSR "$_csrfile")
4917 if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
4918 _err "Can not read subject from csr: $_csrfile"
4919 return 1
4920 fi
4921
4922 _info "Subject=$_csrsubj"
4923
4924 _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
4925 if [ "$?" != "0" ]; then
4926 _err "Can not read domain list from csr: $_csrfile"
4927 return 1
4928 fi
4929 _debug "_csrdomainlist" "$_csrdomainlist"
4930
4931 _info "SubjectAltNames=$_csrdomainlist"
4932
4933 _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
4934 if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
4935 _err "Can not read key length from csr: $_csrfile"
4936 return 1
4937 fi
4938 _info "KeyLength=$_csrkeylength"
4939 }
4940
4941 list() {
4942 _raw="$1"
4943 _initpath
4944
4945 _sep="|"
4946 if [ "$_raw" ]; then
4947 printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
4948 for di in "${CERT_HOME}"/*.*/; do
4949 if ! [ -d "$di" ]; then
4950 _debug "Not directory, skip: $di"
4951 continue
4952 fi
4953 d=$(basename "$di")
4954 _debug d "$d"
4955 (
4956 if _endswith "$d" "$ECC_SUFFIX"; then
4957 _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
4958 d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
4959 fi
4960 _initpath "$d" "$_isEcc"
4961 if [ -f "$DOMAIN_CONF" ]; then
4962 . "$DOMAIN_CONF"
4963 printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
4964 fi
4965 )
4966 done
4967 else
4968 if _exists column; then
4969 list "raw" | column -t -s "$_sep"
4970 else
4971 list "raw" | tr "$_sep" '\t'
4972 fi
4973 fi
4974
4975 }
4976
4977 _deploy() {
4978 _d="$1"
4979 _hooks="$2"
4980
4981 for _d_api in $(echo "$_hooks" | tr ',' " "); do
4982 _deployApi="$(_findHook "$_d" $_SUB_FOLDER_DEPLOY "$_d_api")"
4983 if [ -z "$_deployApi" ]; then
4984 _err "The deploy hook $_d_api is not found."
4985 return 1
4986 fi
4987 _debug _deployApi "$_deployApi"
4988
4989 if ! (
4990 if ! . "$_deployApi"; then
4991 _err "Load file $_deployApi error. Please check your api file and try again."
4992 return 1
4993 fi
4994
4995 d_command="${_d_api}_deploy"
4996 if ! _exists "$d_command"; then
4997 _err "It seems that your api file is not correct, it must have a function named: $d_command"
4998 return 1
4999 fi
5000
5001 if ! $d_command "$_d" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
5002 _err "Error deploy for domain:$_d"
5003 return 1
5004 fi
5005 ); then
5006 _err "Deploy error."
5007 return 1
5008 else
5009 _info "$(__green Success)"
5010 fi
5011 done
5012 }
5013
5014 #domain hooks
5015 deploy() {
5016 _d="$1"
5017 _hooks="$2"
5018 _isEcc="$3"
5019 if [ -z "$_hooks" ]; then
5020 _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
5021 return 1
5022 fi
5023
5024 _initpath "$_d" "$_isEcc"
5025 if [ ! -d "$DOMAIN_PATH" ]; then
5026 _err "The domain '$_d' is not a cert name. You must use the cert name to specify the cert to install."
5027 _err "Can not find path:'$DOMAIN_PATH'"
5028 return 1
5029 fi
5030
5031 . "$DOMAIN_CONF"
5032
5033 _savedomainconf Le_DeployHook "$_hooks"
5034
5035 _deploy "$_d" "$_hooks"
5036 }
5037
5038 installcert() {
5039 _main_domain="$1"
5040 if [ -z "$_main_domain" ]; then
5041 _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]"
5042 return 1
5043 fi
5044
5045 _real_cert="$2"
5046 _real_key="$3"
5047 _real_ca="$4"
5048 _reload_cmd="$5"
5049 _real_fullchain="$6"
5050 _isEcc="$7"
5051
5052 _initpath "$_main_domain" "$_isEcc"
5053 if [ ! -d "$DOMAIN_PATH" ]; then
5054 _err "The domain '$_main_domain' is not a cert name. You must use the cert name to specify the cert to install."
5055 _err "Can not find path:'$DOMAIN_PATH'"
5056 return 1
5057 fi
5058
5059 _savedomainconf "Le_RealCertPath" "$_real_cert"
5060 _savedomainconf "Le_RealCACertPath" "$_real_ca"
5061 _savedomainconf "Le_RealKeyPath" "$_real_key"
5062 _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
5063 _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
5064
5065 _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
5066 }
5067
5068 #domain cert key ca fullchain reloadcmd backup-prefix
5069 _installcert() {
5070 _main_domain="$1"
5071 _real_cert="$2"
5072 _real_key="$3"
5073 _real_ca="$4"
5074 _real_fullchain="$5"
5075 _reload_cmd="$6"
5076 _backup_prefix="$7"
5077
5078 if [ "$_real_cert" = "$NO_VALUE" ]; then
5079 _real_cert=""
5080 fi
5081 if [ "$_real_key" = "$NO_VALUE" ]; then
5082 _real_key=""
5083 fi
5084 if [ "$_real_ca" = "$NO_VALUE" ]; then
5085 _real_ca=""
5086 fi
5087 if [ "$_reload_cmd" = "$NO_VALUE" ]; then
5088 _reload_cmd=""
5089 fi
5090 if [ "$_real_fullchain" = "$NO_VALUE" ]; then
5091 _real_fullchain=""
5092 fi
5093
5094 _backup_path="$DOMAIN_BACKUP_PATH/$_backup_prefix"
5095 mkdir -p "$_backup_path"
5096
5097 if [ "$_real_cert" ]; then
5098 _info "Installing cert to:$_real_cert"
5099 if [ -f "$_real_cert" ] && [ ! "$IS_RENEW" ]; then
5100 cp "$_real_cert" "$_backup_path/cert.bak"
5101 fi
5102 cat "$CERT_PATH" >"$_real_cert" || return 1
5103 fi
5104
5105 if [ "$_real_ca" ]; then
5106 _info "Installing CA to:$_real_ca"
5107 if [ "$_real_ca" = "$_real_cert" ]; then
5108 echo "" >>"$_real_ca"
5109 cat "$CA_CERT_PATH" >>"$_real_ca" || return 1
5110 else
5111 if [ -f "$_real_ca" ] && [ ! "$IS_RENEW" ]; then
5112 cp "$_real_ca" "$_backup_path/ca.bak"
5113 fi
5114 cat "$CA_CERT_PATH" >"$_real_ca" || return 1
5115 fi
5116 fi
5117
5118 if [ "$_real_key" ]; then
5119 _info "Installing key to:$_real_key"
5120 if [ -f "$_real_key" ] && [ ! "$IS_RENEW" ]; then
5121 cp "$_real_key" "$_backup_path/key.bak"
5122 fi
5123 if [ -f "$_real_key" ]; then
5124 cat "$CERT_KEY_PATH" >"$_real_key" || return 1
5125 else
5126 cat "$CERT_KEY_PATH" >"$_real_key" || return 1
5127 chmod 600 "$_real_key"
5128 fi
5129 fi
5130
5131 if [ "$_real_fullchain" ]; then
5132 _info "Installing full chain to:$_real_fullchain"
5133 if [ -f "$_real_fullchain" ] && [ ! "$IS_RENEW" ]; then
5134 cp "$_real_fullchain" "$_backup_path/fullchain.bak"
5135 fi
5136 cat "$CERT_FULLCHAIN_PATH" >"$_real_fullchain" || return 1
5137 fi
5138
5139 if [ "$_reload_cmd" ]; then
5140 _info "Run reload cmd: $_reload_cmd"
5141 if (
5142 export CERT_PATH
5143 export CERT_KEY_PATH
5144 export CA_CERT_PATH
5145 export CERT_FULLCHAIN_PATH
5146 export Le_Domain="$_main_domain"
5147 cd "$DOMAIN_PATH" && eval "$_reload_cmd"
5148 ); then
5149 _info "$(__green "Reload success")"
5150 else
5151 _err "Reload error for :$Le_Domain"
5152 fi
5153 fi
5154
5155 }
5156
5157 __read_password() {
5158 unset _pp
5159 prompt="Enter Password:"
5160 while IFS= read -p "$prompt" -r -s -n 1 char; do
5161 if [ "$char" = $'\0' ]; then
5162 break
5163 fi
5164 prompt='*'
5165 _pp="$_pp$char"
5166 done
5167 echo "$_pp"
5168 }
5169
5170 _install_win_taskscheduler() {
5171 _lesh="$1"
5172 _centry="$2"
5173 _randomminute="$3"
5174 if ! _exists cygpath; then
5175 _err "cygpath not found"
5176 return 1
5177 fi
5178 if ! _exists schtasks; then
5179 _err "schtasks.exe is not found, are you on Windows?"
5180 return 1
5181 fi
5182 _winbash="$(cygpath -w $(which bash))"
5183 _debug _winbash "$_winbash"
5184 if [ -z "$_winbash" ]; then
5185 _err "can not find bash path"
5186 return 1
5187 fi
5188 _myname="$(whoami)"
5189 _debug "_myname" "$_myname"
5190 if [ -z "$_myname" ]; then
5191 _err "can not find my user name"
5192 return 1
5193 fi
5194 _debug "_lesh" "$_lesh"
5195
5196 _info "To install scheduler task in your Windows account, you must input your windows password."
5197 _info "$PROJECT_NAME doesn't save your password."
5198 _info "Please input your Windows password for: $(__green "$_myname")"
5199 _password="$(__read_password)"
5200 #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
5201 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
5202 echo
5203
5204 }
5205
5206 _uninstall_win_taskscheduler() {
5207 if ! _exists schtasks; then
5208 _err "schtasks.exe is not found, are you on Windows?"
5209 return 1
5210 fi
5211 if ! echo SCHTASKS /query /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null; then
5212 _debug "scheduler $_WINDOWS_SCHEDULER_NAME is not found."
5213 else
5214 _info "Removing $_WINDOWS_SCHEDULER_NAME"
5215 echo SCHTASKS /delete /f /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null
5216 fi
5217 }
5218
5219 #confighome
5220 installcronjob() {
5221 _c_home="$1"
5222 _initpath
5223 _CRONTAB="crontab"
5224 if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
5225 lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
5226 else
5227 _err "Can not install cronjob, $PROJECT_ENTRY not found."
5228 return 1
5229 fi
5230 if [ "$_c_home" ]; then
5231 _c_entry="--config-home \"$_c_home\" "
5232 fi
5233 _t=$(_time)
5234 random_minute=$(_math $_t % 60)
5235
5236 if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
5237 _CRONTAB="fcrontab"
5238 fi
5239
5240 if ! _exists "$_CRONTAB"; then
5241 if _exists cygpath && _exists schtasks.exe; then
5242 _info "It seems you are on Windows, let's install Windows scheduler task."
5243 if _install_win_taskscheduler "$lesh" "$_c_entry" "$random_minute"; then
5244 _info "Install Windows scheduler task success."
5245 return 0
5246 else
5247 _err "Install Windows scheduler task failed."
5248 return 1
5249 fi
5250 fi
5251 _err "crontab/fcrontab doesn't exist, so, we can not install cron jobs."
5252 _err "All your certs will not be renewed automatically."
5253 _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
5254 return 1
5255 fi
5256 _info "Installing cron job"
5257 if ! $_CRONTAB -l | grep "$PROJECT_ENTRY --cron"; then
5258 if _exists uname && uname -a | grep SunOS >/dev/null; then
5259 $_CRONTAB -l | {
5260 cat
5261 echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
5262 } | $_CRONTAB --
5263 else
5264 $_CRONTAB -l | {
5265 cat
5266 echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
5267 } | $_CRONTAB -
5268 fi
5269 fi
5270 if [ "$?" != "0" ]; then
5271 _err "Install cron job failed. You need to manually renew your certs."
5272 _err "Or you can add cronjob by yourself:"
5273 _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
5274 return 1
5275 fi
5276 }
5277
5278 uninstallcronjob() {
5279 _CRONTAB="crontab"
5280 if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
5281 _CRONTAB="fcrontab"
5282 fi
5283
5284 if ! _exists "$_CRONTAB"; then
5285 if _exists cygpath && _exists schtasks.exe; then
5286 _info "It seems you are on Windows, let's uninstall Windows scheduler task."
5287 if _uninstall_win_taskscheduler; then
5288 _info "Uninstall Windows scheduler task success."
5289 return 0
5290 else
5291 _err "Uninstall Windows scheduler task failed."
5292 return 1
5293 fi
5294 fi
5295 return
5296 fi
5297 _info "Removing cron job"
5298 cr="$($_CRONTAB -l | grep "$PROJECT_ENTRY --cron")"
5299 if [ "$cr" ]; then
5300 if _exists uname && uname -a | grep solaris >/dev/null; then
5301 $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB --
5302 else
5303 $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB -
5304 fi
5305 LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
5306 _info LE_WORKING_DIR "$LE_WORKING_DIR"
5307 if _contains "$cr" "--config-home"; then
5308 LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
5309 _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
5310 fi
5311 fi
5312 _initpath
5313
5314 }
5315
5316 revoke() {
5317 Le_Domain="$1"
5318 if [ -z "$Le_Domain" ]; then
5319 _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com [--ecc]"
5320 return 1
5321 fi
5322
5323 _isEcc="$2"
5324
5325 _initpath "$Le_Domain" "$_isEcc"
5326 if [ ! -f "$DOMAIN_CONF" ]; then
5327 _err "$Le_Domain is not a issued domain, skip."
5328 return 1
5329 fi
5330
5331 if [ ! -f "$CERT_PATH" ]; then
5332 _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
5333 return 1
5334 fi
5335
5336 cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
5337
5338 if [ -z "$cert" ]; then
5339 _err "Cert for $Le_Domain is empty found, skip."
5340 return 1
5341 fi
5342
5343 _initAPI
5344
5345 if [ "$ACME_VERSION" = "2" ]; then
5346 data="{\"certificate\": \"$cert\"}"
5347 else
5348 data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
5349 fi
5350 uri="${ACME_REVOKE_CERT}"
5351
5352 if [ -f "$CERT_KEY_PATH" ]; then
5353 _info "Try domain key first."
5354 if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
5355 if [ -z "$response" ]; then
5356 _info "Revoke success."
5357 rm -f "$CERT_PATH"
5358 return 0
5359 else
5360 _err "Revoke error by domain key."
5361 _err "$response"
5362 fi
5363 fi
5364 else
5365 _info "Domain key file doesn't exists."
5366 fi
5367
5368 _info "Try account key."
5369
5370 if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
5371 if [ -z "$response" ]; then
5372 _info "Revoke success."
5373 rm -f "$CERT_PATH"
5374 return 0
5375 else
5376 _err "Revoke error."
5377 _debug "$response"
5378 fi
5379 fi
5380 return 1
5381 }
5382
5383 #domain ecc
5384 remove() {
5385 Le_Domain="$1"
5386 if [ -z "$Le_Domain" ]; then
5387 _usage "Usage: $PROJECT_ENTRY --remove -d domain.com [--ecc]"
5388 return 1
5389 fi
5390
5391 _isEcc="$2"
5392
5393 _initpath "$Le_Domain" "$_isEcc"
5394 _removed_conf="$DOMAIN_CONF.removed"
5395 if [ ! -f "$DOMAIN_CONF" ]; then
5396 if [ -f "$_removed_conf" ]; then
5397 _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
5398 else
5399 _err "$Le_Domain is not a issued domain, skip."
5400 fi
5401 return 1
5402 fi
5403
5404 if mv "$DOMAIN_CONF" "$_removed_conf"; then
5405 _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
5406 _info "You can remove them by yourself."
5407 return 0
5408 else
5409 _err "Remove $Le_Domain failed."
5410 return 1
5411 fi
5412 }
5413
5414 #domain vtype
5415 _deactivate() {
5416 _d_domain="$1"
5417 _d_type="$2"
5418 _initpath
5419
5420 if [ "$ACME_VERSION" = "2" ]; then
5421 _identifiers="{\"type\":\"dns\",\"value\":\"$_d_domain\"}"
5422 if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
5423 _err "Can not get domain new order."
5424 return 1
5425 fi
5426 _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
5427 _debug2 _authorizations_seg "$_authorizations_seg"
5428 if [ -z "$_authorizations_seg" ]; then
5429 _err "_authorizations_seg not found."
5430 _clearup
5431 _on_issue_err "$_post_hook"
5432 return 1
5433 fi
5434
5435 authzUri="$_authorizations_seg"
5436 _debug2 "authzUri" "$authzUri"
5437 if ! _send_signed_request "$authzUri"; then
5438 _err "get to authz error."
5439 _err "_authorizations_seg" "$_authorizations_seg"
5440 _err "authzUri" "$authzUri"
5441 _clearup
5442 _on_issue_err "$_post_hook"
5443 return 1
5444 fi
5445
5446 response="$(echo "$response" | _normalizeJson)"
5447 _debug2 response "$response"
5448 _URL_NAME="url"
5449 else
5450 if ! __get_domain_new_authz "$_d_domain"; then
5451 _err "Can not get domain new authz token."
5452 return 1
5453 fi
5454
5455 authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
5456 _debug "authzUri" "$authzUri"
5457 if [ "$code" ] && [ ! "$code" = '201' ]; then
5458 _err "new-authz error: $response"
5459 return 1
5460 fi
5461 _URL_NAME="uri"
5462 fi
5463
5464 entries="$(echo "$response" | _egrep_o "{ *\"type\":\"[^\"]*\", *\"status\": *\"valid\", *\"$_URL_NAME\"[^}]*")"
5465 if [ -z "$entries" ]; then
5466 _info "No valid entries found."
5467 if [ -z "$thumbprint" ]; then
5468 thumbprint="$(__calc_account_thumbprint)"
5469 fi
5470 _debug "Trigger validation."
5471 vtype="$VTYPE_DNS"
5472 entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
5473 _debug entry "$entry"
5474 if [ -z "$entry" ]; then
5475 _err "Error, can not get domain token $d"
5476 return 1
5477 fi
5478 token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
5479 _debug token "$token"
5480
5481 uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
5482 _debug uri "$uri"
5483
5484 keyauthorization="$token.$thumbprint"
5485 _debug keyauthorization "$keyauthorization"
5486 __trigger_validation "$uri" "$keyauthorization"
5487
5488 fi
5489
5490 _d_i=0
5491 _d_max_retry=$(echo "$entries" | wc -l)
5492 while [ "$_d_i" -lt "$_d_max_retry" ]; do
5493 _info "Deactivate: $_d_domain"
5494 _d_i="$(_math $_d_i + 1)"
5495 entry="$(echo "$entries" | sed -n "${_d_i}p")"
5496 _debug entry "$entry"
5497
5498 if [ -z "$entry" ]; then
5499 _info "No more valid entry found."
5500 break
5501 fi
5502
5503 _vtype="$(echo "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
5504 _debug _vtype "$_vtype"
5505 _info "Found $_vtype"
5506
5507 uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
5508 _debug uri "$uri"
5509
5510 if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
5511 _info "Skip $_vtype"
5512 continue
5513 fi
5514
5515 _info "Deactivate: $_vtype"
5516
5517 if [ "$ACME_VERSION" = "2" ]; then
5518 _djson="{\"status\":\"deactivated\"}"
5519 else
5520 _djson="{\"resource\": \"authz\", \"status\":\"deactivated\"}"
5521 fi
5522
5523 if _send_signed_request "$authzUri" "$_djson" && _contains "$response" '"deactivated"'; then
5524 _info "Deactivate: $_vtype success."
5525 else
5526 _err "Can not deactivate $_vtype."
5527 break
5528 fi
5529
5530 done
5531 _debug "$_d_i"
5532 if [ "$_d_i" -eq "$_d_max_retry" ]; then
5533 _info "Deactivated success!"
5534 else
5535 _err "Deactivate failed."
5536 fi
5537
5538 }
5539
5540 deactivate() {
5541 _d_domain_list="$1"
5542 _d_type="$2"
5543 _initpath
5544 _initAPI
5545 _debug _d_domain_list "$_d_domain_list"
5546 if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
5547 _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
5548 return 1
5549 fi
5550 for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
5551 if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
5552 continue
5553 fi
5554 if ! _deactivate "$_d_dm" "$_d_type"; then
5555 return 1
5556 fi
5557 done
5558 }
5559
5560 # Detect profile file if not specified as environment variable
5561 _detect_profile() {
5562 if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
5563 echo "$PROFILE"
5564 return
5565 fi
5566
5567 DETECTED_PROFILE=''
5568 SHELLTYPE="$(basename "/$SHELL")"
5569
5570 if [ "$SHELLTYPE" = "bash" ]; then
5571 if [ -f "$HOME/.bashrc" ]; then
5572 DETECTED_PROFILE="$HOME/.bashrc"
5573 elif [ -f "$HOME/.bash_profile" ]; then
5574 DETECTED_PROFILE="$HOME/.bash_profile"
5575 fi
5576 elif [ "$SHELLTYPE" = "zsh" ]; then
5577 DETECTED_PROFILE="$HOME/.zshrc"
5578 fi
5579
5580 if [ -z "$DETECTED_PROFILE" ]; then
5581 if [ -f "$HOME/.profile" ]; then
5582 DETECTED_PROFILE="$HOME/.profile"
5583 elif [ -f "$HOME/.bashrc" ]; then
5584 DETECTED_PROFILE="$HOME/.bashrc"
5585 elif [ -f "$HOME/.bash_profile" ]; then
5586 DETECTED_PROFILE="$HOME/.bash_profile"
5587 elif [ -f "$HOME/.zshrc" ]; then
5588 DETECTED_PROFILE="$HOME/.zshrc"
5589 fi
5590 fi
5591
5592 echo "$DETECTED_PROFILE"
5593 }
5594
5595 _initconf() {
5596 _initpath
5597 if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
5598 echo "
5599
5600 #LOG_FILE=\"$DEFAULT_LOG_FILE\"
5601 #LOG_LEVEL=1
5602
5603 #AUTO_UPGRADE=\"1\"
5604
5605 #NO_TIMESTAMP=1
5606
5607 " >"$ACCOUNT_CONF_PATH"
5608 fi
5609 }
5610
5611 # nocron
5612 _precheck() {
5613 _nocron="$1"
5614
5615 if ! _exists "curl" && ! _exists "wget"; then
5616 _err "Please install curl or wget first, we need to access http resources."
5617 return 1
5618 fi
5619
5620 if [ -z "$_nocron" ]; then
5621 if ! _exists "crontab" && ! _exists "fcrontab"; then
5622 if _exists cygpath && _exists schtasks.exe; then
5623 _info "It seems you are on Windows, we will install Windows scheduler task."
5624 else
5625 _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
5626 _err "We need to set cron job to renew the certs automatically."
5627 _err "Otherwise, your certs will not be able to be renewed automatically."
5628 if [ -z "$FORCE" ]; then
5629 _err "Please add '--force' and try install again to go without crontab."
5630 _err "./$PROJECT_ENTRY --install --force"
5631 return 1
5632 fi
5633 fi
5634 fi
5635 fi
5636
5637 if ! _exists "${ACME_OPENSSL_BIN:-openssl}"; then
5638 _err "Please install openssl first. ACME_OPENSSL_BIN=$ACME_OPENSSL_BIN"
5639 _err "We need openssl to generate keys."
5640 return 1
5641 fi
5642
5643 if ! _exists "socat"; then
5644 _err "It is recommended to install socat first."
5645 _err "We use socat for standalone server if you use standalone mode."
5646 _err "If you don't use standalone mode, just ignore this warning."
5647 fi
5648
5649 return 0
5650 }
5651
5652 _setShebang() {
5653 _file="$1"
5654 _shebang="$2"
5655 if [ -z "$_shebang" ]; then
5656 _usage "Usage: file shebang"
5657 return 1
5658 fi
5659 cp "$_file" "$_file.tmp"
5660 echo "$_shebang" >"$_file"
5661 sed -n 2,99999p "$_file.tmp" >>"$_file"
5662 rm -f "$_file.tmp"
5663 }
5664
5665 #confighome
5666 _installalias() {
5667 _c_home="$1"
5668 _initpath
5669
5670 _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
5671 if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
5672 echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
5673 echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
5674 echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
5675 fi
5676
5677 if [ "$_c_home" ]; then
5678 _c_entry=" --config-home '$_c_home'"
5679 fi
5680
5681 _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
5682 if [ "$_c_home" ]; then
5683 _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
5684 else
5685 _sed_i "/^export LE_CONFIG_HOME/d" "$_envfile"
5686 fi
5687 _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
5688
5689 _profile="$(_detect_profile)"
5690 if [ "$_profile" ]; then
5691 _debug "Found profile: $_profile"
5692 _info "Installing alias to '$_profile'"
5693 _setopt "$_profile" ". \"$_envfile\""
5694 _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
5695 else
5696 _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
5697 fi
5698
5699 #for csh
5700 _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
5701 _csh_profile="$HOME/.cshrc"
5702 if [ -f "$_csh_profile" ]; then
5703 _info "Installing alias to '$_csh_profile'"
5704 _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
5705 if [ "$_c_home" ]; then
5706 _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
5707 else
5708 _sed_i "/^setenv LE_CONFIG_HOME/d" "$_cshfile"
5709 fi
5710 _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
5711 _setopt "$_csh_profile" "source \"$_cshfile\""
5712 fi
5713
5714 #for tcsh
5715 _tcsh_profile="$HOME/.tcshrc"
5716 if [ -f "$_tcsh_profile" ]; then
5717 _info "Installing alias to '$_tcsh_profile'"
5718 _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
5719 if [ "$_c_home" ]; then
5720 _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
5721 fi
5722 _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
5723 _setopt "$_tcsh_profile" "source \"$_cshfile\""
5724 fi
5725
5726 }
5727
5728 # nocron confighome noprofile
5729 install() {
5730
5731 if [ -z "$LE_WORKING_DIR" ]; then
5732 LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
5733 fi
5734
5735 _nocron="$1"
5736 _c_home="$2"
5737 _noprofile="$3"
5738 if ! _initpath; then
5739 _err "Install failed."
5740 return 1
5741 fi
5742 if [ "$_nocron" ]; then
5743 _debug "Skip install cron job"
5744 fi
5745
5746 if [ "$ACME_IN_CRON" != "1" ]; then
5747 if ! _precheck "$_nocron"; then
5748 _err "Pre-check failed, can not install."
5749 return 1
5750 fi
5751 fi
5752
5753 if [ -z "$_c_home" ] && [ "$LE_CONFIG_HOME" != "$LE_WORKING_DIR" ]; then
5754 _info "Using config home: $LE_CONFIG_HOME"
5755 _c_home="$LE_CONFIG_HOME"
5756 fi
5757
5758 #convert from le
5759 if [ -d "$HOME/.le" ]; then
5760 for envfile in "le.env" "le.sh.env"; do
5761 if [ -f "$HOME/.le/$envfile" ]; then
5762 if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
5763 _upgrading="1"
5764 _info "You are upgrading from le.sh"
5765 _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
5766 mv "$HOME/.le" "$LE_WORKING_DIR"
5767 mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
5768 break
5769 fi
5770 fi
5771 done
5772 fi
5773
5774 _info "Installing to $LE_WORKING_DIR"
5775
5776 if [ ! -d "$LE_WORKING_DIR" ]; then
5777 if ! mkdir -p "$LE_WORKING_DIR"; then
5778 _err "Can not create working dir: $LE_WORKING_DIR"
5779 return 1
5780 fi
5781
5782 chmod 700 "$LE_WORKING_DIR"
5783 fi
5784
5785 if [ ! -d "$LE_CONFIG_HOME" ]; then
5786 if ! mkdir -p "$LE_CONFIG_HOME"; then
5787 _err "Can not create config dir: $LE_CONFIG_HOME"
5788 return 1
5789 fi
5790
5791 chmod 700 "$LE_CONFIG_HOME"
5792 fi
5793
5794 cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
5795
5796 if [ "$?" != "0" ]; then
5797 _err "Install failed, can not copy $PROJECT_ENTRY"
5798 return 1
5799 fi
5800
5801 _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
5802
5803 if [ "$ACME_IN_CRON" != "1" ] && [ -z "$_noprofile" ]; then
5804 _installalias "$_c_home"
5805 fi
5806
5807 for subf in $_SUB_FOLDERS; do
5808 if [ -d "$subf" ]; then
5809 mkdir -p "$LE_WORKING_DIR/$subf"
5810 cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
5811 fi
5812 done
5813
5814 if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
5815 _initconf
5816 fi
5817
5818 if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
5819 _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
5820 fi
5821
5822 if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
5823 _saveaccountconf "CERT_HOME" "$CERT_HOME"
5824 fi
5825
5826 if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
5827 _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
5828 fi
5829
5830 if [ -z "$_nocron" ]; then
5831 installcronjob "$_c_home"
5832 fi
5833
5834 if [ -z "$NO_DETECT_SH" ]; then
5835 #Modify shebang
5836 if _exists bash; then
5837 _bash_path="$(bash -c "command -v bash 2>/dev/null")"
5838 if [ -z "$_bash_path" ]; then
5839 _bash_path="$(bash -c 'echo $SHELL')"
5840 fi
5841 fi
5842 if [ "$_bash_path" ]; then
5843 _info "Good, bash is found, so change the shebang to use bash as preferred."
5844 _shebang='#!'"$_bash_path"
5845 _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
5846 for subf in $_SUB_FOLDERS; do
5847 if [ -d "$LE_WORKING_DIR/$subf" ]; then
5848 for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
5849 _setShebang "$_apifile" "$_shebang"
5850 done
5851 fi
5852 done
5853 fi
5854 fi
5855
5856 _info OK
5857 }
5858
5859 # nocron
5860 uninstall() {
5861 _nocron="$1"
5862 if [ -z "$_nocron" ]; then
5863 uninstallcronjob
5864 fi
5865 _initpath
5866
5867 _uninstallalias
5868
5869 rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
5870 _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
5871
5872 }
5873
5874 _uninstallalias() {
5875 _initpath
5876
5877 _profile="$(_detect_profile)"
5878 if [ "$_profile" ]; then
5879 _info "Uninstalling alias from: '$_profile'"
5880 text="$(cat "$_profile")"
5881 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
5882 fi
5883
5884 _csh_profile="$HOME/.cshrc"
5885 if [ -f "$_csh_profile" ]; then
5886 _info "Uninstalling alias from: '$_csh_profile'"
5887 text="$(cat "$_csh_profile")"
5888 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
5889 fi
5890
5891 _tcsh_profile="$HOME/.tcshrc"
5892 if [ -f "$_tcsh_profile" ]; then
5893 _info "Uninstalling alias from: '$_csh_profile'"
5894 text="$(cat "$_tcsh_profile")"
5895 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
5896 fi
5897
5898 }
5899
5900 cron() {
5901 export ACME_IN_CRON=1
5902 _initpath
5903 _info "$(__green "===Starting cron===")"
5904 if [ "$AUTO_UPGRADE" = "1" ]; then
5905 export LE_WORKING_DIR
5906 (
5907 if ! upgrade; then
5908 _err "Cron:Upgrade failed!"
5909 return 1
5910 fi
5911 )
5912 . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
5913
5914 if [ -t 1 ]; then
5915 __INTERACTIVE="1"
5916 fi
5917
5918 _info "Auto upgraded to: $VER"
5919 fi
5920 renewAll
5921 _ret="$?"
5922 ACME_IN_CRON=""
5923 _info "$(__green "===End cron===")"
5924 exit $_ret
5925 }
5926
5927 version() {
5928 echo "$PROJECT"
5929 echo "v$VER"
5930 }
5931
5932 # subject content hooks code
5933 _send_notify() {
5934 _nsubject="$1"
5935 _ncontent="$2"
5936 _nhooks="$3"
5937 _nerror="$4"
5938
5939 if [ "$NOTIFY_LEVEL" = "$NOTIFY_LEVEL_DISABLE" ]; then
5940 _debug "The NOTIFY_LEVEL is $NOTIFY_LEVEL, disabled, just return."
5941 return 0
5942 fi
5943
5944 if [ -z "$_nhooks" ]; then
5945 _debug "The NOTIFY_HOOK is empty, just return."
5946 return 0
5947 fi
5948
5949 _send_err=0
5950 for _n_hook in $(echo "$_nhooks" | tr ',' " "); do
5951 _n_hook_file="$(_findHook "" $_SUB_FOLDER_NOTIFY "$_n_hook")"
5952 _info "Sending via: $_n_hook"
5953 _debug "Found $_n_hook_file for $_n_hook"
5954 if [ -z "$_n_hook_file" ]; then
5955 _err "Can not find the hook file for $_n_hook"
5956 continue
5957 fi
5958 if ! (
5959 if ! . "$_n_hook_file"; then
5960 _err "Load file $_n_hook_file error. Please check your api file and try again."
5961 return 1
5962 fi
5963
5964 d_command="${_n_hook}_send"
5965 if ! _exists "$d_command"; then
5966 _err "It seems that your api file is not correct, it must have a function named: $d_command"
5967 return 1
5968 fi
5969
5970 if ! $d_command "$_nsubject" "$_ncontent" "$_nerror"; then
5971 _err "Error send message by $d_command"
5972 return 1
5973 fi
5974
5975 return 0
5976 ); then
5977 _err "Set $_n_hook_file error."
5978 _send_err=1
5979 else
5980 _info "$_n_hook $(__green Success)"
5981 fi
5982 done
5983 return $_send_err
5984
5985 }
5986
5987 # hook
5988 _set_notify_hook() {
5989 _nhooks="$1"
5990
5991 _test_subject="Hello, this is notification from $PROJECT_NAME"
5992 _test_content="If you receive this message, your notification works."
5993
5994 _send_notify "$_test_subject" "$_test_content" "$_nhooks" 0
5995
5996 }
5997
5998 #[hook] [level] [mode]
5999 setnotify() {
6000 _nhook="$1"
6001 _nlevel="$2"
6002 _nmode="$3"
6003
6004 _initpath
6005
6006 if [ -z "$_nhook$_nlevel$_nmode" ]; then
6007 _usage "Usage: $PROJECT_ENTRY --set-notify [--notify-hook mailgun] [--notify-level $NOTIFY_LEVEL_DEFAULT] [--notify-mode $NOTIFY_MODE_DEFAULT]"
6008 _usage "$_NOTIFY_WIKI"
6009 return 1
6010 fi
6011
6012 if [ "$_nlevel" ]; then
6013 _info "Set notify level to: $_nlevel"
6014 export "NOTIFY_LEVEL=$_nlevel"
6015 _saveaccountconf "NOTIFY_LEVEL" "$NOTIFY_LEVEL"
6016 fi
6017
6018 if [ "$_nmode" ]; then
6019 _info "Set notify mode to: $_nmode"
6020 export "NOTIFY_MODE=$_nmode"
6021 _saveaccountconf "NOTIFY_MODE" "$NOTIFY_MODE"
6022 fi
6023
6024 if [ "$_nhook" ]; then
6025 _info "Set notify hook to: $_nhook"
6026 if [ "$_nhook" = "$NO_VALUE" ]; then
6027 _info "Clear notify hook"
6028 _clearaccountconf "NOTIFY_HOOK"
6029 else
6030 if _set_notify_hook "$_nhook"; then
6031 export NOTIFY_HOOK="$_nhook"
6032 _saveaccountconf "NOTIFY_HOOK" "$NOTIFY_HOOK"
6033 return 0
6034 else
6035 _err "Can not set notify hook to: $_nhook"
6036 return 1
6037 fi
6038 fi
6039 fi
6040
6041 }
6042
6043 showhelp() {
6044 _initpath
6045 version
6046 echo "Usage: $PROJECT_ENTRY command ...[parameters]....
6047 Commands:
6048 --help, -h Show this help message.
6049 --version, -v Show version info.
6050 --install Install $PROJECT_NAME to your system.
6051 --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
6052 --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT.
6053 --issue Issue a cert.
6054 --signcsr Issue a cert from an existing csr.
6055 --deploy Deploy the cert to your server.
6056 --install-cert Install the issued cert to apache/nginx or any other server.
6057 --renew, -r Renew a cert.
6058 --renew-all Renew all the certs.
6059 --revoke Revoke a cert.
6060 --remove Remove the cert from list of certs known to $PROJECT_NAME.
6061 --list List all the certs.
6062 --showcsr Show the content of a csr.
6063 --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.
6064 --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
6065 --cron Run cron job to renew all the certs.
6066 --toPkcs Export the certificate and key to a pfx file.
6067 --toPkcs8 Convert to pkcs8 format.
6068 --update-account Update account info.
6069 --register-account Register account key.
6070 --deactivate-account Deactivate the account.
6071 --create-account-key Create an account private key, professional use.
6072 --create-domain-key Create an domain private key, professional use.
6073 --createCSR, -ccsr Create CSR , professional use.
6074 --deactivate Deactivate the domain authz, professional use.
6075 --set-notify Set the cron notification hook, level or mode.
6076
6077
6078 Parameters:
6079 --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
6080 --challenge-alias domain.tld The challenge domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
6081 --domain-alias domain.tld The domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
6082 --force, -f Used to force to install or force to renew a cert immediately.
6083 --staging, --test Use staging server, just for test.
6084 --debug Output debug info.
6085 --output-insecure Output all the sensitive messages. By default all the credentials/sensitive messages are hidden from the output/debug/log for secure.
6086 --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
6087 --standalone Use standalone mode.
6088 --alpn Use standalone alpn mode.
6089 --stateless Use stateless mode, see: $_STATELESS_WIKI
6090 --apache Use apache mode.
6091 --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
6092 --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.
6093
6094 --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
6095 --accountkeylength, -ak [2048] Specifies the account key length.
6096 --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
6097 --log-level 1|2 Specifies the log level, default is 1.
6098 --syslog [0|3|6|7] Syslog level, 0: disable syslog, 3: error, 6: info, 7: debug.
6099
6100 These parameters are to install the cert to nginx/apache or any other server after issue/renew a cert:
6101
6102 --cert-file After issue/renew, the cert will be copied to this path.
6103 --key-file After issue/renew, the key will be copied to this path.
6104 --ca-file After issue/renew, the intermediate cert will be copied to this path.
6105 --fullchain-file After issue/renew, the fullchain cert will be copied to this path.
6106
6107 --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
6108
6109 --server SERVER ACME Directory Resource URI. (default: https://acme-v01.api.letsencrypt.org/directory)
6110 --accountconf Specifies a customized account config file.
6111 --home Specifies the home dir for $PROJECT_NAME.
6112 --cert-home Specifies the home dir to save all the certs, only valid for '--install' command.
6113 --config-home Specifies the home dir to save all the configurations.
6114 --useragent Specifies the user agent string. it will be saved for future use too.
6115 --accountemail Specifies the account email, only valid for the '--install' and '--update-account' command.
6116 --accountkey Specifies the account key path, only valid for the '--install' command.
6117 --days Specifies the days to renew the cert when using '--issue' command. The default value is $DEFAULT_RENEW days.
6118 --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
6119 --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
6120 --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
6121 --listraw Only used for '--list' command, list the certs in raw format.
6122 --stopRenewOnError, -se Only valid for '--renew-all' command. Stop if one cert has error in renewal.
6123 --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
6124 --ca-bundle Specifies the path to the CA certificate bundle to verify api server's certificate.
6125 --ca-path Specifies directory containing CA certificates in PEM format, used by wget or curl.
6126 --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.
6127 --noprofile Only valid for '--install' command, which means: do not install aliases to user profile.
6128 --no-color Do not output color text.
6129 --force-color Force output of color text. Useful for non-interactive use with the aha tool for HTML E-Mails.
6130 --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
6131 --csr Specifies the input csr.
6132 --pre-hook Command to be run before obtaining any certificates.
6133 --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obtain/renew is success or failed.
6134 --renew-hook Command to be run once for each successfully renewed certificate.
6135 --deploy-hook The hook file to deploy cert
6136 --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
6137 --always-force-new-domain-key Generate new domain key when renewal. Otherwise, the domain key is not changed by default.
6138 --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
6139 --listen-v4 Force standalone/tls server to listen at ipv4.
6140 --listen-v6 Force standalone/tls server to listen at ipv6.
6141 --openssl-bin Specifies a custom openssl bin location.
6142 --use-wget Force to use wget, if you have both curl and wget installed.
6143 --yes-I-know-dns-manual-mode-enough-go-ahead-please Force to use dns manual mode: $_DNS_MANUAL_WIKI
6144 --branch, -b Only valid for '--upgrade' command, specifies the branch name to upgrade to.
6145
6146 --notify-level 0|1|2|3 Set the notification level: Default value is $NOTIFY_LEVEL_DEFAULT.
6147 0: disabled, no notification will be sent.
6148 1: send notifications only when there is an error.
6149 2: send notifications when a cert is successfully renewed, or there is an error.
6150 3: send notifications when a cert is skipped, renewed, or error.
6151 --notify-mode 0|1 Set notification mode. Default value is $NOTIFY_MODE_DEFAULT.
6152 0: Bulk mode. Send all the domain's notifications in one message(mail).
6153 1: Cert mode. Send a message for every single cert.
6154 --notify-hook [hookname] Set the notify hook
6155
6156 "
6157 }
6158
6159 # nocron noprofile
6160 _installOnline() {
6161 _info "Installing from online archive."
6162 _nocron="$1"
6163 _noprofile="$2"
6164 if [ ! "$BRANCH" ]; then
6165 BRANCH="master"
6166 fi
6167
6168 target="$PROJECT/archive/$BRANCH.tar.gz"
6169 _info "Downloading $target"
6170 localname="$BRANCH.tar.gz"
6171 if ! _get "$target" >$localname; then
6172 _err "Download error."
6173 return 1
6174 fi
6175 (
6176 _info "Extracting $localname"
6177 if ! (tar xzf $localname || gtar xzf $localname); then
6178 _err "Extraction error."
6179 exit 1
6180 fi
6181
6182 cd "$PROJECT_NAME-$BRANCH"
6183 chmod +x $PROJECT_ENTRY
6184 if ./$PROJECT_ENTRY install "$_nocron" "" "$_noprofile"; then
6185 _info "Install success!"
6186 fi
6187
6188 cd ..
6189
6190 rm -rf "$PROJECT_NAME-$BRANCH"
6191 rm -f "$localname"
6192 )
6193 }
6194
6195 upgrade() {
6196 if (
6197 _initpath
6198 export LE_WORKING_DIR
6199 cd "$LE_WORKING_DIR"
6200 _installOnline "nocron" "noprofile"
6201 ); then
6202 _info "Upgrade success!"
6203 exit 0
6204 else
6205 _err "Upgrade failed!"
6206 exit 1
6207 fi
6208 }
6209
6210 _processAccountConf() {
6211 if [ "$_useragent" ]; then
6212 _saveaccountconf "USER_AGENT" "$_useragent"
6213 elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
6214 _saveaccountconf "USER_AGENT" "$USER_AGENT"
6215 fi
6216
6217 if [ "$_accountemail" ]; then
6218 _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
6219 elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
6220 _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
6221 fi
6222
6223 if [ "$_openssl_bin" ]; then
6224 _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
6225 elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
6226 _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
6227 fi
6228
6229 if [ "$_auto_upgrade" ]; then
6230 _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
6231 elif [ "$AUTO_UPGRADE" ]; then
6232 _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
6233 fi
6234
6235 if [ "$_use_wget" ]; then
6236 _saveaccountconf "ACME_USE_WGET" "$_use_wget"
6237 elif [ "$ACME_USE_WGET" ]; then
6238 _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
6239 fi
6240
6241 }
6242
6243 _checkSudo() {
6244 if [ "$SUDO_GID" ] && [ "$SUDO_COMMAND" ] && [ "$SUDO_USER" ] && [ "$SUDO_UID" ]; then
6245 if [ "$SUDO_USER" = "root" ] && [ "$SUDO_UID" = "0" ]; then
6246 #it's root using sudo, no matter it's using sudo or not, just fine
6247 return 0
6248 fi
6249 if [ "$SUDO_COMMAND" = "/bin/su" ]; then
6250 #it's a normal user doing "sudo su"
6251 #fine
6252 return 0
6253 fi
6254 #otherwise
6255 return 1
6256 fi
6257 return 0
6258 }
6259
6260 _process() {
6261 _CMD=""
6262 _domain=""
6263 _altdomains="$NO_VALUE"
6264 _webroot=""
6265 _challenge_alias=""
6266 _keylength=""
6267 _accountkeylength=""
6268 _cert_file=""
6269 _key_file=""
6270 _ca_file=""
6271 _fullchain_file=""
6272 _reloadcmd=""
6273 _password=""
6274 _accountconf=""
6275 _useragent=""
6276 _accountemail=""
6277 _accountkey=""
6278 _certhome=""
6279 _confighome=""
6280 _httpport=""
6281 _tlsport=""
6282 _dnssleep=""
6283 _listraw=""
6284 _stopRenewOnError=""
6285 #_insecure=""
6286 _ca_bundle=""
6287 _ca_path=""
6288 _nocron=""
6289 _noprofile=""
6290 _ecc=""
6291 _csr=""
6292 _pre_hook=""
6293 _post_hook=""
6294 _renew_hook=""
6295 _deploy_hook=""
6296 _logfile=""
6297 _log=""
6298 _local_address=""
6299 _log_level=""
6300 _auto_upgrade=""
6301 _listen_v4=""
6302 _listen_v6=""
6303 _openssl_bin=""
6304 _syslog=""
6305 _use_wget=""
6306 _server=""
6307 _notify_hook=""
6308 _notify_level=""
6309 _notify_mode=""
6310 while [ ${#} -gt 0 ]; do
6311 case "${1}" in
6312
6313 --help | -h)
6314 showhelp
6315 return
6316 ;;
6317 --version | -v)
6318 version
6319 return
6320 ;;
6321 --install)
6322 _CMD="install"
6323 ;;
6324 --uninstall)
6325 _CMD="uninstall"
6326 ;;
6327 --upgrade)
6328 _CMD="upgrade"
6329 ;;
6330 --issue)
6331 _CMD="issue"
6332 ;;
6333 --deploy)
6334 _CMD="deploy"
6335 ;;
6336 --signcsr)
6337 _CMD="signcsr"
6338 ;;
6339 --showcsr)
6340 _CMD="showcsr"
6341 ;;
6342 --installcert | -i | --install-cert)
6343 _CMD="installcert"
6344 ;;
6345 --renew | -r)
6346 _CMD="renew"
6347 ;;
6348 --renewAll | --renewall | --renew-all)
6349 _CMD="renewAll"
6350 ;;
6351 --revoke)
6352 _CMD="revoke"
6353 ;;
6354 --remove)
6355 _CMD="remove"
6356 ;;
6357 --list)
6358 _CMD="list"
6359 ;;
6360 --installcronjob | --install-cronjob)
6361 _CMD="installcronjob"
6362 ;;
6363 --uninstallcronjob | --uninstall-cronjob)
6364 _CMD="uninstallcronjob"
6365 ;;
6366 --cron)
6367 _CMD="cron"
6368 ;;
6369 --toPkcs)
6370 _CMD="toPkcs"
6371 ;;
6372 --toPkcs8)
6373 _CMD="toPkcs8"
6374 ;;
6375 --createAccountKey | --createaccountkey | -cak | --create-account-key)
6376 _CMD="createAccountKey"
6377 ;;
6378 --createDomainKey | --createdomainkey | -cdk | --create-domain-key)
6379 _CMD="createDomainKey"
6380 ;;
6381 --createCSR | --createcsr | -ccr)
6382 _CMD="createCSR"
6383 ;;
6384 --deactivate)
6385 _CMD="deactivate"
6386 ;;
6387 --updateaccount | --update-account)
6388 _CMD="updateaccount"
6389 ;;
6390 --registeraccount | --register-account)
6391 _CMD="registeraccount"
6392 ;;
6393 --deactivate-account)
6394 _CMD="deactivateaccount"
6395 ;;
6396 --set-notify)
6397 _CMD="setnotify"
6398 ;;
6399 --domain | -d)
6400 _dvalue="$2"
6401
6402 if [ "$_dvalue" ]; then
6403 if _startswith "$_dvalue" "-"; then
6404 _err "'$_dvalue' is not a valid domain for parameter '$1'"
6405 return 1
6406 fi
6407 if _is_idn "$_dvalue" && ! _exists idn; then
6408 _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
6409 return 1
6410 fi
6411
6412 if _startswith "$_dvalue" "*."; then
6413 _debug "Wildcard domain"
6414 export ACME_VERSION=2
6415 fi
6416 if [ -z "$_domain" ]; then
6417 _domain="$_dvalue"
6418 else
6419 if [ "$_altdomains" = "$NO_VALUE" ]; then
6420 _altdomains="$_dvalue"
6421 else
6422 _altdomains="$_altdomains,$_dvalue"
6423 fi
6424 fi
6425 fi
6426
6427 shift
6428 ;;
6429
6430 --force | -f)
6431 FORCE="1"
6432 ;;
6433 --staging | --test)
6434 STAGE="1"
6435 ;;
6436 --server)
6437 ACME_DIRECTORY="$2"
6438 _server="$ACME_DIRECTORY"
6439 export ACME_DIRECTORY
6440 shift
6441 ;;
6442 --debug)
6443 if [ -z "$2" ] || _startswith "$2" "-"; then
6444 DEBUG="$DEBUG_LEVEL_DEFAULT"
6445 else
6446 DEBUG="$2"
6447 shift
6448 fi
6449 ;;
6450 --output-insecure)
6451 export OUTPUT_INSECURE=1
6452 ;;
6453 --webroot | -w)
6454 wvalue="$2"
6455 if [ -z "$_webroot" ]; then
6456 _webroot="$wvalue"
6457 else
6458 _webroot="$_webroot,$wvalue"
6459 fi
6460 shift
6461 ;;
6462 --challenge-alias)
6463 cvalue="$2"
6464 _challenge_alias="$_challenge_alias$cvalue,"
6465 shift
6466 ;;
6467 --domain-alias)
6468 cvalue="$DNS_ALIAS_PREFIX$2"
6469 _challenge_alias="$_challenge_alias$cvalue,"
6470 shift
6471 ;;
6472 --standalone)
6473 wvalue="$NO_VALUE"
6474 if [ -z "$_webroot" ]; then
6475 _webroot="$wvalue"
6476 else
6477 _webroot="$_webroot,$wvalue"
6478 fi
6479 ;;
6480 --alpn)
6481 wvalue="$W_ALPN"
6482 if [ -z "$_webroot" ]; then
6483 _webroot="$wvalue"
6484 else
6485 _webroot="$_webroot,$wvalue"
6486 fi
6487 ;;
6488 --stateless)
6489 wvalue="$MODE_STATELESS"
6490 if [ -z "$_webroot" ]; then
6491 _webroot="$wvalue"
6492 else
6493 _webroot="$_webroot,$wvalue"
6494 fi
6495 ;;
6496 --local-address)
6497 lvalue="$2"
6498 _local_address="$_local_address$lvalue,"
6499 shift
6500 ;;
6501 --apache)
6502 wvalue="apache"
6503 if [ -z "$_webroot" ]; then
6504 _webroot="$wvalue"
6505 else
6506 _webroot="$_webroot,$wvalue"
6507 fi
6508 ;;
6509 --nginx)
6510 wvalue="$NGINX"
6511 if [ "$2" ] && ! _startswith "$2" "-"; then
6512 wvalue="$NGINX$2"
6513 shift
6514 fi
6515 if [ -z "$_webroot" ]; then
6516 _webroot="$wvalue"
6517 else
6518 _webroot="$_webroot,$wvalue"
6519 fi
6520 ;;
6521 --dns)
6522 wvalue="$W_DNS"
6523 if [ "$2" ] && ! _startswith "$2" "-"; then
6524 wvalue="$2"
6525 shift
6526 fi
6527 if [ -z "$_webroot" ]; then
6528 _webroot="$wvalue"
6529 else
6530 _webroot="$_webroot,$wvalue"
6531 fi
6532 ;;
6533 --dnssleep)
6534 _dnssleep="$2"
6535 Le_DNSSleep="$_dnssleep"
6536 shift
6537 ;;
6538
6539 --keylength | -k)
6540 _keylength="$2"
6541 shift
6542 ;;
6543 --accountkeylength | -ak)
6544 _accountkeylength="$2"
6545 shift
6546 ;;
6547
6548 --cert-file | --certpath)
6549 _cert_file="$2"
6550 shift
6551 ;;
6552 --key-file | --keypath)
6553 _key_file="$2"
6554 shift
6555 ;;
6556 --ca-file | --capath)
6557 _ca_file="$2"
6558 shift
6559 ;;
6560 --fullchain-file | --fullchainpath)
6561 _fullchain_file="$2"
6562 shift
6563 ;;
6564 --reloadcmd | --reloadCmd)
6565 _reloadcmd="$2"
6566 shift
6567 ;;
6568 --password)
6569 _password="$2"
6570 shift
6571 ;;
6572 --accountconf)
6573 _accountconf="$2"
6574 ACCOUNT_CONF_PATH="$_accountconf"
6575 shift
6576 ;;
6577 --home)
6578 LE_WORKING_DIR="$2"
6579 shift
6580 ;;
6581 --certhome | --cert-home)
6582 _certhome="$2"
6583 CERT_HOME="$_certhome"
6584 shift
6585 ;;
6586 --config-home)
6587 _confighome="$2"
6588 LE_CONFIG_HOME="$_confighome"
6589 shift
6590 ;;
6591 --useragent)
6592 _useragent="$2"
6593 USER_AGENT="$_useragent"
6594 shift
6595 ;;
6596 --accountemail)
6597 _accountemail="$2"
6598 ACCOUNT_EMAIL="$_accountemail"
6599 shift
6600 ;;
6601 --accountkey)
6602 _accountkey="$2"
6603 ACCOUNT_KEY_PATH="$_accountkey"
6604 shift
6605 ;;
6606 --days)
6607 _days="$2"
6608 Le_RenewalDays="$_days"
6609 shift
6610 ;;
6611 --httpport)
6612 _httpport="$2"
6613 Le_HTTPPort="$_httpport"
6614 shift
6615 ;;
6616 --tlsport)
6617 _tlsport="$2"
6618 Le_TLSPort="$_tlsport"
6619 shift
6620 ;;
6621 --listraw)
6622 _listraw="raw"
6623 ;;
6624 --stopRenewOnError | --stoprenewonerror | -se)
6625 _stopRenewOnError="1"
6626 ;;
6627 --insecure)
6628 #_insecure="1"
6629 HTTPS_INSECURE="1"
6630 ;;
6631 --ca-bundle)
6632 _ca_bundle="$(_readlink "$2")"
6633 CA_BUNDLE="$_ca_bundle"
6634 shift
6635 ;;
6636 --ca-path)
6637 _ca_path="$2"
6638 CA_PATH="$_ca_path"
6639 shift
6640 ;;
6641 --nocron)
6642 _nocron="1"
6643 ;;
6644 --noprofile)
6645 _noprofile="1"
6646 ;;
6647 --no-color)
6648 export ACME_NO_COLOR=1
6649 ;;
6650 --force-color)
6651 export ACME_FORCE_COLOR=1
6652 ;;
6653 --ecc)
6654 _ecc="isEcc"
6655 ;;
6656 --csr)
6657 _csr="$2"
6658 shift
6659 ;;
6660 --pre-hook)
6661 _pre_hook="$2"
6662 shift
6663 ;;
6664 --post-hook)
6665 _post_hook="$2"
6666 shift
6667 ;;
6668 --renew-hook)
6669 _renew_hook="$2"
6670 shift
6671 ;;
6672 --deploy-hook)
6673 if [ -z "$2" ] || _startswith "$2" "-"; then
6674 _usage "Please specify a value for '--deploy-hook'"
6675 return 1
6676 fi
6677 _deploy_hook="$_deploy_hook$2,"
6678 shift
6679 ;;
6680 --ocsp-must-staple | --ocsp)
6681 Le_OCSP_Staple="1"
6682 ;;
6683 --always-force-new-domain-key)
6684 if [ -z "$2" ] || _startswith "$2" "-"; then
6685 Le_ForceNewDomainKey=1
6686 else
6687 Le_ForceNewDomainKey="$2"
6688 shift
6689 fi
6690 ;;
6691 --yes-I-know-dns-manual-mode-enough-go-ahead-please)
6692 export FORCE_DNS_MANUAL=1
6693 ;;
6694 --log | --logfile)
6695 _log="1"
6696 _logfile="$2"
6697 if _startswith "$_logfile" '-'; then
6698 _logfile=""
6699 else
6700 shift
6701 fi
6702 LOG_FILE="$_logfile"
6703 if [ -z "$LOG_LEVEL" ]; then
6704 LOG_LEVEL="$DEFAULT_LOG_LEVEL"
6705 fi
6706 ;;
6707 --log-level)
6708 _log_level="$2"
6709 LOG_LEVEL="$_log_level"
6710 shift
6711 ;;
6712 --syslog)
6713 if ! _startswith "$2" '-'; then
6714 _syslog="$2"
6715 shift
6716 fi
6717 if [ -z "$_syslog" ]; then
6718 _syslog="$SYSLOG_LEVEL_DEFAULT"
6719 fi
6720 ;;
6721 --auto-upgrade)
6722 _auto_upgrade="$2"
6723 if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
6724 _auto_upgrade="1"
6725 else
6726 shift
6727 fi
6728 AUTO_UPGRADE="$_auto_upgrade"
6729 ;;
6730 --listen-v4)
6731 _listen_v4="1"
6732 Le_Listen_V4="$_listen_v4"
6733 ;;
6734 --listen-v6)
6735 _listen_v6="1"
6736 Le_Listen_V6="$_listen_v6"
6737 ;;
6738 --openssl-bin)
6739 _openssl_bin="$2"
6740 ACME_OPENSSL_BIN="$_openssl_bin"
6741 shift
6742 ;;
6743 --use-wget)
6744 _use_wget="1"
6745 ACME_USE_WGET="1"
6746 ;;
6747 --branch | -b)
6748 export BRANCH="$2"
6749 shift
6750 ;;
6751 --notify-hook)
6752 _nhook="$2"
6753 if _startswith "$_nhook" "-"; then
6754 _err "'$_nhook' is not a hook name for '$1'"
6755 return 1
6756 fi
6757 if [ "$_notify_hook" ]; then
6758 _notify_hook="$_notify_hook,$_nhook"
6759 else
6760 _notify_hook="$_nhook"
6761 fi
6762 shift
6763 ;;
6764 --notify-level)
6765 _nlevel="$2"
6766 if _startswith "$_nlevel" "-"; then
6767 _err "'$_nlevel' is not a integer for '$1'"
6768 return 1
6769 fi
6770 _notify_level="$_nlevel"
6771 shift
6772 ;;
6773 --notify-mode)
6774 _nmode="$2"
6775 if _startswith "$_nmode" "-"; then
6776 _err "'$_nmode' is not a integer for '$1'"
6777 return 1
6778 fi
6779 _notify_mode="$_nmode"
6780 shift
6781 ;;
6782 *)
6783 _err "Unknown parameter : $1"
6784 return 1
6785 ;;
6786 esac
6787
6788 shift 1
6789 done
6790
6791 if [ "${_CMD}" != "install" ]; then
6792 if [ "$__INTERACTIVE" ] && ! _checkSudo; then
6793 if [ -z "$FORCE" ]; then
6794 #Use "echo" here, instead of _info. it's too early
6795 echo "It seems that you are using sudo, please read this link first:"
6796 echo "$_SUDO_WIKI"
6797 return 1
6798 fi
6799 fi
6800 __initHome
6801 if [ "$_log" ]; then
6802 if [ -z "$_logfile" ]; then
6803 _logfile="$DEFAULT_LOG_FILE"
6804 fi
6805 fi
6806 if [ "$_logfile" ]; then
6807 _saveaccountconf "LOG_FILE" "$_logfile"
6808 LOG_FILE="$_logfile"
6809 fi
6810
6811 if [ "$_log_level" ]; then
6812 _saveaccountconf "LOG_LEVEL" "$_log_level"
6813 LOG_LEVEL="$_log_level"
6814 fi
6815
6816 if [ "$_syslog" ]; then
6817 if _exists logger; then
6818 if [ "$_syslog" = "0" ]; then
6819 _clearaccountconf "SYS_LOG"
6820 else
6821 _saveaccountconf "SYS_LOG" "$_syslog"
6822 fi
6823 SYS_LOG="$_syslog"
6824 else
6825 _err "The 'logger' command is not found, can not enable syslog."
6826 _clearaccountconf "SYS_LOG"
6827 SYS_LOG=""
6828 fi
6829 fi
6830
6831 _processAccountConf
6832 fi
6833
6834 _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
6835
6836 if [ "$DEBUG" ]; then
6837 version
6838 if [ "$_server" ]; then
6839 _debug "Using server: $_server"
6840 fi
6841 fi
6842 _debug "Running cmd: ${_CMD}"
6843 case "${_CMD}" in
6844 install) install "$_nocron" "$_confighome" "$_noprofile" ;;
6845 uninstall) uninstall "$_nocron" ;;
6846 upgrade) upgrade ;;
6847 issue)
6848 issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
6849 ;;
6850 deploy)
6851 deploy "$_domain" "$_deploy_hook" "$_ecc"
6852 ;;
6853 signcsr)
6854 signcsr "$_csr" "$_webroot" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
6855 ;;
6856 showcsr)
6857 showcsr "$_csr" "$_domain"
6858 ;;
6859 installcert)
6860 installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
6861 ;;
6862 renew)
6863 renew "$_domain" "$_ecc"
6864 ;;
6865 renewAll)
6866 renewAll "$_stopRenewOnError"
6867 ;;
6868 revoke)
6869 revoke "$_domain" "$_ecc"
6870 ;;
6871 remove)
6872 remove "$_domain" "$_ecc"
6873 ;;
6874 deactivate)
6875 deactivate "$_domain,$_altdomains"
6876 ;;
6877 registeraccount)
6878 registeraccount "$_accountkeylength"
6879 ;;
6880 updateaccount)
6881 updateaccount
6882 ;;
6883 deactivateaccount)
6884 deactivateaccount
6885 ;;
6886 list)
6887 list "$_listraw"
6888 ;;
6889 installcronjob) installcronjob "$_confighome" ;;
6890 uninstallcronjob) uninstallcronjob ;;
6891 cron) cron ;;
6892 toPkcs)
6893 toPkcs "$_domain" "$_password" "$_ecc"
6894 ;;
6895 toPkcs8)
6896 toPkcs8 "$_domain" "$_ecc"
6897 ;;
6898 createAccountKey)
6899 createAccountKey "$_accountkeylength"
6900 ;;
6901 createDomainKey)
6902 createDomainKey "$_domain" "$_keylength"
6903 ;;
6904 createCSR)
6905 createCSR "$_domain" "$_altdomains" "$_ecc"
6906 ;;
6907 setnotify)
6908 setnotify "$_notify_hook" "$_notify_level" "$_notify_mode"
6909 ;;
6910 *)
6911 if [ "$_CMD" ]; then
6912 _err "Invalid command: $_CMD"
6913 fi
6914 showhelp
6915 return 1
6916 ;;
6917 esac
6918 _ret="$?"
6919 if [ "$_ret" != "0" ]; then
6920 return $_ret
6921 fi
6922
6923 if [ "${_CMD}" = "install" ]; then
6924 if [ "$_log" ]; then
6925 if [ -z "$LOG_FILE" ]; then
6926 LOG_FILE="$DEFAULT_LOG_FILE"
6927 fi
6928 _saveaccountconf "LOG_FILE" "$LOG_FILE"
6929 fi
6930
6931 if [ "$_log_level" ]; then
6932 _saveaccountconf "LOG_LEVEL" "$_log_level"
6933 fi
6934
6935 if [ "$_syslog" ]; then
6936 if _exists logger; then
6937 if [ "$_syslog" = "0" ]; then
6938 _clearaccountconf "SYS_LOG"
6939 else
6940 _saveaccountconf "SYS_LOG" "$_syslog"
6941 fi
6942 else
6943 _err "The 'logger' command is not found, can not enable syslog."
6944 _clearaccountconf "SYS_LOG"
6945 SYS_LOG=""
6946 fi
6947 fi
6948
6949 _processAccountConf
6950 fi
6951
6952 }
6953
6954 if [ "$INSTALLONLINE" ]; then
6955 INSTALLONLINE=""
6956 _installOnline
6957 exit
6958 fi
6959
6960 main() {
6961 [ -z "$1" ] && showhelp && return
6962 if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
6963 }
6964
6965 main "$@"