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