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