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