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