]> git.proxmox.com Git - mirror_acme.sh.git/blame - le.sh
Merge branch 'master' of https://github.com/Neilpang/le
[mirror_acme.sh.git] / le.sh
CommitLineData
4c3b3608 1#!/usr/bin/env bash
c09dc68b 2VER=1.2.1
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
14165e5a 197 if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
edf08da6 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"
6d60f288 604 elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
605 _NC="nc -N -l"
f76eb452 606 else
607 _NC="nc -l"
608 fi
4c3b3608 609 fi
1b2e940d 610
f76eb452 611 _debug "_NC" "$_NC"
4c3b3608 612# while true ; do
613 if [ "$DEBUG" ] ; then
3aff11f6 614 if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
615 echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
616 fi
4c3b3608 617 else
bac3b6b0 618 if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
619 echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
3aff11f6 620 fi
4c3b3608 621 fi
051c706d 622 if [ "$?" != "0" ] ; then
623 _err "nc listen error."
624 return 1
625 fi
4c3b3608 626# done
627}
628
629_stopserver() {
630 pid="$1"
631
632}
633
634_initpath() {
635
636 if [ -z "$LE_WORKING_DIR" ]; then
637 LE_WORKING_DIR=$HOME/.le
638 fi
639
640 if [ -z "$ACCOUNT_CONF_PATH" ] ; then
641 ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
642 fi
643
644 if [ -f "$ACCOUNT_CONF_PATH" ] ; then
645 source "$ACCOUNT_CONF_PATH"
646 fi
647
648 if [ -z "$API" ] ; then
649 if [ -z "$STAGE" ] ; then
650 API="$DEFAULT_CA"
651 else
652 API="$STAGE_CA"
653 _info "Using stage api:$API"
654 fi
655 fi
656
657 if [ -z "$ACME_DIR" ] ; then
658 ACME_DIR="/home/.acme"
659 fi
660
661 if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
662 APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR/"
663 fi
664
bbbdcb09 665 if [ -z "$USER_AGENT" ] ; then
666 USER_AGENT="$DEFAULT_USER_AGENT"
667 fi
668
669 HTTP_HEADER="$LE_WORKING_DIR/http.header"
670
671 WGET="wget -q"
672 if [ "$DEBUG" ] ; then
673 WGET="$WGET -d "
674 fi
675
676 dp="$LE_WORKING_DIR/curl.dump"
4a0f23e2 677 CURL="curl -L --silent"
bbbdcb09 678 if [ "$DEBUG" ] ; then
4a0f23e2 679 CURL="$CURL -L --trace-ascii $dp "
bbbdcb09 680 fi
681
4c3b3608 682 domain="$1"
4c3b3608 683
684 if [ -z "$ACCOUNT_KEY_PATH" ] ; then
685 ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
686 fi
687
688 if [ -z "$domain" ] ; then
689 return 0
690 fi
691
692 domainhome="$LE_WORKING_DIR/$domain"
693 mkdir -p "$domainhome"
694
695 if [ -z "$DOMAIN_PATH" ] ; then
696 DOMAIN_PATH="$domainhome"
697 fi
698 if [ -z "$DOMAIN_CONF" ] ; then
1ad65f7d 699 DOMAIN_CONF="$domainhome/$domain.conf"
4c3b3608 700 fi
701
702 if [ -z "$DOMAIN_SSL_CONF" ] ; then
1ad65f7d 703 DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
4c3b3608 704 fi
705
706 if [ -z "$CSR_PATH" ] ; then
707 CSR_PATH="$domainhome/$domain.csr"
708 fi
709 if [ -z "$CERT_KEY_PATH" ] ; then
710 CERT_KEY_PATH="$domainhome/$domain.key"
711 fi
712 if [ -z "$CERT_PATH" ] ; then
713 CERT_PATH="$domainhome/$domain.cer"
714 fi
715 if [ -z "$CA_CERT_PATH" ] ; then
716 CA_CERT_PATH="$domainhome/ca.cer"
717 fi
caf1fc10 718 if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
850db6d4 719 CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
caf1fc10 720 fi
4c3b3608 721
722}
723
724
725_apachePath() {
726 httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
727 httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
728 httpdconf="$httpdroot/$httpdconfname"
729 if [ ! -f $httpdconf ] ; then
730 _err "Apache Config file not found" $httpdconf
731 return 1
732 fi
733 return 0
734}
735
736_restoreApache() {
737 if [ -z "$usingApache" ] ; then
738 return 0
739 fi
740 _initpath
741 if ! _apachePath ; then
742 return 1
743 fi
744
745 if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
746 _debug "No config file to restore."
747 return 0
748 fi
749
750 cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
751 if ! apachectl -t ; then
752 _err "Sorry, restore apache config error, please contact me."
753 return 1;
754 fi
755 rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
756 return 0
757}
758
759_setApache() {
760 _initpath
761 if ! _apachePath ; then
762 return 1
763 fi
764
765 #backup the conf
766 _debug "Backup apache config file" $httpdconf
767 cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
768 _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
769 _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
770 _info "The backup file will be deleted on sucess, just forget it."
771
772 #add alias
773 echo "
774Alias /.well-known/acme-challenge $ACME_DIR
775
776<Directory $ACME_DIR >
777Require all granted
778</Directory>
779 " >> $httpdconf
780
781 if ! apachectl -t ; then
782 _err "Sorry, apache config error, please contact me."
783 _restoreApache
784 return 1;
785 fi
786
787 if [ ! -d "$ACME_DIR" ] ; then
788 mkdir -p "$ACME_DIR"
789 chmod 755 "$ACME_DIR"
790 fi
791
792 if ! apachectl graceful ; then
793 _err "Sorry, apachectl graceful error, please contact me."
794 _restoreApache
795 return 1;
796 fi
797 usingApache="1"
798 return 0
799}
800
801_clearup () {
802 _stopserver $serverproc
803 serverproc=""
804 _restoreApache
805}
806
807# webroot removelevel tokenfile
808_clearupwebbroot() {
809 __webroot="$1"
810 if [ -z "$__webroot" ] ; then
811 _debug "no webroot specified, skip"
812 return 0
813 fi
814
815 if [ "$2" == '1' ] ; then
816 _debug "remove $__webroot/.well-known"
817 rm -rf "$__webroot/.well-known"
818 elif [ "$2" == '2' ] ; then
819 _debug "remove $__webroot/.well-known/acme-challenge"
820 rm -rf "$__webroot/.well-known/acme-challenge"
821 elif [ "$2" == '3' ] ; then
822 _debug "remove $__webroot/.well-known/acme-challenge/$3"
823 rm -rf "$__webroot/.well-known/acme-challenge/$3"
824 else
825 _info "Skip for removelevel:$2"
826 fi
827
828 return 0
829
830}
831
832issue() {
833 if [ -z "$2" ] ; then
834 _err "Usage: le issue webroot|no|apache|dns a.com [www.a.com,b.com,c.com]|no [key-length]|no"
835 return 1
836 fi
837 Le_Webroot="$1"
838 Le_Domain="$2"
839 Le_Alt="$3"
840 Le_Keylength="$4"
841 Le_RealCertPath="$5"
842 Le_RealKeyPath="$6"
843 Le_RealCACertPath="$7"
844 Le_ReloadCmd="$8"
845
846
847 _initpath $Le_Domain
848
849 if [ -f "$DOMAIN_CONF" ] ; then
850 Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
851 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
852 _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
853 return 2
854 fi
855 fi
856
857 if [ "$Le_Alt" == "no" ] ; then
858 Le_Alt=""
859 fi
860 if [ "$Le_Keylength" == "no" ] ; then
861 Le_Keylength=""
862 fi
863 if [ "$Le_RealCertPath" == "no" ] ; then
864 Le_RealCertPath=""
865 fi
866 if [ "$Le_RealKeyPath" == "no" ] ; then
867 Le_RealKeyPath=""
868 fi
869 if [ "$Le_RealCACertPath" == "no" ] ; then
870 Le_RealCACertPath=""
871 fi
872 if [ "$Le_ReloadCmd" == "no" ] ; then
873 Le_ReloadCmd=""
874 fi
875
876 _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
877 _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
878 _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
879 _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
880 _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
881 _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
882 _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
883 _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
884
885 if [ "$Le_Webroot" == "no" ] ; then
886 _info "Standalone mode."
887 if ! command -v "nc" > /dev/null ; then
888 _err "Please install netcat(nc) tools first."
889 return 1
890 fi
891
892 if [ -z "$Le_HTTPPort" ] ; then
893 Le_HTTPPort=80
894 fi
895 _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
896
251fc37c 897 netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
4c3b3608 898 if [ "$netprc" ] ; then
899 _err "$netprc"
900 _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
901 _err "Please stop it first"
902 return 1
903 fi
904 fi
905
906 if [ "$Le_Webroot" == "apache" ] ; then
907 if ! _setApache ; then
908 _err "set up apache error. Report error to me."
909 return 1
910 fi
911 wellknown_path="$ACME_DIR"
912 else
913 usingApache=""
914 fi
915
916 createAccountKey $Le_Domain $Le_Keylength
166096dc 917
918 if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
919 return 1
920 fi
921
922 accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
88fab7d6 923 thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
4c3b3608 924
88fab7d6 925 accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
166096dc 926
927 if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
928 _info "Registering account"
929 regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
930 if [ "$ACCOUNT_EMAIL" ] ; then
931 regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
932 fi
933 _send_signed_request "$API/acme/new-reg" "$regjson"
934
935 if [ "$code" == "" ] || [ "$code" == '201' ] ; then
936 _info "Registered"
937 echo $response > $LE_WORKING_DIR/account.json
938 elif [ "$code" == '409' ] ; then
939 _info "Already registered"
940 else
941 _err "Register account Error: $response"
942 _clearup
943 return 1
944 fi
945 ACCOUNT_KEY_HASH="$accountkeyhash"
946 _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
947 else
948 _info "Skip register account key"
949 fi
950
4c3b3608 951 if ! createDomainKey $Le_Domain $Le_Keylength ; then
952 _err "Create domain key error."
953 return 1
954 fi
955
956 if ! createCSR $Le_Domain $Le_Alt ; then
957 _err "Create CSR error."
958 return 1
959 fi
4c3b3608 960
961 vtype="$VTYPE_HTTP"
962 if [[ "$Le_Webroot" == "dns"* ]] ; then
963 vtype="$VTYPE_DNS"
964 fi
965
966 vlist="$Le_Vlist"
967 # verify each domain
968 _info "Verify each domain"
969 sep='#'
970 if [ -z "$vlist" ] ; then
971 alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
972 for d in $alldomains
973 do
974 _info "Getting token for domain" $d
975 _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
976 if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
977 _err "new-authz error: $response"
978 _clearup
979 return 1
980 fi
981
348cddd7 982 entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
4c3b3608 983 _debug entry "$entry"
984
985 token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
986 _debug token $token
987
988 uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
989 _debug uri $uri
990
991 keyauthorization="$token.$thumbprint"
992 _debug keyauthorization "$keyauthorization"
993
994 dvlist="$d$sep$keyauthorization$sep$uri"
995 _debug dvlist "$dvlist"
996
997 vlist="$vlist$dvlist,"
998
999 done
1000
1001 #add entry
1002 dnsadded=""
1003 ventries=$(echo "$vlist" | tr ',' ' ' )
1004 for ventry in $ventries
1005 do
1006 d=$(echo $ventry | cut -d $sep -f 1)
1007 keyauthorization=$(echo $ventry | cut -d $sep -f 2)
1008
1009 if [ "$vtype" == "$VTYPE_DNS" ] ; then
1010 dnsadded='0'
1011 txtdomain="_acme-challenge.$d"
1012 _debug txtdomain "$txtdomain"
88fab7d6 1013 txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
4c3b3608 1014 _debug txt "$txt"
1015 #dns
1016 #1. check use api
1017 d_api=""
1018 if [ -f "$LE_WORKING_DIR/$d/$Le_Webroot" ] ; then
1019 d_api="$LE_WORKING_DIR/$d/$Le_Webroot"
1020 elif [ -f "$LE_WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
1021 d_api="$LE_WORKING_DIR/$d/$Le_Webroot.sh"
1022 elif [ -f "$LE_WORKING_DIR/$Le_Webroot" ] ; then
1023 d_api="$LE_WORKING_DIR/$Le_Webroot"
1024 elif [ -f "$LE_WORKING_DIR/$Le_Webroot.sh" ] ; then
1025 d_api="$LE_WORKING_DIR/$Le_Webroot.sh"
1026 elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
1027 d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot"
1028 elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
1029 d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh"
1030 fi
1031 _debug d_api "$d_api"
1032
1033 if [ "$d_api" ]; then
1034 _info "Found domain api file: $d_api"
1035 else
1036 _err "Add the following TXT record:"
1037 _err "Domain: $txtdomain"
1038 _err "TXT value: $txt"
1039 _err "Please be aware that you prepend _acme-challenge. before your domain"
1040 _err "so the resulting subdomain will be: $txtdomain"
1041 continue
1042 fi
1043
1044 if ! source $d_api ; then
1045 _err "Load file $d_api error. Please check your api file and try again."
1046 return 1
1047 fi
1048
1049 addcommand="$Le_Webroot-add"
1050 if ! command -v $addcommand ; then
f8ad8f34 1051 _err "It seems that your api file is not correct, it must have a function named: $addcommand"
4c3b3608 1052 return 1
1053 fi
1054
1055 if ! $addcommand $txtdomain $txt ; then
1056 _err "Error add txt for domain:$txtdomain"
1057 return 1
1058 fi
1059 dnsadded='1'
1060 fi
1061 done
1062
1063 if [ "$dnsadded" == '0' ] ; then
1064 _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
1065 _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
1066 _err "Please add the TXT records to the domains, and retry again."
1067 return 1
1068 fi
1069
1070 fi
1071
1072 if [ "$dnsadded" == '1' ] ; then
1073 _info "Sleep 60 seconds for the txt records to take effect"
1074 sleep 60
1075 fi
1076
1077 _debug "ok, let's start to verify"
1078 ventries=$(echo "$vlist" | tr ',' ' ' )
1079 for ventry in $ventries
1080 do
1081 d=$(echo $ventry | cut -d $sep -f 1)
1082 keyauthorization=$(echo $ventry | cut -d $sep -f 2)
1083 uri=$(echo $ventry | cut -d $sep -f 3)
1084 _info "Verifying:$d"
1085 _debug "d" "$d"
1086 _debug "keyauthorization" "$keyauthorization"
1087 _debug "uri" "$uri"
1088 removelevel=""
1089 token=""
1090 if [ "$vtype" == "$VTYPE_HTTP" ] ; then
1091 if [ "$Le_Webroot" == "no" ] ; then
1092 _info "Standalone mode server"
1093 _startserver "$keyauthorization" &
1094 serverproc="$!"
1095 sleep 2
1096 _debug serverproc $serverproc
1097 else
1098 if [ -z "$wellknown_path" ] ; then
1099 wellknown_path="$Le_Webroot/.well-known/acme-challenge"
1100 fi
1101 _debug wellknown_path "$wellknown_path"
1102
1103 if [ ! -d "$Le_Webroot/.well-known" ] ; then
1104 removelevel='1'
1105 elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
1106 removelevel='2'
1107 else
1108 removelevel='3'
1109 fi
1110
1111 token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
1112 _debug "writing token:$token to $wellknown_path/$token"
1113
1114 mkdir -p "$wellknown_path"
1115 echo -n "$keyauthorization" > "$wellknown_path/$token"
1116
44df2967 1117 webroot_owner=$(_stat $Le_Webroot)
4c3b3608 1118 _debug "Changing owner/group of .well-known to $webroot_owner"
1119 chown -R $webroot_owner "$Le_Webroot/.well-known"
1120
1121 fi
1122 fi
1123
1124 _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
1125
1126 if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
c60883ef 1127 _err "$d:Challenge error: $response"
4c3b3608 1128 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1129 _clearup
1130 return 1
1131 fi
1132
1133 while [ "1" ] ; do
1134 _debug "sleep 5 secs to verify"
1135 sleep 5
1136 _debug "checking"
c60883ef 1137 response="$(_get $uri)"
1138 if [ "$?" != "0" ] ; then
1139 _err "$d:Verify error:$response"
4c3b3608 1140 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1141 _clearup
1142 return 1
1143 fi
1144
7d91e35f 1145 status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
4c3b3608 1146 if [ "$status" == "valid" ] ; then
1147 _info "Success"
1148 _stopserver $serverproc
1149 serverproc=""
1150 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1151 break;
1152 fi
1153
1154 if [ "$status" == "invalid" ] ; then
1155 error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
1156 _err "$d:Verify error:$error"
1157 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1158 _clearup
1159 return 1;
1160 fi
1161
1162 if [ "$status" == "pending" ] ; then
1163 _info "Pending"
1164 else
1165 _err "$d:Verify error:$response"
1166 _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
1167 _clearup
1168 return 1
1169 fi
1170
1171 done
1172
1173 done
1174
1175 _clearup
1176 _info "Verify finished, start to sign."
fa8311dc 1177 der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
4c3b3608 1178 _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
1179
1180
bbbdcb09 1181 Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
4c3b3608 1182 _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
1183
1184 if [ "$Le_LinkCert" ] ; then
88fab7d6 1185 echo "$BEGIN_CERT" > "$CERT_PATH"
c60883ef 1186 _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
88fab7d6 1187 echo "$END_CERT" >> "$CERT_PATH"
4c3b3608 1188 _info "Cert success."
1189 cat "$CERT_PATH"
1190
1191 _info "Your cert is in $CERT_PATH"
caf1fc10 1192 cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
4c3b3608 1193 fi
1194
1195
1196 if [ -z "$Le_LinkCert" ] ; then
88fab7d6 1197 response="$(echo $response | _dbase64 "multiline" )"
4c3b3608 1198 _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
1199 return 1
1200 fi
1201
1202 _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
1203
bbbdcb09 1204 Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
4c3b3608 1205 _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
1206
1207 if [ "$Le_LinkIssuer" ] ; then
88fab7d6 1208 echo "$BEGIN_CERT" > "$CA_CERT_PATH"
c60883ef 1209 _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
88fab7d6 1210 echo "$END_CERT" >> "$CA_CERT_PATH"
4c3b3608 1211 _info "The intermediate CA cert is in $CA_CERT_PATH"
caf1fc10 1212 cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
1213 _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
4c3b3608 1214 fi
1215
1216 Le_CertCreateTime=$(date -u "+%s")
1217 _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
1218
1219 Le_CertCreateTimeStr=$(date -u )
1220 _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
1221
1222 if [ ! "$Le_RenewalDays" ] ; then
1223 Le_RenewalDays=80
1224 fi
1225
1226 _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
1227
1228 let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
1229 _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
1230
1231 Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
1232 _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
1233
1234
1235 installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
1236
1237}
1238
1239renew() {
1240 Le_Domain="$1"
1241 if [ -z "$Le_Domain" ] ; then
1242 _err "Usage: $0 domain.com"
1243 return 1
1244 fi
1245
1246 _initpath $Le_Domain
1247
1248 if [ ! -f "$DOMAIN_CONF" ] ; then
1249 _info "$Le_Domain is not a issued domain, skip."
1250 return 0;
1251 fi
1252
1253 source "$DOMAIN_CONF"
1254 if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
1255 _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
1256 return 2
1257 fi
1258
1259 IS_RENEW="1"
1260 issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
1261 local res=$?
1262 IS_RENEW=""
1263
1264 return $res
1265}
1266
1267renewAll() {
1268 _initpath
1269 _info "renewAll"
1270
bb4db3e9 1271 for d in $(ls -F ${LE_WORKING_DIR}/ | grep [^.].*[.].*/$ ) ; do
4c3b3608 1272 d=$(echo $d | cut -d '/' -f 1)
1273 _info "renew $d"
1274
1275 Le_LinkCert=""
1276 Le_Domain=""
1277 Le_Alt=""
1278 Le_Webroot=""
1279 Le_Keylength=""
1280 Le_LinkIssuer=""
1281
1282 Le_CertCreateTime=""
1283 Le_CertCreateTimeStr=""
1284 Le_RenewalDays=""
1285 Le_NextRenewTime=""
1286 Le_NextRenewTimeStr=""
1287
1288 Le_RealCertPath=""
1289 Le_RealKeyPath=""
1290
1291 Le_RealCACertPath=""
1292
1293 Le_ReloadCmd=""
1294
1295 DOMAIN_PATH=""
1296 DOMAIN_CONF=""
1297 DOMAIN_SSL_CONF=""
1298 CSR_PATH=""
1299 CERT_KEY_PATH=""
1300 CERT_PATH=""
1301 CA_CERT_PATH=""
caf1fc10 1302 CERT_FULLCHAIN_PATH=""
4c3b3608 1303 ACCOUNT_KEY_PATH=""
1304
1305 wellknown_path=""
1306
1307 renew "$d"
1308 done
1309
1310}
1311
1312installcert() {
1313 Le_Domain="$1"
1314 if [ -z "$Le_Domain" ] ; then
1315 _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
1316 return 1
1317 fi
1318
1319 Le_RealCertPath="$2"
1320 Le_RealKeyPath="$3"
1321 Le_RealCACertPath="$4"
1322 Le_ReloadCmd="$5"
1323
1324 _initpath $Le_Domain
1325
1326 _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
1327 _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
1328 _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
1329 _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
1330
1331 if [ "$Le_RealCertPath" ] ; then
1332 if [ -f "$Le_RealCertPath" ] ; then
1333 cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
1334 fi
1335 cat "$CERT_PATH" > "$Le_RealCertPath"
1336 fi
1337
1338 if [ "$Le_RealCACertPath" ] ; then
1339 if [ -f "$Le_RealCACertPath" ] ; then
1340 cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
1341 fi
1342 if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
1343 echo "" >> "$Le_RealCACertPath"
1344 cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
1345 else
1346 cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
1347 fi
1348 fi
1349
1350
1351 if [ "$Le_RealKeyPath" ] ; then
1352 if [ -f "$Le_RealKeyPath" ] ; then
1353 cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
1354 fi
1355 cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
1356 fi
1357
1358 if [ "$Le_ReloadCmd" ] ; then
1359 _info "Run Le_ReloadCmd: $Le_ReloadCmd"
1360 (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
1361 fi
1362
1363}
1364
1365installcronjob() {
1366 _initpath
77546ea5 1367 if ! _exists "crontab" ; then
1368 _err "crontab doesn't exist, so, we can not install cron jobs."
1369 _err "All your certs will not be renewed automatically."
1370 _err "You must add your own cron job to call 'le.sh cron' everyday."
1371 return 1
1372 fi
1373
4c3b3608 1374 _info "Installing cron job"
1375 if ! crontab -l | grep 'le.sh cron' ; then
1376 if [ -f "$LE_WORKING_DIR/le.sh" ] ; then
1377 lesh="\"$LE_WORKING_DIR\"/le.sh"
1378 else
1379 _err "Can not install cronjob, le.sh not found."
1380 return 1
1381 fi
1382 crontab -l | { cat; echo "0 0 * * * LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
1383 fi
1384 if [ "$?" != "0" ] ; then
1385 _err "Install cron job failed. You need to manually renew your certs."
1386 _err "Or you can add cronjob by yourself:"
1387 _err "LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"
1388 return 1
1389 fi
1390}
1391
1392uninstallcronjob() {
37db5b81 1393 if ! _exists "crontab" ; then
1394 return
1395 fi
4c3b3608 1396 _info "Removing cron job"
1397 cr="$(crontab -l | grep 'le.sh cron')"
1398 if [ "$cr" ] ; then
1399 crontab -l | sed "/le.sh cron/d" | crontab -
1400 LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 6 | cut -d '=' -f 2 | tr -d '"')"
1401 _info LE_WORKING_DIR "$LE_WORKING_DIR"
1402 fi
1403 _initpath
1404
1405}
1406
1407
1408# Detect profile file if not specified as environment variable
1409_detect_profile() {
1410 if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
1411 echo "$PROFILE"
1412 return
1413 fi
1414
1415 local DETECTED_PROFILE
1416 DETECTED_PROFILE=''
1417 local SHELLTYPE
1418 SHELLTYPE="$(basename "/$SHELL")"
1419
1420 if [ "$SHELLTYPE" = "bash" ]; then
1421 if [ -f "$HOME/.bashrc" ]; then
1422 DETECTED_PROFILE="$HOME/.bashrc"
1423 elif [ -f "$HOME/.bash_profile" ]; then
1424 DETECTED_PROFILE="$HOME/.bash_profile"
1425 fi
1426 elif [ "$SHELLTYPE" = "zsh" ]; then
1427 DETECTED_PROFILE="$HOME/.zshrc"
1428 fi
1429
1430 if [ -z "$DETECTED_PROFILE" ]; then
1431 if [ -f "$HOME/.profile" ]; then
1432 DETECTED_PROFILE="$HOME/.profile"
1433 elif [ -f "$HOME/.bashrc" ]; then
1434 DETECTED_PROFILE="$HOME/.bashrc"
1435 elif [ -f "$HOME/.bash_profile" ]; then
1436 DETECTED_PROFILE="$HOME/.bash_profile"
1437 elif [ -f "$HOME/.zshrc" ]; then
1438 DETECTED_PROFILE="$HOME/.zshrc"
1439 fi
1440 fi
1441
1442 if [ ! -z "$DETECTED_PROFILE" ]; then
1443 echo "$DETECTED_PROFILE"
1444 fi
1445}
1446
1447_initconf() {
1448 _initpath
1449 if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
1450 echo "#Account configurations:
1451#Here are the supported macros, uncomment them to make them take effect.
1452#ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
5fd3f21b 1453#ACCOUNT_KEY_PATH=\"/path/to/account.key\"
4c3b3608 1454
1455#STAGE=1 # Use the staging api
1456#FORCE=1 # Force to issue cert
1457#DEBUG=1 # Debug mode
1458
166096dc 1459#ACCOUNT_KEY_HASH=account key hash
1460
bbbdcb09 1461USER_AGENT=\"le.sh client: $PROJECT\"
4c3b3608 1462#dns api
1463#######################
1464#Cloudflare:
1465#api key
3d49985a 1466#CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
4c3b3608 1467#account email
3d49985a 1468#CF_Email=\"xxxx@sss.com\"
4c3b3608 1469
1470#######################
1471#Dnspod.cn:
1472#api key id
3d49985a 1473#DP_Id=\"1234\"
4c3b3608 1474#api key
3d49985a 1475#DP_Key=\"sADDsdasdgdsf\"
4c3b3608 1476
1477#######################
1478#Cloudxns.com:
3d49985a 1479#CX_Key=\"1234\"
4c3b3608 1480#
3d49985a 1481#CX_Secret=\"sADDsdasdgdsf\"
4c3b3608 1482
1483 " > $ACCOUNT_CONF_PATH
1484 fi
1485}
1486
c60883ef 1487_precheck() {
1488 if ! _exists "curl" && ! _exists "wget"; then
1489 _err "Please install curl or wget first, we need to access http resources."
4c3b3608 1490 return 1
1491 fi
1492
c60883ef 1493 if ! _exists "crontab" ; then
77546ea5 1494 _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
c60883ef 1495 _err "We need to set cron job to renew the certs automatically."
77546ea5 1496 _err "Otherwise, your certs will not be able to be renewed automatically."
1497 if [ -z "$FORCE" ] ; then
1498 _err "Please define 'FORCE=1' and try install again to go without crontab."
1499 _err "FORCE=1 ./le.sh install"
1500 return 1
1501 fi
4c3b3608 1502 fi
1503
c60883ef 1504 if ! _exists "openssl" ; then
1505 _err "Please install openssl first."
1506 _err "We need openssl to generate keys."
4c3b3608 1507 return 1
1508 fi
1509
c60883ef 1510 if ! _exists "nc" ; then
1511 _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
1512 _err "We use nc for standalone server if you use standalone mode."
1513 _err "If you don't use standalone mode, just ignore this warning."
1514 fi
1515
1516 return 0
1517}
1518
1519install() {
1520 if ! _initpath ; then
1521 _err "Install failed."
4c3b3608 1522 return 1
1523 fi
1524
c60883ef 1525 if ! _precheck ; then
1526 _err "Pre-check failed, can not install."
4c3b3608 1527 return 1
1528 fi
c60883ef 1529
4c3b3608 1530 _info "Installing to $LE_WORKING_DIR"
4a0f23e2 1531
1532 if ! mkdir -p "$LE_WORKING_DIR" ; then
1533 _err "Can not craete working dir: $LE_WORKING_DIR"
1534 return 1
1535 fi
1536
4c3b3608 1537 cp le.sh "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/le.sh"
1538
1539 if [ "$?" != "0" ] ; then
1540 _err "Install failed, can not copy le.sh"
1541 return 1
1542 fi
1543
1544 _info "Installed to $LE_WORKING_DIR/le.sh"
1545
1546 _profile="$(_detect_profile)"
1547 if [ "$_profile" ] ; then
1548 _debug "Found profile: $_profile"
1549
1550 echo "LE_WORKING_DIR=$LE_WORKING_DIR
1551alias le=\"$LE_WORKING_DIR/le.sh\"
1552alias le.sh=\"$LE_WORKING_DIR/le.sh\"
1553 " > "$LE_WORKING_DIR/le.env"
b86869a0 1554 echo "" >> "$_profile"
4c3b3608 1555 _setopt "$_profile" "source \"$LE_WORKING_DIR/le.env\""
1556 _info "OK, Close and reopen your terminal to start using le"
1557 else
1558 _info "No profile is found, you will need to go into $LE_WORKING_DIR to use le.sh"
1559 fi
1560
1561 mkdir -p $LE_WORKING_DIR/dnsapi
1562 cp dnsapi/* $LE_WORKING_DIR/dnsapi/
1563
1564 #to keep compatible mv the .acc file to .key file
1565 if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
1566 mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
1567 fi
1568
1569 installcronjob
1570
1571 if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
1572 _initconf
1573 fi
1574 _info OK
1575}
1576
1577uninstall() {
1578 uninstallcronjob
1579 _initpath
1580
1581 _profile="$(_detect_profile)"
1582 if [ "$_profile" ] ; then
7203a1c1 1583 text="$(cat $_profile)"
1584 echo "$text" | sed "s|^source.*le.env.*$||" > "$_profile"
4c3b3608 1585 fi
1586
1587 rm -f $LE_WORKING_DIR/le.sh
1588 _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
1589
1590}
1591
1592cron() {
1593 renewAll
1594}
1595
1596version() {
1597 _info "$PROJECT"
1598 _info "v$VER"
1599}
1600
1601showhelp() {
1602 version
1603 echo "Usage: le.sh [command] ...[args]....
1604Avalible commands:
1605
1606install:
1607 Install le.sh to your system.
1608issue:
1609 Issue a cert.
1610installcert:
1611 Install the issued cert to apache/nginx or any other server.
1612renew:
1613 Renew a cert.
1614renewAll:
1615 Renew all the certs.
1616uninstall:
1617 Uninstall le.sh, and uninstall the cron job.
1618version:
1619 Show version info.
1620installcronjob:
1621 Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
1622uninstallcronjob:
1623 Uninstall the cron job. The 'uninstall' command can do this automatically.
1624createAccountKey:
1625 Create an account private key, professional use.
1626createDomainKey:
1627 Create an domain private key, professional use.
1628createCSR:
1629 Create CSR , professional use.
1630 "
1631}
1632
4a0f23e2 1633_installOnline() {
1634 _info "Installing from online archive."
1635 if [ ! "$BRANCH" ] ; then
1636 BRANCH="master"
1637 fi
1638 _initpath
1639 target="$PROJECT/archive/$BRANCH.tar.gz"
1640 _info "Downloading $target"
1641 localname="$BRANCH.tar.gz"
1642 if ! _get "$target" > $localname ; then
1643 _debug "Download error."
1644 return 1
1645 fi
1646 _info "Extracting $localname"
1647 tar xzf $localname
1648 cd "le-$BRANCH"
1649 chmod +x le.sh
1650 if ./le.sh install ; then
1651 _info "Install success!"
1652 fi
1653
1654 cd ..
1655 rm -rf "le-$BRANCH"
1656 rm -f "$localname"
1657}
1658
1659if [ "$INSTALLONLINE" ] ; then
d1f97fc8 1660 INSTALLONLINE=""
4a0f23e2 1661 _installOnline $BRANCH
1662 exit
1663fi
4c3b3608 1664
1665if [ -z "$1" ] ; then
1666 showhelp
1667else
1668 "$@"
1669fi