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