]> git.proxmox.com Git - mirror_acme.sh.git/blob - acme.sh
fix issue when there is no one records in the domain.
[mirror_acme.sh.git] / acme.sh
1 #!/usr/bin/env sh
2
3 VER=2.6.5
4
5 PROJECT_NAME="acme.sh"
6
7 PROJECT_ENTRY="acme.sh"
8
9 PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
10
11 DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
12 _SCRIPT_="$0"
13
14 _SUB_FOLDERS="dnsapi deploy"
15
16 DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
17 DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
18
19 DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
20 DEFAULT_ACCOUNT_EMAIL=""
21
22 DEFAULT_ACCOUNT_KEY_LENGTH=2048
23 DEFAULT_DOMAIN_KEY_LENGTH=2048
24
25 DEFAULT_OPENSSL_BIN="openssl"
26
27 STAGE_CA="https://acme-staging.api.letsencrypt.org"
28
29 VTYPE_HTTP="http-01"
30 VTYPE_DNS="dns-01"
31 VTYPE_TLS="tls-sni-01"
32 #VTYPE_TLS2="tls-sni-02"
33
34 LOCAL_ANY_ADDRESS="0.0.0.0"
35
36 MAX_RENEW=60
37
38 DEFAULT_DNS_SLEEP=120
39
40 NO_VALUE="no"
41
42 W_TLS="tls"
43
44 STATE_VERIFIED="verified_ok"
45
46 BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
47 END_CSR="-----END CERTIFICATE REQUEST-----"
48
49 BEGIN_CERT="-----BEGIN CERTIFICATE-----"
50 END_CERT="-----END CERTIFICATE-----"
51
52 RENEW_SKIP=2
53
54 ECC_SEP="_"
55 ECC_SUFFIX="${ECC_SEP}ecc"
56
57 LOG_LEVEL_1=1
58 LOG_LEVEL_2=2
59 LOG_LEVEL_3=3
60 DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
61
62 _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
63
64 __INTERACTIVE=""
65 if [ -t 1 ]; then
66 __INTERACTIVE="1"
67 fi
68
69 __green() {
70 if [ "$__INTERACTIVE" ]; then
71 printf '\033[1;31;32m'
72 fi
73 printf -- "$1"
74 if [ "$__INTERACTIVE" ]; then
75 printf '\033[0m'
76 fi
77 }
78
79 __red() {
80 if [ "$__INTERACTIVE" ]; then
81 printf '\033[1;31;40m'
82 fi
83 printf -- "$1"
84 if [ "$__INTERACTIVE" ]; then
85 printf '\033[0m'
86 fi
87 }
88
89 _printargs() {
90 if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
91 printf -- "%s" "[$(date)] "
92 fi
93 if [ -z "$2" ]; then
94 printf -- "%s" "$1"
95 else
96 printf -- "%s" "$1='$2'"
97 fi
98 printf "\n"
99 }
100
101 _dlg_versions() {
102 echo "Diagnosis versions: "
103 echo "openssl:$OPENSSL_BIN"
104 if _exists "$OPENSSL_BIN"; then
105 $OPENSSL_BIN version 2>&1
106 else
107 echo "$OPENSSL_BIN doesn't exists."
108 fi
109
110 echo "apache:"
111 if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
112 _APACHECTL -V 2>&1
113 else
114 echo "apache doesn't exists."
115 fi
116
117 echo "nc:"
118 if _exists "nc"; then
119 nc -h 2>&1
120 else
121 _debug "nc doesn't exists."
122 fi
123 }
124
125 _log() {
126 [ -z "$LOG_FILE" ] && return
127 _printargs "$@" >>"$LOG_FILE"
128 }
129
130 _info() {
131 _log "$@"
132 _printargs "$@"
133 }
134
135 _err() {
136 _log "$@"
137 if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
138 printf -- "%s" "[$(date)] " >&2
139 fi
140 if [ -z "$2" ]; then
141 __red "$1" >&2
142 else
143 __red "$1='$2'" >&2
144 fi
145 printf "\n" >&2
146 return 1
147 }
148
149 _usage() {
150 __red "$@" >&2
151 printf "\n" >&2
152 }
153
154 _debug() {
155 if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ]; then
156 _log "$@"
157 fi
158 if [ -z "$DEBUG" ]; then
159 return
160 fi
161 _printargs "$@" >&2
162 }
163
164 _debug2() {
165 if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ]; then
166 _log "$@"
167 fi
168 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
169 _debug "$@"
170 fi
171 }
172
173 _debug3() {
174 if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ]; then
175 _log "$@"
176 fi
177 if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ]; then
178 _debug "$@"
179 fi
180 }
181
182 _startswith() {
183 _str="$1"
184 _sub="$2"
185 echo "$_str" | grep "^$_sub" >/dev/null 2>&1
186 }
187
188 _endswith() {
189 _str="$1"
190 _sub="$2"
191 echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
192 }
193
194 _contains() {
195 _str="$1"
196 _sub="$2"
197 echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
198 }
199
200 _hasfield() {
201 _str="$1"
202 _field="$2"
203 _sep="$3"
204 if [ -z "$_field" ]; then
205 _usage "Usage: str field [sep]"
206 return 1
207 fi
208
209 if [ -z "$_sep" ]; then
210 _sep=","
211 fi
212
213 for f in $(echo "$_str" | tr ',' ' '); do
214 if [ "$f" = "$_field" ]; then
215 _debug2 "'$_str' contains '$_field'"
216 return 0 #contains ok
217 fi
218 done
219 _debug2 "'$_str' does not contain '$_field'"
220 return 1 #not contains
221 }
222
223 _getfield() {
224 _str="$1"
225 _findex="$2"
226 _sep="$3"
227
228 if [ -z "$_findex" ]; then
229 _usage "Usage: str field [sep]"
230 return 1
231 fi
232
233 if [ -z "$_sep" ]; then
234 _sep=","
235 fi
236
237 _ffi="$_findex"
238 while [ "$_ffi" -gt "0" ]; do
239 _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
240 if [ "$_fv" ]; then
241 printf -- "%s" "$_fv"
242 return 0
243 fi
244 _ffi="$(_math "$_ffi" - 1)"
245 done
246
247 printf -- "%s" "$_str"
248
249 }
250
251 _exists() {
252 cmd="$1"
253 if [ -z "$cmd" ]; then
254 _usage "Usage: _exists cmd"
255 return 1
256 fi
257
258 if eval type type >/dev/null 2>&1; then
259 eval type "$cmd" >/dev/null 2>&1
260 elif command >/dev/null 2>&1; then
261 command -v "$cmd" >/dev/null 2>&1
262 else
263 which "$cmd" >/dev/null 2>&1
264 fi
265 ret="$?"
266 _debug3 "$cmd exists=$ret"
267 return $ret
268 }
269
270 #a + b
271 _math() {
272 _m_opts="$@"
273 printf "%s" "$(($_m_opts))"
274 }
275
276 _h_char_2_dec() {
277 _ch=$1
278 case "${_ch}" in
279 a | A)
280 printf "10"
281 ;;
282 b | B)
283 printf "11"
284 ;;
285 c | C)
286 printf "12"
287 ;;
288 d | D)
289 printf "13"
290 ;;
291 e | E)
292 printf "14"
293 ;;
294 f | F)
295 printf "15"
296 ;;
297 *)
298 printf "%s" "$_ch"
299 ;;
300 esac
301
302 }
303
304 _URGLY_PRINTF=""
305 if [ "$(printf '\x41')" != 'A' ]; then
306 _URGLY_PRINTF=1
307 fi
308
309 _h2b() {
310 hex=$(cat)
311 i=1
312 j=2
313
314 _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
315 while true; do
316 if [ -z "$_URGLY_PRINTF" ]; then
317 h="$(printf "%s" "$hex" | cut -c $i-$j)"
318 if [ -z "$h" ]; then
319 break
320 fi
321 printf "\x$h%s"
322 else
323 ic="$(printf "%s" "$hex" | cut -c $i)"
324 jc="$(printf "%s" "$hex" | cut -c $j)"
325 if [ -z "$ic$jc" ]; then
326 break
327 fi
328 ic="$(_h_char_2_dec "$ic")"
329 jc="$(_h_char_2_dec "$jc")"
330 printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
331 fi
332
333 i="$(_math "$i" + 2)"
334 j="$(_math "$j" + 2)"
335
336 done
337 }
338
339 #hex string
340 _hex() {
341 _str="$1"
342 _str_len=${#_str}
343 _h_i=1
344 while [ "$_h_i" -le "$_str_len" ]; do
345 _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
346 printf "%02x" "'$_str_c"
347 _h_i="$(_math "$_h_i" + 1)"
348 done
349 }
350
351 #options file
352 _sed_i() {
353 options="$1"
354 filename="$2"
355 if [ -z "$filename" ]; then
356 _usage "Usage:_sed_i options filename"
357 return 1
358 fi
359 _debug2 options "$options"
360 if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
361 _debug "Using sed -i"
362 sed -i "$options" "$filename"
363 else
364 _debug "No -i support in sed"
365 text="$(cat "$filename")"
366 echo "$text" | sed "$options" >"$filename"
367 fi
368 }
369
370 _egrep_o() {
371 if ! egrep -o "$1" 2>/dev/null; then
372 sed -n 's/.*\('"$1"'\).*/\1/p'
373 fi
374 }
375
376 #Usage: file startline endline
377 _getfile() {
378 filename="$1"
379 startline="$2"
380 endline="$3"
381 if [ -z "$endline" ]; then
382 _usage "Usage: file startline endline"
383 return 1
384 fi
385
386 i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
387 if [ -z "$i" ]; then
388 _err "Can not find start line: $startline"
389 return 1
390 fi
391 i="$(_math "$i" + 1)"
392 _debug i "$i"
393
394 j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
395 if [ -z "$j" ]; then
396 _err "Can not find end line: $endline"
397 return 1
398 fi
399 j="$(_math "$j" - 1)"
400 _debug j "$j"
401
402 sed -n "$i,${j}p" "$filename"
403
404 }
405
406 #Usage: multiline
407 _base64() {
408 if [ "$1" ]; then
409 $OPENSSL_BIN base64 -e
410 else
411 $OPENSSL_BIN base64 -e | tr -d '\r\n'
412 fi
413 }
414
415 #Usage: multiline
416 _dbase64() {
417 if [ "$1" ]; then
418 $OPENSSL_BIN base64 -d -A
419 else
420 $OPENSSL_BIN base64 -d
421 fi
422 }
423
424 #Usage: hashalg [outputhex]
425 #Output Base64-encoded digest
426 _digest() {
427 alg="$1"
428 if [ -z "$alg" ]; then
429 _usage "Usage: _digest hashalg"
430 return 1
431 fi
432
433 outputhex="$2"
434
435 if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
436 if [ "$outputhex" ]; then
437 $OPENSSL_BIN dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
438 else
439 $OPENSSL_BIN dgst -"$alg" -binary | _base64
440 fi
441 else
442 _err "$alg is not supported yet"
443 return 1
444 fi
445
446 }
447
448 #Usage: hashalg secret_hex [outputhex]
449 #Output binary hmac
450 _hmac() {
451 alg="$1"
452 secret_hex="$2"
453 outputhex="$3"
454
455 if [ -z "$secret_hex" ]; then
456 _usage "Usage: _hmac hashalg secret [outputhex]"
457 return 1
458 fi
459
460 if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
461 if [ "$outputhex" ]; then
462 $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" | cut -d = -f 2 | tr -d ' '
463 else
464 $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary
465 fi
466 else
467 _err "$alg is not supported yet"
468 return 1
469 fi
470
471 }
472
473 #Usage: keyfile hashalg
474 #Output: Base64-encoded signature value
475 _sign() {
476 keyfile="$1"
477 alg="$2"
478 if [ -z "$alg" ]; then
479 _usage "Usage: _sign keyfile hashalg"
480 return 1
481 fi
482
483 _sign_openssl="$OPENSSL_BIN dgst -sign $keyfile "
484 if [ "$alg" = "sha256" ]; then
485 _sign_openssl="$_sign_openssl -$alg"
486 else
487 _err "$alg is not supported yet"
488 return 1
489 fi
490
491 if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
492 $_sign_openssl | _base64
493 elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
494 if ! _signedECText="$($_sign_openssl | $OPENSSL_BIN asn1parse -inform DER)"; then
495 _err "Sign failed: $_sign_openssl"
496 _err "Key file: $keyfile"
497 _err "Key content:$(wc -l <"$keyfile") lises"
498 return 1
499 fi
500 _debug3 "_signedECText" "$_signedECText"
501 _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
502 _debug3 "_ec_r" "$_ec_r"
503 _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
504 _debug3 "_ec_s" "$_ec_s"
505 printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
506 else
507 _err "Unknown key file format."
508 return 1
509 fi
510
511 }
512
513 #keylength
514 _isEccKey() {
515 _length="$1"
516
517 if [ -z "$_length" ]; then
518 return 1
519 fi
520
521 [ "$_length" != "1024" ] \
522 && [ "$_length" != "2048" ] \
523 && [ "$_length" != "3072" ] \
524 && [ "$_length" != "4096" ] \
525 && [ "$_length" != "8192" ]
526 }
527
528 # _createkey 2048|ec-256 file
529 _createkey() {
530 length="$1"
531 f="$2"
532 eccname="$length"
533 if _startswith "$length" "ec-"; then
534 length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
535
536 if [ "$length" = "256" ]; then
537 eccname="prime256v1"
538 fi
539 if [ "$length" = "384" ]; then
540 eccname="secp384r1"
541 fi
542 if [ "$length" = "521" ]; then
543 eccname="secp521r1"
544 fi
545
546 fi
547
548 if [ -z "$length" ]; then
549 length=2048
550 fi
551
552 _debug "Use length $length"
553
554 if _isEccKey "$length"; then
555 _debug "Using ec name: $eccname"
556 $OPENSSL_BIN ecparam -name "$eccname" -genkey 2>/dev/null >"$f"
557 else
558 _debug "Using RSA: $length"
559 $OPENSSL_BIN genrsa "$length" 2>/dev/null >"$f"
560 fi
561
562 if [ "$?" != "0" ]; then
563 _err "Create key error."
564 return 1
565 fi
566 }
567
568 #domain
569 _is_idn() {
570 _is_idn_d="$1"
571 _debug2 _is_idn_d "$_is_idn_d"
572 _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '[0-9]' | tr -d '[a-z]' | tr -d '[A-Z]' | tr -d '.,-')
573 _debug2 _idn_temp "$_idn_temp"
574 [ "$_idn_temp" ]
575 }
576
577 #aa.com
578 #aa.com,bb.com,cc.com
579 _idn() {
580 __idn_d="$1"
581 if ! _is_idn "$__idn_d"; then
582 printf "%s" "$__idn_d"
583 return 0
584 fi
585
586 if _exists idn; then
587 if _contains "$__idn_d" ','; then
588 _i_first="1"
589 for f in $(echo "$__idn_d" | tr ',' ' '); do
590 [ -z "$f" ] && continue
591 if [ -z "$_i_first" ]; then
592 printf "%s" ","
593 else
594 _i_first=""
595 fi
596 idn --quiet "$f" | tr -d "\r\n"
597 done
598 else
599 idn "$__idn_d" | tr -d "\r\n"
600 fi
601 else
602 _err "Please install idn to process IDN names."
603 fi
604 }
605
606 #_createcsr cn san_list keyfile csrfile conf
607 _createcsr() {
608 _debug _createcsr
609 domain="$1"
610 domainlist="$2"
611 csrkey="$3"
612 csr="$4"
613 csrconf="$5"
614 _debug2 domain "$domain"
615 _debug2 domainlist "$domainlist"
616 _debug2 csrkey "$csrkey"
617 _debug2 csr "$csr"
618 _debug2 csrconf "$csrconf"
619
620 printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
621
622 if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
623 #single domain
624 _info "Single domain" "$domain"
625 else
626 domainlist="$(_idn "$domainlist")"
627 _debug2 domainlist "$domainlist"
628 if _contains "$domainlist" ","; then
629 alt="DNS:$(echo "$domainlist" | sed "s/,/,DNS:/g")"
630 else
631 alt="DNS:$domainlist"
632 fi
633 #multi
634 _info "Multi domain" "$alt"
635 printf -- "\nsubjectAltName=$alt" >>"$csrconf"
636 fi
637 if [ "$Le_OCSP_Stable" ]; then
638 _savedomainconf Le_OCSP_Stable "$Le_OCSP_Stable"
639 printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
640 fi
641
642 _csr_cn="$(_idn "$domain")"
643 _debug2 _csr_cn "$_csr_cn"
644 $OPENSSL_BIN req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
645 }
646
647 #_signcsr key csr conf cert
648 _signcsr() {
649 key="$1"
650 csr="$2"
651 conf="$3"
652 cert="$4"
653 _debug "_signcsr"
654
655 _msg="$($OPENSSL_BIN x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
656 _ret="$?"
657 _debug "$_msg"
658 return $_ret
659 }
660
661 #_csrfile
662 _readSubjectFromCSR() {
663 _csrfile="$1"
664 if [ -z "$_csrfile" ]; then
665 _usage "_readSubjectFromCSR mycsr.csr"
666 return 1
667 fi
668 $OPENSSL_BIN req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
669 }
670
671 #_csrfile
672 #echo comma separated domain list
673 _readSubjectAltNamesFromCSR() {
674 _csrfile="$1"
675 if [ -z "$_csrfile" ]; then
676 _usage "_readSubjectAltNamesFromCSR mycsr.csr"
677 return 1
678 fi
679
680 _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
681 _debug _csrsubj "$_csrsubj"
682
683 _dnsAltnames="$($OPENSSL_BIN req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
684 _debug _dnsAltnames "$_dnsAltnames"
685
686 if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
687 _debug "AltNames contains subject"
688 _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
689 else
690 _debug "AltNames doesn't contain subject"
691 fi
692
693 printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
694 }
695
696 #_csrfile
697 _readKeyLengthFromCSR() {
698 _csrfile="$1"
699 if [ -z "$_csrfile" ]; then
700 _usage "_readKeyLengthFromCSR mycsr.csr"
701 return 1
702 fi
703
704 _outcsr="$($OPENSSL_BIN req -noout -text -in "$_csrfile")"
705 if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
706 _debug "ECC CSR"
707 echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
708 else
709 _debug "RSA CSR"
710 echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
711 fi
712 }
713
714 _ss() {
715 _port="$1"
716
717 if _exists "ss"; then
718 _debug "Using: ss"
719 ss -ntpl | grep ":$_port "
720 return 0
721 fi
722
723 if _exists "netstat"; then
724 _debug "Using: netstat"
725 if netstat -h 2>&1 | grep "\-p proto" >/dev/null; then
726 #for windows version netstat tool
727 netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
728 else
729 if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
730 netstat -an -p tcp | grep LISTEN | grep ":$_port "
731 elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
732 #for solaris
733 netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
734 else
735 netstat -ntpl | grep ":$_port "
736 fi
737 fi
738 return 0
739 fi
740
741 return 1
742 }
743
744 #domain [password] [isEcc]
745 toPkcs() {
746 domain="$1"
747 pfxPassword="$2"
748 if [ -z "$domain" ]; then
749 _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
750 return 1
751 fi
752
753 _isEcc="$3"
754
755 _initpath "$domain" "$_isEcc"
756
757 if [ "$pfxPassword" ]; then
758 $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
759 else
760 $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
761 fi
762
763 if [ "$?" = "0" ]; then
764 _info "Success, Pfx is exported to: $CERT_PFX_PATH"
765 fi
766
767 }
768
769 #[2048]
770 createAccountKey() {
771 _info "Creating account key"
772 if [ -z "$1" ]; then
773 _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
774 return
775 fi
776
777 length=$1
778 _create_account_key "$length"
779
780 }
781
782 _create_account_key() {
783
784 length=$1
785
786 if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
787 _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
788 length="$DEFAULT_ACCOUNT_KEY_LENGTH"
789 fi
790
791 _debug length "$length"
792 _initpath
793
794 mkdir -p "$CA_DIR"
795 if [ -f "$ACCOUNT_KEY_PATH" ]; then
796 _info "Account key exists, skip"
797 return
798 else
799 #generate account key
800 _createkey "$length" "$ACCOUNT_KEY_PATH"
801 fi
802
803 }
804
805 #domain [length]
806 createDomainKey() {
807 _info "Creating domain key"
808 if [ -z "$1" ]; then
809 _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
810 return
811 fi
812
813 domain=$1
814 length=$2
815
816 if [ -z "$length" ]; then
817 _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
818 length="$DEFAULT_DOMAIN_KEY_LENGTH"
819 fi
820
821 _initpath "$domain" "$length"
822
823 if [ ! -f "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$IS_RENEW" ]); then
824 _createkey "$length" "$CERT_KEY_PATH"
825 else
826 if [ "$IS_RENEW" ]; then
827 _info "Domain key exists, skip"
828 return 0
829 else
830 _err "Domain key exists, do you want to overwrite the key?"
831 _err "Add '--force', and try again."
832 return 1
833 fi
834 fi
835
836 }
837
838 # domain domainlist isEcc
839 createCSR() {
840 _info "Creating csr"
841 if [ -z "$1" ]; then
842 _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
843 return
844 fi
845
846 domain="$1"
847 domainlist="$2"
848 _isEcc="$3"
849
850 _initpath "$domain" "$_isEcc"
851
852 if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
853 _info "CSR exists, skip"
854 return
855 fi
856
857 if [ ! -f "$CERT_KEY_PATH" ]; then
858 _err "The key file is not found: $CERT_KEY_PATH"
859 _err "Please create the key file first."
860 return 1
861 fi
862 _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
863
864 }
865
866 _urlencode() {
867 tr '/+' '_-' | tr -d '= '
868 }
869
870 _time2str() {
871 #BSD
872 if date -u -d@"$1" 2>/dev/null; then
873 return
874 fi
875
876 #Linux
877 if date -u -r "$1" 2>/dev/null; then
878 return
879 fi
880
881 #Soaris
882 if _exists adb; then
883 _t_s_a=$(echo "0t${1}=Y" | adb)
884 echo "$_t_s_a"
885 fi
886
887 }
888
889 _normalizeJson() {
890 sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
891 }
892
893 _stat() {
894 #Linux
895 if stat -c '%U:%G' "$1" 2>/dev/null; then
896 return
897 fi
898
899 #BSD
900 if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
901 return
902 fi
903
904 return 1 #error, 'stat' not found
905 }
906
907 #keyfile
908 _calcjwk() {
909 keyfile="$1"
910 if [ -z "$keyfile" ]; then
911 _usage "Usage: _calcjwk keyfile"
912 return 1
913 fi
914
915 if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
916 _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
917 return 0
918 fi
919
920 if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
921 _debug "RSA key"
922 pub_exp=$($OPENSSL_BIN rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
923 if [ "${#pub_exp}" = "5" ]; then
924 pub_exp=0$pub_exp
925 fi
926 _debug3 pub_exp "$pub_exp"
927
928 e=$(echo "$pub_exp" | _h2b | _base64)
929 _debug3 e "$e"
930
931 modulus=$($OPENSSL_BIN rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
932 _debug3 modulus "$modulus"
933 n="$(printf "%s" "$modulus" | _h2b | _base64 | _urlencode)"
934 jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
935 _debug3 jwk "$jwk"
936
937 JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
938 JWK_HEADERPLACE_PART1='{"nonce": "'
939 JWK_HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
940 elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
941 _debug "EC key"
942 crv="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
943 _debug3 crv "$crv"
944
945 if [ -z "$crv" ]; then
946 _debug "Let's try ASN1 OID"
947 crv_oid="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
948 _debug3 crv_oid "$crv_oid"
949 case "${crv_oid}" in
950 "prime256v1")
951 crv="P-256"
952 ;;
953 "secp384r1")
954 crv="P-384"
955 ;;
956 "secp521r1")
957 crv="P-521"
958 ;;
959 *)
960 _err "ECC oid : $crv_oid"
961 return 1
962 ;;
963 esac
964 _debug3 crv "$crv"
965 fi
966
967 pubi="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
968 pubi=$(_math "$pubi" + 1)
969 _debug3 pubi "$pubi"
970
971 pubj="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
972 pubj=$(_math "$pubj" - 1)
973 _debug3 pubj "$pubj"
974
975 pubtext="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
976 _debug3 pubtext "$pubtext"
977
978 xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
979 xlen=$(_math "$xlen" / 4)
980 _debug3 xlen "$xlen"
981
982 xend=$(_math "$xlen" + 1)
983 x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
984 _debug3 x "$x"
985
986 x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _urlencode)"
987 _debug3 x64 "$x64"
988
989 xend=$(_math "$xend" + 1)
990 y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
991 _debug3 y "$y"
992
993 y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _urlencode)"
994 _debug3 y64 "$y64"
995
996 jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
997 _debug3 jwk "$jwk"
998
999 JWK_HEADER='{"alg": "ES256", "jwk": '$jwk'}'
1000 JWK_HEADERPLACE_PART1='{"nonce": "'
1001 JWK_HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
1002 else
1003 _err "Only RSA or EC key is supported."
1004 return 1
1005 fi
1006
1007 _debug3 JWK_HEADER "$JWK_HEADER"
1008 __CACHED_JWK_KEY_FILE="$keyfile"
1009 }
1010
1011 _time() {
1012 date -u "+%s"
1013 }
1014
1015 _mktemp() {
1016 if _exists mktemp; then
1017 if mktemp 2>/dev/null; then
1018 return 0
1019 elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
1020 #for Mac osx
1021 return 0
1022 fi
1023 fi
1024 if [ -d "/tmp" ]; then
1025 echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
1026 return 0
1027 elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
1028 echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
1029 return 0
1030 fi
1031 _err "Can not create temp file."
1032 }
1033
1034 _inithttp() {
1035
1036 if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
1037 HTTP_HEADER="$(_mktemp)"
1038 _debug2 HTTP_HEADER "$HTTP_HEADER"
1039 fi
1040
1041 if [ "$__HTTP_INITIALIZED" ]; then
1042 if [ "$_ACME_CURL$_ACME_WGET" ]; then
1043 _debug2 "Http already initialized."
1044 return 0
1045 fi
1046 fi
1047
1048 if [ -z "$_ACME_CURL" ] && _exists "curl"; then
1049 _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
1050 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1051 _CURL_DUMP="$(_mktemp)"
1052 _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
1053 fi
1054
1055 if [ "$CA_BUNDLE" ]; then
1056 _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
1057 fi
1058
1059 fi
1060
1061 if [ -z "$_ACME_WGET" ] && _exists "wget"; then
1062 _ACME_WGET="wget -q"
1063 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1064 _ACME_WGET="$_ACME_WGET -d "
1065 fi
1066 if [ "$CA_BUNDLE" ]; then
1067 _ACME_WGET="$_ACME_WGET --ca-certificate $CA_BUNDLE "
1068 fi
1069 fi
1070
1071 __HTTP_INITIALIZED=1
1072
1073 }
1074
1075 # body url [needbase64] [POST|PUT]
1076 _post() {
1077 body="$1"
1078 url="$2"
1079 needbase64="$3"
1080 httpmethod="$4"
1081
1082 if [ -z "$httpmethod" ]; then
1083 httpmethod="POST"
1084 fi
1085 _debug $httpmethod
1086 _debug "url" "$url"
1087 _debug2 "body" "$body"
1088
1089 _inithttp
1090
1091 if [ "$_ACME_CURL" ]; then
1092 _CURL="$_ACME_CURL"
1093 if [ "$HTTPS_INSECURE" ]; then
1094 _CURL="$_CURL --insecure "
1095 fi
1096 _debug "_CURL" "$_CURL"
1097 if [ "$needbase64" ]; then
1098 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
1099 else
1100 response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url")"
1101 fi
1102 _ret="$?"
1103 if [ "$_ret" != "0" ]; then
1104 _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
1105 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1106 _err "Here is the curl dump log:"
1107 _err "$(cat "$_CURL_DUMP")"
1108 fi
1109 fi
1110 elif [ "$_ACME_WGET" ]; then
1111 _WGET="$_ACME_WGET"
1112 if [ "$HTTPS_INSECURE" ]; then
1113 _WGET="$_WGET --no-check-certificate "
1114 fi
1115 _debug "_WGET" "$_WGET"
1116 if [ "$needbase64" ]; then
1117 if [ "$httpmethod" = "POST" ]; then
1118 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
1119 else
1120 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
1121 fi
1122 else
1123 if [ "$httpmethod" = "POST" ]; then
1124 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
1125 else
1126 response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
1127 fi
1128 fi
1129 _ret="$?"
1130 if [ "$_ret" = "8" ]; then
1131 _ret=0
1132 _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
1133 fi
1134 if [ "$_ret" != "0" ]; then
1135 _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
1136 fi
1137 _sed_i "s/^ *//g" "$HTTP_HEADER"
1138 else
1139 _ret="$?"
1140 _err "Neither curl nor wget is found, can not do $httpmethod."
1141 fi
1142 _debug "_ret" "$_ret"
1143 printf "%s" "$response"
1144 return $_ret
1145 }
1146
1147 # url getheader timeout
1148 _get() {
1149 _debug GET
1150 url="$1"
1151 onlyheader="$2"
1152 t="$3"
1153 _debug url "$url"
1154 _debug "timeout" "$t"
1155
1156 _inithttp
1157
1158 if [ "$_ACME_CURL" ]; then
1159 _CURL="$_ACME_CURL"
1160 if [ "$HTTPS_INSECURE" ]; then
1161 _CURL="$_CURL --insecure "
1162 fi
1163 if [ "$t" ]; then
1164 _CURL="$_CURL --connect-timeout $t"
1165 fi
1166 _debug "_CURL" "$_CURL"
1167 if [ "$onlyheader" ]; then
1168 $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
1169 else
1170 $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
1171 fi
1172 ret=$?
1173 if [ "$ret" != "0" ]; then
1174 _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
1175 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1176 _err "Here is the curl dump log:"
1177 _err "$(cat "$_CURL_DUMP")"
1178 fi
1179 fi
1180 elif [ "$_ACME_WGET" ]; then
1181 _WGET="$_ACME_WGET"
1182 if [ "$HTTPS_INSECURE" ]; then
1183 _WGET="$_WGET --no-check-certificate "
1184 fi
1185 if [ "$t" ]; then
1186 _WGET="$_WGET --timeout=$t"
1187 fi
1188 _debug "_WGET" "$_WGET"
1189 if [ "$onlyheader" ]; then
1190 $_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'
1191 else
1192 $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
1193 fi
1194 ret=$?
1195 if [ "$_ret" = "8" ]; then
1196 _ret=0
1197 _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
1198 fi
1199 if [ "$ret" != "0" ]; then
1200 _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
1201 fi
1202 else
1203 ret=$?
1204 _err "Neither curl nor wget is found, can not do GET."
1205 fi
1206 _debug "ret" "$ret"
1207 return $ret
1208 }
1209
1210 _head_n() {
1211 head -n "$1"
1212 }
1213
1214 _tail_n() {
1215 if ! tail -n "$1" 2>/dev/null; then
1216 #fix for solaris
1217 tail -"$1"
1218 fi
1219 }
1220
1221 # url payload needbase64 keyfile
1222 _send_signed_request() {
1223 url=$1
1224 payload=$2
1225 needbase64=$3
1226 keyfile=$4
1227 if [ -z "$keyfile" ]; then
1228 keyfile="$ACCOUNT_KEY_PATH"
1229 fi
1230 _debug url "$url"
1231 _debug payload "$payload"
1232
1233 if ! _calcjwk "$keyfile"; then
1234 return 1
1235 fi
1236
1237 payload64=$(printf "%s" "$payload" | _base64 | _urlencode)
1238 _debug3 payload64 "$payload64"
1239
1240 if [ -z "$_CACHED_NONCE" ]; then
1241 _debug2 "Get nonce."
1242 nonceurl="$API/directory"
1243 _headers="$(_get "$nonceurl" "onlyheader")"
1244
1245 if [ "$?" != "0" ]; then
1246 _err "Can not connect to $nonceurl to get nonce."
1247 return 1
1248 fi
1249
1250 _debug2 _headers "$_headers"
1251
1252 _CACHED_NONCE="$(echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
1253 _debug2 _CACHED_NONCE "$_CACHED_NONCE"
1254 else
1255 _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
1256 fi
1257 nonce="$_CACHED_NONCE"
1258 _debug2 nonce "$nonce"
1259
1260 protected="$JWK_HEADERPLACE_PART1$nonce$JWK_HEADERPLACE_PART2"
1261 _debug3 protected "$protected"
1262
1263 protected64="$(printf "%s" "$protected" | _base64 | _urlencode)"
1264 _debug3 protected64 "$protected64"
1265
1266 if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
1267 _err "Sign request failed."
1268 return 1
1269 fi
1270 _debug3 _sig_t "$_sig_t"
1271
1272 sig="$(printf "%s" "$_sig_t" | _urlencode)"
1273 _debug3 sig "$sig"
1274
1275 body="{\"header\": $JWK_HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
1276 _debug3 body "$body"
1277
1278 response="$(_post "$body" "$url" "$needbase64")"
1279 _CACHED_NONCE=""
1280 if [ "$?" != "0" ]; then
1281 _err "Can not post to $url"
1282 return 1
1283 fi
1284 _debug2 original "$response"
1285
1286 response="$(echo "$response" | _normalizeJson)"
1287
1288 responseHeaders="$(cat "$HTTP_HEADER")"
1289
1290 _debug2 responseHeaders "$responseHeaders"
1291 _debug2 response "$response"
1292 code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
1293 _debug code "$code"
1294
1295 _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
1296
1297 }
1298
1299 #setopt "file" "opt" "=" "value" [";"]
1300 _setopt() {
1301 __conf="$1"
1302 __opt="$2"
1303 __sep="$3"
1304 __val="$4"
1305 __end="$5"
1306 if [ -z "$__opt" ]; then
1307 _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
1308 return
1309 fi
1310 if [ ! -f "$__conf" ]; then
1311 touch "$__conf"
1312 fi
1313
1314 if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
1315 _debug3 OK
1316 if _contains "$__val" "&"; then
1317 __val="$(echo "$__val" | sed 's/&/\\&/g')"
1318 fi
1319 text="$(cat "$__conf")"
1320 echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
1321
1322 elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
1323 if _contains "$__val" "&"; then
1324 __val="$(echo "$__val" | sed 's/&/\\&/g')"
1325 fi
1326 text="$(cat "$__conf")"
1327 echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
1328
1329 else
1330 _debug3 APP
1331 echo "$__opt$__sep$__val$__end" >>"$__conf"
1332 fi
1333 _debug2 "$(grep -n "^$__opt$__sep" "$__conf")"
1334 }
1335
1336 #_save_conf file key value
1337 #save to conf
1338 _save_conf() {
1339 _s_c_f="$1"
1340 _sdkey="$2"
1341 _sdvalue="$3"
1342 if [ "$_s_c_f" ]; then
1343 _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
1344 else
1345 _err "config file is empty, can not save $_sdkey=$_sdvalue"
1346 fi
1347 }
1348
1349 #_clear_conf file key
1350 _clear_conf() {
1351 _c_c_f="$1"
1352 _sdkey="$2"
1353 if [ "$_c_c_f" ]; then
1354 _conf_data="$(cat "$_c_c_f")"
1355 echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
1356 else
1357 _err "config file is empty, can not clear"
1358 fi
1359 }
1360
1361 #_read_conf file key
1362 _read_conf() {
1363 _r_c_f="$1"
1364 _sdkey="$2"
1365 if [ -f "$_r_c_f" ]; then
1366 (
1367 eval "$(grep "^$_sdkey *=" "$_r_c_f")"
1368 eval "printf \"%s\" \"\$$_sdkey\""
1369 )
1370 else
1371 _debug "config file is empty, can not read $_sdkey"
1372 fi
1373 }
1374
1375 #_savedomainconf key value
1376 #save to domain.conf
1377 _savedomainconf() {
1378 _save_conf "$DOMAIN_CONF" "$1" "$2"
1379 }
1380
1381 #_cleardomainconf key
1382 _cleardomainconf() {
1383 _clear_conf "$DOMAIN_CONF" "$1"
1384 }
1385
1386 #_readdomainconf key
1387 _readdomainconf() {
1388 _read_conf "$DOMAIN_CONF" "$1"
1389 }
1390
1391 #_saveaccountconf key value
1392 _saveaccountconf() {
1393 _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
1394 }
1395
1396 #_clearaccountconf key
1397 _clearaccountconf() {
1398 _clear_conf "$ACCOUNT_CONF_PATH" "$1"
1399 }
1400
1401 #_savecaconf key value
1402 _savecaconf() {
1403 _save_conf "$CA_CONF" "$1" "$2"
1404 }
1405
1406 #_readcaconf key
1407 _readcaconf() {
1408 _read_conf "$CA_CONF" "$1"
1409 }
1410
1411 #_clearaccountconf key
1412 _clearcaconf() {
1413 _clear_conf "$CA_CONF" "$1"
1414 }
1415
1416 # content localaddress
1417 _startserver() {
1418 content="$1"
1419 ncaddr="$2"
1420 _debug "ncaddr" "$ncaddr"
1421
1422 _debug "startserver: $$"
1423 nchelp="$(nc -h 2>&1)"
1424
1425 _debug Le_HTTPPort "$Le_HTTPPort"
1426 _debug Le_Listen_V4 "$Le_Listen_V4"
1427 _debug Le_Listen_V6 "$Le_Listen_V6"
1428 _NC="nc"
1429
1430 if [ "$Le_Listen_V4" ]; then
1431 _NC="$_NC -4"
1432 elif [ "$Le_Listen_V6" ]; then
1433 _NC="$_NC -6"
1434 fi
1435
1436 if echo "$nchelp" | grep "\-q[ ,]" >/dev/null; then
1437 _NC="$_NC -q 1 -l $ncaddr"
1438 else
1439 if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null; then
1440 _NC="$_NC -c -l $ncaddr"
1441 elif echo "$nchelp" | grep "\-N" | grep "Shutdown the network socket after EOF on stdin" >/dev/null; then
1442 _NC="$_NC -N -l $ncaddr"
1443 else
1444 _NC="$_NC -l $ncaddr"
1445 fi
1446 fi
1447
1448 _debug "_NC" "$_NC"
1449
1450 #for centos ncat
1451 if _contains "$nchelp" "nmap.org"; then
1452 _debug "Using ncat: nmap.org"
1453 if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"; then
1454 _exec_err
1455 return 1
1456 fi
1457 if [ "$DEBUG" ]; then
1458 _exec_err
1459 fi
1460 return
1461 fi
1462
1463 # while true ; do
1464 if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC -p \"$Le_HTTPPort\" >&2"; then
1465 _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"
1466 fi
1467
1468 if [ "$?" != "0" ]; then
1469 _err "nc listen error."
1470 _exec_err
1471 exit 1
1472 fi
1473 if [ "$DEBUG" ]; then
1474 _exec_err
1475 fi
1476 # done
1477 }
1478
1479 _stopserver() {
1480 pid="$1"
1481 _debug "pid" "$pid"
1482 if [ -z "$pid" ]; then
1483 return
1484 fi
1485
1486 _debug2 "Le_HTTPPort" "$Le_HTTPPort"
1487 if [ "$Le_HTTPPort" ]; then
1488 if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
1489 _get "http://localhost:$Le_HTTPPort" "" 1
1490 else
1491 _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
1492 fi
1493 fi
1494
1495 _debug2 "Le_TLSPort" "$Le_TLSPort"
1496 if [ "$Le_TLSPort" ]; then
1497 if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
1498 _get "https://localhost:$Le_TLSPort" "" 1
1499 _get "https://localhost:$Le_TLSPort" "" 1
1500 else
1501 _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
1502 _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
1503 fi
1504 fi
1505 }
1506
1507 # sleep sec
1508 _sleep() {
1509 _sleep_sec="$1"
1510 if [ "$__INTERACTIVE" ]; then
1511 _sleep_c="$_sleep_sec"
1512 while [ "$_sleep_c" -ge "0" ]; do
1513 printf "\r \r"
1514 __green "$_sleep_c"
1515 _sleep_c="$(_math "$_sleep_c" - 1)"
1516 sleep 1
1517 done
1518 printf "\r"
1519 else
1520 sleep "$_sleep_sec"
1521 fi
1522 }
1523
1524 # _starttlsserver san_a san_b port content _ncaddr
1525 _starttlsserver() {
1526 _info "Starting tls server."
1527 san_a="$1"
1528 san_b="$2"
1529 port="$3"
1530 content="$4"
1531 opaddr="$5"
1532
1533 _debug san_a "$san_a"
1534 _debug san_b "$san_b"
1535 _debug port "$port"
1536
1537 #create key TLS_KEY
1538 if ! _createkey "2048" "$TLS_KEY"; then
1539 _err "Create tls validation key error."
1540 return 1
1541 fi
1542
1543 #create csr
1544 alt="$san_a"
1545 if [ "$san_b" ]; then
1546 alt="$alt,$san_b"
1547 fi
1548 if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF"; then
1549 _err "Create tls validation csr error."
1550 return 1
1551 fi
1552
1553 #self signed
1554 if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
1555 _err "Create tls validation cert error."
1556 return 1
1557 fi
1558
1559 __S_OPENSSL="$OPENSSL_BIN s_server -cert $TLS_CERT -key $TLS_KEY "
1560 if [ "$opaddr" ]; then
1561 __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
1562 else
1563 __S_OPENSSL="$__S_OPENSSL -accept $port"
1564 fi
1565
1566 _debug Le_Listen_V4 "$Le_Listen_V4"
1567 _debug Le_Listen_V6 "$Le_Listen_V6"
1568 if [ "$Le_Listen_V4" ]; then
1569 __S_OPENSSL="$__S_OPENSSL -4"
1570 elif [ "$Le_Listen_V6" ]; then
1571 __S_OPENSSL="$__S_OPENSSL -6"
1572 fi
1573
1574 _debug "$__S_OPENSSL"
1575 if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
1576 (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL -tlsextdebug) &
1577 else
1578 (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL >/dev/null 2>&1) &
1579 fi
1580
1581 serverproc="$!"
1582 sleep 1
1583 _debug serverproc "$serverproc"
1584 }
1585
1586 #file
1587 _readlink() {
1588 _rf="$1"
1589 if ! readlink -f "$_rf" 2>/dev/null; then
1590 if _startswith "$_rf" "\./$PROJECT_ENTRY"; then
1591 printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
1592 return 0
1593 fi
1594 readlink "$_rf"
1595 fi
1596 }
1597
1598 __initHome() {
1599 if [ -z "$_SCRIPT_HOME" ]; then
1600 if _exists readlink && _exists dirname; then
1601 _debug "Lets find script dir."
1602 _debug "_SCRIPT_" "$_SCRIPT_"
1603 _script="$(_readlink "$_SCRIPT_")"
1604 _debug "_script" "$_script"
1605 _script_home="$(dirname "$_script")"
1606 _debug "_script_home" "$_script_home"
1607 if [ -d "$_script_home" ]; then
1608 _SCRIPT_HOME="$_script_home"
1609 else
1610 _err "It seems the script home is not correct:$_script_home"
1611 fi
1612 fi
1613 fi
1614
1615 # if [ -z "$LE_WORKING_DIR" ]; then
1616 # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
1617 # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
1618 # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
1619 # else
1620 # LE_WORKING_DIR="$_SCRIPT_HOME"
1621 # fi
1622 # fi
1623
1624 if [ -z "$LE_WORKING_DIR" ]; then
1625 _debug "Using default home:$DEFAULT_INSTALL_HOME"
1626 LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
1627 fi
1628 export LE_WORKING_DIR
1629
1630 _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
1631
1632 if [ -z "$ACCOUNT_CONF_PATH" ]; then
1633 if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
1634 . "$_DEFAULT_ACCOUNT_CONF_PATH"
1635 fi
1636 fi
1637
1638 if [ -z "$ACCOUNT_CONF_PATH" ]; then
1639 ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
1640 fi
1641
1642 DEFAULT_LOG_FILE="$LE_WORKING_DIR/$PROJECT_NAME.log"
1643
1644 DEFAULT_CA_HOME="$LE_WORKING_DIR/ca"
1645
1646 if [ -z "$LE_TEMP_DIR" ]; then
1647 LE_TEMP_DIR="$LE_WORKING_DIR/tmp"
1648 fi
1649 }
1650
1651 #[domain] [keylength]
1652 _initpath() {
1653
1654 __initHome
1655
1656 if [ -f "$ACCOUNT_CONF_PATH" ]; then
1657 . "$ACCOUNT_CONF_PATH"
1658 fi
1659
1660 if [ "$IN_CRON" ]; then
1661 if [ ! "$_USER_PATH_EXPORTED" ]; then
1662 _USER_PATH_EXPORTED=1
1663 export PATH="$USER_PATH:$PATH"
1664 fi
1665 fi
1666
1667 if [ -z "$CA_HOME" ]; then
1668 CA_HOME="$DEFAULT_CA_HOME"
1669 fi
1670
1671 if [ -z "$API" ]; then
1672 if [ -z "$STAGE" ]; then
1673 API="$DEFAULT_CA"
1674 else
1675 API="$STAGE_CA"
1676 _info "Using stage api:$API"
1677 fi
1678 fi
1679
1680 _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
1681 CA_DIR="$CA_HOME/$_API_HOST"
1682
1683 _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
1684
1685 if [ -z "$CA_CONF" ]; then
1686 CA_CONF="$_DEFAULT_CA_CONF"
1687 fi
1688
1689 if [ -f "$CA_CONF" ]; then
1690 . "$CA_CONF"
1691 fi
1692
1693 if [ -z "$ACME_DIR" ]; then
1694 ACME_DIR="/home/.acme"
1695 fi
1696
1697 if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
1698 APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
1699 fi
1700
1701 if [ -z "$USER_AGENT" ]; then
1702 USER_AGENT="$DEFAULT_USER_AGENT"
1703 fi
1704
1705 if [ -z "$HTTP_HEADER" ]; then
1706 HTTP_HEADER="$LE_WORKING_DIR/http.header"
1707 fi
1708
1709 _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
1710 _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
1711
1712 _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
1713 _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
1714 if [ -z "$ACCOUNT_KEY_PATH" ]; then
1715 ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
1716 fi
1717
1718 if [ -z "$ACCOUNT_JSON_PATH" ]; then
1719 ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
1720 fi
1721
1722 _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
1723 if [ -z "$CERT_HOME" ]; then
1724 CERT_HOME="$_DEFAULT_CERT_HOME"
1725 fi
1726
1727 if [ -z "$OPENSSL_BIN" ]; then
1728 OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
1729 fi
1730
1731 if [ -z "$1" ]; then
1732 return 0
1733 fi
1734
1735 domain="$1"
1736 _ilength="$2"
1737
1738 if [ -z "$DOMAIN_PATH" ]; then
1739 domainhome="$CERT_HOME/$domain"
1740 domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
1741
1742 DOMAIN_PATH="$domainhome"
1743
1744 if _isEccKey "$_ilength"; then
1745 DOMAIN_PATH="$domainhomeecc"
1746 else
1747 if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
1748 _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
1749 fi
1750 fi
1751 _debug DOMAIN_PATH "$DOMAIN_PATH"
1752 fi
1753
1754 if [ -z "$DOMAIN_CONF" ]; then
1755 DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
1756 fi
1757
1758 if [ -z "$DOMAIN_SSL_CONF" ]; then
1759 DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
1760 fi
1761
1762 if [ -z "$CSR_PATH" ]; then
1763 CSR_PATH="$DOMAIN_PATH/$domain.csr"
1764 fi
1765 if [ -z "$CERT_KEY_PATH" ]; then
1766 CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
1767 fi
1768 if [ -z "$CERT_PATH" ]; then
1769 CERT_PATH="$DOMAIN_PATH/$domain.cer"
1770 fi
1771 if [ -z "$CA_CERT_PATH" ]; then
1772 CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
1773 fi
1774 if [ -z "$CERT_FULLCHAIN_PATH" ]; then
1775 CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
1776 fi
1777 if [ -z "$CERT_PFX_PATH" ]; then
1778 CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
1779 fi
1780
1781 if [ -z "$TLS_CONF" ]; then
1782 TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
1783 fi
1784 if [ -z "$TLS_CERT" ]; then
1785 TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
1786 fi
1787 if [ -z "$TLS_KEY" ]; then
1788 TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
1789 fi
1790 if [ -z "$TLS_CSR" ]; then
1791 TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
1792 fi
1793
1794 }
1795
1796 _exec() {
1797 if [ -z "$_EXEC_TEMP_ERR" ]; then
1798 _EXEC_TEMP_ERR="$(_mktemp)"
1799 fi
1800
1801 if [ "$_EXEC_TEMP_ERR" ]; then
1802 eval "$@ 2>>$_EXEC_TEMP_ERR"
1803 else
1804 eval "$@"
1805 fi
1806 }
1807
1808 _exec_err() {
1809 [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
1810 }
1811
1812 _apachePath() {
1813 _APACHECTL="apachectl"
1814 if ! _exists apachectl; then
1815 if _exists apache2ctl; then
1816 _APACHECTL="apache2ctl"
1817 else
1818 _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
1819 _err "Please use webroot mode to try again."
1820 return 1
1821 fi
1822 fi
1823
1824 if ! _exec $_APACHECTL -V >/dev/null; then
1825 _exec_err
1826 return 1
1827 fi
1828
1829 if [ "$APACHE_HTTPD_CONF" ]; then
1830 _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
1831 httpdconf="$APACHE_HTTPD_CONF"
1832 httpdconfname="$(basename "$httpdconfname")"
1833 else
1834 httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
1835 _debug httpdconfname "$httpdconfname"
1836
1837 if [ -z "$httpdconfname" ]; then
1838 _err "Can not read apache config file."
1839 return 1
1840 fi
1841
1842 if _startswith "$httpdconfname" '/'; then
1843 httpdconf="$httpdconfname"
1844 httpdconfname="$(basename "$httpdconfname")"
1845 else
1846 httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
1847 _debug httpdroot "$httpdroot"
1848 httpdconf="$httpdroot/$httpdconfname"
1849 httpdconfname="$(basename "$httpdconfname")"
1850 fi
1851 fi
1852 _debug httpdconf "$httpdconf"
1853 _debug httpdconfname "$httpdconfname"
1854 if [ ! -f "$httpdconf" ]; then
1855 _err "Apache Config file not found" "$httpdconf"
1856 return 1
1857 fi
1858 return 0
1859 }
1860
1861 _restoreApache() {
1862 if [ -z "$usingApache" ]; then
1863 return 0
1864 fi
1865 _initpath
1866 if ! _apachePath; then
1867 return 1
1868 fi
1869
1870 if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
1871 _debug "No config file to restore."
1872 return 0
1873 fi
1874
1875 cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
1876 _debug "Restored: $httpdconf."
1877 if ! _exec $_APACHECTL -t; then
1878 _exec_err
1879 _err "Sorry, restore apache config error, please contact me."
1880 return 1
1881 fi
1882 _debug "Restored successfully."
1883 rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
1884 return 0
1885 }
1886
1887 _setApache() {
1888 _initpath
1889 if ! _apachePath; then
1890 return 1
1891 fi
1892
1893 #test the conf first
1894 _info "Checking if there is an error in the apache config file before starting."
1895
1896 if ! _exec "$_APACHECTL" -t >/dev/null; then
1897 _exec_err
1898 _err "The apache config file has error, please fix it first, then try again."
1899 _err "Don't worry, there is nothing changed to your system."
1900 return 1
1901 else
1902 _info "OK"
1903 fi
1904
1905 #backup the conf
1906 _debug "Backup apache config file" "$httpdconf"
1907 if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
1908 _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
1909 _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
1910 return 1
1911 fi
1912 _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
1913 _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
1914 _info "The backup file will be deleted on sucess, just forget it."
1915
1916 #add alias
1917
1918 apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
1919 _debug "apacheVer" "$apacheVer"
1920 apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
1921 apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
1922
1923 if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
1924 echo "
1925 Alias /.well-known/acme-challenge $ACME_DIR
1926
1927 <Directory $ACME_DIR >
1928 Require all granted
1929 </Directory>
1930 " >>"$httpdconf"
1931 else
1932 echo "
1933 Alias /.well-known/acme-challenge $ACME_DIR
1934
1935 <Directory $ACME_DIR >
1936 Order allow,deny
1937 Allow from all
1938 </Directory>
1939 " >>"$httpdconf"
1940 fi
1941
1942 _msg="$($_APACHECTL -t 2>&1)"
1943 if [ "$?" != "0" ]; then
1944 _err "Sorry, apache config error"
1945 if _restoreApache; then
1946 _err "The apache config file is restored."
1947 else
1948 _err "Sorry, The apache config file can not be restored, please report bug."
1949 fi
1950 return 1
1951 fi
1952
1953 if [ ! -d "$ACME_DIR" ]; then
1954 mkdir -p "$ACME_DIR"
1955 chmod 755 "$ACME_DIR"
1956 fi
1957
1958 if ! _exec "$_APACHECTL" graceful; then
1959 _exec_err
1960 _err "$_APACHECTL graceful error, please contact me."
1961 _restoreApache
1962 return 1
1963 fi
1964 usingApache="1"
1965 return 0
1966 }
1967
1968 _clearup() {
1969 _stopserver "$serverproc"
1970 serverproc=""
1971 _restoreApache
1972 _clearupdns
1973 if [ -z "$DEBUG" ]; then
1974 rm -f "$TLS_CONF"
1975 rm -f "$TLS_CERT"
1976 rm -f "$TLS_KEY"
1977 rm -f "$TLS_CSR"
1978 fi
1979 }
1980
1981 _clearupdns() {
1982 _debug "_clearupdns"
1983 if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
1984 _debug "Dns not added, skip."
1985 return
1986 fi
1987
1988 ventries=$(echo "$vlist" | tr ',' ' ')
1989 for ventry in $ventries; do
1990 d=$(echo "$ventry" | cut -d "$sep" -f 1)
1991 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
1992 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
1993 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
1994
1995 if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
1996 _info "$d is already verified, skip $vtype."
1997 continue
1998 fi
1999
2000 if [ "$vtype" != "$VTYPE_DNS" ]; then
2001 _info "Skip $d for $vtype"
2002 continue
2003 fi
2004
2005 d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
2006 _debug d_api "$d_api"
2007
2008 if [ -z "$d_api" ]; then
2009 _info "Not Found domain api file: $d_api"
2010 continue
2011 fi
2012
2013 (
2014 if ! . "$d_api"; then
2015 _err "Load file $d_api error. Please check your api file and try again."
2016 return 1
2017 fi
2018
2019 rmcommand="${_currentRoot}_rm"
2020 if ! _exists "$rmcommand"; then
2021 _err "It seems that your api file doesn't define $rmcommand"
2022 return 1
2023 fi
2024
2025 txtdomain="_acme-challenge.$d"
2026
2027 if ! $rmcommand "$txtdomain"; then
2028 _err "Error removing txt for domain:$txtdomain"
2029 return 1
2030 fi
2031 )
2032
2033 done
2034 }
2035
2036 # webroot removelevel tokenfile
2037 _clearupwebbroot() {
2038 __webroot="$1"
2039 if [ -z "$__webroot" ]; then
2040 _debug "no webroot specified, skip"
2041 return 0
2042 fi
2043
2044 _rmpath=""
2045 if [ "$2" = '1' ]; then
2046 _rmpath="$__webroot/.well-known"
2047 elif [ "$2" = '2' ]; then
2048 _rmpath="$__webroot/.well-known/acme-challenge"
2049 elif [ "$2" = '3' ]; then
2050 _rmpath="$__webroot/.well-known/acme-challenge/$3"
2051 else
2052 _debug "Skip for removelevel:$2"
2053 fi
2054
2055 if [ "$_rmpath" ]; then
2056 if [ "$DEBUG" ]; then
2057 _debug "Debugging, skip removing: $_rmpath"
2058 else
2059 rm -rf "$_rmpath"
2060 fi
2061 fi
2062
2063 return 0
2064
2065 }
2066
2067 _on_before_issue() {
2068 _debug _on_before_issue
2069 if _hasfield "$Le_Webroot" "$NO_VALUE"; then
2070 if ! _exists "nc"; then
2071 _err "Please install netcat(nc) tools first."
2072 return 1
2073 fi
2074 fi
2075
2076 _debug Le_LocalAddress "$Le_LocalAddress"
2077
2078 alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
2079 _index=1
2080 _currentRoot=""
2081 _addrIndex=1
2082 for d in $alldomains; do
2083 _debug "Check for domain" "$d"
2084 _currentRoot="$(_getfield "$Le_Webroot" $_index)"
2085 _debug "_currentRoot" "$_currentRoot"
2086 _index=$(_math $_index + 1)
2087 _checkport=""
2088 if [ "$_currentRoot" = "$NO_VALUE" ]; then
2089 _info "Standalone mode."
2090 if [ -z "$Le_HTTPPort" ]; then
2091 Le_HTTPPort=80
2092 else
2093 _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
2094 fi
2095 _checkport="$Le_HTTPPort"
2096 elif [ "$_currentRoot" = "$W_TLS" ]; then
2097 _info "Standalone tls mode."
2098 if [ -z "$Le_TLSPort" ]; then
2099 Le_TLSPort=443
2100 else
2101 _savedomainconf "Le_TLSPort" "$Le_TLSPort"
2102 fi
2103 _checkport="$Le_TLSPort"
2104 fi
2105
2106 if [ "$_checkport" ]; then
2107 _debug _checkport "$_checkport"
2108 _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
2109 _debug _checkaddr "$_checkaddr"
2110
2111 _addrIndex="$(_math $_addrIndex + 1)"
2112
2113 _netprc="$(_ss "$_checkport" | grep "$_checkport")"
2114 netprc="$(echo "$_netprc" | grep "$_checkaddr")"
2115 if [ -z "$netprc" ]; then
2116 netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
2117 fi
2118 if [ "$netprc" ]; then
2119 _err "$netprc"
2120 _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
2121 _err "Please stop it first"
2122 return 1
2123 fi
2124 fi
2125 done
2126
2127 if _hasfield "$Le_Webroot" "apache"; then
2128 if ! _setApache; then
2129 _err "set up apache error. Report error to me."
2130 return 1
2131 fi
2132 else
2133 usingApache=""
2134 fi
2135
2136 #run pre hook
2137 if [ "$Le_PreHook" ]; then
2138 _info "Run pre hook:'$Le_PreHook'"
2139 if ! (
2140 cd "$DOMAIN_PATH" && eval "$Le_PreHook"
2141 ); then
2142 _err "Error when run pre hook."
2143 return 1
2144 fi
2145 fi
2146 }
2147
2148 _on_issue_err() {
2149 _debug _on_issue_err
2150 if [ "$LOG_FILE" ]; then
2151 _err "Please check log file for more details: $LOG_FILE"
2152 else
2153 _err "Please add '--debug' or '--log' to check more details."
2154 _err "See: $_DEBUG_WIKI"
2155 fi
2156
2157 if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
2158 _debug "$(_dlg_versions)"
2159 fi
2160
2161 #run the post hook
2162 if [ "$Le_PostHook" ]; then
2163 _info "Run post hook:'$Le_PostHook'"
2164 if ! (
2165 cd "$DOMAIN_PATH" && eval "$Le_PostHook"
2166 ); then
2167 _err "Error when run post hook."
2168 return 1
2169 fi
2170 fi
2171 }
2172
2173 _on_issue_success() {
2174 _debug _on_issue_success
2175 #run the post hook
2176 if [ "$Le_PostHook" ]; then
2177 _info "Run post hook:'$Le_PostHook'"
2178 if ! (
2179 cd "$DOMAIN_PATH" && eval "$Le_PostHook"
2180 ); then
2181 _err "Error when run post hook."
2182 return 1
2183 fi
2184 fi
2185
2186 #run renew hook
2187 if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ]; then
2188 _info "Run renew hook:'$Le_RenewHook'"
2189 if ! (
2190 cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
2191 ); then
2192 _err "Error when run renew hook."
2193 return 1
2194 fi
2195 fi
2196
2197 }
2198
2199 updateaccount() {
2200 _initpath
2201 _regAccount
2202 }
2203
2204 registeraccount() {
2205 _reg_length="$1"
2206 _initpath
2207 _regAccount "$_reg_length"
2208 }
2209
2210 __calcAccountKeyHash() {
2211 [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
2212 }
2213
2214 #keylength
2215 _regAccount() {
2216 _initpath
2217 _reg_length="$1"
2218
2219 if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
2220 _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
2221 mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
2222 fi
2223
2224 if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
2225 _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
2226 mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
2227 fi
2228
2229 if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
2230 if ! _create_account_key "$_reg_length"; then
2231 _err "Create account key error."
2232 return 1
2233 fi
2234 fi
2235
2236 if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
2237 return 1
2238 fi
2239
2240 _updateTos=""
2241 _reg_res="new-reg"
2242 while true; do
2243 _debug AGREEMENT "$AGREEMENT"
2244
2245 regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
2246
2247 if [ "$ACCOUNT_EMAIL" ]; then
2248 regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
2249 fi
2250
2251 if [ -z "$_updateTos" ]; then
2252 _info "Registering account"
2253
2254 if ! _send_signed_request "$API/acme/new-reg" "$regjson"; then
2255 _err "Register account Error: $response"
2256 return 1
2257 fi
2258
2259 if [ "$code" = "" ] || [ "$code" = '201' ]; then
2260 echo "$response" >"$ACCOUNT_JSON_PATH"
2261 _info "Registered"
2262 elif [ "$code" = '409' ]; then
2263 _info "Already registered"
2264 else
2265 _err "Register account Error: $response"
2266 return 1
2267 fi
2268
2269 _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
2270 _debug "_accUri" "$_accUri"
2271
2272 _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
2273 _debug "_tos" "$_tos"
2274 if [ -z "$_tos" ]; then
2275 _debug "Use default tos: $DEFAULT_AGREEMENT"
2276 _tos="$DEFAULT_AGREEMENT"
2277 fi
2278 if [ "$_tos" != "$AGREEMENT" ]; then
2279 _updateTos=1
2280 AGREEMENT="$_tos"
2281 _reg_res="reg"
2282 continue
2283 fi
2284
2285 else
2286 _debug "Update tos: $_tos"
2287 if ! _send_signed_request "$_accUri" "$regjson"; then
2288 _err "Update tos error."
2289 return 1
2290 fi
2291 if [ "$code" = '202' ]; then
2292 _info "Update success."
2293
2294 CA_KEY_HASH="$(__calcAccountKeyHash)"
2295 _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
2296 _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
2297 else
2298 _err "Update account error."
2299 return 1
2300 fi
2301 fi
2302 return 0
2303 done
2304
2305 }
2306
2307 # domain folder file
2308 _findHook() {
2309 _hookdomain="$1"
2310 _hookcat="$2"
2311 _hookname="$3"
2312
2313 if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
2314 d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
2315 elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
2316 d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
2317 elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
2318 d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
2319 elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
2320 d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
2321 elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
2322 d_api="$LE_WORKING_DIR/$_hookname"
2323 elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
2324 d_api="$LE_WORKING_DIR/$_hookname.sh"
2325 elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
2326 d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
2327 elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
2328 d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
2329 fi
2330
2331 printf "%s" "$d_api"
2332 }
2333
2334 #domain
2335 __get_domain_new_authz() {
2336 _gdnd="$1"
2337 _info "Getting new-authz for domain" "$_gdnd"
2338
2339 _Max_new_authz_retry_times=5
2340 _authz_i=0
2341 while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
2342 _debug "Try new-authz for the $_authz_i time."
2343 if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
2344 _err "Can not get domain new authz."
2345 return 1
2346 fi
2347 if ! _contains "$response" "An error occurred while processing your request"; then
2348 _info "The new-authz request is ok."
2349 break
2350 fi
2351 _authz_i="$(_math "$_authz_i" + 1)"
2352 _info "The server is busy, Sleep $_authz_i to retry."
2353 _sleep "$_authz_i"
2354 done
2355
2356 if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
2357 _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
2358 fi
2359
2360 if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
2361 _err "new-authz error: $response"
2362 return 1
2363 fi
2364
2365 }
2366
2367 #webroot, domain domainlist keylength
2368 issue() {
2369 if [ -z "$2" ]; then
2370 _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
2371 return 1
2372 fi
2373 Le_Webroot="$1"
2374 Le_Domain="$2"
2375 Le_Alt="$3"
2376 Le_Keylength="$4"
2377 Le_RealCertPath="$5"
2378 Le_RealKeyPath="$6"
2379 Le_RealCACertPath="$7"
2380 Le_ReloadCmd="$8"
2381 Le_RealFullChainPath="$9"
2382 Le_PreHook="${10}"
2383 Le_PostHook="${11}"
2384 Le_RenewHook="${12}"
2385 Le_LocalAddress="${13}"
2386
2387 #remove these later.
2388 if [ "$Le_Webroot" = "dns-cf" ]; then
2389 Le_Webroot="dns_cf"
2390 fi
2391 if [ "$Le_Webroot" = "dns-dp" ]; then
2392 Le_Webroot="dns_dp"
2393 fi
2394 if [ "$Le_Webroot" = "dns-cx" ]; then
2395 Le_Webroot="dns_cx"
2396 fi
2397 _debug "Using api: $API"
2398
2399 if [ ! "$IS_RENEW" ]; then
2400 _initpath "$Le_Domain" "$Le_Keylength"
2401 mkdir -p "$DOMAIN_PATH"
2402 fi
2403
2404 if [ -f "$DOMAIN_CONF" ]; then
2405 Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
2406 _debug Le_NextRenewTime "$Le_NextRenewTime"
2407 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
2408 _saved_domain=$(_readdomainconf Le_Domain)
2409 _debug _saved_domain "$_saved_domain"
2410 _saved_alt=$(_readdomainconf Le_Alt)
2411 _debug _saved_alt "$_saved_alt"
2412 if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ]; then
2413 _info "Domains not changed."
2414 _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
2415 _info "Add '$(__red '--force')' to force to renew."
2416 return $RENEW_SKIP
2417 else
2418 _info "Domains have changed."
2419 fi
2420 fi
2421 fi
2422
2423 _savedomainconf "Le_Domain" "$Le_Domain"
2424 _savedomainconf "Le_Alt" "$Le_Alt"
2425 _savedomainconf "Le_Webroot" "$Le_Webroot"
2426
2427 _savedomainconf "Le_PreHook" "$Le_PreHook"
2428 _savedomainconf "Le_PostHook" "$Le_PostHook"
2429 _savedomainconf "Le_RenewHook" "$Le_RenewHook"
2430
2431 if [ "$Le_LocalAddress" ]; then
2432 _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
2433 else
2434 _cleardomainconf "Le_LocalAddress"
2435 fi
2436
2437 Le_API="$API"
2438 _savedomainconf "Le_API" "$Le_API"
2439
2440 if [ "$Le_Alt" = "$NO_VALUE" ]; then
2441 Le_Alt=""
2442 fi
2443
2444 if [ "$Le_Keylength" = "$NO_VALUE" ]; then
2445 Le_Keylength=""
2446 fi
2447
2448 if ! _on_before_issue; then
2449 _err "_on_before_issue."
2450 return 1
2451 fi
2452
2453 _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
2454 _debug2 _saved_account_key_hash "$_saved_account_key_hash"
2455
2456 if [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
2457 if ! _regAccount "$_accountkeylength"; then
2458 _on_issue_err
2459 return 1
2460 fi
2461 else
2462 _debug "_saved_account_key_hash is not changed, skip register account."
2463 fi
2464
2465 if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
2466 _info "Signing from existing CSR."
2467 else
2468 _key=$(_readdomainconf Le_Keylength)
2469 _debug "Read key length:$_key"
2470 if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ]; then
2471 if ! createDomainKey "$Le_Domain" "$Le_Keylength"; then
2472 _err "Create domain key error."
2473 _clearup
2474 _on_issue_err
2475 return 1
2476 fi
2477 fi
2478
2479 if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
2480 _err "Create CSR error."
2481 _clearup
2482 _on_issue_err
2483 return 1
2484 fi
2485 fi
2486
2487 _savedomainconf "Le_Keylength" "$Le_Keylength"
2488
2489 vlist="$Le_Vlist"
2490
2491 _info "Getting domain auth token for each domain"
2492 sep='#'
2493 if [ -z "$vlist" ]; then
2494 alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
2495 _index=1
2496 _currentRoot=""
2497 for d in $alldomains; do
2498 _info "Getting webroot for domain" "$d"
2499 _w="$(echo $Le_Webroot | cut -d , -f $_index)"
2500 _info _w "$_w"
2501 if [ "$_w" ]; then
2502 _currentRoot="$_w"
2503 fi
2504 _debug "_currentRoot" "$_currentRoot"
2505 _index=$(_math $_index + 1)
2506
2507 vtype="$VTYPE_HTTP"
2508 if _startswith "$_currentRoot" "dns"; then
2509 vtype="$VTYPE_DNS"
2510 fi
2511
2512 if [ "$_currentRoot" = "$W_TLS" ]; then
2513 vtype="$VTYPE_TLS"
2514 fi
2515
2516 if ! __get_domain_new_authz "$d"; then
2517 _clearup
2518 _on_issue_err
2519 return 1
2520 fi
2521
2522 if [ -z "$thumbprint" ]; then
2523 accountkey_json=$(printf "%s" "$jwk" | tr -d ' ')
2524 thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
2525 fi
2526
2527 entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
2528 _debug entry "$entry"
2529 if [ -z "$entry" ]; then
2530 _err "Error, can not get domain token $d"
2531 _clearup
2532 _on_issue_err
2533 return 1
2534 fi
2535 token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
2536 _debug token "$token"
2537
2538 uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
2539 _debug uri "$uri"
2540
2541 keyauthorization="$token.$thumbprint"
2542 _debug keyauthorization "$keyauthorization"
2543
2544 if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
2545 _info "$d is already verified, skip."
2546 keyauthorization="$STATE_VERIFIED"
2547 _debug keyauthorization "$keyauthorization"
2548 fi
2549
2550 dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
2551 _debug dvlist "$dvlist"
2552
2553 vlist="$vlist$dvlist,"
2554
2555 done
2556
2557 #add entry
2558 dnsadded=""
2559 ventries=$(echo "$vlist" | tr ',' ' ')
2560 for ventry in $ventries; do
2561 d=$(echo "$ventry" | cut -d "$sep" -f 1)
2562 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
2563 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
2564 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
2565
2566 if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
2567 _info "$d is already verified, skip $vtype."
2568 continue
2569 fi
2570
2571 if [ "$vtype" = "$VTYPE_DNS" ]; then
2572 dnsadded='0'
2573 txtdomain="_acme-challenge.$d"
2574 _debug txtdomain "$txtdomain"
2575 txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
2576 _debug txt "$txt"
2577
2578 d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
2579
2580 _debug d_api "$d_api"
2581
2582 if [ "$d_api" ]; then
2583 _info "Found domain api file: $d_api"
2584 else
2585 _err "Add the following TXT record:"
2586 _err "Domain: '$(__green "$txtdomain")'"
2587 _err "TXT value: '$(__green "$txt")'"
2588 _err "Please be aware that you prepend _acme-challenge. before your domain"
2589 _err "so the resulting subdomain will be: $txtdomain"
2590 continue
2591 fi
2592
2593 (
2594 if ! . "$d_api"; then
2595 _err "Load file $d_api error. Please check your api file and try again."
2596 return 1
2597 fi
2598
2599 addcommand="${_currentRoot}_add"
2600 if ! _exists "$addcommand"; then
2601 _err "It seems that your api file is not correct, it must have a function named: $addcommand"
2602 return 1
2603 fi
2604
2605 if ! $addcommand "$txtdomain" "$txt"; then
2606 _err "Error add txt for domain:$txtdomain"
2607 return 1
2608 fi
2609 )
2610
2611 if [ "$?" != "0" ]; then
2612 _clearup
2613 _on_issue_err
2614 return 1
2615 fi
2616 dnsadded='1'
2617 fi
2618 done
2619
2620 if [ "$dnsadded" = '0' ]; then
2621 _savedomainconf "Le_Vlist" "$vlist"
2622 _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
2623 _err "Please add the TXT records to the domains, and retry again."
2624 _clearup
2625 _on_issue_err
2626 return 1
2627 fi
2628
2629 fi
2630
2631 if [ "$dnsadded" = '1' ]; then
2632 if [ -z "$Le_DNSSleep" ]; then
2633 Le_DNSSleep="$DEFAULT_DNS_SLEEP"
2634 else
2635 _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
2636 fi
2637
2638 _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
2639 _sleep "$Le_DNSSleep"
2640 fi
2641
2642 _debug "ok, let's start to verify"
2643
2644 _ncIndex=1
2645 ventries=$(echo "$vlist" | tr ',' ' ')
2646 for ventry in $ventries; do
2647 d=$(echo "$ventry" | cut -d "$sep" -f 1)
2648 keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
2649 uri=$(echo "$ventry" | cut -d "$sep" -f 3)
2650 vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
2651 _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
2652
2653 if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
2654 _info "$d is already verified, skip $vtype."
2655 continue
2656 fi
2657
2658 _info "Verifying:$d"
2659 _debug "d" "$d"
2660 _debug "keyauthorization" "$keyauthorization"
2661 _debug "uri" "$uri"
2662 removelevel=""
2663 token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
2664
2665 _debug "_currentRoot" "$_currentRoot"
2666
2667 if [ "$vtype" = "$VTYPE_HTTP" ]; then
2668 if [ "$_currentRoot" = "$NO_VALUE" ]; then
2669 _info "Standalone mode server"
2670 _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
2671 _ncIndex="$(_math $_ncIndex + 1)"
2672 _startserver "$keyauthorization" "$_ncaddr" &
2673 if [ "$?" != "0" ]; then
2674 _clearup
2675 _on_issue_err
2676 return 1
2677 fi
2678 serverproc="$!"
2679 sleep 1
2680 _debug serverproc "$serverproc"
2681
2682 else
2683 if [ "$_currentRoot" = "apache" ]; then
2684 wellknown_path="$ACME_DIR"
2685 else
2686 wellknown_path="$_currentRoot/.well-known/acme-challenge"
2687 if [ ! -d "$_currentRoot/.well-known" ]; then
2688 removelevel='1'
2689 elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
2690 removelevel='2'
2691 else
2692 removelevel='3'
2693 fi
2694 fi
2695
2696 _debug wellknown_path "$wellknown_path"
2697
2698 _debug "writing token:$token to $wellknown_path/$token"
2699
2700 mkdir -p "$wellknown_path"
2701
2702 if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
2703 _err "$d:Can not write token to file : $wellknown_path/$token"
2704 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2705 _clearup
2706 _on_issue_err
2707 return 1
2708 fi
2709
2710 if [ ! "$usingApache" ]; then
2711 if webroot_owner=$(_stat "$_currentRoot"); then
2712 _debug "Changing owner/group of .well-known to $webroot_owner"
2713 chown -R "$webroot_owner" "$_currentRoot/.well-known"
2714 else
2715 _debug "not chaning owner/group of webroot"
2716 fi
2717 fi
2718
2719 fi
2720
2721 elif [ "$vtype" = "$VTYPE_TLS" ]; then
2722 #create A
2723 #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
2724 #_debug2 _hash_A "$_hash_A"
2725 #_x="$(echo $_hash_A | cut -c 1-32)"
2726 #_debug2 _x "$_x"
2727 #_y="$(echo $_hash_A | cut -c 33-64)"
2728 #_debug2 _y "$_y"
2729 #_SAN_A="$_x.$_y.token.acme.invalid"
2730 #_debug2 _SAN_A "$_SAN_A"
2731
2732 #create B
2733 _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
2734 _debug2 _hash_B "$_hash_B"
2735 _x="$(echo "$_hash_B" | cut -c 1-32)"
2736 _debug2 _x "$_x"
2737 _y="$(echo "$_hash_B" | cut -c 33-64)"
2738 _debug2 _y "$_y"
2739
2740 #_SAN_B="$_x.$_y.ka.acme.invalid"
2741
2742 _SAN_B="$_x.$_y.acme.invalid"
2743 _debug2 _SAN_B "$_SAN_B"
2744
2745 _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
2746 _ncIndex="$(_math "$_ncIndex" + 1)"
2747 if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
2748 _err "Start tls server error."
2749 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2750 _clearup
2751 _on_issue_err
2752 return 1
2753 fi
2754 fi
2755
2756 if ! _send_signed_request "$uri" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"; then
2757 _err "$d:Can not get challenge: $response"
2758 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2759 _clearup
2760 _on_issue_err
2761 return 1
2762 fi
2763
2764 if [ ! -z "$code" ] && [ ! "$code" = '202' ]; then
2765 _err "$d:Challenge error: $response"
2766 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2767 _clearup
2768 _on_issue_err
2769 return 1
2770 fi
2771
2772 waittimes=0
2773 if [ -z "$MAX_RETRY_TIMES" ]; then
2774 MAX_RETRY_TIMES=30
2775 fi
2776
2777 while true; do
2778 waittimes=$(_math "$waittimes" + 1)
2779 if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
2780 _err "$d:Timeout"
2781 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2782 _clearup
2783 _on_issue_err
2784 return 1
2785 fi
2786
2787 _debug "sleep 2 secs to verify"
2788 sleep 2
2789 _debug "checking"
2790 response="$(_get "$uri")"
2791 if [ "$?" != "0" ]; then
2792 _err "$d:Verify error:$response"
2793 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2794 _clearup
2795 _on_issue_err
2796 return 1
2797 fi
2798 _debug2 original "$response"
2799
2800 response="$(echo "$response" | _normalizeJson)"
2801 _debug2 response "$response"
2802
2803 status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
2804 if [ "$status" = "valid" ]; then
2805 _info "$(__green Success)"
2806 _stopserver "$serverproc"
2807 serverproc=""
2808 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2809 break
2810 fi
2811
2812 if [ "$status" = "invalid" ]; then
2813 error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
2814 _debug2 error "$error"
2815 errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
2816 _debug2 errordetail "$errordetail"
2817 if [ "$errordetail" ]; then
2818 _err "$d:Verify error:$errordetail"
2819 else
2820 _err "$d:Verify error:$error"
2821 fi
2822 if [ "$DEBUG" ]; then
2823 if [ "$vtype" = "$VTYPE_HTTP" ]; then
2824 _debug "Debug: get token url."
2825 _get "http://$d/.well-known/acme-challenge/$token" "" 1
2826 fi
2827 fi
2828 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2829 _clearup
2830 _on_issue_err
2831 return 1
2832 fi
2833
2834 if [ "$status" = "pending" ]; then
2835 _info "Pending"
2836 else
2837 _err "$d:Verify error:$response"
2838 _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
2839 _clearup
2840 _on_issue_err
2841 return 1
2842 fi
2843
2844 done
2845
2846 done
2847
2848 _clearup
2849 _info "Verify finished, start to sign."
2850 der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
2851
2852 if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"; then
2853 _err "Sign failed."
2854 _on_issue_err
2855 return 1
2856 fi
2857
2858 _rcert="$response"
2859 Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
2860 _savedomainconf "Le_LinkCert" "$Le_LinkCert"
2861
2862 if [ "$Le_LinkCert" ]; then
2863 echo "$BEGIN_CERT" >"$CERT_PATH"
2864
2865 #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
2866 # _debug "Get cert failed. Let's try last response."
2867 # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
2868 #fi
2869
2870 if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
2871 _debug "Try cert link."
2872 _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
2873 fi
2874
2875 echo "$END_CERT" >>"$CERT_PATH"
2876 _info "$(__green "Cert success.")"
2877 cat "$CERT_PATH"
2878
2879 _info "Your cert is in $(__green " $CERT_PATH ")"
2880
2881 if [ -f "$CERT_KEY_PATH" ]; then
2882 _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
2883 fi
2884
2885 cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
2886
2887 if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
2888 USER_PATH="$PATH"
2889 _saveaccountconf "USER_PATH" "$USER_PATH"
2890 fi
2891 fi
2892
2893 if [ -z "$Le_LinkCert" ]; then
2894 response="$(echo "$response" | _dbase64 "multiline" | _normalizeJson)"
2895 _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
2896 _on_issue_err
2897 return 1
2898 fi
2899
2900 _cleardomainconf "Le_Vlist"
2901
2902 Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
2903 if ! _contains "$Le_LinkIssuer" ":"; then
2904 Le_LinkIssuer="$API$Le_LinkIssuer"
2905 fi
2906
2907 _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
2908
2909 if [ "$Le_LinkIssuer" ]; then
2910 echo "$BEGIN_CERT" >"$CA_CERT_PATH"
2911 _get "$Le_LinkIssuer" | _base64 "multiline" >>"$CA_CERT_PATH"
2912 echo "$END_CERT" >>"$CA_CERT_PATH"
2913 _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
2914 cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
2915 _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
2916 fi
2917
2918 Le_CertCreateTime=$(_time)
2919 _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
2920
2921 Le_CertCreateTimeStr=$(date -u)
2922 _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
2923
2924 if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
2925 Le_RenewalDays="$MAX_RENEW"
2926 else
2927 _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
2928 fi
2929
2930 if [ "$CA_BUNDLE" ]; then
2931 _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
2932 else
2933 _clearaccountconf "CA_BUNDLE"
2934 fi
2935
2936 if [ "$HTTPS_INSECURE" ]; then
2937 _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
2938 else
2939 _clearaccountconf "HTTPS_INSECURE"
2940 fi
2941
2942 if [ "$Le_Listen_V4" ]; then
2943 _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
2944 _cleardomainconf Le_Listen_V6
2945 elif [ "$Le_Listen_V6" ]; then
2946 _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
2947 _cleardomainconf Le_Listen_V4
2948 fi
2949
2950 Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
2951
2952 Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
2953 _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
2954
2955 Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
2956 _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
2957
2958 _on_issue_success
2959
2960 if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ]; then
2961 _installcert
2962 fi
2963
2964 }
2965
2966 #domain [isEcc]
2967 renew() {
2968 Le_Domain="$1"
2969 if [ -z "$Le_Domain" ]; then
2970 _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
2971 return 1
2972 fi
2973
2974 _isEcc="$2"
2975
2976 _initpath "$Le_Domain" "$_isEcc"
2977
2978 _info "$(__green "Renew: '$Le_Domain'")"
2979 if [ ! -f "$DOMAIN_CONF" ]; then
2980 _info "'$Le_Domain' is not a issued domain, skip."
2981 return 0
2982 fi
2983
2984 if [ "$Le_RenewalDays" ]; then
2985 _savedomainconf Le_RenewalDays "$Le_RenewalDays"
2986 fi
2987
2988 . "$DOMAIN_CONF"
2989
2990 if [ "$Le_API" ]; then
2991 API="$Le_API"
2992 fi
2993
2994 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
2995 _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
2996 _info "Add '$(__red '--force')' to force to renew."
2997 return "$RENEW_SKIP"
2998 fi
2999
3000 IS_RENEW="1"
3001 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"
3002 res="$?"
3003 if [ "$res" != "0" ]; then
3004 return "$res"
3005 fi
3006
3007 if [ "$Le_DeployHook" ]; then
3008 deploy "$Le_Domain" "$Le_DeployHook" "$Le_Keylength"
3009 res="$?"
3010 fi
3011
3012 IS_RENEW=""
3013
3014 return "$res"
3015 }
3016
3017 #renewAll [stopRenewOnError]
3018 renewAll() {
3019 _initpath
3020 _stopRenewOnError="$1"
3021 _debug "_stopRenewOnError" "$_stopRenewOnError"
3022 _ret="0"
3023
3024 for di in "${CERT_HOME}"/*.*/; do
3025 _debug di "$di"
3026 if ! [ -d "$di" ]; then
3027 _debug "Not directory, skip: $di"
3028 continue
3029 fi
3030 d=$(basename "$di")
3031 _debug d "$d"
3032 (
3033 if _endswith "$d" "$ECC_SUFFIX"; then
3034 _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
3035 d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
3036 fi
3037 renew "$d" "$_isEcc"
3038 )
3039 rc="$?"
3040 _debug "Return code: $rc"
3041 if [ "$rc" != "0" ]; then
3042 if [ "$rc" = "$RENEW_SKIP" ]; then
3043 _info "Skipped $d"
3044 elif [ "$_stopRenewOnError" ]; then
3045 _err "Error renew $d, stop now."
3046 return "$rc"
3047 else
3048 _ret="$rc"
3049 _err "Error renew $d, Go ahead to next one."
3050 fi
3051 fi
3052 done
3053 return "$_ret"
3054 }
3055
3056 #csr webroot
3057 signcsr() {
3058 _csrfile="$1"
3059 _csrW="$2"
3060 if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
3061 _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
3062 return 1
3063 fi
3064
3065 _initpath
3066
3067 _csrsubj=$(_readSubjectFromCSR "$_csrfile")
3068 if [ "$?" != "0" ]; then
3069 _err "Can not read subject from csr: $_csrfile"
3070 return 1
3071 fi
3072 _debug _csrsubj "$_csrsubj"
3073
3074 _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
3075 if [ "$?" != "0" ]; then
3076 _err "Can not read domain list from csr: $_csrfile"
3077 return 1
3078 fi
3079 _debug "_csrdomainlist" "$_csrdomainlist"
3080
3081 if [ -z "$_csrsubj" ]; then
3082 _csrsubj="$(_getfield "$_csrdomainlist" 1)"
3083 _debug _csrsubj "$_csrsubj"
3084 _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
3085 _debug "_csrdomainlist" "$_csrdomainlist"
3086 fi
3087
3088 if [ -z "$_csrsubj" ]; then
3089 _err "Can not read subject from csr: $_csrfile"
3090 return 1
3091 fi
3092
3093 _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
3094 if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
3095 _err "Can not read key length from csr: $_csrfile"
3096 return 1
3097 fi
3098
3099 _initpath "$_csrsubj" "$_csrkeylength"
3100 mkdir -p "$DOMAIN_PATH"
3101
3102 _info "Copy csr to: $CSR_PATH"
3103 cp "$_csrfile" "$CSR_PATH"
3104
3105 issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
3106
3107 }
3108
3109 showcsr() {
3110 _csrfile="$1"
3111 _csrd="$2"
3112 if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
3113 _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
3114 return 1
3115 fi
3116
3117 _initpath
3118
3119 _csrsubj=$(_readSubjectFromCSR "$_csrfile")
3120 if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
3121 _err "Can not read subject from csr: $_csrfile"
3122 return 1
3123 fi
3124
3125 _info "Subject=$_csrsubj"
3126
3127 _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
3128 if [ "$?" != "0" ]; then
3129 _err "Can not read domain list from csr: $_csrfile"
3130 return 1
3131 fi
3132 _debug "_csrdomainlist" "$_csrdomainlist"
3133
3134 _info "SubjectAltNames=$_csrdomainlist"
3135
3136 _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
3137 if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
3138 _err "Can not read key length from csr: $_csrfile"
3139 return 1
3140 fi
3141 _info "KeyLength=$_csrkeylength"
3142 }
3143
3144 list() {
3145 _raw="$1"
3146 _initpath
3147
3148 _sep="|"
3149 if [ "$_raw" ]; then
3150 printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
3151 for di in "${CERT_HOME}"/*.*/; do
3152 if ! [ -d "$di" ]; then
3153 _debug "Not directory, skip: $di"
3154 continue
3155 fi
3156 d=$(basename "$di")
3157 _debug d "$d"
3158 (
3159 if _endswith "$d" "$ECC_SUFFIX"; then
3160 _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
3161 d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
3162 fi
3163 _initpath "$d" "$_isEcc"
3164 if [ -f "$DOMAIN_CONF" ]; then
3165 . "$DOMAIN_CONF"
3166 printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
3167 fi
3168 )
3169 done
3170 else
3171 if _exists column; then
3172 list "raw" | column -t -s "$_sep"
3173 else
3174 list "raw" | tr "$_sep" '\t'
3175 fi
3176 fi
3177
3178 }
3179
3180 deploy() {
3181 Le_Domain="$1"
3182 Le_DeployHook="$2"
3183 _isEcc="$3"
3184 if [ -z "$Le_DeployHook" ]; then
3185 _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
3186 return 1
3187 fi
3188
3189 _initpath "$Le_Domain" "$_isEcc"
3190 if [ ! -d "$DOMAIN_PATH" ]; then
3191 _err "Domain is not valid:'$Le_Domain'"
3192 return 1
3193 fi
3194
3195 _deployApi="$(_findHook "$Le_Domain" deploy "$Le_DeployHook")"
3196 if [ -z "$_deployApi" ]; then
3197 _err "The deploy hook $Le_DeployHook is not found."
3198 return 1
3199 fi
3200 _debug _deployApi "$_deployApi"
3201
3202 _savedomainconf Le_DeployHook "$Le_DeployHook"
3203
3204 if ! (
3205 if ! . "$_deployApi"; then
3206 _err "Load file $_deployApi error. Please check your api file and try again."
3207 return 1
3208 fi
3209
3210 d_command="${Le_DeployHook}_deploy"
3211 if ! _exists "$d_command"; then
3212 _err "It seems that your api file is not correct, it must have a function named: $d_command"
3213 return 1
3214 fi
3215
3216 if ! $d_command "$Le_Domain" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
3217 _err "Error deploy for domain:$Le_Domain"
3218 _on_issue_err
3219 return 1
3220 fi
3221 ); then
3222 _err "Deploy error."
3223 return 1
3224 else
3225 _info "$(__green Success)"
3226 fi
3227
3228 }
3229
3230 installcert() {
3231 Le_Domain="$1"
3232 if [ -z "$Le_Domain" ]; then
3233 _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
3234 return 1
3235 fi
3236
3237 Le_RealCertPath="$2"
3238 Le_RealKeyPath="$3"
3239 Le_RealCACertPath="$4"
3240 Le_ReloadCmd="$5"
3241 Le_RealFullChainPath="$6"
3242 _isEcc="$7"
3243
3244 _initpath "$Le_Domain" "$_isEcc"
3245 if [ ! -d "$DOMAIN_PATH" ]; then
3246 _err "Domain is not valid:'$Le_Domain'"
3247 return 1
3248 fi
3249
3250 _installcert
3251 }
3252
3253 _installcert() {
3254 _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
3255 _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
3256 _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
3257 _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
3258 _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
3259
3260 if [ "$Le_RealCertPath" = "$NO_VALUE" ]; then
3261 Le_RealCertPath=""
3262 fi
3263 if [ "$Le_RealKeyPath" = "$NO_VALUE" ]; then
3264 Le_RealKeyPath=""
3265 fi
3266 if [ "$Le_RealCACertPath" = "$NO_VALUE" ]; then
3267 Le_RealCACertPath=""
3268 fi
3269 if [ "$Le_ReloadCmd" = "$NO_VALUE" ]; then
3270 Le_ReloadCmd=""
3271 fi
3272 if [ "$Le_RealFullChainPath" = "$NO_VALUE" ]; then
3273 Le_RealFullChainPath=""
3274 fi
3275
3276 if [ "$Le_RealCertPath" ]; then
3277
3278 _info "Installing cert to:$Le_RealCertPath"
3279 if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ]; then
3280 cp "$Le_RealCertPath" "$Le_RealCertPath".bak
3281 fi
3282 cat "$CERT_PATH" >"$Le_RealCertPath"
3283 fi
3284
3285 if [ "$Le_RealCACertPath" ]; then
3286
3287 _info "Installing CA to:$Le_RealCACertPath"
3288 if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ]; then
3289 echo "" >>"$Le_RealCACertPath"
3290 cat "$CA_CERT_PATH" >>"$Le_RealCACertPath"
3291 else
3292 if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ]; then
3293 cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
3294 fi
3295 cat "$CA_CERT_PATH" >"$Le_RealCACertPath"
3296 fi
3297 fi
3298
3299 if [ "$Le_RealKeyPath" ]; then
3300
3301 _info "Installing key to:$Le_RealKeyPath"
3302 if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ]; then
3303 cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
3304 fi
3305 cat "$CERT_KEY_PATH" >"$Le_RealKeyPath"
3306 fi
3307
3308 if [ "$Le_RealFullChainPath" ]; then
3309
3310 _info "Installing full chain to:$Le_RealFullChainPath"
3311 if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ]; then
3312 cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
3313 fi
3314 cat "$CERT_FULLCHAIN_PATH" >"$Le_RealFullChainPath"
3315 fi
3316
3317 if [ "$Le_ReloadCmd" ]; then
3318
3319 _info "Run Le_ReloadCmd: $Le_ReloadCmd"
3320 if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd"); then
3321 _info "$(__green "Reload success")"
3322 else
3323 _err "Reload error for :$Le_Domain"
3324 fi
3325 fi
3326
3327 }
3328
3329 installcronjob() {
3330 _initpath
3331 if ! _exists "crontab"; then
3332 _err "crontab doesn't exist, so, we can not install cron jobs."
3333 _err "All your certs will not be renewed automatically."
3334 _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
3335 return 1
3336 fi
3337
3338 _info "Installing cron job"
3339 if ! crontab -l | grep "$PROJECT_ENTRY --cron"; then
3340 if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
3341 lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
3342 else
3343 _err "Can not install cronjob, $PROJECT_ENTRY not found."
3344 return 1
3345 fi
3346 if _exists uname && uname -a | grep solaris >/dev/null; then
3347 crontab -l | {
3348 cat
3349 echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
3350 } | crontab --
3351 else
3352 crontab -l | {
3353 cat
3354 echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
3355 } | crontab -
3356 fi
3357 fi
3358 if [ "$?" != "0" ]; then
3359 _err "Install cron job failed. You need to manually renew your certs."
3360 _err "Or you can add cronjob by yourself:"
3361 _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
3362 return 1
3363 fi
3364 }
3365
3366 uninstallcronjob() {
3367 if ! _exists "crontab"; then
3368 return
3369 fi
3370 _info "Removing cron job"
3371 cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
3372 if [ "$cr" ]; then
3373 if _exists uname && uname -a | grep solaris >/dev/null; then
3374 crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
3375 else
3376 crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
3377 fi
3378 LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
3379 _info LE_WORKING_DIR "$LE_WORKING_DIR"
3380 fi
3381 _initpath
3382
3383 }
3384
3385 revoke() {
3386 Le_Domain="$1"
3387 if [ -z "$Le_Domain" ]; then
3388 _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com"
3389 return 1
3390 fi
3391
3392 _isEcc="$2"
3393
3394 _initpath "$Le_Domain" "$_isEcc"
3395 if [ ! -f "$DOMAIN_CONF" ]; then
3396 _err "$Le_Domain is not a issued domain, skip."
3397 return 1
3398 fi
3399
3400 if [ ! -f "$CERT_PATH" ]; then
3401 _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
3402 return 1
3403 fi
3404
3405 cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _urlencode)"
3406
3407 if [ -z "$cert" ]; then
3408 _err "Cert for $Le_Domain is empty found, skip."
3409 return 1
3410 fi
3411
3412 data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
3413 uri="$API/acme/revoke-cert"
3414
3415 if [ -f "$CERT_KEY_PATH" ]; then
3416 _info "Try domain key first."
3417 if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
3418 if [ -z "$response" ]; then
3419 _info "Revoke success."
3420 rm -f "$CERT_PATH"
3421 return 0
3422 else
3423 _err "Revoke error by domain key."
3424 _err "$response"
3425 fi
3426 fi
3427 else
3428 _info "Domain key file doesn't exists."
3429 fi
3430
3431 _info "Try account key."
3432
3433 if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
3434 if [ -z "$response" ]; then
3435 _info "Revoke success."
3436 rm -f "$CERT_PATH"
3437 return 0
3438 else
3439 _err "Revoke error."
3440 _debug "$response"
3441 fi
3442 fi
3443 return 1
3444 }
3445
3446 #domain vtype
3447 _deactivate() {
3448 _d_domain="$1"
3449 _d_type="$2"
3450 _initpath
3451
3452 _d_i=0
3453 _d_max_retry=9
3454 while [ "$_d_i" -lt "$_d_max_retry" ]; do
3455 _info "Deactivate: $_d_domain"
3456 _d_i="$(_math $_d_i + 1)"
3457
3458 if ! __get_domain_new_authz "$_d_domain"; then
3459 _err "Can not get domain new authz token."
3460 return 1
3461 fi
3462
3463 authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
3464 _debug "authzUri" "$authzUri"
3465
3466 if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
3467 _err "new-authz error: $response"
3468 return 1
3469 fi
3470
3471 entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"status":"valid","uri"[^\}]*')"
3472 _debug entry "$entry"
3473
3474 if [ -z "$entry" ]; then
3475 _info "No more valid entry found."
3476 break
3477 fi
3478
3479 _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
3480 _debug _vtype "$_vtype"
3481 _info "Found $_vtype"
3482
3483 uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
3484 _debug uri "$uri"
3485
3486 if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
3487 _info "Skip $_vtype"
3488 continue
3489 fi
3490
3491 _info "Deactivate: $_vtype"
3492
3493 if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}"; then
3494 _err "Can not deactivate $_vtype."
3495 return 1
3496 fi
3497
3498 _info "Deactivate: $_vtype success."
3499
3500 done
3501 _debug "$_d_i"
3502 if [ "$_d_i" -lt "$_d_max_retry" ]; then
3503 _info "Deactivated success!"
3504 else
3505 _err "Deactivate failed."
3506 fi
3507
3508 }
3509
3510 deactivate() {
3511 _d_domain_list="$1"
3512 _d_type="$2"
3513 _initpath
3514 _debug _d_domain_list "$_d_domain_list"
3515 if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
3516 _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
3517 return 1
3518 fi
3519 for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
3520 if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
3521 continue
3522 fi
3523 if ! _deactivate "$_d_dm" "$_d_type"; then
3524 return 1
3525 fi
3526 done
3527 }
3528
3529 # Detect profile file if not specified as environment variable
3530 _detect_profile() {
3531 if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
3532 echo "$PROFILE"
3533 return
3534 fi
3535
3536 DETECTED_PROFILE=''
3537 SHELLTYPE="$(basename "/$SHELL")"
3538
3539 if [ "$SHELLTYPE" = "bash" ]; then
3540 if [ -f "$HOME/.bashrc" ]; then
3541 DETECTED_PROFILE="$HOME/.bashrc"
3542 elif [ -f "$HOME/.bash_profile" ]; then
3543 DETECTED_PROFILE="$HOME/.bash_profile"
3544 fi
3545 elif [ "$SHELLTYPE" = "zsh" ]; then
3546 DETECTED_PROFILE="$HOME/.zshrc"
3547 fi
3548
3549 if [ -z "$DETECTED_PROFILE" ]; then
3550 if [ -f "$HOME/.profile" ]; then
3551 DETECTED_PROFILE="$HOME/.profile"
3552 elif [ -f "$HOME/.bashrc" ]; then
3553 DETECTED_PROFILE="$HOME/.bashrc"
3554 elif [ -f "$HOME/.bash_profile" ]; then
3555 DETECTED_PROFILE="$HOME/.bash_profile"
3556 elif [ -f "$HOME/.zshrc" ]; then
3557 DETECTED_PROFILE="$HOME/.zshrc"
3558 fi
3559 fi
3560
3561 if [ ! -z "$DETECTED_PROFILE" ]; then
3562 echo "$DETECTED_PROFILE"
3563 fi
3564 }
3565
3566 _initconf() {
3567 _initpath
3568 if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
3569 echo "#ACCOUNT_CONF_PATH=xxxx
3570
3571 #Account configurations:
3572 #Here are the supported macros, uncomment them to make them take effect.
3573
3574 #ACCOUNT_EMAIL=aaa@example.com # the account email used to register account.
3575 #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
3576 #CERT_HOME=\"/path/to/cert/home\"
3577
3578
3579
3580 #LOG_FILE=\"$DEFAULT_LOG_FILE\"
3581 #LOG_LEVEL=1
3582
3583 #AUTO_UPGRADE=\"1\"
3584
3585 #STAGE=1 # Use the staging api
3586 #FORCE=1 # Force to issue cert
3587 #DEBUG=1 # Debug mode
3588 #NO_TIMESTAMP=1
3589 #OPENSSL_BIN=openssl
3590
3591 #USER_AGENT=\"$USER_AGENT\"
3592
3593 #USER_PATH=
3594
3595 #dns api
3596 #######################
3597 #Cloudflare:
3598 #api key
3599 #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
3600 #account email
3601 #CF_Email=\"xxxx@sss.com\"
3602
3603 #######################
3604 #Dnspod.cn:
3605 #api key id
3606 #DP_Id=\"1234\"
3607 #api key
3608 #DP_Key=\"sADDsdasdgdsf\"
3609
3610 #######################
3611 #Cloudxns.com:
3612 #CX_Key=\"1234\"
3613 #
3614 #CX_Secret=\"sADDsdasdgdsf\"
3615
3616 #######################
3617 #Godaddy.com:
3618 #GD_Key=\"sdfdsgdgdfdasfds\"
3619 #
3620 #GD_Secret=\"sADDsdasdfsdfdssdgdsf\"
3621
3622 #######################
3623 #nsupdate:
3624 #NSUPDATE_KEY=\"/path/to/update.key\"
3625 #NSUPDATE_SERVER=\"192.168.0.1\"
3626
3627 #######################
3628 #PowerDNS:
3629 #PDNS_Url=\"http://ns.example.com:8081\"
3630 #PDNS_ServerId=\"localhost\"
3631 #PDNS_Token=\"0123456789ABCDEF\"
3632 #PDNS_Ttl=60
3633
3634 #######################
3635 #Amazon Route53:
3636 #AWS_ACCESS_KEY_ID=XXXXXXXXXX
3637 #AWS_SECRET_ACCESS_KEY=XXXXXXXXXXXXXXX
3638
3639 " >"$ACCOUNT_CONF_PATH"
3640 fi
3641 }
3642
3643 # nocron
3644 _precheck() {
3645 _nocron="$1"
3646
3647 if ! _exists "curl" && ! _exists "wget"; then
3648 _err "Please install curl or wget first, we need to access http resources."
3649 return 1
3650 fi
3651
3652 if [ -z "$_nocron" ]; then
3653 if ! _exists "crontab"; then
3654 _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
3655 _err "We need to set cron job to renew the certs automatically."
3656 _err "Otherwise, your certs will not be able to be renewed automatically."
3657 if [ -z "$FORCE" ]; then
3658 _err "Please add '--force' and try install again to go without crontab."
3659 _err "./$PROJECT_ENTRY --install --force"
3660 return 1
3661 fi
3662 fi
3663 fi
3664
3665 if ! _exists "$OPENSSL_BIN"; then
3666 _err "Please install openssl first."
3667 _err "We need openssl to generate keys."
3668 return 1
3669 fi
3670
3671 if ! _exists "nc"; then
3672 _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
3673 _err "We use nc for standalone server if you use standalone mode."
3674 _err "If you don't use standalone mode, just ignore this warning."
3675 fi
3676
3677 return 0
3678 }
3679
3680 _setShebang() {
3681 _file="$1"
3682 _shebang="$2"
3683 if [ -z "$_shebang" ]; then
3684 _usage "Usage: file shebang"
3685 return 1
3686 fi
3687 cp "$_file" "$_file.tmp"
3688 echo "$_shebang" >"$_file"
3689 sed -n 2,99999p "$_file.tmp" >>"$_file"
3690 rm -f "$_file.tmp"
3691 }
3692
3693 _installalias() {
3694 _initpath
3695
3696 _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
3697 if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
3698 echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
3699 echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
3700 echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
3701 fi
3702
3703 _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
3704 _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
3705
3706 _profile="$(_detect_profile)"
3707 if [ "$_profile" ]; then
3708 _debug "Found profile: $_profile"
3709 _info "Installing alias to '$_profile'"
3710 _setopt "$_profile" ". \"$_envfile\""
3711 _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
3712 else
3713 _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
3714 fi
3715
3716 #for csh
3717 _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
3718 _csh_profile="$HOME/.cshrc"
3719 if [ -f "$_csh_profile" ]; then
3720 _info "Installing alias to '$_csh_profile'"
3721 _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
3722 _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
3723 _setopt "$_csh_profile" "source \"$_cshfile\""
3724 fi
3725
3726 #for tcsh
3727 _tcsh_profile="$HOME/.tcshrc"
3728 if [ -f "$_tcsh_profile" ]; then
3729 _info "Installing alias to '$_tcsh_profile'"
3730 _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
3731 _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
3732 _setopt "$_tcsh_profile" "source \"$_cshfile\""
3733 fi
3734
3735 }
3736
3737 # nocron
3738 install() {
3739
3740 if [ -z "$LE_WORKING_DIR" ]; then
3741 LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
3742 fi
3743
3744 _nocron="$1"
3745 if ! _initpath; then
3746 _err "Install failed."
3747 return 1
3748 fi
3749 if [ "$_nocron" ]; then
3750 _debug "Skip install cron job"
3751 fi
3752
3753 if ! _precheck "$_nocron"; then
3754 _err "Pre-check failed, can not install."
3755 return 1
3756 fi
3757
3758 #convert from le
3759 if [ -d "$HOME/.le" ]; then
3760 for envfile in "le.env" "le.sh.env"; do
3761 if [ -f "$HOME/.le/$envfile" ]; then
3762 if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
3763 _upgrading="1"
3764 _info "You are upgrading from le.sh"
3765 _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
3766 mv "$HOME/.le" "$LE_WORKING_DIR"
3767 mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
3768 break
3769 fi
3770 fi
3771 done
3772 fi
3773
3774 _info "Installing to $LE_WORKING_DIR"
3775
3776 if ! mkdir -p "$LE_WORKING_DIR"; then
3777 _err "Can not create working dir: $LE_WORKING_DIR"
3778 return 1
3779 fi
3780
3781 chmod 700 "$LE_WORKING_DIR"
3782
3783 cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
3784
3785 if [ "$?" != "0" ]; then
3786 _err "Install failed, can not copy $PROJECT_ENTRY"
3787 return 1
3788 fi
3789
3790 _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
3791
3792 _installalias
3793
3794 for subf in $_SUB_FOLDERS; do
3795 if [ -d "$subf" ]; then
3796 mkdir -p "$LE_WORKING_DIR/$subf"
3797 cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
3798 fi
3799 done
3800
3801 if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
3802 _initconf
3803 fi
3804
3805 if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
3806 _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
3807 fi
3808
3809 if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
3810 _saveaccountconf "CERT_HOME" "$CERT_HOME"
3811 fi
3812
3813 if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
3814 _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
3815 fi
3816
3817 if [ -z "$_nocron" ]; then
3818 installcronjob
3819 fi
3820
3821 if [ -z "$NO_DETECT_SH" ]; then
3822 #Modify shebang
3823 if _exists bash; then
3824 _info "Good, bash is found, so change the shebang to use bash as prefered."
3825 _shebang='#!/usr/bin/env bash'
3826 _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
3827 for subf in $_SUB_FOLDERS; do
3828 if [ -d "$LE_WORKING_DIR/$subf" ]; then
3829 for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
3830 _setShebang "$_apifile" "$_shebang"
3831 done
3832 fi
3833 done
3834 fi
3835 fi
3836
3837 _info OK
3838 }
3839
3840 # nocron
3841 uninstall() {
3842 _nocron="$1"
3843 if [ -z "$_nocron" ]; then
3844 uninstallcronjob
3845 fi
3846 _initpath
3847
3848 _uninstallalias
3849
3850 rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
3851 _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
3852
3853 }
3854
3855 _uninstallalias() {
3856 _initpath
3857
3858 _profile="$(_detect_profile)"
3859 if [ "$_profile" ]; then
3860 _info "Uninstalling alias from: '$_profile'"
3861 text="$(cat "$_profile")"
3862 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
3863 fi
3864
3865 _csh_profile="$HOME/.cshrc"
3866 if [ -f "$_csh_profile" ]; then
3867 _info "Uninstalling alias from: '$_csh_profile'"
3868 text="$(cat "$_csh_profile")"
3869 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
3870 fi
3871
3872 _tcsh_profile="$HOME/.tcshrc"
3873 if [ -f "$_tcsh_profile" ]; then
3874 _info "Uninstalling alias from: '$_csh_profile'"
3875 text="$(cat "$_tcsh_profile")"
3876 echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
3877 fi
3878
3879 }
3880
3881 cron() {
3882 IN_CRON=1
3883 _initpath
3884 if [ "$AUTO_UPGRADE" = "1" ]; then
3885 export LE_WORKING_DIR
3886 (
3887 if ! upgrade; then
3888 _err "Cron:Upgrade failed!"
3889 return 1
3890 fi
3891 )
3892 . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
3893
3894 if [ -t 1 ]; then
3895 __INTERACTIVE="1"
3896 fi
3897
3898 _info "Auto upgraded to: $VER"
3899 fi
3900 renewAll
3901 _ret="$?"
3902 IN_CRON=""
3903 exit $_ret
3904 }
3905
3906 version() {
3907 echo "$PROJECT"
3908 echo "v$VER"
3909 }
3910
3911 showhelp() {
3912 _initpath
3913 version
3914 echo "Usage: $PROJECT_ENTRY command ...[parameters]....
3915 Commands:
3916 --help, -h Show this help message.
3917 --version, -v Show version info.
3918 --install Install $PROJECT_NAME to your system.
3919 --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
3920 --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
3921 --issue Issue a cert.
3922 --signcsr Issue a cert from an existing csr.
3923 --deploy Deploy the cert to your server.
3924 --installcert Install the issued cert to apache/nginx or any other server.
3925 --renew, -r Renew a cert.
3926 --renewAll Renew all the certs.
3927 --revoke Revoke a cert.
3928 --list List all the certs.
3929 --showcsr Show the content of a csr.
3930 --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
3931 --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
3932 --cron Run cron job to renew all the certs.
3933 --toPkcs Export the certificate and key to a pfx file.
3934 --updateaccount Update account info.
3935 --registeraccount Register account key.
3936 --createAccountKey, -cak Create an account private key, professional use.
3937 --createDomainKey, -cdk Create an domain private key, professional use.
3938 --createCSR, -ccsr Create CSR , professional use.
3939 --deactivate Deactivate the domain authz, professional use.
3940
3941 Parameters:
3942 --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
3943 --force, -f Used to force to install or force to renew a cert immediately.
3944 --staging, --test Use staging server, just for test.
3945 --debug Output debug info.
3946
3947 --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
3948 --standalone Use standalone mode.
3949 --tls Use standalone tls mode.
3950 --apache Use apache mode.
3951 --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
3952 --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
3953
3954 --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
3955 --accountkeylength, -ak [2048] Specifies the account key length.
3956 --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
3957 --log-level 1|2 Specifies the log level, default is 1.
3958
3959 These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
3960
3961 --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
3962 --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
3963 --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
3964 --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
3965
3966 --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
3967
3968 --accountconf Specifies a customized account config file.
3969 --home Specifies the home dir for $PROJECT_NAME .
3970 --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
3971 --useragent Specifies the user agent string. it will be saved for future use too.
3972 --accountemail Specifies the account email for registering, Only valid for the '--install' command.
3973 --accountkey Specifies the account key path, Only valid for the '--install' command.
3974 --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
3975 --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
3976 --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
3977 --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
3978 --listraw Only used for '--list' command, list the certs in raw format.
3979 --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
3980 --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
3981 --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
3982 --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
3983 --ecc Specifies to use the ECC cert. Valid for '--installcert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
3984 --csr Specifies the input csr.
3985 --pre-hook Command to be run before obtaining any certificates.
3986 --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
3987 --renew-hook Command to be run once for each successfully renewed certificate.
3988 --deploy-hook The hook file to deploy cert
3989 --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
3990 --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
3991 --listen-v4 Force standalone/tls server to listen at ipv4.
3992 --listen-v6 Force standalone/tls server to listen at ipv6.
3993 --openssl-bin Specifies a custom openssl bin location.
3994 "
3995 }
3996
3997 # nocron
3998 _installOnline() {
3999 _info "Installing from online archive."
4000 _nocron="$1"
4001 if [ ! "$BRANCH" ]; then
4002 BRANCH="master"
4003 fi
4004
4005 target="$PROJECT/archive/$BRANCH.tar.gz"
4006 _info "Downloading $target"
4007 localname="$BRANCH.tar.gz"
4008 if ! _get "$target" >$localname; then
4009 _err "Download error."
4010 return 1
4011 fi
4012 (
4013 _info "Extracting $localname"
4014 tar xzf $localname
4015
4016 cd "$PROJECT_NAME-$BRANCH"
4017 chmod +x $PROJECT_ENTRY
4018 if ./$PROJECT_ENTRY install "$_nocron"; then
4019 _info "Install success!"
4020 fi
4021
4022 cd ..
4023
4024 rm -rf "$PROJECT_NAME-$BRANCH"
4025 rm -f "$localname"
4026 )
4027 }
4028
4029 upgrade() {
4030 if (
4031 _initpath
4032 export LE_WORKING_DIR
4033 cd "$LE_WORKING_DIR"
4034 _installOnline "nocron"
4035 ); then
4036 _info "Upgrade success!"
4037 exit 0
4038 else
4039 _err "Upgrade failed!"
4040 exit 1
4041 fi
4042 }
4043
4044 _processAccountConf() {
4045 if [ "$_useragent" ]; then
4046 _saveaccountconf "USER_AGENT" "$_useragent"
4047 elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
4048 _saveaccountconf "USER_AGENT" "$USER_AGENT"
4049 fi
4050
4051 if [ "$_accountemail" ]; then
4052 _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
4053 elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
4054 _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
4055 fi
4056
4057 if [ "$_openssl_bin" ]; then
4058 _saveaccountconf "OPENSSL_BIN" "$_openssl_bin"
4059 elif [ "$OPENSSL_BIN" ] && [ "$OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
4060 _saveaccountconf "OPENSSL_BIN" "$OPENSSL_BIN"
4061 fi
4062
4063 if [ "$_auto_upgrade" ]; then
4064 _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
4065 elif [ "$AUTO_UPGRADE" ]; then
4066 _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
4067 fi
4068
4069 }
4070
4071 _process() {
4072 _CMD=""
4073 _domain=""
4074 _altdomains="$NO_VALUE"
4075 _webroot=""
4076 _keylength=""
4077 _accountkeylength=""
4078 _certpath=""
4079 _keypath=""
4080 _capath=""
4081 _fullchainpath=""
4082 _reloadcmd=""
4083 _password=""
4084 _accountconf=""
4085 _useragent=""
4086 _accountemail=""
4087 _accountkey=""
4088 _certhome=""
4089 _httpport=""
4090 _tlsport=""
4091 _dnssleep=""
4092 _listraw=""
4093 _stopRenewOnError=""
4094 #_insecure=""
4095 _ca_bundle=""
4096 _nocron=""
4097 _ecc=""
4098 _csr=""
4099 _pre_hook=""
4100 _post_hook=""
4101 _renew_hook=""
4102 _deploy_hook=""
4103 _logfile=""
4104 _log=""
4105 _local_address=""
4106 _log_level=""
4107 _auto_upgrade=""
4108 _listen_v4=""
4109 _listen_v6=""
4110 _openssl_bin=""
4111 while [ ${#} -gt 0 ]; do
4112 case "${1}" in
4113
4114 --help | -h)
4115 showhelp
4116 return
4117 ;;
4118 --version | -v)
4119 version
4120 return
4121 ;;
4122 --install)
4123 _CMD="install"
4124 ;;
4125 --uninstall)
4126 _CMD="uninstall"
4127 ;;
4128 --upgrade)
4129 _CMD="upgrade"
4130 ;;
4131 --issue)
4132 _CMD="issue"
4133 ;;
4134 --deploy)
4135 _CMD="deploy"
4136 ;;
4137 --signcsr)
4138 _CMD="signcsr"
4139 ;;
4140 --showcsr)
4141 _CMD="showcsr"
4142 ;;
4143 --installcert | -i)
4144 _CMD="installcert"
4145 ;;
4146 --renew | -r)
4147 _CMD="renew"
4148 ;;
4149 --renewAll | --renewall)
4150 _CMD="renewAll"
4151 ;;
4152 --revoke)
4153 _CMD="revoke"
4154 ;;
4155 --list)
4156 _CMD="list"
4157 ;;
4158 --installcronjob)
4159 _CMD="installcronjob"
4160 ;;
4161 --uninstallcronjob)
4162 _CMD="uninstallcronjob"
4163 ;;
4164 --cron)
4165 _CMD="cron"
4166 ;;
4167 --toPkcs)
4168 _CMD="toPkcs"
4169 ;;
4170 --createAccountKey | --createaccountkey | -cak)
4171 _CMD="createAccountKey"
4172 ;;
4173 --createDomainKey | --createdomainkey | -cdk)
4174 _CMD="createDomainKey"
4175 ;;
4176 --createCSR | --createcsr | -ccr)
4177 _CMD="createCSR"
4178 ;;
4179 --deactivate)
4180 _CMD="deactivate"
4181 ;;
4182 --updateaccount)
4183 _CMD="updateaccount"
4184 ;;
4185 --registeraccount)
4186 _CMD="registeraccount"
4187 ;;
4188 --domain | -d)
4189 _dvalue="$2"
4190
4191 if [ "$_dvalue" ]; then
4192 if _startswith "$_dvalue" "-"; then
4193 _err "'$_dvalue' is not a valid domain for parameter '$1'"
4194 return 1
4195 fi
4196 if _is_idn "$_dvalue" && ! _exists idn; then
4197 _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
4198 return 1
4199 fi
4200
4201 if [ -z "$_domain" ]; then
4202 _domain="$_dvalue"
4203 else
4204 if [ "$_altdomains" = "$NO_VALUE" ]; then
4205 _altdomains="$_dvalue"
4206 else
4207 _altdomains="$_altdomains,$_dvalue"
4208 fi
4209 fi
4210 fi
4211
4212 shift
4213 ;;
4214
4215 --force | -f)
4216 FORCE="1"
4217 ;;
4218 --staging | --test)
4219 STAGE="1"
4220 ;;
4221 --debug)
4222 if [ -z "$2" ] || _startswith "$2" "-"; then
4223 DEBUG="1"
4224 else
4225 DEBUG="$2"
4226 shift
4227 fi
4228 ;;
4229 --webroot | -w)
4230 wvalue="$2"
4231 if [ -z "$_webroot" ]; then
4232 _webroot="$wvalue"
4233 else
4234 _webroot="$_webroot,$wvalue"
4235 fi
4236 shift
4237 ;;
4238 --standalone)
4239 wvalue="$NO_VALUE"
4240 if [ -z "$_webroot" ]; then
4241 _webroot="$wvalue"
4242 else
4243 _webroot="$_webroot,$wvalue"
4244 fi
4245 ;;
4246 --local-address)
4247 lvalue="$2"
4248 _local_address="$_local_address$lvalue,"
4249 shift
4250 ;;
4251 --apache)
4252 wvalue="apache"
4253 if [ -z "$_webroot" ]; then
4254 _webroot="$wvalue"
4255 else
4256 _webroot="$_webroot,$wvalue"
4257 fi
4258 ;;
4259 --tls)
4260 wvalue="$W_TLS"
4261 if [ -z "$_webroot" ]; then
4262 _webroot="$wvalue"
4263 else
4264 _webroot="$_webroot,$wvalue"
4265 fi
4266 ;;
4267 --dns)
4268 wvalue="dns"
4269 if ! _startswith "$2" "-"; then
4270 wvalue="$2"
4271 shift
4272 fi
4273 if [ -z "$_webroot" ]; then
4274 _webroot="$wvalue"
4275 else
4276 _webroot="$_webroot,$wvalue"
4277 fi
4278 ;;
4279 --dnssleep)
4280 _dnssleep="$2"
4281 Le_DNSSleep="$_dnssleep"
4282 shift
4283 ;;
4284
4285 --keylength | -k)
4286 _keylength="$2"
4287 shift
4288 ;;
4289 --accountkeylength | -ak)
4290 _accountkeylength="$2"
4291 shift
4292 ;;
4293
4294 --certpath)
4295 _certpath="$2"
4296 shift
4297 ;;
4298 --keypath)
4299 _keypath="$2"
4300 shift
4301 ;;
4302 --capath)
4303 _capath="$2"
4304 shift
4305 ;;
4306 --fullchainpath)
4307 _fullchainpath="$2"
4308 shift
4309 ;;
4310 --reloadcmd | --reloadCmd)
4311 _reloadcmd="$2"
4312 shift
4313 ;;
4314 --password)
4315 _password="$2"
4316 shift
4317 ;;
4318 --accountconf)
4319 _accountconf="$2"
4320 ACCOUNT_CONF_PATH="$_accountconf"
4321 shift
4322 ;;
4323 --home)
4324 LE_WORKING_DIR="$2"
4325 shift
4326 ;;
4327 --certhome)
4328 _certhome="$2"
4329 CERT_HOME="$_certhome"
4330 shift
4331 ;;
4332 --useragent)
4333 _useragent="$2"
4334 USER_AGENT="$_useragent"
4335 shift
4336 ;;
4337 --accountemail)
4338 _accountemail="$2"
4339 ACCOUNT_EMAIL="$_accountemail"
4340 shift
4341 ;;
4342 --accountkey)
4343 _accountkey="$2"
4344 ACCOUNT_KEY_PATH="$_accountkey"
4345 shift
4346 ;;
4347 --days)
4348 _days="$2"
4349 Le_RenewalDays="$_days"
4350 shift
4351 ;;
4352 --httpport)
4353 _httpport="$2"
4354 Le_HTTPPort="$_httpport"
4355 shift
4356 ;;
4357 --tlsport)
4358 _tlsport="$2"
4359 Le_TLSPort="$_tlsport"
4360 shift
4361 ;;
4362
4363 --listraw)
4364 _listraw="raw"
4365 ;;
4366 --stopRenewOnError | --stoprenewonerror | -se)
4367 _stopRenewOnError="1"
4368 ;;
4369 --insecure)
4370 #_insecure="1"
4371 HTTPS_INSECURE="1"
4372 ;;
4373 --ca-bundle)
4374 _ca_bundle="$(readlink -f "$2")"
4375 CA_BUNDLE="$_ca_bundle"
4376 shift
4377 ;;
4378 --nocron)
4379 _nocron="1"
4380 ;;
4381 --ecc)
4382 _ecc="isEcc"
4383 ;;
4384 --csr)
4385 _csr="$2"
4386 shift
4387 ;;
4388 --pre-hook)
4389 _pre_hook="$2"
4390 shift
4391 ;;
4392 --post-hook)
4393 _post_hook="$2"
4394 shift
4395 ;;
4396 --renew-hook)
4397 _renew_hook="$2"
4398 shift
4399 ;;
4400 --deploy-hook)
4401 _deploy_hook="$2"
4402 shift
4403 ;;
4404 --ocsp-must-staple | --ocsp)
4405 Le_OCSP_Stable="1"
4406 ;;
4407 --log | --logfile)
4408 _log="1"
4409 _logfile="$2"
4410 if _startswith "$_logfile" '-'; then
4411 _logfile=""
4412 else
4413 shift
4414 fi
4415 LOG_FILE="$_logfile"
4416 if [ -z "$LOG_LEVEL" ]; then
4417 LOG_LEVEL="$DEFAULT_LOG_LEVEL"
4418 fi
4419 ;;
4420 --log-level)
4421 _log_level="$2"
4422 LOG_LEVEL="$_log_level"
4423 shift
4424 ;;
4425 --auto-upgrade)
4426 _auto_upgrade="$2"
4427 if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
4428 _auto_upgrade="1"
4429 else
4430 shift
4431 fi
4432 AUTO_UPGRADE="$_auto_upgrade"
4433 ;;
4434 --listen-v4)
4435 _listen_v4="1"
4436 Le_Listen_V4="$_listen_v4"
4437 ;;
4438 --listen-v6)
4439 _listen_v6="1"
4440 Le_Listen_V6="$_listen_v6"
4441 ;;
4442 --openssl-bin)
4443 _openssl_bin="$2"
4444 OPENSSL_BIN="$_openssl_bin"
4445 ;;
4446 *)
4447 _err "Unknown parameter : $1"
4448 return 1
4449 ;;
4450 esac
4451
4452 shift 1
4453 done
4454
4455 if [ "${_CMD}" != "install" ]; then
4456 __initHome
4457 if [ "$_log" ]; then
4458 if [ -z "$_logfile" ]; then
4459 _logfile="$DEFAULT_LOG_FILE"
4460 fi
4461 fi
4462 if [ "$_logfile" ]; then
4463 _saveaccountconf "LOG_FILE" "$_logfile"
4464 LOG_FILE="$_logfile"
4465 fi
4466
4467 if [ "$_log_level" ]; then
4468 _saveaccountconf "LOG_LEVEL" "$_log_level"
4469 LOG_LEVEL="$_log_level"
4470 fi
4471
4472 _processAccountConf
4473 fi
4474
4475 _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
4476
4477 if [ "$DEBUG" ]; then
4478 version
4479 fi
4480
4481 case "${_CMD}" in
4482 install) install "$_nocron" ;;
4483 uninstall) uninstall "$_nocron" ;;
4484 upgrade) upgrade ;;
4485 issue)
4486 issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
4487 ;;
4488 deploy)
4489 deploy "$_domain" "$_deploy_hook" "$_ecc"
4490 ;;
4491 signcsr)
4492 signcsr "$_csr" "$_webroot"
4493 ;;
4494 showcsr)
4495 showcsr "$_csr" "$_domain"
4496 ;;
4497 installcert)
4498 installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
4499 ;;
4500 renew)
4501 renew "$_domain" "$_ecc"
4502 ;;
4503 renewAll)
4504 renewAll "$_stopRenewOnError"
4505 ;;
4506 revoke)
4507 revoke "$_domain" "$_ecc"
4508 ;;
4509 deactivate)
4510 deactivate "$_domain,$_altdomains"
4511 ;;
4512 registeraccount)
4513 registeraccount "$_accountkeylength"
4514 ;;
4515 updateaccount)
4516 updateaccount
4517 ;;
4518 list)
4519 list "$_listraw"
4520 ;;
4521 installcronjob) installcronjob ;;
4522 uninstallcronjob) uninstallcronjob ;;
4523 cron) cron ;;
4524 toPkcs)
4525 toPkcs "$_domain" "$_password" "$_ecc"
4526 ;;
4527 createAccountKey)
4528 createAccountKey "$_accountkeylength"
4529 ;;
4530 createDomainKey)
4531 createDomainKey "$_domain" "$_keylength"
4532 ;;
4533 createCSR)
4534 createCSR "$_domain" "$_altdomains" "$_ecc"
4535 ;;
4536
4537 *)
4538 _err "Invalid command: $_CMD"
4539 showhelp
4540 return 1
4541 ;;
4542 esac
4543 _ret="$?"
4544 if [ "$_ret" != "0" ]; then
4545 return $_ret
4546 fi
4547
4548 if [ "${_CMD}" = "install" ]; then
4549 if [ "$_log" ]; then
4550 if [ -z "$LOG_FILE" ]; then
4551 LOG_FILE="$DEFAULT_LOG_FILE"
4552 fi
4553 _saveaccountconf "LOG_FILE" "$LOG_FILE"
4554 fi
4555
4556 if [ "$_log_level" ]; then
4557 _saveaccountconf "LOG_LEVEL" "$_log_level"
4558 fi
4559 _processAccountConf
4560 fi
4561
4562 }
4563
4564 if [ "$INSTALLONLINE" ]; then
4565 INSTALLONLINE=""
4566 _installOnline $BRANCH
4567 exit
4568 fi
4569
4570 main() {
4571 [ -z "$1" ] && showhelp && return
4572 if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
4573 }
4574
4575 main "$@"