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