]> git.proxmox.com Git - mirror_acme.sh.git/blame - le.sh
compatible for netstat on FreeBSD
[mirror_acme.sh.git] / le.sh
CommitLineData
4c3b3608 1#!/usr/bin/env bash
c60883ef 2VER=1.2.0
4c3b3608 3PROJECT="https://github.com/Neilpang/le"
4
5DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
6DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
7
bbbdcb09 8DEFAULT_USER_AGENT="le.sh client: $PROJECT"
9
4c3b3608 10STAGE_CA="https://acme-staging.api.letsencrypt.org"
11
12VTYPE_HTTP="http-01"
13VTYPE_DNS="dns-01"
14
88fab7d6 15BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
16END_CSR="-----END CERTIFICATE REQUEST-----"
17
18BEGIN_CERT="-----BEGIN CERTIFICATE-----"
19END_CERT="-----END CERTIFICATE-----"
20
4c3b3608 21if [ -z "$AGREEMENT" ] ; then
22 AGREEMENT="$DEFAULT_AGREEMENT"
23fi
24
4c3b3608 25
26_info() {
27 if [ -z "$2" ] ; then
28 echo "$1"
29 else
30 echo "$1"="$2"
31 fi
32}
33
34_err() {
35 if [ -z "$2" ] ; then
36 echo "$1" >&2
37 else
bbbdcb09 38 echo "$1"="'$2'" >&2
4c3b3608 39 fi
40 return 1
41}
42
c60883ef 43_debug() {
44 if [ -z "$DEBUG" ] ; then
45 return
46 fi
47 _err "$1" "$2"
48 return 0
49}
50
51_exists() {
52 cmd="$1"
53 if [ -z "$cmd" ] ; then
54 _err "Usage: _exists cmd"
55 return 1
56 fi
57 command -v $cmd >/dev/null 2>&1
58 ret="$?"
59 _debug "$cmd exists=$ret"
60 return $ret
61}
62
4c3b3608 63_h2b() {
64 hex=$(cat)
65 i=1
66 j=2
67 while [ '1' ] ; do
68 h=$(printf $hex | cut -c $i-$j)
69 if [ -z "$h" ] ; then
70 break;
71 fi
72 printf "\x$h"
73 let "i+=2"
74 let "j+=2"
75 done
76}
77
c60883ef 78#options file
79_sed_i() {
80 options="$1"
81 filename="$2"
82 if [ -z "$filename" ] ; then
83 _err "Usage:_sed_i options filename"
84 return 1
85 fi
86
87 if sed -h 2>&1 | grep "\-i[SUFFIX]" ; then
88 _debug "Using sed -i"
89 sed -i ""
90 else
91 _debug "No -i support in sed"
92 text="$(cat $filename)"
93 echo "$text" | sed "$options" > "$filename"
94 fi
95}
96
88fab7d6 97#Usage: file startline endline
98_getfile() {
99 filename="$1"
100 startline="$2"
101 endline="$3"
102 if [ -z "$endline" ] ; then
103 _err "Usage: file startline endline"
104 return 1
105 fi
106
107 i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
108 if [ -z "$i" ] ; then
109 _err "Can not find start line: $startline"
110 return 1
111 fi
112 let "i+=1"
113 _debug i $i
114
115 j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
116 if [ -z "$j" ] ; then
117 _err "Can not find end line: $endline"
118 return 1
119 fi
120 let "j-=1"
121 _debug j $j
122
123 sed -n $i,${j}p "$filename"
124
125}
126
127#Usage: multiline
4c3b3608 128_base64() {
88fab7d6 129 if [ "$1" ] ; then
130 openssl base64 -e
131 else
132 openssl base64 -e | tr -d '\r\n'
133 fi
134}
135
136#Usage: multiline
137_dbase64() {
138 if [ "$1" ] ; then
139 openssl base64 -d -A
140 else
141 openssl base64 -d
142 fi
143}
144
145#Usage: hashalg
146#Output Base64-encoded digest
147_digest() {
148 alg="$1"
149 if [ -z "$alg" ] ; then
150 _err "Usage: _digest hashalg"
151 return 1
152 fi
153
154 if [ "$alg" == "sha256" ] ; then
155 openssl dgst -sha256 -binary | _base64
156 else
157 _err "$alg is not supported yet"
158 return 1
159 fi
160
161}
162
163#Usage: keyfile hashalg
164#Output: Base64-encoded signature value
165_sign() {
166 keyfile="$1"
167 alg="$2"
168 if [ -z "$alg" ] ; then
169 _err "Usage: _sign keyfile hashalg"
170 return 1
171 fi
172
173 if [ "$alg" == "sha256" ] ; then
174 openssl dgst -sha256 -sign "$keyfile" | _base64
175 else
176 _err "$alg is not supported yet"
177 return 1
178 fi
179
4c3b3608 180}
181
34c27e09 182_ss() {
183 _port="$1"
edf08da6 184
185 if _exists "ss" ; then
186 _debug "Using: ss"
187 ss -ntpl | grep :$_port" "
188 return 0
189 fi
190
191 if _exists "netstat" ; then
251fc37c 192 _debug "Using: netstat"
ccb96535 193 if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
194 #for windows version netstat tool
50a4ef9c 195 netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
ccb96535 196 else
edf08da6 197 if netstat -help 2>&1 | grep "-p protocol" >/dev/null ; then
198 netstat -an -p tcp | grep LISTEN | grep :$_port" "
199 else
200 netstat -ntpl | grep :$_port" "
201 fi
ccb96535 202 fi
34c27e09 203 return 0
204 fi
edf08da6 205
34c27e09 206 return 1
207}
208
4c3b3608 209#domain [2048]
210createAccountKey() {
211 _info "Creating account key"
212 if [ -z "$1" ] ; then
213 echo Usage: createAccountKey account-domain [2048]
214 return
215 fi
216
217 account=$1
218 length=$2
219
220 if [[ "$length" == "ec-"* ]] ; then
221 length=2048
222 fi
223
224 if [ -z "$2" ] ; then
225 _info "Use default length 2048"
226 length=2048
227 fi
228 _initpath
229
230 if [ -f "$ACCOUNT_KEY_PATH" ] ; then
231 _info "Account key exists, skip"
232 return
233 else
234 #generate account key
f89d991d 235 openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
4c3b3608 236 fi
237
238}
239
240#domain length
241createDomainKey() {
242 _info "Creating domain key"
243 if [ -z "$1" ] ; then
244 echo Usage: createDomainKey domain [2048]
245 return
246 fi
247
248 domain=$1
249 length=$2
250 isec=""
251 if [[ "$length" == "ec-"* ]] ; then
252 isec="1"
253 length=$(printf $length | cut -d '-' -f 2-100)
254 eccname="$length"
255 fi
256
257 if [ -z "$length" ] ; then
258 if [ "$isec" ] ; then
259 length=256
260 else
261 length=2048
262 fi
263 fi
264 _info "Use length $length"
265
266 if [ "$isec" ] ; then
267 if [ "$length" == "256" ] ; then
268 eccname="prime256v1"
269 fi
270 if [ "$length" == "384" ] ; then
271 eccname="secp384r1"
272 fi
273 if [ "$length" == "521" ] ; then
274 eccname="secp521r1"
275 fi
276 _info "Using ec name: $eccname"
277 fi
278
279 _initpath $domain
280
281 if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
282 #generate account key
283 if [ "$isec" ] ; then
284 openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
285 else
286 openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
287 fi
288 else
289 if [ "$IS_RENEW" ] ; then
290 _info "Domain key exists, skip"
291 return 0
292 else
293 _err "Domain key exists, do you want to overwrite the key?"
294 _err "Set FORCE=1, and try again."
295 return 1
296 fi
297 fi
298
299}
300
301# domain domainlist
302createCSR() {
303 _info "Creating csr"
304 if [ -z "$1" ] ; then
305 echo Usage: $0 domain [domainlist]
306 return
307 fi
308 domain=$1
309 _initpath $domain
310
311 domainlist=$2
312
313 if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && ! [ "$FORCE" ]; then
314 _info "CSR exists, skip"
315 return
316 fi
317
318 if [ -z "$domainlist" ] ; then
319 #single domain
320 _info "Single domain" $domain
1ad65f7d 321 printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
322 openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
4c3b3608 323 else
324 alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
325 #multi
326 _info "Multi domain" "$alt"
327 printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
328 openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
329 fi
330
331}
332
166096dc 333_urlencode() {
4c3b3608 334 __n=$(cat)
335 echo $__n | tr '/+' '_-' | tr -d '= '
336}
337
338_time2str() {
339 #BSD
340 if date -u -d@$1 2>/dev/null ; then
341 return
342 fi
343
344 #Linux
345 if date -u -r $1 2>/dev/null ; then
346 return
347 fi
348
349}
350
44df2967 351_stat() {
352 #Linux
353 if stat -c '%U:%G' "$1" 2>/dev/null ; then
354 return
355 fi
356
357 #BSD
358 if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
359 return
360 fi
361}
362
166096dc 363#keyfile
364_calcjwk() {
365 keyfile="$1"
366 if [ -z "$keyfile" ] ; then
367 _err "Usage: _calcjwk keyfile"
368 return 1
369 fi
370 EC_SIGN=""
371 if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
372 _debug "RSA key"
373 pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
374 if [ "${#pub_exp}" == "5" ] ; then
375 pub_exp=0$pub_exp
376 fi
377 _debug pub_exp "$pub_exp"
378
379 e=$(echo $pub_exp | _h2b | _base64)
380 _debug e "$e"
381
382 modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
383 n=$(echo $modulus| _h2b | _base64 | _urlencode )
384 jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
385 _debug jwk "$jwk"
386
387 HEADER='{"alg": "RS256", "jwk": '$jwk'}'
388 HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
389 elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
390 _debug "EC key"
391 EC_SIGN="1"
392 crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
393 _debug crv $crv
394
395 pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
396 _debug pubi $pubi
397 let "pubi=pubi+1"
398
399 pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
400 _debug pubj $pubj
401 let "pubj=pubj-1"
402
403 pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
404 _debug pubtext "$pubtext"
405
406 xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
407 let "xlen=xlen/4"
408 _debug xlen $xlen
409
410 let "xend=xlen+1"
411 x="$(printf $pubtext | cut -d : -f 2-$xend)"
412 _debug x $x
413
414 x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
415 _debug x64 $x64
416
417 let "xend+=1"
418 y="$(printf $pubtext | cut -d : -f $xend-10000)"
419 _debug y $y
420
421 y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
422 _debug y64 $y64
423
424 jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
425 _debug jwk "$jwk"
426
427 HEADER='{"alg": "ES256", "jwk": '$jwk'}'
428 HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
429
430 else
431 _err "Only RSA or EC key is supported."
432 return 1
433 fi
434
435 _debug HEADER "$HEADER"
436}
c60883ef 437# body url [needbase64]
438_post() {
439 body="$1"
440 url="$2"
441 needbase64="$3"
442
443 if _exists "curl" ; then
bbbdcb09 444 CURL="$CURL --dump-header $HTTP_HEADER "
c60883ef 445 if [ "$needbase64" ] ; then
bbbdcb09 446 response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
c60883ef 447 else
bbbdcb09 448 response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
c60883ef 449 fi
450 else
451 if [ "$needbase64" ] ; then
bbbdcb09 452 response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
c60883ef 453 else
bbbdcb09 454 response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
c60883ef 455 fi
456 _sed_i "s/^ *//g" "$HTTP_HEADER"
457 fi
458 echo -n "$response"
459
460}
461
462# url getheader
463_get() {
464 url="$1"
465 onlyheader="$2"
466 _debug url $url
467 if _exists "curl" ; then
468 if [ "$onlyheader" ] ; then
bbbdcb09 469 $CURL -I -A "User-Agent: $USER_AGENT" $url
c60883ef 470 else
bbbdcb09 471 $CURL -A "User-Agent: $USER_AGENT" $url
c60883ef 472 fi
473 else
bbbdcb09 474 _debug "WGET" "$WGET"
c60883ef 475 if [ "$onlyheader" ] ; then
bbbdcb09 476 eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
c60883ef 477 else
bbbdcb09 478 eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
c60883ef 479 fi
480 fi
481 ret=$?
482 return $ret
483}
166096dc 484
485# url payload needbase64 keyfile
4c3b3608 486_send_signed_request() {
487 url=$1
488 payload=$2
489 needbase64=$3
166096dc 490 keyfile=$4
491 if [ -z "$keyfile" ] ; then
492 keyfile="$ACCOUNT_KEY_PATH"
493 fi
4c3b3608 494 _debug url $url
495 _debug payload "$payload"
496
166096dc 497 if ! _calcjwk "$keyfile" ; then
498 return 1
499 fi
c60883ef 500
166096dc 501 payload64=$(echo -n $payload | _base64 | _urlencode)
4c3b3608 502 _debug payload64 $payload64
503
504 nonceurl="$API/directory"
bbbdcb09 505 nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
4c3b3608 506
507 _debug nonce "$nonce"
508
509 protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
510 _debug protected "$protected"
511
166096dc 512 protected64="$(printf "$protected" | _base64 | _urlencode)"
4c3b3608 513 _debug protected64 "$protected64"
166096dc 514
88fab7d6 515 sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
4c3b3608 516 _debug sig "$sig"
517
518 body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
519 _debug body "$body"
520
bbbdcb09 521
c60883ef 522 response="$(_post "$body" $url "$needbase64" )"
4c3b3608 523
c60883ef 524 responseHeaders="$(cat $HTTP_HEADER)"
4c3b3608 525
526 _debug responseHeaders "$responseHeaders"
527 _debug response "$response"
c60883ef 528 code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
4c3b3608 529 _debug code $code
530
531}
532
4c3b3608 533
534#setopt "file" "opt" "=" "value" [";"]
535_setopt() {
536 __conf="$1"
537 __opt="$2"
538 __sep="$3"
539 __val="$4"
540 __end="$5"
541 if [ -z "$__opt" ] ; then
542 echo usage: _setopt '"file" "opt" "=" "value" [";"]'
543 return
544 fi
545 if [ ! -f "$__conf" ] ; then
546 touch "$__conf"
547 fi
548
549 if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
550 _debug OK
551 if [[ "$__val" == *"&"* ]] ; then
552 __val="$(echo $__val | sed 's/&/\\&/g')"
553 fi
554 text="$(cat $__conf)"
6dfaaa70 555 echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
4c3b3608 556
557 elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
558 if [[ "$__val" == *"&"* ]] ; then
559 __val="$(echo $__val | sed 's/&/\\&/g')"
560 fi
561 text="$(cat $__conf)"
6dfaaa70 562 echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
4c3b3608 563
564 else
565 _debug APP
4c3b3608 566 echo "$__opt$__sep$__val$__end" >> "$__conf"
567 fi
568 _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
569}
570
571#_savedomainconf key value
572#save to domain.conf
573_savedomainconf() {
574 key="$1"
575 value="$2"
576 if [ "$DOMAIN_CONF" ] ; then
577 _setopt $DOMAIN_CONF "$key" "=" "$value"
578 else
579 _err "DOMAIN_CONF is empty, can not save $key=$value"
580 fi
581}
582
583#_saveaccountconf key value
584_saveaccountconf() {
585 key="$1"
586 value="$2"
587 if [ "$ACCOUNT_CONF_PATH" ] ; then
588 _setopt $ACCOUNT_CONF_PATH "$key" "=" "$value"
589 else
590 _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
591 fi
592}
593
594_startserver() {
595 content="$1"
850c1128 596
1b2e940d 597 nchelp="$(nc -h 2>&1)"
850c1128 598
0f4e8b0e 599 if echo "$nchelp" | grep "\-q " >/dev/null ; then
850c1128 600 _NC="nc -q 1 -l"
601 else
f76eb452 602 if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
603 _NC="nc -c -l"
604 else
605 _NC="nc -l"
606 fi
4c3b3608 607 fi
1b2e940d 608
f76eb452 609 _debug "_NC" "$_NC"
4c3b3608 610# while true ; do
611 if [ "$DEBUG" ] ; then
3aff11f6 612 if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
613 echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
614 fi
4c3b3608 615 else
bac3b6b0 616 if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
617 echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
3aff11f6 618 fi
4c3b3608 619 fi
051c706d 620 if [ "$?" != "0" ] ; then
621 _err "nc listen error."
622 return 1
623 fi
4c3b3608 624# done
625}
626
627_stopserver() {
628 pid="$1"
629
630}
631
632_initpath() {
633
634 if [ -z "$LE_WORKING_DIR" ]; then
635 LE_WORKING_DIR=$HOME/.le
636 fi
637
638 if [ -z "$ACCOUNT_CONF_PATH" ] ; then
639 ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
640 fi
641
642 if [ -f "$ACCOUNT_CONF_PATH" ] ; then
643 source "$ACCOUNT_CONF_PATH"
644 fi
645
646 if [ -z "$API" ] ; then
647 if [ -z "$STAGE" ] ; then
648 API="$DEFAULT_CA"
649 else
650 API="$STAGE_CA"
651 _info "Using stage api:$API"
652 fi
653 fi
654
655 if [ -z "$ACME_DIR" ] ; then
656 ACME_DIR="/home/.acme"
657 fi
658
659 if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
660 APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR/"
661 fi
662
bbbdcb09 663 if [ -z "$USER_AGENT" ] ; then
664 USER_AGENT="$DEFAULT_USER_AGENT"
665 fi
666
667 HTTP_HEADER="$LE_WORKING_DIR/http.header"
668
669 WGET="wget -q"
670 if [ "$DEBUG" ] ; then
671 WGET="$WGET -d "
672 fi
673
674 dp="$LE_WORKING_DIR/curl.dump"
675 CURL="curl --silent"
676 if [ "$DEBUG" ] ; then
677 CURL="$CURL --trace-ascii $dp "
678 fi
679
4c3b3608 680 domain="$1"
681 if ! mkdir -p "$LE_WORKING_DIR" ; then
682 _err "Can not craete working dir: $LE_WORKING_DIR"
683 return 1
684 fi
685
686 if [ -z "$ACCOUNT_KEY_PATH" ] ; then
687 ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
688 fi
689
690 if [ -z "$domain" ] ; then
691 return 0
692 fi
693
694 domainhome="$LE_WORKING_DIR/$domain"
695 mkdir -p "$domainhome"
696
697 if [ -z "$DOMAIN_PATH" ] ; then
698 DOMAIN_PATH="$domainhome"
699 fi
700 if [ -z "$DOMAIN_CONF" ] ; then
1ad65f7d 701 DOMAIN_CONF="$domainhome/$domain.conf"
4c3b3608 702 fi
703
704 if [ -z "$DOMAIN_SSL_CONF" ] ; then
1ad65f7d 705 DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
4c3b3608 706 fi
707
708 if [ -z "$CSR_PATH" ] ; then
709 CSR_PATH="$domainhome/$domain.csr"
710 fi
711 if [ -z "$CERT_KEY_PATH" ] ; then
712 CERT_KEY_PATH="$domainhome/$domain.key"
713 fi
714 if [ -z "$CERT_PATH" ] ; then
715 CERT_PATH="$domainhome/$domain.cer"
716 fi
717 if [ -z "$CA_CERT_PATH" ] ; then
718 CA_CERT_PATH="$domainhome/ca.cer"
719 fi
caf1fc10 720 if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
850db6d4 721 CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
caf1fc10 722 fi
4c3b3608 723
724}
725
726
727_apachePath() {
728 httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
729 httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
730 httpdconf="$httpdroot/$httpdconfname"
731 if [ ! -f $httpdconf ] ; then
732 _err "Apache Config file not found" $httpdconf
733 return 1
734 fi
735 return 0
736}
737
738_restoreApache() {
739 if [ -z "$usingApache" ] ; then
740 return 0
741 fi
742 _initpath
743 if ! _apachePath ; then
744 return 1
745 fi
746
747 if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
748 _debug "No config file to restore."
749 return 0
750 fi
751
752 cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
753 if ! apachectl -t ; then
754 _err "Sorry, restore apache config error, please contact me."
755 return 1;
756 fi
757 rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
758 return 0
759}
760
761_setApache() {
762 _initpath
763 if ! _apachePath ; then
764 return 1
765 fi
766
767 #backup the conf
768 _debug "Backup apache config file" $httpdconf
769 cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
770 _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
771 _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
772 _info "The backup file will be deleted on sucess, just forget it."
773
774 #add alias
775 echo "
776Alias /.well-known/acme-challenge $ACME_DIR
777
778<Directory $ACME_DIR >
779Require all granted
780</Directory>
781 " >> $httpdconf
782
783 if ! apachectl -t ; then
784 _err "Sorry, apache config error, please contact me."
785 _restoreApache
786 return 1;
787 fi
788
789 if [ ! -d "$ACME_DIR" ] ; then
790 mkdir -p "$ACME_DIR"
791 chmod 755 "$ACME_DIR"
792 fi
793
794 if ! apachectl graceful ; then
795 _err "Sorry, apachectl graceful error, please contact me."
796 _restoreApache
797 return 1;
798 fi
799 usingApache="1"
800 return 0
801}
802
803_clearup () {
804 _stopserver $serverproc
805 serverproc=""
806 _restoreApache
807}
808
809# webroot removelevel tokenfile
810_clearupwebbroot() {
811 __webroot="$1"
812 if [ -z "$__webroot" ] ; then
813 _debug "no webroot specified, skip"
814 return 0
815 fi
816
817 if [ "$2" == '1' ] ; then
818 _debug "remove $__webroot/.well-known"
819 rm -rf "$__webroot/.well-known"
820 elif [ "$2" == '2' ] ; then
821 _debug "remove $__webroot/.well-known/acme-challenge"
822 rm -rf "$__webroot/.well-known/acme-challenge"
823 elif [ "$2" == '3' ] ; then
824 _debug "remove $__webroot/.well-known/acme-challenge/$3"
825 rm -rf "$__webroot/.well-known/acme-challenge/$3"
826 else
827 _info "Skip for removelevel:$2"
828 fi
829
830 return 0
831
832}
833
834issue() {
835 if [ -z "$2" ] ; then
836 _err "Usage: le issue webroot|no|apache|dns a.com [www.a.com,b.com,c.com]|no [key-length]|no"
837 return 1
838 fi
839 Le_Webroot="$1"
840 Le_Domain="$2"
841 Le_Alt="$3"
842 Le_Keylength="$4"
843 Le_RealCertPath="$5"
844 Le_RealKeyPath="$6"
845 Le_RealCACertPath="$7"
846 Le_ReloadCmd="$8"
847
848
849 _initpath $Le_Domain
850
851 if [ -f "$DOMAIN_CONF" ] ; then
852 Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
853 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
854 _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
855 return 2
856 fi
857 fi
858
859 if [ "$Le_Alt" == "no" ] ; then
860 Le_Alt=""
861 fi
862 if [ "$Le_Keylength" == "no" ] ; then
863 Le_Keylength=""
864 fi
865 if [ "$Le_RealCertPath" == "no" ] ; then
866 Le_RealCertPath=""
867 fi
868 if [ "$Le_RealKeyPath" == "no" ] ; then
869 Le_RealKeyPath=""
870 fi
871 if [ "$Le_RealCACertPath" == "no" ] ; then
872 Le_RealCACertPath=""
873 fi
874 if [ "$Le_ReloadCmd" == "no" ] ; then
875 Le_ReloadCmd=""
876 fi
877
878 _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
879 _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
880 _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
881 _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
882 _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
883 _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
884 _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
885 _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
886
887 if [ "$Le_Webroot" == "no" ] ; then
888 _info "Standalone mode."
889 if ! command -v "nc" > /dev/null ; then
890 _err "Please install netcat(nc) tools first."
891 return 1
892 fi
893
894 if [ -z "$Le_HTTPPort" ] ; then
895 Le_HTTPPort=80
896 fi
897 _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
898
251fc37c 899 netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
4c3b3608 900 if [ "$netprc" ] ; then
901 _err "$netprc"
902 _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
903 _err "Please stop it first"
904 return 1
905 fi
906 fi
907
908 if [ "$Le_Webroot" == "apache" ] ; then
909 if ! _setApache ; then
910 _err "set up apache error. Report error to me."
911 return 1
912 fi
913 wellknown_path="$ACME_DIR"
914 else
915 usingApache=""
916 fi
917
918 createAccountKey $Le_Domain $Le_Keylength
166096dc 919
920 if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
921 return 1
922 fi
923
924 accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
88fab7d6 925 thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
4c3b3608 926
88fab7d6 927 accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
166096dc 928
929 if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
930 _info "Registering account"
931 regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
932 if [ "$ACCOUNT_EMAIL" ] ; then
933 regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
934 fi
935 _send_signed_request "$API/acme/new-reg" "$regjson"
936
937 if [ "$code" == "" ] || [ "$code" == '201' ] ; then
938 _info "Registered"
939 echo $response > $LE_WORKING_DIR/account.json
940 elif [ "$code" == '409' ] ; then
941 _info "Already registered"
942 else
943 _err "Register account Error: $response"
944 _clearup
945 return 1
946 fi
947 ACCOUNT_KEY_HASH="$accountkeyhash"
948 _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
949 else
950 _info "Skip register account key"
951 fi
952
4c3b3608 953 if ! createDomainKey $Le_Domain $Le_Keylength ; then
954 _err "Create domain key error."
955 return 1
956 fi
957
958 if ! createCSR $Le_Domain $Le_Alt ; then
959 _err "Create CSR error."
960 return 1
961 fi
4c3b3608 962
963 vtype="$VTYPE_HTTP"
964 if [[ "$Le_Webroot" == "dns"* ]] ; then
965 vtype="$VTYPE_DNS"
966 fi
967
968 vlist="$Le_Vlist"
969 # verify each domain
970 _info "Verify each domain"
971 sep='#'
972 if [ -z "$vlist" ] ; then
973 alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
974 for d in $alldomains
975 do
976 _info "Getting token for domain" $d
977 _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
978 if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
979 _err "new-authz error: $response"
980 _clearup
981 return 1
982 fi
983
348cddd7 984 entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
4c3b3608 985 _debug entry "$entry"
986
987 token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
988 _debug token $token
989
990 uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
991 _debug uri $uri
992
993 keyauthorization="$token.$thumbprint"
994 _debug keyauthorization "$keyauthorization"
995
996 dvlist="$d$sep$keyauthorization$sep$uri"
997 _debug dvlist "$dvlist"
998
999 vlist="$vlist$dvlist,"
1000
1001 done
1002
1003 #add entry
1004 dnsadded=""
1005 ventries=$(echo "$vlist" | tr ',' ' ' )
1006 for ventry in $ventries
1007 do
1008 d=$(echo $ventry | cut -d $sep -f 1)
1009 keyauthorization=$(echo $ventry | cut -d $sep -f 2)
1010
1011 if [ "$vtype" == "$VTYPE_DNS" ] ; then
1012 dnsadded='0'
1013 txtdomain="_acme-challenge.$d"
1014 _debug txtdomain "$txtdomain"
88fab7d6 1015 txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
4c3b3608 1016 _debug txt "$txt"
1017 #dns
1018 #1. check use api
1019 d_api=""
1020 if [ -f "$LE_WORKING_DIR/$d/$Le_Webroot" ] ; then
1021 d_api="$LE_WORKING_DIR/$d/$Le_Webroot"
1022 elif [ -f "$LE_WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
1023 d_api="$LE_WORKING_DIR/$d/$Le_Webroot.sh"
1024 elif [ -f "$LE_WORKING_DIR/$Le_Webroot" ] ; then
1025 d_api="$LE_WORKING_DIR/$Le_Webroot"
1026 elif [ -f "$LE_WORKING_DIR/$Le_Webroot.sh" ] ; then
1027 d_api="$LE_WORKING_DIR/$Le_Webroot.sh"
1028 elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
1029 d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot"
1030 elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
1031 d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh"
1032 fi
1033 _debug d_api "$d_api"
1034
1035 if [ "$d_api" ]; then
1036 _info "Found domain api file: $d_api"
1037 else
1038 _err "Add the following TXT record:"
1039 _err "Domain: $txtdomain"
1040 _err "TXT value: $txt"
1041 _err "Please be aware that you prepend _acme-challenge. before your domain"
1042 _err "so the resulting subdomain will be: $txtdomain"
1043 continue
1044 fi
1045
1046 if ! source $d_api ; then
1047 _err "Load file $d_api error. Please check your api file and try again."
1048 return 1
1049 fi
1050
1051 addcommand="$Le_Webroot-add"
1052 if ! command -v $addcommand ; then
f8ad8f34 1053 _err "It seems that your api file is not correct, it must have a function named: $addcommand"
4c3b3608 1054 return 1
1055 fi
1056
1057 if ! $addcommand $txtdomain $txt ; then
1058 _err "Error add txt for domain:$txtdomain"
1059 return 1
1060 fi
1061 dnsadded='1'
1062 fi
1063 done
1064
1065 if [ "$dnsadded" == '0' ] ; then
1066 _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
1067 _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
1068 _err "Please add the TXT records to the domains, and retry again."
1069 return 1
1070 fi
1071
1072 fi
1073
1074 if [ "$dnsadded" == '1' ] ; then
1075 _info "Sleep 60 seconds for the txt records to take effect"
1076 sleep 60
1077 fi
1078
1079 _debug "ok, let's start to verify"
1080 ventries=$(echo "$vlist" | tr ',' ' ' )
1081 for ventry in $ventries
1082 do
1083 d=$(echo $ventry | cut -d $sep -f 1)
1084 keyauthorization=$(echo $ventry | cut -d $sep -f 2)
1085 uri=$(echo $ventry | cut -d $sep -f 3)
1086 _info "Verifying:$d"
1087 _debug "d" "$d"
1088 _debug "keyauthorization" "$keyauthorization"
1089 _debug "uri" "$uri"
1090 removelevel=""
1091 token=""
1092 if [ "$vtype" == "$VTYPE_HTTP" ] ; then
1093 if [ "$Le_Webroot" == "no" ] ; then
1094 _info "Standalone mode server"
1095 _startserver "$keyauthorization" &
1096 serverproc="$!"
1097 sleep 2
1098 _debug serverproc $serverproc
1099 else
1100 if [ -z "$wellknown_path" ] ; then
1101 wellknown_path="$Le_Webroot/.well-known/acme-challenge"
1102 fi
1103 _debug wellknown_path "$wellknown_path"
1104
1105 if [ ! -d "$Le_Webroot/.well-known" ] ; then
1106 removelevel='1'
1107 elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
1108 removelevel='2'
1109 else
1110 removelevel='3'
1111 fi
1112
1113 token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
1114 _debug "writing token:$token to $wellknown_path/$token"
1115
1116 mkdir -p "$wellknown_path"
1117 echo -n "$keyauthorization" > "$wellknown_path/$token"
1118
44df2967 1119 webroot_owner=$(_stat $Le_Webroot)
4c3b3608 1120 _debug "Changing owner/group of .well-known to $webroot_owner"
1121 chown -R $webroot_owner "$Le_Webroot/.well-known"
1122
1123 fi
1124 fi
1125
1126 _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
1127
1128 if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
c60883ef 1129 _err "$d:Challenge error: $response"
4c3b3608 1130 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1131 _clearup
1132 return 1
1133 fi
1134
1135 while [ "1" ] ; do
1136 _debug "sleep 5 secs to verify"
1137 sleep 5
1138 _debug "checking"
c60883ef 1139 response="$(_get $uri)"
1140 if [ "$?" != "0" ] ; then
1141 _err "$d:Verify error:$response"
4c3b3608 1142 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1143 _clearup
1144 return 1
1145 fi
1146
1147 status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | tr -d '"')
1148 if [ "$status" == "valid" ] ; then
1149 _info "Success"
1150 _stopserver $serverproc
1151 serverproc=""
1152 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1153 break;
1154 fi
1155
1156 if [ "$status" == "invalid" ] ; then
1157 error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
1158 _err "$d:Verify error:$error"
1159 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1160 _clearup
1161 return 1;
1162 fi
1163
1164 if [ "$status" == "pending" ] ; then
1165 _info "Pending"
1166 else
1167 _err "$d:Verify error:$response"
1168 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1169 _clearup
1170 return 1
1171 fi
1172
1173 done
1174
1175 done
1176
1177 _clearup
1178 _info "Verify finished, start to sign."
88fab7d6 1179 der="$(_getfile "$CSR_PATH" "$BEGIN_CSR" "$END_CSR" | tr -d "\r\n" | _urlencode)"
4c3b3608 1180 _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
1181
1182
bbbdcb09 1183 Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
4c3b3608 1184 _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
1185
1186 if [ "$Le_LinkCert" ] ; then
88fab7d6 1187 echo "$BEGIN_CERT" > "$CERT_PATH"
c60883ef 1188 _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
88fab7d6 1189 echo "$END_CERT" >> "$CERT_PATH"
4c3b3608 1190 _info "Cert success."
1191 cat "$CERT_PATH"
1192
1193 _info "Your cert is in $CERT_PATH"
caf1fc10 1194 cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
4c3b3608 1195 fi
1196
1197
1198 if [ -z "$Le_LinkCert" ] ; then
88fab7d6 1199 response="$(echo $response | _dbase64 "multiline" )"
4c3b3608 1200 _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
1201 return 1
1202 fi
1203
1204 _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
1205
bbbdcb09 1206 Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
4c3b3608 1207 _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
1208
1209 if [ "$Le_LinkIssuer" ] ; then
88fab7d6 1210 echo "$BEGIN_CERT" > "$CA_CERT_PATH"
c60883ef 1211 _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
88fab7d6 1212 echo "$END_CERT" >> "$CA_CERT_PATH"
4c3b3608 1213 _info "The intermediate CA cert is in $CA_CERT_PATH"
caf1fc10 1214 cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
1215 _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
4c3b3608 1216 fi
1217
1218 Le_CertCreateTime=$(date -u "+%s")
1219 _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
1220
1221 Le_CertCreateTimeStr=$(date -u )
1222 _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
1223
1224 if [ ! "$Le_RenewalDays" ] ; then
1225 Le_RenewalDays=80
1226 fi
1227
1228 _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
1229
1230 let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
1231 _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
1232
1233 Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
1234 _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
1235
1236
1237 installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
1238
1239}
1240
1241renew() {
1242 Le_Domain="$1"
1243 if [ -z "$Le_Domain" ] ; then
1244 _err "Usage: $0 domain.com"
1245 return 1
1246 fi
1247
1248 _initpath $Le_Domain
1249
1250 if [ ! -f "$DOMAIN_CONF" ] ; then
1251 _info "$Le_Domain is not a issued domain, skip."
1252 return 0;
1253 fi
1254
1255 source "$DOMAIN_CONF"
1256 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
1257 _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
1258 return 2
1259 fi
1260
1261 IS_RENEW="1"
1262 issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
1263 local res=$?
1264 IS_RENEW=""
1265
1266 return $res
1267}
1268
1269renewAll() {
1270 _initpath
1271 _info "renewAll"
1272
bb4db3e9 1273 for d in $(ls -F ${LE_WORKING_DIR}/ | grep [^.].*[.].*/$ ) ; do
4c3b3608 1274 d=$(echo $d | cut -d '/' -f 1)
1275 _info "renew $d"
1276
1277 Le_LinkCert=""
1278 Le_Domain=""
1279 Le_Alt=""
1280 Le_Webroot=""
1281 Le_Keylength=""
1282 Le_LinkIssuer=""
1283
1284 Le_CertCreateTime=""
1285 Le_CertCreateTimeStr=""
1286 Le_RenewalDays=""
1287 Le_NextRenewTime=""
1288 Le_NextRenewTimeStr=""
1289
1290 Le_RealCertPath=""
1291 Le_RealKeyPath=""
1292
1293 Le_RealCACertPath=""
1294
1295 Le_ReloadCmd=""
1296
1297 DOMAIN_PATH=""
1298 DOMAIN_CONF=""
1299 DOMAIN_SSL_CONF=""
1300 CSR_PATH=""
1301 CERT_KEY_PATH=""
1302 CERT_PATH=""
1303 CA_CERT_PATH=""
caf1fc10 1304 CERT_FULLCHAIN_PATH=""
4c3b3608 1305 ACCOUNT_KEY_PATH=""
1306
1307 wellknown_path=""
1308
1309 renew "$d"
1310 done
1311
1312}
1313
1314installcert() {
1315 Le_Domain="$1"
1316 if [ -z "$Le_Domain" ] ; then
1317 _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
1318 return 1
1319 fi
1320
1321 Le_RealCertPath="$2"
1322 Le_RealKeyPath="$3"
1323 Le_RealCACertPath="$4"
1324 Le_ReloadCmd="$5"
1325
1326 _initpath $Le_Domain
1327
1328 _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
1329 _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
1330 _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
1331 _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
1332
1333 if [ "$Le_RealCertPath" ] ; then
1334 if [ -f "$Le_RealCertPath" ] ; then
1335 cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
1336 fi
1337 cat "$CERT_PATH" > "$Le_RealCertPath"
1338 fi
1339
1340 if [ "$Le_RealCACertPath" ] ; then
1341 if [ -f "$Le_RealCACertPath" ] ; then
1342 cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
1343 fi
1344 if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
1345 echo "" >> "$Le_RealCACertPath"
1346 cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
1347 else
1348 cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
1349 fi
1350 fi
1351
1352
1353 if [ "$Le_RealKeyPath" ] ; then
1354 if [ -f "$Le_RealKeyPath" ] ; then
1355 cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
1356 fi
1357 cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
1358 fi
1359
1360 if [ "$Le_ReloadCmd" ] ; then
1361 _info "Run Le_ReloadCmd: $Le_ReloadCmd"
1362 (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
1363 fi
1364
1365}
1366
1367installcronjob() {
1368 _initpath
1369 _info "Installing cron job"
1370 if ! crontab -l | grep 'le.sh cron' ; then
1371 if [ -f "$LE_WORKING_DIR/le.sh" ] ; then
1372 lesh="\"$LE_WORKING_DIR\"/le.sh"
1373 else
1374 _err "Can not install cronjob, le.sh not found."
1375 return 1
1376 fi
1377 crontab -l | { cat; echo "0 0 * * * LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
1378 fi
1379 if [ "$?" != "0" ] ; then
1380 _err "Install cron job failed. You need to manually renew your certs."
1381 _err "Or you can add cronjob by yourself:"
1382 _err "LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"
1383 return 1
1384 fi
1385}
1386
1387uninstallcronjob() {
1388 _info "Removing cron job"
1389 cr="$(crontab -l | grep 'le.sh cron')"
1390 if [ "$cr" ] ; then
1391 crontab -l | sed "/le.sh cron/d" | crontab -
1392 LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 6 | cut -d '=' -f 2 | tr -d '"')"
1393 _info LE_WORKING_DIR "$LE_WORKING_DIR"
1394 fi
1395 _initpath
1396
1397}
1398
1399
1400# Detect profile file if not specified as environment variable
1401_detect_profile() {
1402 if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
1403 echo "$PROFILE"
1404 return
1405 fi
1406
1407 local DETECTED_PROFILE
1408 DETECTED_PROFILE=''
1409 local SHELLTYPE
1410 SHELLTYPE="$(basename "/$SHELL")"
1411
1412 if [ "$SHELLTYPE" = "bash" ]; then
1413 if [ -f "$HOME/.bashrc" ]; then
1414 DETECTED_PROFILE="$HOME/.bashrc"
1415 elif [ -f "$HOME/.bash_profile" ]; then
1416 DETECTED_PROFILE="$HOME/.bash_profile"
1417 fi
1418 elif [ "$SHELLTYPE" = "zsh" ]; then
1419 DETECTED_PROFILE="$HOME/.zshrc"
1420 fi
1421
1422 if [ -z "$DETECTED_PROFILE" ]; then
1423 if [ -f "$HOME/.profile" ]; then
1424 DETECTED_PROFILE="$HOME/.profile"
1425 elif [ -f "$HOME/.bashrc" ]; then
1426 DETECTED_PROFILE="$HOME/.bashrc"
1427 elif [ -f "$HOME/.bash_profile" ]; then
1428 DETECTED_PROFILE="$HOME/.bash_profile"
1429 elif [ -f "$HOME/.zshrc" ]; then
1430 DETECTED_PROFILE="$HOME/.zshrc"
1431 fi
1432 fi
1433
1434 if [ ! -z "$DETECTED_PROFILE" ]; then
1435 echo "$DETECTED_PROFILE"
1436 fi
1437}
1438
1439_initconf() {
1440 _initpath
1441 if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
1442 echo "#Account configurations:
1443#Here are the supported macros, uncomment them to make them take effect.
1444#ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
5fd3f21b 1445#ACCOUNT_KEY_PATH=\"/path/to/account.key\"
4c3b3608 1446
1447#STAGE=1 # Use the staging api
1448#FORCE=1 # Force to issue cert
1449#DEBUG=1 # Debug mode
1450
166096dc 1451#ACCOUNT_KEY_HASH=account key hash
1452
bbbdcb09 1453USER_AGENT=\"le.sh client: $PROJECT\"
4c3b3608 1454#dns api
1455#######################
1456#Cloudflare:
1457#api key
3d49985a 1458#CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
4c3b3608 1459#account email
3d49985a 1460#CF_Email=\"xxxx@sss.com\"
4c3b3608 1461
1462#######################
1463#Dnspod.cn:
1464#api key id
3d49985a 1465#DP_Id=\"1234\"
4c3b3608 1466#api key
3d49985a 1467#DP_Key=\"sADDsdasdgdsf\"
4c3b3608 1468
1469#######################
1470#Cloudxns.com:
3d49985a 1471#CX_Key=\"1234\"
4c3b3608 1472#
3d49985a 1473#CX_Secret=\"sADDsdasdgdsf\"
4c3b3608 1474
1475 " > $ACCOUNT_CONF_PATH
1476 fi
1477}
1478
c60883ef 1479_precheck() {
1480 if ! _exists "curl" && ! _exists "wget"; then
1481 _err "Please install curl or wget first, we need to access http resources."
4c3b3608 1482 return 1
1483 fi
1484
c60883ef 1485 if ! _exists "crontab" ; then
1486 _err "Please install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
1487 _err "We need to set cron job to renew the certs automatically."
1488 return 1
4c3b3608 1489 fi
1490
c60883ef 1491 if ! _exists "openssl" ; then
1492 _err "Please install openssl first."
1493 _err "We need openssl to generate keys."
4c3b3608 1494 return 1
1495 fi
1496
c60883ef 1497 if ! _exists "nc" ; then
1498 _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
1499 _err "We use nc for standalone server if you use standalone mode."
1500 _err "If you don't use standalone mode, just ignore this warning."
1501 fi
1502
1503 return 0
1504}
1505
1506install() {
1507 if ! _initpath ; then
1508 _err "Install failed."
4c3b3608 1509 return 1
1510 fi
1511
c60883ef 1512 if ! _precheck ; then
1513 _err "Pre-check failed, can not install."
4c3b3608 1514 return 1
1515 fi
c60883ef 1516
4c3b3608 1517 _info "Installing to $LE_WORKING_DIR"
1518
1519 cp le.sh "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/le.sh"
1520
1521 if [ "$?" != "0" ] ; then
1522 _err "Install failed, can not copy le.sh"
1523 return 1
1524 fi
1525
1526 _info "Installed to $LE_WORKING_DIR/le.sh"
1527
1528 _profile="$(_detect_profile)"
1529 if [ "$_profile" ] ; then
1530 _debug "Found profile: $_profile"
1531
1532 echo "LE_WORKING_DIR=$LE_WORKING_DIR
1533alias le=\"$LE_WORKING_DIR/le.sh\"
1534alias le.sh=\"$LE_WORKING_DIR/le.sh\"
1535 " > "$LE_WORKING_DIR/le.env"
b86869a0 1536 echo "" >> "$_profile"
4c3b3608 1537 _setopt "$_profile" "source \"$LE_WORKING_DIR/le.env\""
1538 _info "OK, Close and reopen your terminal to start using le"
1539 else
1540 _info "No profile is found, you will need to go into $LE_WORKING_DIR to use le.sh"
1541 fi
1542
1543 mkdir -p $LE_WORKING_DIR/dnsapi
1544 cp dnsapi/* $LE_WORKING_DIR/dnsapi/
1545
1546 #to keep compatible mv the .acc file to .key file
1547 if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
1548 mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
1549 fi
1550
1551 installcronjob
1552
1553 if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
1554 _initconf
1555 fi
1556 _info OK
1557}
1558
1559uninstall() {
1560 uninstallcronjob
1561 _initpath
1562
1563 _profile="$(_detect_profile)"
1564 if [ "$_profile" ] ; then
7203a1c1 1565 text="$(cat $_profile)"
1566 echo "$text" | sed "s|^source.*le.env.*$||" > "$_profile"
4c3b3608 1567 fi
1568
1569 rm -f $LE_WORKING_DIR/le.sh
1570 _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
1571
1572}
1573
1574cron() {
1575 renewAll
1576}
1577
1578version() {
1579 _info "$PROJECT"
1580 _info "v$VER"
1581}
1582
1583showhelp() {
1584 version
1585 echo "Usage: le.sh [command] ...[args]....
1586Avalible commands:
1587
1588install:
1589 Install le.sh to your system.
1590issue:
1591 Issue a cert.
1592installcert:
1593 Install the issued cert to apache/nginx or any other server.
1594renew:
1595 Renew a cert.
1596renewAll:
1597 Renew all the certs.
1598uninstall:
1599 Uninstall le.sh, and uninstall the cron job.
1600version:
1601 Show version info.
1602installcronjob:
1603 Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
1604uninstallcronjob:
1605 Uninstall the cron job. The 'uninstall' command can do this automatically.
1606createAccountKey:
1607 Create an account private key, professional use.
1608createDomainKey:
1609 Create an domain private key, professional use.
1610createCSR:
1611 Create CSR , professional use.
1612 "
1613}
1614
1615
1616if [ -z "$1" ] ; then
1617 showhelp
1618else
1619 "$@"
1620fi