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