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.

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