You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1613 lines
39 KiB

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