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.

4875 lines
119 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
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 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
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 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
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 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
8 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
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 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
8 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
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 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
8 years ago
9 years ago
9 years ago
8 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
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 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
8 years ago
8 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
8 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
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
  1. #!/usr/bin/env sh
  2. VER=2.6.6
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. _SUB_FOLDERS="dnsapi deploy"
  9. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  10. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  11. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  12. DEFAULT_ACCOUNT_EMAIL=""
  13. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  14. DEFAULT_DOMAIN_KEY_LENGTH=2048
  15. DEFAULT_OPENSSL_BIN="openssl"
  16. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  17. VTYPE_HTTP="http-01"
  18. VTYPE_DNS="dns-01"
  19. VTYPE_TLS="tls-sni-01"
  20. #VTYPE_TLS2="tls-sni-02"
  21. LOCAL_ANY_ADDRESS="0.0.0.0"
  22. MAX_RENEW=60
  23. DEFAULT_DNS_SLEEP=120
  24. NO_VALUE="no"
  25. W_TLS="tls"
  26. STATE_VERIFIED="verified_ok"
  27. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  28. END_CSR="-----END CERTIFICATE REQUEST-----"
  29. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  30. END_CERT="-----END CERTIFICATE-----"
  31. RENEW_SKIP=2
  32. ECC_SEP="_"
  33. ECC_SUFFIX="${ECC_SEP}ecc"
  34. LOG_LEVEL_1=1
  35. LOG_LEVEL_2=2
  36. LOG_LEVEL_3=3
  37. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  38. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  39. __INTERACTIVE=""
  40. if [ -t 1 ]; then
  41. __INTERACTIVE="1"
  42. fi
  43. __green() {
  44. if [ "$__INTERACTIVE" ]; then
  45. printf '\033[1;31;32m'
  46. fi
  47. printf -- "$1"
  48. if [ "$__INTERACTIVE" ]; then
  49. printf '\033[0m'
  50. fi
  51. }
  52. __red() {
  53. if [ "$__INTERACTIVE" ]; then
  54. printf '\033[1;31;40m'
  55. fi
  56. printf -- "$1"
  57. if [ "$__INTERACTIVE" ]; then
  58. printf '\033[0m'
  59. fi
  60. }
  61. _printargs() {
  62. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  63. printf -- "%s" "[$(date)] "
  64. fi
  65. if [ -z "$2" ]; then
  66. printf -- "%s" "$1"
  67. else
  68. printf -- "%s" "$1='$2'"
  69. fi
  70. printf "\n"
  71. }
  72. _dlg_versions() {
  73. echo "Diagnosis versions: "
  74. echo "openssl:$OPENSSL_BIN"
  75. if _exists "$OPENSSL_BIN"; then
  76. $OPENSSL_BIN version 2>&1
  77. else
  78. echo "$OPENSSL_BIN doesn't exists."
  79. fi
  80. echo "apache:"
  81. if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
  82. _APACHECTL -V 2>&1
  83. else
  84. echo "apache doesn't exists."
  85. fi
  86. echo "nc:"
  87. if _exists "nc"; then
  88. nc -h 2>&1
  89. else
  90. _debug "nc doesn't exists."
  91. fi
  92. }
  93. _log() {
  94. [ -z "$LOG_FILE" ] && return
  95. _printargs "$@" >>"$LOG_FILE"
  96. }
  97. _info() {
  98. _log "$@"
  99. _printargs "$@"
  100. }
  101. _err() {
  102. _log "$@"
  103. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  104. printf -- "%s" "[$(date)] " >&2
  105. fi
  106. if [ -z "$2" ]; then
  107. __red "$1" >&2
  108. else
  109. __red "$1='$2'" >&2
  110. fi
  111. printf "\n" >&2
  112. return 1
  113. }
  114. _usage() {
  115. __red "$@" >&2
  116. printf "\n" >&2
  117. }
  118. _debug() {
  119. if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ]; then
  120. _log "$@"
  121. fi
  122. if [ -z "$DEBUG" ]; then
  123. return
  124. fi
  125. _printargs "$@" >&2
  126. }
  127. _debug2() {
  128. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ]; then
  129. _log "$@"
  130. fi
  131. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  132. _debug "$@"
  133. fi
  134. }
  135. _debug3() {
  136. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ]; then
  137. _log "$@"
  138. fi
  139. if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ]; then
  140. _debug "$@"
  141. fi
  142. }
  143. _startswith() {
  144. _str="$1"
  145. _sub="$2"
  146. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  147. }
  148. _endswith() {
  149. _str="$1"
  150. _sub="$2"
  151. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  152. }
  153. _contains() {
  154. _str="$1"
  155. _sub="$2"
  156. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  157. }
  158. _hasfield() {
  159. _str="$1"
  160. _field="$2"
  161. _sep="$3"
  162. if [ -z "$_field" ]; then
  163. _usage "Usage: str field [sep]"
  164. return 1
  165. fi
  166. if [ -z "$_sep" ]; then
  167. _sep=","
  168. fi
  169. for f in $(echo "$_str" | tr ',' ' '); do
  170. if [ "$f" = "$_field" ]; then
  171. _debug2 "'$_str' contains '$_field'"
  172. return 0 #contains ok
  173. fi
  174. done
  175. _debug2 "'$_str' does not contain '$_field'"
  176. return 1 #not contains
  177. }
  178. _getfield() {
  179. _str="$1"
  180. _findex="$2"
  181. _sep="$3"
  182. if [ -z "$_findex" ]; then
  183. _usage "Usage: str field [sep]"
  184. return 1
  185. fi
  186. if [ -z "$_sep" ]; then
  187. _sep=","
  188. fi
  189. _ffi="$_findex"
  190. while [ "$_ffi" -gt "0" ]; do
  191. _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
  192. if [ "$_fv" ]; then
  193. printf -- "%s" "$_fv"
  194. return 0
  195. fi
  196. _ffi="$(_math "$_ffi" - 1)"
  197. done
  198. printf -- "%s" "$_str"
  199. }
  200. _exists() {
  201. cmd="$1"
  202. if [ -z "$cmd" ]; then
  203. _usage "Usage: _exists cmd"
  204. return 1
  205. fi
  206. if eval type type >/dev/null 2>&1; then
  207. eval type "$cmd" >/dev/null 2>&1
  208. elif command >/dev/null 2>&1; then
  209. command -v "$cmd" >/dev/null 2>&1
  210. else
  211. which "$cmd" >/dev/null 2>&1
  212. fi
  213. ret="$?"
  214. _debug3 "$cmd exists=$ret"
  215. return $ret
  216. }
  217. #a + b
  218. _math() {
  219. _m_opts="$@"
  220. printf "%s" "$(($_m_opts))"
  221. }
  222. _h_char_2_dec() {
  223. _ch=$1
  224. case "${_ch}" in
  225. a | A)
  226. printf "10"
  227. ;;
  228. b | B)
  229. printf "11"
  230. ;;
  231. c | C)
  232. printf "12"
  233. ;;
  234. d | D)
  235. printf "13"
  236. ;;
  237. e | E)
  238. printf "14"
  239. ;;
  240. f | F)
  241. printf "15"
  242. ;;
  243. *)
  244. printf "%s" "$_ch"
  245. ;;
  246. esac
  247. }
  248. _URGLY_PRINTF=""
  249. if [ "$(printf '\x41')" != 'A' ]; then
  250. _URGLY_PRINTF=1
  251. fi
  252. _h2b() {
  253. hex=$(cat)
  254. i=1
  255. j=2
  256. _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
  257. while true; do
  258. if [ -z "$_URGLY_PRINTF" ]; then
  259. h="$(printf "%s" "$hex" | cut -c $i-$j)"
  260. if [ -z "$h" ]; then
  261. break
  262. fi
  263. printf "\x$h%s"
  264. else
  265. ic="$(printf "%s" "$hex" | cut -c $i)"
  266. jc="$(printf "%s" "$hex" | cut -c $j)"
  267. if [ -z "$ic$jc" ]; then
  268. break
  269. fi
  270. ic="$(_h_char_2_dec "$ic")"
  271. jc="$(_h_char_2_dec "$jc")"
  272. printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
  273. fi
  274. i="$(_math "$i" + 2)"
  275. j="$(_math "$j" + 2)"
  276. done
  277. }
  278. _is_solaris() {
  279. _contains "${__OS__:=$(uname -a)}" "solaris" || _contains "${__OS__:=$(uname -a)}" "SunOS"
  280. }
  281. #stdin output hexstr splited by one space
  282. #input:"abc"
  283. #output: " 61 62 63"
  284. _hex_dump() {
  285. od -A n -v -t x1 | tr -d "\r\t" | tr -s " " | sed "s/ $//" | tr -d "\n"
  286. }
  287. #url encode, no-preserved chars
  288. #A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  289. #41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a
  290. #a b c d e f g h i j k l m n o p q r s t u v w x y z
  291. #61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79 7a
  292. #0 1 2 3 4 5 6 7 8 9 - _ . ~
  293. #30 31 32 33 34 35 36 37 38 39 2d 5f 2e 7e
  294. #stdin stdout
  295. _url_encode() {
  296. _hex_str=$(_hex_dump)
  297. _debug3 "_url_encode"
  298. _debug3 "_hex_str" "$_hex_str"
  299. for _hex_code in $_hex_str; do
  300. #upper case
  301. case "${_hex_code}" in
  302. "41")
  303. printf "%s" "A"
  304. ;;
  305. "42")
  306. printf "%s" "B"
  307. ;;
  308. "43")
  309. printf "%s" "C"
  310. ;;
  311. "44")
  312. printf "%s" "D"
  313. ;;
  314. "45")
  315. printf "%s" "E"
  316. ;;
  317. "46")
  318. printf "%s" "F"
  319. ;;
  320. "47")
  321. printf "%s" "G"
  322. ;;
  323. "48")
  324. printf "%s" "H"
  325. ;;
  326. "49")
  327. printf "%s" "I"
  328. ;;
  329. "4a")
  330. printf "%s" "J"
  331. ;;
  332. "4b")
  333. printf "%s" "K"
  334. ;;
  335. "4c")
  336. printf "%s" "L"
  337. ;;
  338. "4d")
  339. printf "%s" "M"
  340. ;;
  341. "4e")
  342. printf "%s" "N"
  343. ;;
  344. "4f")
  345. printf "%s" "O"
  346. ;;
  347. "50")
  348. printf "%s" "P"
  349. ;;
  350. "51")
  351. printf "%s" "Q"
  352. ;;
  353. "52")
  354. printf "%s" "R"
  355. ;;
  356. "53")
  357. printf "%s" "S"
  358. ;;
  359. "54")
  360. printf "%s" "T"
  361. ;;
  362. "55")
  363. printf "%s" "U"
  364. ;;
  365. "56")
  366. printf "%s" "V"
  367. ;;
  368. "57")
  369. printf "%s" "W"
  370. ;;
  371. "58")
  372. printf "%s" "X"
  373. ;;
  374. "59")
  375. printf "%s" "Y"
  376. ;;
  377. "5a")
  378. printf "%s" "Z"
  379. ;;
  380. #lower case
  381. "61")
  382. printf "%s" "a"
  383. ;;
  384. "62")
  385. printf "%s" "b"
  386. ;;
  387. "63")
  388. printf "%s" "c"
  389. ;;
  390. "64")
  391. printf "%s" "d"
  392. ;;
  393. "65")
  394. printf "%s" "e"
  395. ;;
  396. "66")
  397. printf "%s" "f"
  398. ;;
  399. "67")
  400. printf "%s" "g"
  401. ;;
  402. "68")
  403. printf "%s" "h"
  404. ;;
  405. "69")
  406. printf "%s" "i"
  407. ;;
  408. "6a")
  409. printf "%s" "j"
  410. ;;
  411. "6b")
  412. printf "%s" "k"
  413. ;;
  414. "6c")
  415. printf "%s" "l"
  416. ;;
  417. "6d")
  418. printf "%s" "m"
  419. ;;
  420. "6e")
  421. printf "%s" "n"
  422. ;;
  423. "6f")
  424. printf "%s" "o"
  425. ;;
  426. "70")
  427. printf "%s" "p"
  428. ;;
  429. "71")
  430. printf "%s" "q"
  431. ;;
  432. "72")
  433. printf "%s" "r"
  434. ;;
  435. "73")
  436. printf "%s" "s"
  437. ;;
  438. "74")
  439. printf "%s" "t"
  440. ;;
  441. "75")
  442. printf "%s" "u"
  443. ;;
  444. "76")
  445. printf "%s" "v"
  446. ;;
  447. "77")
  448. printf "%s" "w"
  449. ;;
  450. "78")
  451. printf "%s" "x"
  452. ;;
  453. "79")
  454. printf "%s" "y"
  455. ;;
  456. "7a")
  457. printf "%s" "z"
  458. ;;
  459. #numbers
  460. "30")
  461. printf "%s" "0"
  462. ;;
  463. "31")
  464. printf "%s" "1"
  465. ;;
  466. "32")
  467. printf "%s" "2"
  468. ;;
  469. "33")
  470. printf "%s" "3"
  471. ;;
  472. "34")
  473. printf "%s" "4"
  474. ;;
  475. "35")
  476. printf "%s" "5"
  477. ;;
  478. "36")
  479. printf "%s" "6"
  480. ;;
  481. "37")
  482. printf "%s" "7"
  483. ;;
  484. "38")
  485. printf "%s" "8"
  486. ;;
  487. "39")
  488. printf "%s" "9"
  489. ;;
  490. "2d")
  491. printf "%s" "-"
  492. ;;
  493. "5f")
  494. printf "%s" "_"
  495. ;;
  496. "2e")
  497. printf "%s" "."
  498. ;;
  499. "7e")
  500. printf "%s" "~"
  501. ;;
  502. #other hex
  503. *)
  504. printf '%%%s' "$_hex_code"
  505. ;;
  506. esac
  507. done
  508. }
  509. #options file
  510. _sed_i() {
  511. options="$1"
  512. filename="$2"
  513. if [ -z "$filename" ]; then
  514. _usage "Usage:_sed_i options filename"
  515. return 1
  516. fi
  517. _debug2 options "$options"
  518. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  519. _debug "Using sed -i"
  520. sed -i "$options" "$filename"
  521. else
  522. _debug "No -i support in sed"
  523. text="$(cat "$filename")"
  524. echo "$text" | sed "$options" >"$filename"
  525. fi
  526. }
  527. _egrep_o() {
  528. if ! egrep -o "$1" 2>/dev/null; then
  529. sed -n 's/.*\('"$1"'\).*/\1/p'
  530. fi
  531. }
  532. #Usage: file startline endline
  533. _getfile() {
  534. filename="$1"
  535. startline="$2"
  536. endline="$3"
  537. if [ -z "$endline" ]; then
  538. _usage "Usage: file startline endline"
  539. return 1
  540. fi
  541. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  542. if [ -z "$i" ]; then
  543. _err "Can not find start line: $startline"
  544. return 1
  545. fi
  546. i="$(_math "$i" + 1)"
  547. _debug i "$i"
  548. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  549. if [ -z "$j" ]; then
  550. _err "Can not find end line: $endline"
  551. return 1
  552. fi
  553. j="$(_math "$j" - 1)"
  554. _debug j "$j"
  555. sed -n "$i,${j}p" "$filename"
  556. }
  557. #Usage: multiline
  558. _base64() {
  559. [ "" ] #urgly
  560. if [ "$1" ]; then
  561. _debug3 "base64 multiline:'$1'"
  562. $OPENSSL_BIN base64 -e
  563. else
  564. _debug3 "base64 single line."
  565. $OPENSSL_BIN base64 -e | tr -d '\r\n'
  566. fi
  567. }
  568. #Usage: multiline
  569. _dbase64() {
  570. if [ "$1" ]; then
  571. $OPENSSL_BIN base64 -d -A
  572. else
  573. $OPENSSL_BIN base64 -d
  574. fi
  575. }
  576. #Usage: hashalg [outputhex]
  577. #Output Base64-encoded digest
  578. _digest() {
  579. alg="$1"
  580. if [ -z "$alg" ]; then
  581. _usage "Usage: _digest hashalg"
  582. return 1
  583. fi
  584. outputhex="$2"
  585. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
  586. if [ "$outputhex" ]; then
  587. $OPENSSL_BIN dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
  588. else
  589. $OPENSSL_BIN dgst -"$alg" -binary | _base64
  590. fi
  591. else
  592. _err "$alg is not supported yet"
  593. return 1
  594. fi
  595. }
  596. #Usage: hashalg secret_hex [outputhex]
  597. #Output binary hmac
  598. _hmac() {
  599. alg="$1"
  600. secret_hex="$2"
  601. outputhex="$3"
  602. if [ -z "$secret_hex" ]; then
  603. _usage "Usage: _hmac hashalg secret [outputhex]"
  604. return 1
  605. fi
  606. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  607. if [ "$outputhex" ]; then
  608. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" | cut -d = -f 2 | tr -d ' '
  609. else
  610. $OPENSSL_BIN dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary
  611. fi
  612. else
  613. _err "$alg is not supported yet"
  614. return 1
  615. fi
  616. }
  617. #Usage: keyfile hashalg
  618. #Output: Base64-encoded signature value
  619. _sign() {
  620. keyfile="$1"
  621. alg="$2"
  622. if [ -z "$alg" ]; then
  623. _usage "Usage: _sign keyfile hashalg"
  624. return 1
  625. fi
  626. _sign_openssl="$OPENSSL_BIN dgst -sign $keyfile "
  627. if [ "$alg" = "sha256" ]; then
  628. _sign_openssl="$_sign_openssl -$alg"
  629. else
  630. _err "$alg is not supported yet"
  631. return 1
  632. fi
  633. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  634. $_sign_openssl | _base64
  635. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  636. if ! _signedECText="$($_sign_openssl | $OPENSSL_BIN asn1parse -inform DER)"; then
  637. _err "Sign failed: $_sign_openssl"
  638. _err "Key file: $keyfile"
  639. _err "Key content:$(wc -l <"$keyfile") lises"
  640. return 1
  641. fi
  642. _debug3 "_signedECText" "$_signedECText"
  643. _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  644. _debug3 "_ec_r" "$_ec_r"
  645. _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  646. _debug3 "_ec_s" "$_ec_s"
  647. printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
  648. else
  649. _err "Unknown key file format."
  650. return 1
  651. fi
  652. }
  653. #keylength
  654. _isEccKey() {
  655. _length="$1"
  656. if [ -z "$_length" ]; then
  657. return 1
  658. fi
  659. [ "$_length" != "1024" ] \
  660. && [ "$_length" != "2048" ] \
  661. && [ "$_length" != "3072" ] \
  662. && [ "$_length" != "4096" ] \
  663. && [ "$_length" != "8192" ]
  664. }
  665. # _createkey 2048|ec-256 file
  666. _createkey() {
  667. length="$1"
  668. f="$2"
  669. _debug2 "_createkey for file:$f"
  670. eccname="$length"
  671. if _startswith "$length" "ec-"; then
  672. length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
  673. if [ "$length" = "256" ]; then
  674. eccname="prime256v1"
  675. fi
  676. if [ "$length" = "384" ]; then
  677. eccname="secp384r1"
  678. fi
  679. if [ "$length" = "521" ]; then
  680. eccname="secp521r1"
  681. fi
  682. fi
  683. if [ -z "$length" ]; then
  684. length=2048
  685. fi
  686. _debug "Use length $length"
  687. if _isEccKey "$length"; then
  688. _debug "Using ec name: $eccname"
  689. $OPENSSL_BIN ecparam -name "$eccname" -genkey 2>/dev/null >"$f"
  690. else
  691. _debug "Using RSA: $length"
  692. $OPENSSL_BIN genrsa "$length" 2>/dev/null >"$f"
  693. fi
  694. if [ "$?" != "0" ]; then
  695. _err "Create key error."
  696. return 1
  697. fi
  698. }
  699. #domain
  700. _is_idn() {
  701. _is_idn_d="$1"
  702. _debug2 _is_idn_d "$_is_idn_d"
  703. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '0-9' | tr -d 'a-z' | tr -d 'A-Z' | tr -d '.,-')
  704. _debug2 _idn_temp "$_idn_temp"
  705. [ "$_idn_temp" ]
  706. }
  707. #aa.com
  708. #aa.com,bb.com,cc.com
  709. _idn() {
  710. __idn_d="$1"
  711. if ! _is_idn "$__idn_d"; then
  712. printf "%s" "$__idn_d"
  713. return 0
  714. fi
  715. if _exists idn; then
  716. if _contains "$__idn_d" ','; then
  717. _i_first="1"
  718. for f in $(echo "$__idn_d" | tr ',' ' '); do
  719. [ -z "$f" ] && continue
  720. if [ -z "$_i_first" ]; then
  721. printf "%s" ","
  722. else
  723. _i_first=""
  724. fi
  725. idn --quiet "$f" | tr -d "\r\n"
  726. done
  727. else
  728. idn "$__idn_d" | tr -d "\r\n"
  729. fi
  730. else
  731. _err "Please install idn to process IDN names."
  732. fi
  733. }
  734. #_createcsr cn san_list keyfile csrfile conf
  735. _createcsr() {
  736. _debug _createcsr
  737. domain="$1"
  738. domainlist="$2"
  739. csrkey="$3"
  740. csr="$4"
  741. csrconf="$5"
  742. _debug2 domain "$domain"
  743. _debug2 domainlist "$domainlist"
  744. _debug2 csrkey "$csrkey"
  745. _debug2 csr "$csr"
  746. _debug2 csrconf "$csrconf"
  747. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
  748. if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  749. #single domain
  750. _info "Single domain" "$domain"
  751. else
  752. domainlist="$(_idn "$domainlist")"
  753. _debug2 domainlist "$domainlist"
  754. if _contains "$domainlist" ","; then
  755. alt="DNS:$(echo "$domainlist" | sed "s/,/,DNS:/g")"
  756. else
  757. alt="DNS:$domainlist"
  758. fi
  759. #multi
  760. _info "Multi domain" "$alt"
  761. printf -- "\nsubjectAltName=$alt" >>"$csrconf"
  762. fi
  763. if [ "$Le_OCSP_Staple" ] || [ "$Le_OCSP_Stable" ]; then
  764. _savedomainconf Le_OCSP_Staple "$Le_OCSP_Staple"
  765. _cleardomainconf Le_OCSP_Stable
  766. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
  767. fi
  768. _csr_cn="$(_idn "$domain")"
  769. _debug2 _csr_cn "$_csr_cn"
  770. $OPENSSL_BIN req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  771. }
  772. #_signcsr key csr conf cert
  773. _signcsr() {
  774. key="$1"
  775. csr="$2"
  776. conf="$3"
  777. cert="$4"
  778. _debug "_signcsr"
  779. _msg="$($OPENSSL_BIN x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  780. _ret="$?"
  781. _debug "$_msg"
  782. return $_ret
  783. }
  784. #_csrfile
  785. _readSubjectFromCSR() {
  786. _csrfile="$1"
  787. if [ -z "$_csrfile" ]; then
  788. _usage "_readSubjectFromCSR mycsr.csr"
  789. return 1
  790. fi
  791. $OPENSSL_BIN req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
  792. }
  793. #_csrfile
  794. #echo comma separated domain list
  795. _readSubjectAltNamesFromCSR() {
  796. _csrfile="$1"
  797. if [ -z "$_csrfile" ]; then
  798. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  799. return 1
  800. fi
  801. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  802. _debug _csrsubj "$_csrsubj"
  803. _dnsAltnames="$($OPENSSL_BIN req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  804. _debug _dnsAltnames "$_dnsAltnames"
  805. if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
  806. _debug "AltNames contains subject"
  807. _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
  808. else
  809. _debug "AltNames doesn't contain subject"
  810. fi
  811. printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
  812. }
  813. #_csrfile
  814. _readKeyLengthFromCSR() {
  815. _csrfile="$1"
  816. if [ -z "$_csrfile" ]; then
  817. _usage "_readKeyLengthFromCSR mycsr.csr"
  818. return 1
  819. fi
  820. _outcsr="$($OPENSSL_BIN req -noout -text -in "$_csrfile")"
  821. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
  822. _debug "ECC CSR"
  823. echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  824. else
  825. _debug "RSA CSR"
  826. echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  827. fi
  828. }
  829. _ss() {
  830. _port="$1"
  831. if _exists "ss"; then
  832. _debug "Using: ss"
  833. ss -ntpl | grep ":$_port "
  834. return 0
  835. fi
  836. if _exists "netstat"; then
  837. _debug "Using: netstat"
  838. if netstat -h 2>&1 | grep "\-p proto" >/dev/null; then
  839. #for windows version netstat tool
  840. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  841. else
  842. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
  843. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  844. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
  845. #for solaris
  846. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  847. else
  848. netstat -ntpl | grep ":$_port "
  849. fi
  850. fi
  851. return 0
  852. fi
  853. return 1
  854. }
  855. #domain [password] [isEcc]
  856. toPkcs() {
  857. domain="$1"
  858. pfxPassword="$2"
  859. if [ -z "$domain" ]; then
  860. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  861. return 1
  862. fi
  863. _isEcc="$3"
  864. _initpath "$domain" "$_isEcc"
  865. if [ "$pfxPassword" ]; then
  866. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  867. else
  868. $OPENSSL_BIN pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  869. fi
  870. if [ "$?" = "0" ]; then
  871. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  872. fi
  873. }
  874. #[2048]
  875. createAccountKey() {
  876. _info "Creating account key"
  877. if [ -z "$1" ]; then
  878. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  879. return
  880. fi
  881. length=$1
  882. _create_account_key "$length"
  883. }
  884. _create_account_key() {
  885. length=$1
  886. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
  887. _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
  888. length="$DEFAULT_ACCOUNT_KEY_LENGTH"
  889. fi
  890. _debug length "$length"
  891. _initpath
  892. mkdir -p "$CA_DIR"
  893. if [ -f "$ACCOUNT_KEY_PATH" ]; then
  894. _info "Account key exists, skip"
  895. return
  896. else
  897. #generate account key
  898. _createkey "$length" "$ACCOUNT_KEY_PATH"
  899. fi
  900. }
  901. #domain [length]
  902. createDomainKey() {
  903. _info "Creating domain key"
  904. if [ -z "$1" ]; then
  905. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  906. return
  907. fi
  908. domain=$1
  909. length=$2
  910. if [ -z "$length" ]; then
  911. _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
  912. length="$DEFAULT_DOMAIN_KEY_LENGTH"
  913. fi
  914. _initpath "$domain" "$length"
  915. if [ ! -f "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$IS_RENEW" ]); then
  916. _createkey "$length" "$CERT_KEY_PATH"
  917. else
  918. if [ "$IS_RENEW" ]; then
  919. _info "Domain key exists, skip"
  920. return 0
  921. else
  922. _err "Domain key exists, do you want to overwrite the key?"
  923. _err "Add '--force', and try again."
  924. return 1
  925. fi
  926. fi
  927. }
  928. # domain domainlist isEcc
  929. createCSR() {
  930. _info "Creating csr"
  931. if [ -z "$1" ]; then
  932. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  933. return
  934. fi
  935. domain="$1"
  936. domainlist="$2"
  937. _isEcc="$3"
  938. _initpath "$domain" "$_isEcc"
  939. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  940. _info "CSR exists, skip"
  941. return
  942. fi
  943. if [ ! -f "$CERT_KEY_PATH" ]; then
  944. _err "The key file is not found: $CERT_KEY_PATH"
  945. _err "Please create the key file first."
  946. return 1
  947. fi
  948. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  949. }
  950. _url_replace() {
  951. tr '/+' '_-' | tr -d '= '
  952. }
  953. _time2str() {
  954. #BSD
  955. if date -u -d@"$1" 2>/dev/null; then
  956. return
  957. fi
  958. #Linux
  959. if date -u -r "$1" 2>/dev/null; then
  960. return
  961. fi
  962. #Soaris
  963. if _exists adb; then
  964. _t_s_a=$(echo "0t${1}=Y" | adb)
  965. echo "$_t_s_a"
  966. fi
  967. }
  968. _normalizeJson() {
  969. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  970. }
  971. _stat() {
  972. #Linux
  973. if stat -c '%U:%G' "$1" 2>/dev/null; then
  974. return
  975. fi
  976. #BSD
  977. if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
  978. return
  979. fi
  980. return 1 #error, 'stat' not found
  981. }
  982. #keyfile
  983. _calcjwk() {
  984. keyfile="$1"
  985. if [ -z "$keyfile" ]; then
  986. _usage "Usage: _calcjwk keyfile"
  987. return 1
  988. fi
  989. if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
  990. _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
  991. return 0
  992. fi
  993. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  994. _debug "RSA key"
  995. pub_exp=$($OPENSSL_BIN rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  996. if [ "${#pub_exp}" = "5" ]; then
  997. pub_exp=0$pub_exp
  998. fi
  999. _debug3 pub_exp "$pub_exp"
  1000. e=$(echo "$pub_exp" | _h2b | _base64)
  1001. _debug3 e "$e"
  1002. modulus=$($OPENSSL_BIN rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
  1003. _debug3 modulus "$modulus"
  1004. n="$(printf "%s" "$modulus" | _h2b | _base64 | _url_replace)"
  1005. _debug3 n "$n"
  1006. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  1007. _debug3 jwk "$jwk"
  1008. JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  1009. JWK_HEADERPLACE_PART1='{"nonce": "'
  1010. JWK_HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
  1011. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  1012. _debug "EC key"
  1013. crv="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1014. _debug3 crv "$crv"
  1015. if [ -z "$crv" ]; then
  1016. _debug "Let's try ASN1 OID"
  1017. crv_oid="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1018. _debug3 crv_oid "$crv_oid"
  1019. case "${crv_oid}" in
  1020. "prime256v1")
  1021. crv="P-256"
  1022. ;;
  1023. "secp384r1")
  1024. crv="P-384"
  1025. ;;
  1026. "secp521r1")
  1027. crv="P-521"
  1028. ;;
  1029. *)
  1030. _err "ECC oid : $crv_oid"
  1031. return 1
  1032. ;;
  1033. esac
  1034. _debug3 crv "$crv"
  1035. fi
  1036. pubi="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  1037. pubi=$(_math "$pubi" + 1)
  1038. _debug3 pubi "$pubi"
  1039. pubj="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  1040. pubj=$(_math "$pubj" - 1)
  1041. _debug3 pubj "$pubj"
  1042. pubtext="$($OPENSSL_BIN ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  1043. _debug3 pubtext "$pubtext"
  1044. xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
  1045. xlen=$(_math "$xlen" / 4)
  1046. _debug3 xlen "$xlen"
  1047. xend=$(_math "$xlen" + 1)
  1048. x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
  1049. _debug3 x "$x"
  1050. x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _url_replace)"
  1051. _debug3 x64 "$x64"
  1052. xend=$(_math "$xend" + 1)
  1053. y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
  1054. _debug3 y "$y"
  1055. y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _url_replace)"
  1056. _debug3 y64 "$y64"
  1057. jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
  1058. _debug3 jwk "$jwk"
  1059. JWK_HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  1060. JWK_HEADERPLACE_PART1='{"nonce": "'
  1061. JWK_HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
  1062. else
  1063. _err "Only RSA or EC key is supported."
  1064. return 1
  1065. fi
  1066. _debug3 JWK_HEADER "$JWK_HEADER"
  1067. __CACHED_JWK_KEY_FILE="$keyfile"
  1068. }
  1069. _time() {
  1070. date -u "+%s"
  1071. }
  1072. _mktemp() {
  1073. if _exists mktemp; then
  1074. if mktemp 2>/dev/null; then
  1075. return 0
  1076. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
  1077. #for Mac osx
  1078. return 0
  1079. fi
  1080. fi
  1081. if [ -d "/tmp" ]; then
  1082. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  1083. return 0
  1084. elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
  1085. echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
  1086. return 0
  1087. fi
  1088. _err "Can not create temp file."
  1089. }
  1090. _inithttp() {
  1091. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
  1092. HTTP_HEADER="$(_mktemp)"
  1093. _debug2 HTTP_HEADER "$HTTP_HEADER"
  1094. fi
  1095. if [ "$__HTTP_INITIALIZED" ]; then
  1096. if [ "$_ACME_CURL$_ACME_WGET" ]; then
  1097. _debug2 "Http already initialized."
  1098. return 0
  1099. fi
  1100. fi
  1101. if [ -z "$_ACME_CURL" ] && _exists "curl"; then
  1102. _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
  1103. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1104. _CURL_DUMP="$(_mktemp)"
  1105. _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
  1106. fi
  1107. if [ "$CA_BUNDLE" ]; then
  1108. _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
  1109. fi
  1110. fi
  1111. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  1112. _ACME_WGET="wget -q"
  1113. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1114. _ACME_WGET="$_ACME_WGET -d "
  1115. fi
  1116. if [ "$CA_BUNDLE" ]; then
  1117. _ACME_WGET="$_ACME_WGET --ca-certificate $CA_BUNDLE "
  1118. fi
  1119. fi
  1120. __HTTP_INITIALIZED=1
  1121. }
  1122. # body url [needbase64] [POST|PUT]
  1123. _post() {
  1124. body="$1"
  1125. url="$2"
  1126. needbase64="$3"
  1127. httpmethod="$4"
  1128. if [ -z "$httpmethod" ]; then
  1129. httpmethod="POST"
  1130. fi
  1131. _debug $httpmethod
  1132. _debug "url" "$url"
  1133. _debug2 "body" "$body"
  1134. _inithttp
  1135. if [ "$_ACME_CURL" ]; then
  1136. _CURL="$_ACME_CURL"
  1137. if [ "$HTTPS_INSECURE" ]; then
  1138. _CURL="$_CURL --insecure "
  1139. fi
  1140. _debug "_CURL" "$_CURL"
  1141. if [ "$needbase64" ]; then
  1142. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
  1143. else
  1144. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url")"
  1145. fi
  1146. _ret="$?"
  1147. if [ "$_ret" != "0" ]; then
  1148. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  1149. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1150. _err "Here is the curl dump log:"
  1151. _err "$(cat "$_CURL_DUMP")"
  1152. fi
  1153. fi
  1154. elif [ "$_ACME_WGET" ]; then
  1155. _WGET="$_ACME_WGET"
  1156. if [ "$HTTPS_INSECURE" ]; then
  1157. _WGET="$_WGET --no-check-certificate "
  1158. fi
  1159. _debug "_WGET" "$_WGET"
  1160. if [ "$needbase64" ]; then
  1161. if [ "$httpmethod" = "POST" ]; then
  1162. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  1163. else
  1164. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  1165. fi
  1166. else
  1167. if [ "$httpmethod" = "POST" ]; then
  1168. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  1169. else
  1170. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  1171. fi
  1172. fi
  1173. _ret="$?"
  1174. if [ "$_ret" = "8" ]; then
  1175. _ret=0
  1176. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  1177. fi
  1178. if [ "$_ret" != "0" ]; then
  1179. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  1180. fi
  1181. _sed_i "s/^ *//g" "$HTTP_HEADER"
  1182. else
  1183. _ret="$?"
  1184. _err "Neither curl nor wget is found, can not do $httpmethod."
  1185. fi
  1186. _debug "_ret" "$_ret"
  1187. printf "%s" "$response"
  1188. return $_ret
  1189. }
  1190. # url getheader timeout
  1191. _get() {
  1192. _debug GET
  1193. url="$1"
  1194. onlyheader="$2"
  1195. t="$3"
  1196. _debug url "$url"
  1197. _debug "timeout" "$t"
  1198. _inithttp
  1199. if [ "$_ACME_CURL" ]; then
  1200. _CURL="$_ACME_CURL"
  1201. if [ "$HTTPS_INSECURE" ]; then
  1202. _CURL="$_CURL --insecure "
  1203. fi
  1204. if [ "$t" ]; then
  1205. _CURL="$_CURL --connect-timeout $t"
  1206. fi
  1207. _debug "_CURL" "$_CURL"
  1208. if [ "$onlyheader" ]; then
  1209. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1210. else
  1211. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1212. fi
  1213. ret=$?
  1214. if [ "$ret" != "0" ]; then
  1215. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  1216. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1217. _err "Here is the curl dump log:"
  1218. _err "$(cat "$_CURL_DUMP")"
  1219. fi
  1220. fi
  1221. elif [ "$_ACME_WGET" ]; then
  1222. _WGET="$_ACME_WGET"
  1223. if [ "$HTTPS_INSECURE" ]; then
  1224. _WGET="$_WGET --no-check-certificate "
  1225. fi
  1226. if [ "$t" ]; then
  1227. _WGET="$_WGET --timeout=$t"
  1228. fi
  1229. _debug "_WGET" "$_WGET"
  1230. if [ "$onlyheader" ]; then
  1231. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null "$url" 2>&1 | sed 's/^[ ]*//g'
  1232. else
  1233. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1234. fi
  1235. ret=$?
  1236. if [ "$_ret" = "8" ]; then
  1237. _ret=0
  1238. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  1239. fi
  1240. if [ "$ret" != "0" ]; then
  1241. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1242. fi
  1243. else
  1244. ret=$?
  1245. _err "Neither curl nor wget is found, can not do GET."
  1246. fi
  1247. _debug "ret" "$ret"
  1248. return $ret
  1249. }
  1250. _head_n() {
  1251. head -n "$1"
  1252. }
  1253. _tail_n() {
  1254. if ! tail -n "$1" 2>/dev/null; then
  1255. #fix for solaris
  1256. tail -"$1"
  1257. fi
  1258. }
  1259. # url payload needbase64 keyfile
  1260. _send_signed_request() {
  1261. url=$1
  1262. payload=$2
  1263. needbase64=$3
  1264. keyfile=$4
  1265. if [ -z "$keyfile" ]; then
  1266. keyfile="$ACCOUNT_KEY_PATH"
  1267. fi
  1268. _debug url "$url"
  1269. _debug payload "$payload"
  1270. if ! _calcjwk "$keyfile"; then
  1271. return 1
  1272. fi
  1273. payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
  1274. _debug3 payload64 "$payload64"
  1275. if [ -z "$_CACHED_NONCE" ]; then
  1276. _debug2 "Get nonce."
  1277. nonceurl="$API/directory"
  1278. _headers="$(_get "$nonceurl" "onlyheader")"
  1279. if [ "$?" != "0" ]; then
  1280. _err "Can not connect to $nonceurl to get nonce."
  1281. return 1
  1282. fi
  1283. _debug2 _headers "$_headers"
  1284. _CACHED_NONCE="$(echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1285. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1286. else
  1287. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1288. fi
  1289. nonce="$_CACHED_NONCE"
  1290. _debug2 nonce "$nonce"
  1291. protected="$JWK_HEADERPLACE_PART1$nonce$JWK_HEADERPLACE_PART2"
  1292. _debug3 protected "$protected"
  1293. protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
  1294. _debug3 protected64 "$protected64"
  1295. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1296. _err "Sign request failed."
  1297. return 1
  1298. fi
  1299. _debug3 _sig_t "$_sig_t"
  1300. sig="$(printf "%s" "$_sig_t" | _url_replace)"
  1301. _debug3 sig "$sig"
  1302. body="{\"header\": $JWK_HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1303. _debug3 body "$body"
  1304. response="$(_post "$body" "$url" "$needbase64")"
  1305. _CACHED_NONCE=""
  1306. if [ "$?" != "0" ]; then
  1307. _err "Can not post to $url"
  1308. return 1
  1309. fi
  1310. _debug2 original "$response"
  1311. response="$(echo "$response" | _normalizeJson)"
  1312. responseHeaders="$(cat "$HTTP_HEADER")"
  1313. _debug2 responseHeaders "$responseHeaders"
  1314. _debug2 response "$response"
  1315. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1316. _debug code "$code"
  1317. _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1318. }
  1319. #setopt "file" "opt" "=" "value" [";"]
  1320. _setopt() {
  1321. __conf="$1"
  1322. __opt="$2"
  1323. __sep="$3"
  1324. __val="$4"
  1325. __end="$5"
  1326. if [ -z "$__opt" ]; then
  1327. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1328. return
  1329. fi
  1330. if [ ! -f "$__conf" ]; then
  1331. touch "$__conf"
  1332. fi
  1333. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1334. _debug3 OK
  1335. if _contains "$__val" "&"; then
  1336. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1337. fi
  1338. text="$(cat "$__conf")"
  1339. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1340. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1341. if _contains "$__val" "&"; then
  1342. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1343. fi
  1344. text="$(cat "$__conf")"
  1345. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1346. else
  1347. _debug3 APP
  1348. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1349. fi
  1350. _debug2 "$(grep -n "^$__opt$__sep" "$__conf")"
  1351. }
  1352. #_save_conf file key value
  1353. #save to conf
  1354. _save_conf() {
  1355. _s_c_f="$1"
  1356. _sdkey="$2"
  1357. _sdvalue="$3"
  1358. if [ "$_s_c_f" ]; then
  1359. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1360. else
  1361. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1362. fi
  1363. }
  1364. #_clear_conf file key
  1365. _clear_conf() {
  1366. _c_c_f="$1"
  1367. _sdkey="$2"
  1368. if [ "$_c_c_f" ]; then
  1369. _conf_data="$(cat "$_c_c_f")"
  1370. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1371. else
  1372. _err "config file is empty, can not clear"
  1373. fi
  1374. }
  1375. #_read_conf file key
  1376. _read_conf() {
  1377. _r_c_f="$1"
  1378. _sdkey="$2"
  1379. if [ -f "$_r_c_f" ]; then
  1380. (
  1381. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1382. eval "printf \"%s\" \"\$$_sdkey\""
  1383. )
  1384. else
  1385. _debug "config file is empty, can not read $_sdkey"
  1386. fi
  1387. }
  1388. #_savedomainconf key value
  1389. #save to domain.conf
  1390. _savedomainconf() {
  1391. _save_conf "$DOMAIN_CONF" "$1" "$2"
  1392. }
  1393. #_cleardomainconf key
  1394. _cleardomainconf() {
  1395. _clear_conf "$DOMAIN_CONF" "$1"
  1396. }
  1397. #_readdomainconf key
  1398. _readdomainconf() {
  1399. _read_conf "$DOMAIN_CONF" "$1"
  1400. }
  1401. #_saveaccountconf key value
  1402. _saveaccountconf() {
  1403. _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
  1404. }
  1405. #_clearaccountconf key
  1406. _clearaccountconf() {
  1407. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1408. }
  1409. #_savecaconf key value
  1410. _savecaconf() {
  1411. _save_conf "$CA_CONF" "$1" "$2"
  1412. }
  1413. #_readcaconf key
  1414. _readcaconf() {
  1415. _read_conf "$CA_CONF" "$1"
  1416. }
  1417. #_clearaccountconf key
  1418. _clearcaconf() {
  1419. _clear_conf "$CA_CONF" "$1"
  1420. }
  1421. # content localaddress
  1422. _startserver() {
  1423. content="$1"
  1424. ncaddr="$2"
  1425. _debug "ncaddr" "$ncaddr"
  1426. _debug "startserver: $$"
  1427. nchelp="$(nc -h 2>&1)"
  1428. _debug Le_HTTPPort "$Le_HTTPPort"
  1429. _debug Le_Listen_V4 "$Le_Listen_V4"
  1430. _debug Le_Listen_V6 "$Le_Listen_V6"
  1431. _NC="nc"
  1432. if [ "$Le_Listen_V4" ]; then
  1433. _NC="$_NC -4"
  1434. elif [ "$Le_Listen_V6" ]; then
  1435. _NC="$_NC -6"
  1436. fi
  1437. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null; then
  1438. _NC="$_NC -q 1 -l $ncaddr"
  1439. else
  1440. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null; then
  1441. _NC="$_NC -c -l $ncaddr"
  1442. elif echo "$nchelp" | grep "\-N" | grep "Shutdown the network socket after EOF on stdin" >/dev/null; then
  1443. _NC="$_NC -N -l $ncaddr"
  1444. else
  1445. _NC="$_NC -l $ncaddr"
  1446. fi
  1447. fi
  1448. _debug "_NC" "$_NC"
  1449. #for centos ncat
  1450. if _contains "$nchelp" "nmap.org"; then
  1451. _debug "Using ncat: nmap.org"
  1452. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"; then
  1453. _exec_err
  1454. return 1
  1455. fi
  1456. if [ "$DEBUG" ]; then
  1457. _exec_err
  1458. fi
  1459. return
  1460. fi
  1461. # while true ; do
  1462. if ! _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC -p \"$Le_HTTPPort\" >&2"; then
  1463. _exec "printf \"%s\r\n\r\n%s\" \"HTTP/1.1 200 OK\" \"$content\" | $_NC \"$Le_HTTPPort\" >&2"
  1464. fi
  1465. if [ "$?" != "0" ]; then
  1466. _err "nc listen error."
  1467. _exec_err
  1468. exit 1
  1469. fi
  1470. if [ "$DEBUG" ]; then
  1471. _exec_err
  1472. fi
  1473. # done
  1474. }
  1475. _stopserver() {
  1476. pid="$1"
  1477. _debug "pid" "$pid"
  1478. if [ -z "$pid" ]; then
  1479. return
  1480. fi
  1481. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  1482. if [ "$Le_HTTPPort" ]; then
  1483. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1484. _get "http://localhost:$Le_HTTPPort" "" 1
  1485. else
  1486. _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
  1487. fi
  1488. fi
  1489. _debug2 "Le_TLSPort" "$Le_TLSPort"
  1490. if [ "$Le_TLSPort" ]; then
  1491. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ]; then
  1492. _get "https://localhost:$Le_TLSPort" "" 1
  1493. _get "https://localhost:$Le_TLSPort" "" 1
  1494. else
  1495. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1496. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1497. fi
  1498. fi
  1499. }
  1500. # sleep sec
  1501. _sleep() {
  1502. _sleep_sec="$1"
  1503. if [ "$__INTERACTIVE" ]; then
  1504. _sleep_c="$_sleep_sec"
  1505. while [ "$_sleep_c" -ge "0" ]; do
  1506. printf "\r \r"
  1507. __green "$_sleep_c"
  1508. _sleep_c="$(_math "$_sleep_c" - 1)"
  1509. sleep 1
  1510. done
  1511. printf "\r"
  1512. else
  1513. sleep "$_sleep_sec"
  1514. fi
  1515. }
  1516. # _starttlsserver san_a san_b port content _ncaddr
  1517. _starttlsserver() {
  1518. _info "Starting tls server."
  1519. san_a="$1"
  1520. san_b="$2"
  1521. port="$3"
  1522. content="$4"
  1523. opaddr="$5"
  1524. _debug san_a "$san_a"
  1525. _debug san_b "$san_b"
  1526. _debug port "$port"
  1527. #create key TLS_KEY
  1528. if ! _createkey "2048" "$TLS_KEY"; then
  1529. _err "Create tls validation key error."
  1530. return 1
  1531. fi
  1532. #create csr
  1533. alt="$san_a"
  1534. if [ "$san_b" ]; then
  1535. alt="$alt,$san_b"
  1536. fi
  1537. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF"; then
  1538. _err "Create tls validation csr error."
  1539. return 1
  1540. fi
  1541. #self signed
  1542. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1543. _err "Create tls validation cert error."
  1544. return 1
  1545. fi
  1546. __S_OPENSSL="$OPENSSL_BIN s_server -cert $TLS_CERT -key $TLS_KEY "
  1547. if [ "$opaddr" ]; then
  1548. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1549. else
  1550. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1551. fi
  1552. _debug Le_Listen_V4 "$Le_Listen_V4"
  1553. _debug Le_Listen_V6 "$Le_Listen_V6"
  1554. if [ "$Le_Listen_V4" ]; then
  1555. __S_OPENSSL="$__S_OPENSSL -4"
  1556. elif [ "$Le_Listen_V6" ]; then
  1557. __S_OPENSSL="$__S_OPENSSL -6"
  1558. fi
  1559. _debug "$__S_OPENSSL"
  1560. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1561. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL -tlsextdebug) &
  1562. else
  1563. (printf "%s\r\n\r\n%s" "HTTP/1.1 200 OK" "$content" | $__S_OPENSSL >/dev/null 2>&1) &
  1564. fi
  1565. serverproc="$!"
  1566. sleep 1
  1567. _debug serverproc "$serverproc"
  1568. }
  1569. #file
  1570. _readlink() {
  1571. _rf="$1"
  1572. if ! readlink -f "$_rf" 2>/dev/null; then
  1573. if _startswith "$_rf" "\./$PROJECT_ENTRY"; then
  1574. printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
  1575. return 0
  1576. fi
  1577. readlink "$_rf"
  1578. fi
  1579. }
  1580. __initHome() {
  1581. if [ -z "$_SCRIPT_HOME" ]; then
  1582. if _exists readlink && _exists dirname; then
  1583. _debug "Lets find script dir."
  1584. _debug "_SCRIPT_" "$_SCRIPT_"
  1585. _script="$(_readlink "$_SCRIPT_")"
  1586. _debug "_script" "$_script"
  1587. _script_home="$(dirname "$_script")"
  1588. _debug "_script_home" "$_script_home"
  1589. if [ -d "$_script_home" ]; then
  1590. _SCRIPT_HOME="$_script_home"
  1591. else
  1592. _err "It seems the script home is not correct:$_script_home"
  1593. fi
  1594. fi
  1595. fi
  1596. # if [ -z "$LE_WORKING_DIR" ]; then
  1597. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1598. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1599. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1600. # else
  1601. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1602. # fi
  1603. # fi
  1604. if [ -z "$LE_WORKING_DIR" ]; then
  1605. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1606. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1607. fi
  1608. export LE_WORKING_DIR
  1609. if [ -z "$LE_CONFIG_HOME" ]; then
  1610. LE_CONFIG_HOME="$LE_WORKING_DIR"
  1611. fi
  1612. _debug "Using config home:$LE_CONFIG_HOME"
  1613. export LE_CONFIG_HOME
  1614. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  1615. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1616. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1617. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1618. fi
  1619. fi
  1620. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1621. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1622. fi
  1623. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  1624. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  1625. if [ -z "$LE_TEMP_DIR" ]; then
  1626. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  1627. fi
  1628. }
  1629. #[domain] [keylength]
  1630. _initpath() {
  1631. __initHome
  1632. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  1633. . "$ACCOUNT_CONF_PATH"
  1634. fi
  1635. if [ "$IN_CRON" ]; then
  1636. if [ ! "$_USER_PATH_EXPORTED" ]; then
  1637. _USER_PATH_EXPORTED=1
  1638. export PATH="$USER_PATH:$PATH"
  1639. fi
  1640. fi
  1641. if [ -z "$CA_HOME" ]; then
  1642. CA_HOME="$DEFAULT_CA_HOME"
  1643. fi
  1644. if [ -z "$API" ]; then
  1645. if [ -z "$STAGE" ]; then
  1646. API="$DEFAULT_CA"
  1647. else
  1648. API="$STAGE_CA"
  1649. _info "Using stage api:$API"
  1650. fi
  1651. fi
  1652. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1653. CA_DIR="$CA_HOME/$_API_HOST"
  1654. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1655. if [ -z "$CA_CONF" ]; then
  1656. CA_CONF="$_DEFAULT_CA_CONF"
  1657. fi
  1658. _debug3 CA_CONF "$CA_CONF"
  1659. if [ -f "$CA_CONF" ]; then
  1660. . "$CA_CONF"
  1661. fi
  1662. if [ -z "$ACME_DIR" ]; then
  1663. ACME_DIR="/home/.acme"
  1664. fi
  1665. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  1666. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  1667. fi
  1668. if [ -z "$USER_AGENT" ]; then
  1669. USER_AGENT="$DEFAULT_USER_AGENT"
  1670. fi
  1671. if [ -z "$HTTP_HEADER" ]; then
  1672. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  1673. fi
  1674. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1675. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1676. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1677. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1678. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  1679. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1680. fi
  1681. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  1682. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1683. fi
  1684. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  1685. if [ -z "$CERT_HOME" ]; then
  1686. CERT_HOME="$_DEFAULT_CERT_HOME"
  1687. fi
  1688. if [ -z "$OPENSSL_BIN" ]; then
  1689. OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  1690. fi
  1691. if [ -z "$1" ]; then
  1692. return 0
  1693. fi
  1694. domain="$1"
  1695. _ilength="$2"
  1696. if [ -z "$DOMAIN_PATH" ]; then
  1697. domainhome="$CERT_HOME/$domain"
  1698. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1699. DOMAIN_PATH="$domainhome"
  1700. if _isEccKey "$_ilength"; then
  1701. DOMAIN_PATH="$domainhomeecc"
  1702. else
  1703. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  1704. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1705. fi
  1706. fi
  1707. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1708. fi
  1709. if [ -z "$DOMAIN_CONF" ]; then
  1710. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1711. fi
  1712. if [ -z "$DOMAIN_SSL_CONF" ]; then
  1713. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1714. fi
  1715. if [ -z "$CSR_PATH" ]; then
  1716. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1717. fi
  1718. if [ -z "$CERT_KEY_PATH" ]; then
  1719. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1720. fi
  1721. if [ -z "$CERT_PATH" ]; then
  1722. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1723. fi
  1724. if [ -z "$CA_CERT_PATH" ]; then
  1725. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1726. fi
  1727. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  1728. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1729. fi
  1730. if [ -z "$CERT_PFX_PATH" ]; then
  1731. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1732. fi
  1733. if [ -z "$TLS_CONF" ]; then
  1734. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1735. fi
  1736. if [ -z "$TLS_CERT" ]; then
  1737. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1738. fi
  1739. if [ -z "$TLS_KEY" ]; then
  1740. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1741. fi
  1742. if [ -z "$TLS_CSR" ]; then
  1743. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1744. fi
  1745. }
  1746. _exec() {
  1747. if [ -z "$_EXEC_TEMP_ERR" ]; then
  1748. _EXEC_TEMP_ERR="$(_mktemp)"
  1749. fi
  1750. if [ "$_EXEC_TEMP_ERR" ]; then
  1751. eval "$@ 2>>$_EXEC_TEMP_ERR"
  1752. else
  1753. eval "$@"
  1754. fi
  1755. }
  1756. _exec_err() {
  1757. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  1758. }
  1759. _apachePath() {
  1760. _APACHECTL="apachectl"
  1761. if ! _exists apachectl; then
  1762. if _exists apache2ctl; then
  1763. _APACHECTL="apache2ctl"
  1764. else
  1765. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1766. _err "Please use webroot mode to try again."
  1767. return 1
  1768. fi
  1769. fi
  1770. if ! _exec $_APACHECTL -V >/dev/null; then
  1771. _exec_err
  1772. return 1
  1773. fi
  1774. if [ "$APACHE_HTTPD_CONF" ]; then
  1775. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  1776. httpdconf="$APACHE_HTTPD_CONF"
  1777. httpdconfname="$(basename "$httpdconfname")"
  1778. else
  1779. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  1780. _debug httpdconfname "$httpdconfname"
  1781. if [ -z "$httpdconfname" ]; then
  1782. _err "Can not read apache config file."
  1783. return 1
  1784. fi
  1785. if _startswith "$httpdconfname" '/'; then
  1786. httpdconf="$httpdconfname"
  1787. httpdconfname="$(basename "$httpdconfname")"
  1788. else
  1789. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  1790. _debug httpdroot "$httpdroot"
  1791. httpdconf="$httpdroot/$httpdconfname"
  1792. httpdconfname="$(basename "$httpdconfname")"
  1793. fi
  1794. fi
  1795. _debug httpdconf "$httpdconf"
  1796. _debug httpdconfname "$httpdconfname"
  1797. if [ ! -f "$httpdconf" ]; then
  1798. _err "Apache Config file not found" "$httpdconf"
  1799. return 1
  1800. fi
  1801. return 0
  1802. }
  1803. _restoreApache() {
  1804. if [ -z "$usingApache" ]; then
  1805. return 0
  1806. fi
  1807. _initpath
  1808. if ! _apachePath; then
  1809. return 1
  1810. fi
  1811. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  1812. _debug "No config file to restore."
  1813. return 0
  1814. fi
  1815. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  1816. _debug "Restored: $httpdconf."
  1817. if ! _exec $_APACHECTL -t; then
  1818. _exec_err
  1819. _err "Sorry, restore apache config error, please contact me."
  1820. return 1
  1821. fi
  1822. _debug "Restored successfully."
  1823. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1824. return 0
  1825. }
  1826. _setApache() {
  1827. _initpath
  1828. if ! _apachePath; then
  1829. return 1
  1830. fi
  1831. #test the conf first
  1832. _info "Checking if there is an error in the apache config file before starting."
  1833. if ! _exec "$_APACHECTL" -t >/dev/null; then
  1834. _exec_err
  1835. _err "The apache config file has error, please fix it first, then try again."
  1836. _err "Don't worry, there is nothing changed to your system."
  1837. return 1
  1838. else
  1839. _info "OK"
  1840. fi
  1841. #backup the conf
  1842. _debug "Backup apache config file" "$httpdconf"
  1843. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  1844. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1845. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1846. return 1
  1847. fi
  1848. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1849. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1850. _info "The backup file will be deleted on success, just forget it."
  1851. #add alias
  1852. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  1853. _debug "apacheVer" "$apacheVer"
  1854. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1855. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1856. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  1857. echo "
  1858. Alias /.well-known/acme-challenge $ACME_DIR
  1859. <Directory $ACME_DIR >
  1860. Require all granted
  1861. </Directory>
  1862. " >>"$httpdconf"
  1863. else
  1864. echo "
  1865. Alias /.well-known/acme-challenge $ACME_DIR
  1866. <Directory $ACME_DIR >
  1867. Order allow,deny
  1868. Allow from all
  1869. </Directory>
  1870. " >>"$httpdconf"
  1871. fi
  1872. _msg="$($_APACHECTL -t 2>&1)"
  1873. if [ "$?" != "0" ]; then
  1874. _err "Sorry, apache config error"
  1875. if _restoreApache; then
  1876. _err "The apache config file is restored."
  1877. else
  1878. _err "Sorry, The apache config file can not be restored, please report bug."
  1879. fi
  1880. return 1
  1881. fi
  1882. if [ ! -d "$ACME_DIR" ]; then
  1883. mkdir -p "$ACME_DIR"
  1884. chmod 755 "$ACME_DIR"
  1885. fi
  1886. if ! _exec "$_APACHECTL" graceful; then
  1887. _exec_err
  1888. _err "$_APACHECTL graceful error, please contact me."
  1889. _restoreApache
  1890. return 1
  1891. fi
  1892. usingApache="1"
  1893. return 0
  1894. }
  1895. _clearup() {
  1896. _stopserver "$serverproc"
  1897. serverproc=""
  1898. _restoreApache
  1899. _clearupdns
  1900. if [ -z "$DEBUG" ]; then
  1901. rm -f "$TLS_CONF"
  1902. rm -f "$TLS_CERT"
  1903. rm -f "$TLS_KEY"
  1904. rm -f "$TLS_CSR"
  1905. fi
  1906. }
  1907. _clearupdns() {
  1908. _debug "_clearupdns"
  1909. if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
  1910. _debug "Dns not added, skip."
  1911. return
  1912. fi
  1913. ventries=$(echo "$vlist" | tr ',' ' ')
  1914. for ventry in $ventries; do
  1915. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  1916. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  1917. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  1918. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  1919. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  1920. _debug txt "$txt"
  1921. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  1922. _info "$d is already verified, skip $vtype."
  1923. continue
  1924. fi
  1925. if [ "$vtype" != "$VTYPE_DNS" ]; then
  1926. _info "Skip $d for $vtype"
  1927. continue
  1928. fi
  1929. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  1930. _debug d_api "$d_api"
  1931. if [ -z "$d_api" ]; then
  1932. _info "Not Found domain api file: $d_api"
  1933. continue
  1934. fi
  1935. (
  1936. if ! . "$d_api"; then
  1937. _err "Load file $d_api error. Please check your api file and try again."
  1938. return 1
  1939. fi
  1940. rmcommand="${_currentRoot}_rm"
  1941. if ! _exists "$rmcommand"; then
  1942. _err "It seems that your api file doesn't define $rmcommand"
  1943. return 1
  1944. fi
  1945. txtdomain="_acme-challenge.$d"
  1946. if ! $rmcommand "$txtdomain" "$txt"; then
  1947. _err "Error removing txt for domain:$txtdomain"
  1948. return 1
  1949. fi
  1950. )
  1951. done
  1952. }
  1953. # webroot removelevel tokenfile
  1954. _clearupwebbroot() {
  1955. __webroot="$1"
  1956. if [ -z "$__webroot" ]; then
  1957. _debug "no webroot specified, skip"
  1958. return 0
  1959. fi
  1960. _rmpath=""
  1961. if [ "$2" = '1' ]; then
  1962. _rmpath="$__webroot/.well-known"
  1963. elif [ "$2" = '2' ]; then
  1964. _rmpath="$__webroot/.well-known/acme-challenge"
  1965. elif [ "$2" = '3' ]; then
  1966. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1967. else
  1968. _debug "Skip for removelevel:$2"
  1969. fi
  1970. if [ "$_rmpath" ]; then
  1971. if [ "$DEBUG" ]; then
  1972. _debug "Debugging, skip removing: $_rmpath"
  1973. else
  1974. rm -rf "$_rmpath"
  1975. fi
  1976. fi
  1977. return 0
  1978. }
  1979. _on_before_issue() {
  1980. _debug _on_before_issue
  1981. #run pre hook
  1982. if [ "$Le_PreHook" ]; then
  1983. _info "Run pre hook:'$Le_PreHook'"
  1984. if ! (
  1985. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1986. ); then
  1987. _err "Error when run pre hook."
  1988. return 1
  1989. fi
  1990. fi
  1991. if _hasfield "$Le_Webroot" "$NO_VALUE"; then
  1992. if ! _exists "nc"; then
  1993. _err "Please install netcat(nc) tools first."
  1994. return 1
  1995. fi
  1996. fi
  1997. _debug Le_LocalAddress "$Le_LocalAddress"
  1998. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  1999. _index=1
  2000. _currentRoot=""
  2001. _addrIndex=1
  2002. for d in $alldomains; do
  2003. _debug "Check for domain" "$d"
  2004. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  2005. _debug "_currentRoot" "$_currentRoot"
  2006. _index=$(_math $_index + 1)
  2007. _checkport=""
  2008. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2009. _info "Standalone mode."
  2010. if [ -z "$Le_HTTPPort" ]; then
  2011. Le_HTTPPort=80
  2012. else
  2013. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  2014. fi
  2015. _checkport="$Le_HTTPPort"
  2016. elif [ "$_currentRoot" = "$W_TLS" ]; then
  2017. _info "Standalone tls mode."
  2018. if [ -z "$Le_TLSPort" ]; then
  2019. Le_TLSPort=443
  2020. else
  2021. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  2022. fi
  2023. _checkport="$Le_TLSPort"
  2024. fi
  2025. if [ "$_checkport" ]; then
  2026. _debug _checkport "$_checkport"
  2027. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  2028. _debug _checkaddr "$_checkaddr"
  2029. _addrIndex="$(_math $_addrIndex + 1)"
  2030. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  2031. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  2032. if [ -z "$netprc" ]; then
  2033. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  2034. fi
  2035. if [ "$netprc" ]; then
  2036. _err "$netprc"
  2037. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  2038. _err "Please stop it first"
  2039. return 1
  2040. fi
  2041. fi
  2042. done
  2043. if _hasfield "$Le_Webroot" "apache"; then
  2044. if ! _setApache; then
  2045. _err "set up apache error. Report error to me."
  2046. return 1
  2047. fi
  2048. else
  2049. usingApache=""
  2050. fi
  2051. }
  2052. _on_issue_err() {
  2053. _debug _on_issue_err
  2054. if [ "$LOG_FILE" ]; then
  2055. _err "Please check log file for more details: $LOG_FILE"
  2056. else
  2057. _err "Please add '--debug' or '--log' to check more details."
  2058. _err "See: $_DEBUG_WIKI"
  2059. fi
  2060. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  2061. _debug "$(_dlg_versions)"
  2062. fi
  2063. #run the post hook
  2064. if [ "$Le_PostHook" ]; then
  2065. _info "Run post hook:'$Le_PostHook'"
  2066. if ! (
  2067. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  2068. ); then
  2069. _err "Error when run post hook."
  2070. return 1
  2071. fi
  2072. fi
  2073. }
  2074. _on_issue_success() {
  2075. _debug _on_issue_success
  2076. #run the post hook
  2077. if [ "$Le_PostHook" ]; then
  2078. _info "Run post hook:'$Le_PostHook'"
  2079. if ! (
  2080. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  2081. ); then
  2082. _err "Error when run post hook."
  2083. return 1
  2084. fi
  2085. fi
  2086. #run renew hook
  2087. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ]; then
  2088. _info "Run renew hook:'$Le_RenewHook'"
  2089. if ! (
  2090. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  2091. ); then
  2092. _err "Error when run renew hook."
  2093. return 1
  2094. fi
  2095. fi
  2096. }
  2097. updateaccount() {
  2098. _initpath
  2099. _regAccount
  2100. }
  2101. registeraccount() {
  2102. _reg_length="$1"
  2103. _initpath
  2104. _regAccount "$_reg_length"
  2105. }
  2106. __calcAccountKeyHash() {
  2107. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  2108. }
  2109. #keylength
  2110. _regAccount() {
  2111. _initpath
  2112. _reg_length="$1"
  2113. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2114. mkdir -p "$CA_DIR"
  2115. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2116. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2117. fi
  2118. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2119. mkdir -p "$CA_DIR"
  2120. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2121. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2122. fi
  2123. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2124. if ! _create_account_key "$_reg_length"; then
  2125. _err "Create account key error."
  2126. return 1
  2127. fi
  2128. fi
  2129. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2130. return 1
  2131. fi
  2132. _updateTos=""
  2133. _reg_res="new-reg"
  2134. while true; do
  2135. _debug AGREEMENT "$AGREEMENT"
  2136. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  2137. if [ "$ACCOUNT_EMAIL" ]; then
  2138. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  2139. fi
  2140. if [ -z "$_updateTos" ]; then
  2141. _info "Registering account"
  2142. if ! _send_signed_request "$API/acme/new-reg" "$regjson"; then
  2143. _err "Register account Error: $response"
  2144. return 1
  2145. fi
  2146. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  2147. echo "$response" >"$ACCOUNT_JSON_PATH"
  2148. _info "Registered"
  2149. elif [ "$code" = '409' ]; then
  2150. _info "Already registered"
  2151. else
  2152. _err "Register account Error: $response"
  2153. return 1
  2154. fi
  2155. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2156. _debug "_accUri" "$_accUri"
  2157. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  2158. _debug "_tos" "$_tos"
  2159. if [ -z "$_tos" ]; then
  2160. _debug "Use default tos: $DEFAULT_AGREEMENT"
  2161. _tos="$DEFAULT_AGREEMENT"
  2162. fi
  2163. if [ "$_tos" != "$AGREEMENT" ]; then
  2164. _updateTos=1
  2165. AGREEMENT="$_tos"
  2166. _reg_res="reg"
  2167. continue
  2168. fi
  2169. else
  2170. _debug "Update tos: $_tos"
  2171. if ! _send_signed_request "$_accUri" "$regjson"; then
  2172. _err "Update tos error."
  2173. return 1
  2174. fi
  2175. if [ "$code" = '202' ]; then
  2176. _info "Update success."
  2177. CA_KEY_HASH="$(__calcAccountKeyHash)"
  2178. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  2179. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  2180. else
  2181. _err "Update account error."
  2182. return 1
  2183. fi
  2184. fi
  2185. return 0
  2186. done
  2187. }
  2188. # domain folder file
  2189. _findHook() {
  2190. _hookdomain="$1"
  2191. _hookcat="$2"
  2192. _hookname="$3"
  2193. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  2194. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  2195. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  2196. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  2197. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  2198. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  2199. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  2200. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  2201. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  2202. d_api="$LE_WORKING_DIR/$_hookname"
  2203. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  2204. d_api="$LE_WORKING_DIR/$_hookname.sh"
  2205. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  2206. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  2207. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  2208. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  2209. fi
  2210. printf "%s" "$d_api"
  2211. }
  2212. #domain
  2213. __get_domain_new_authz() {
  2214. _gdnd="$1"
  2215. _info "Getting new-authz for domain" "$_gdnd"
  2216. _Max_new_authz_retry_times=5
  2217. _authz_i=0
  2218. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  2219. _debug "Try new-authz for the $_authz_i time."
  2220. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  2221. _err "Can not get domain new authz."
  2222. return 1
  2223. fi
  2224. if _contains "$response" "No registration exists matching provided key"; then
  2225. _err "It seems there is an error, but it's recovered now, please try again."
  2226. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  2227. _clearcaconf "CA_KEY_HASH"
  2228. break
  2229. fi
  2230. if ! _contains "$response" "An error occurred while processing your request"; then
  2231. _info "The new-authz request is ok."
  2232. break
  2233. fi
  2234. _authz_i="$(_math "$_authz_i" + 1)"
  2235. _info "The server is busy, Sleep $_authz_i to retry."
  2236. _sleep "$_authz_i"
  2237. done
  2238. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  2239. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2240. fi
  2241. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2242. _err "new-authz error: $response"
  2243. return 1
  2244. fi
  2245. }
  2246. #webroot, domain domainlist keylength
  2247. issue() {
  2248. if [ -z "$2" ]; then
  2249. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2250. return 1
  2251. fi
  2252. Le_Webroot="$1"
  2253. Le_Domain="$2"
  2254. Le_Alt="$3"
  2255. if _contains "$Le_Domain" ","; then
  2256. Le_Domain=$(echo "$2,$3" | cut -d , -f 1)
  2257. Le_Alt=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  2258. fi
  2259. Le_Keylength="$4"
  2260. Le_RealCertPath="$5"
  2261. Le_RealKeyPath="$6"
  2262. Le_RealCACertPath="$7"
  2263. Le_ReloadCmd="$8"
  2264. Le_RealFullChainPath="$9"
  2265. Le_PreHook="${10}"
  2266. Le_PostHook="${11}"
  2267. Le_RenewHook="${12}"
  2268. Le_LocalAddress="${13}"
  2269. #remove these later.
  2270. if [ "$Le_Webroot" = "dns-cf" ]; then
  2271. Le_Webroot="dns_cf"
  2272. fi
  2273. if [ "$Le_Webroot" = "dns-dp" ]; then
  2274. Le_Webroot="dns_dp"
  2275. fi
  2276. if [ "$Le_Webroot" = "dns-cx" ]; then
  2277. Le_Webroot="dns_cx"
  2278. fi
  2279. _debug "Using api: $API"
  2280. if [ ! "$IS_RENEW" ]; then
  2281. _initpath "$Le_Domain" "$Le_Keylength"
  2282. mkdir -p "$DOMAIN_PATH"
  2283. fi
  2284. if [ -f "$DOMAIN_CONF" ]; then
  2285. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  2286. _debug Le_NextRenewTime "$Le_NextRenewTime"
  2287. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2288. _saved_domain=$(_readdomainconf Le_Domain)
  2289. _debug _saved_domain "$_saved_domain"
  2290. _saved_alt=$(_readdomainconf Le_Alt)
  2291. _debug _saved_alt "$_saved_alt"
  2292. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ]; then
  2293. _info "Domains not changed."
  2294. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  2295. _info "Add '$(__red '--force')' to force to renew."
  2296. return $RENEW_SKIP
  2297. else
  2298. _info "Domains have changed."
  2299. fi
  2300. fi
  2301. fi
  2302. _savedomainconf "Le_Domain" "$Le_Domain"
  2303. _savedomainconf "Le_Alt" "$Le_Alt"
  2304. _savedomainconf "Le_Webroot" "$Le_Webroot"
  2305. _savedomainconf "Le_PreHook" "$Le_PreHook"
  2306. _savedomainconf "Le_PostHook" "$Le_PostHook"
  2307. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  2308. if [ "$Le_LocalAddress" ]; then
  2309. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  2310. else
  2311. _cleardomainconf "Le_LocalAddress"
  2312. fi
  2313. Le_API="$API"
  2314. _savedomainconf "Le_API" "$Le_API"
  2315. if [ "$Le_Alt" = "$NO_VALUE" ]; then
  2316. Le_Alt=""
  2317. fi
  2318. if [ "$Le_Keylength" = "$NO_VALUE" ]; then
  2319. Le_Keylength=""
  2320. fi
  2321. if ! _on_before_issue; then
  2322. _err "_on_before_issue."
  2323. return 1
  2324. fi
  2325. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  2326. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  2327. if [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  2328. if ! _regAccount "$_accountkeylength"; then
  2329. _on_issue_err
  2330. return 1
  2331. fi
  2332. else
  2333. _debug "_saved_account_key_hash is not changed, skip register account."
  2334. fi
  2335. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  2336. _info "Signing from existing CSR."
  2337. else
  2338. _key=$(_readdomainconf Le_Keylength)
  2339. _debug "Read key length:$_key"
  2340. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ]; then
  2341. if ! createDomainKey "$Le_Domain" "$Le_Keylength"; then
  2342. _err "Create domain key error."
  2343. _clearup
  2344. _on_issue_err
  2345. return 1
  2346. fi
  2347. fi
  2348. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  2349. _err "Create CSR error."
  2350. _clearup
  2351. _on_issue_err
  2352. return 1
  2353. fi
  2354. fi
  2355. _savedomainconf "Le_Keylength" "$Le_Keylength"
  2356. vlist="$Le_Vlist"
  2357. _info "Getting domain auth token for each domain"
  2358. sep='#'
  2359. if [ -z "$vlist" ]; then
  2360. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ')
  2361. _index=1
  2362. _currentRoot=""
  2363. for d in $alldomains; do
  2364. _info "Getting webroot for domain" "$d"
  2365. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  2366. _info _w "$_w"
  2367. if [ "$_w" ]; then
  2368. _currentRoot="$_w"
  2369. fi
  2370. _debug "_currentRoot" "$_currentRoot"
  2371. _index=$(_math $_index + 1)
  2372. vtype="$VTYPE_HTTP"
  2373. if _startswith "$_currentRoot" "dns"; then
  2374. vtype="$VTYPE_DNS"
  2375. fi
  2376. if [ "$_currentRoot" = "$W_TLS" ]; then
  2377. vtype="$VTYPE_TLS"
  2378. fi
  2379. if ! __get_domain_new_authz "$d"; then
  2380. _clearup
  2381. _on_issue_err
  2382. return 1
  2383. fi
  2384. if [ -z "$thumbprint" ]; then
  2385. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ')
  2386. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _url_replace)
  2387. fi
  2388. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  2389. _debug entry "$entry"
  2390. if [ -z "$entry" ]; then
  2391. _err "Error, can not get domain token $d"
  2392. _clearup
  2393. _on_issue_err
  2394. return 1
  2395. fi
  2396. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  2397. _debug token "$token"
  2398. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  2399. _debug uri "$uri"
  2400. keyauthorization="$token.$thumbprint"
  2401. _debug keyauthorization "$keyauthorization"
  2402. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  2403. _info "$d is already verified, skip."
  2404. keyauthorization="$STATE_VERIFIED"
  2405. _debug keyauthorization "$keyauthorization"
  2406. fi
  2407. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  2408. _debug dvlist "$dvlist"
  2409. vlist="$vlist$dvlist,"
  2410. done
  2411. #add entry
  2412. dnsadded=""
  2413. ventries=$(echo "$vlist" | tr ',' ' ')
  2414. for ventry in $ventries; do
  2415. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2416. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2417. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2418. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2419. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2420. _info "$d is already verified, skip $vtype."
  2421. continue
  2422. fi
  2423. if [ "$vtype" = "$VTYPE_DNS" ]; then
  2424. dnsadded='0'
  2425. txtdomain="_acme-challenge.$d"
  2426. _debug txtdomain "$txtdomain"
  2427. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  2428. _debug txt "$txt"
  2429. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2430. _debug d_api "$d_api"
  2431. if [ "$d_api" ]; then
  2432. _info "Found domain api file: $d_api"
  2433. else
  2434. _err "Add the following TXT record:"
  2435. _err "Domain: '$(__green "$txtdomain")'"
  2436. _err "TXT value: '$(__green "$txt")'"
  2437. _err "Please be aware that you prepend _acme-challenge. before your domain"
  2438. _err "so the resulting subdomain will be: $txtdomain"
  2439. continue
  2440. fi
  2441. (
  2442. if ! . "$d_api"; then
  2443. _err "Load file $d_api error. Please check your api file and try again."
  2444. return 1
  2445. fi
  2446. addcommand="${_currentRoot}_add"
  2447. if ! _exists "$addcommand"; then
  2448. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  2449. return 1
  2450. fi
  2451. if ! $addcommand "$txtdomain" "$txt"; then
  2452. _err "Error add txt for domain:$txtdomain"
  2453. return 1
  2454. fi
  2455. )
  2456. if [ "$?" != "0" ]; then
  2457. _clearup
  2458. _on_issue_err
  2459. return 1
  2460. fi
  2461. dnsadded='1'
  2462. fi
  2463. done
  2464. if [ "$dnsadded" = '0' ]; then
  2465. _savedomainconf "Le_Vlist" "$vlist"
  2466. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  2467. _err "Please add the TXT records to the domains, and retry again."
  2468. _clearup
  2469. _on_issue_err
  2470. return 1
  2471. fi
  2472. fi
  2473. if [ "$dnsadded" = '1' ]; then
  2474. if [ -z "$Le_DNSSleep" ]; then
  2475. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  2476. else
  2477. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  2478. fi
  2479. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  2480. _sleep "$Le_DNSSleep"
  2481. fi
  2482. _debug "ok, let's start to verify"
  2483. _ncIndex=1
  2484. ventries=$(echo "$vlist" | tr ',' ' ')
  2485. for ventry in $ventries; do
  2486. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2487. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2488. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2489. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2490. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2491. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2492. _info "$d is already verified, skip $vtype."
  2493. continue
  2494. fi
  2495. _info "Verifying:$d"
  2496. _debug "d" "$d"
  2497. _debug "keyauthorization" "$keyauthorization"
  2498. _debug "uri" "$uri"
  2499. removelevel=""
  2500. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  2501. _debug "_currentRoot" "$_currentRoot"
  2502. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2503. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2504. _info "Standalone mode server"
  2505. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2506. _ncIndex="$(_math $_ncIndex + 1)"
  2507. _startserver "$keyauthorization" "$_ncaddr" &
  2508. if [ "$?" != "0" ]; then
  2509. _clearup
  2510. _on_issue_err
  2511. return 1
  2512. fi
  2513. serverproc="$!"
  2514. sleep 1
  2515. _debug serverproc "$serverproc"
  2516. else
  2517. if [ "$_currentRoot" = "apache" ]; then
  2518. wellknown_path="$ACME_DIR"
  2519. else
  2520. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  2521. if [ ! -d "$_currentRoot/.well-known" ]; then
  2522. removelevel='1'
  2523. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  2524. removelevel='2'
  2525. else
  2526. removelevel='3'
  2527. fi
  2528. fi
  2529. _debug wellknown_path "$wellknown_path"
  2530. _debug "writing token:$token to $wellknown_path/$token"
  2531. mkdir -p "$wellknown_path"
  2532. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  2533. _err "$d:Can not write token to file : $wellknown_path/$token"
  2534. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2535. _clearup
  2536. _on_issue_err
  2537. return 1
  2538. fi
  2539. if [ ! "$usingApache" ]; then
  2540. if webroot_owner=$(_stat "$_currentRoot"); then
  2541. _debug "Changing owner/group of .well-known to $webroot_owner"
  2542. chown -R "$webroot_owner" "$_currentRoot/.well-known"
  2543. else
  2544. _debug "not chaning owner/group of webroot"
  2545. fi
  2546. fi
  2547. fi
  2548. elif [ "$vtype" = "$VTYPE_TLS" ]; then
  2549. #create A
  2550. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  2551. #_debug2 _hash_A "$_hash_A"
  2552. #_x="$(echo $_hash_A | cut -c 1-32)"
  2553. #_debug2 _x "$_x"
  2554. #_y="$(echo $_hash_A | cut -c 33-64)"
  2555. #_debug2 _y "$_y"
  2556. #_SAN_A="$_x.$_y.token.acme.invalid"
  2557. #_debug2 _SAN_A "$_SAN_A"
  2558. #create B
  2559. _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  2560. _debug2 _hash_B "$_hash_B"
  2561. _x="$(echo "$_hash_B" | cut -c 1-32)"
  2562. _debug2 _x "$_x"
  2563. _y="$(echo "$_hash_B" | cut -c 33-64)"
  2564. _debug2 _y "$_y"
  2565. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2566. _SAN_B="$_x.$_y.acme.invalid"
  2567. _debug2 _SAN_B "$_SAN_B"
  2568. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex")"
  2569. _ncIndex="$(_math "$_ncIndex" + 1)"
  2570. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2571. _err "Start tls server error."
  2572. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2573. _clearup
  2574. _on_issue_err
  2575. return 1
  2576. fi
  2577. fi
  2578. if ! _send_signed_request "$uri" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"; then
  2579. _err "$d:Can not get challenge: $response"
  2580. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2581. _clearup
  2582. _on_issue_err
  2583. return 1
  2584. fi
  2585. if [ ! -z "$code" ] && [ ! "$code" = '202' ]; then
  2586. _err "$d:Challenge error: $response"
  2587. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2588. _clearup
  2589. _on_issue_err
  2590. return 1
  2591. fi
  2592. waittimes=0
  2593. if [ -z "$MAX_RETRY_TIMES" ]; then
  2594. MAX_RETRY_TIMES=30
  2595. fi
  2596. while true; do
  2597. waittimes=$(_math "$waittimes" + 1)
  2598. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  2599. _err "$d:Timeout"
  2600. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2601. _clearup
  2602. _on_issue_err
  2603. return 1
  2604. fi
  2605. _debug "sleep 2 secs to verify"
  2606. sleep 2
  2607. _debug "checking"
  2608. response="$(_get "$uri")"
  2609. if [ "$?" != "0" ]; then
  2610. _err "$d:Verify error:$response"
  2611. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2612. _clearup
  2613. _on_issue_err
  2614. return 1
  2615. fi
  2616. _debug2 original "$response"
  2617. response="$(echo "$response" | _normalizeJson)"
  2618. _debug2 response "$response"
  2619. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2620. if [ "$status" = "valid" ]; then
  2621. _info "$(__green Success)"
  2622. _stopserver "$serverproc"
  2623. serverproc=""
  2624. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2625. break
  2626. fi
  2627. if [ "$status" = "invalid" ]; then
  2628. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  2629. _debug2 error "$error"
  2630. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  2631. _debug2 errordetail "$errordetail"
  2632. if [ "$errordetail" ]; then
  2633. _err "$d:Verify error:$errordetail"
  2634. else
  2635. _err "$d:Verify error:$error"
  2636. fi
  2637. if [ "$DEBUG" ]; then
  2638. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  2639. _debug "Debug: get token url."
  2640. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  2641. fi
  2642. fi
  2643. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2644. _clearup
  2645. _on_issue_err
  2646. return 1
  2647. fi
  2648. if [ "$status" = "pending" ]; then
  2649. _info "Pending"
  2650. else
  2651. _err "$d:Verify error:$response"
  2652. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2653. _clearup
  2654. _on_issue_err
  2655. return 1
  2656. fi
  2657. done
  2658. done
  2659. _clearup
  2660. _info "Verify finished, start to sign."
  2661. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
  2662. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"; then
  2663. _err "Sign failed."
  2664. _on_issue_err
  2665. return 1
  2666. fi
  2667. _rcert="$response"
  2668. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2669. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2670. if [ "$Le_LinkCert" ]; then
  2671. echo "$BEGIN_CERT" >"$CERT_PATH"
  2672. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2673. # _debug "Get cert failed. Let's try last response."
  2674. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2675. #fi
  2676. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  2677. _debug "Try cert link."
  2678. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  2679. fi
  2680. echo "$END_CERT" >>"$CERT_PATH"
  2681. _info "$(__green "Cert success.")"
  2682. cat "$CERT_PATH"
  2683. _info "Your cert is in $(__green " $CERT_PATH ")"
  2684. if [ -f "$CERT_KEY_PATH" ]; then
  2685. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  2686. fi
  2687. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2688. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  2689. USER_PATH="$PATH"
  2690. _saveaccountconf "USER_PATH" "$USER_PATH"
  2691. fi
  2692. fi
  2693. if [ -z "$Le_LinkCert" ]; then
  2694. response="$(echo "$response" | _dbase64 "multiline" | _normalizeJson)"
  2695. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2696. _on_issue_err
  2697. return 1
  2698. fi
  2699. _cleardomainconf "Le_Vlist"
  2700. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  2701. if ! _contains "$Le_LinkIssuer" ":"; then
  2702. Le_LinkIssuer="$API$Le_LinkIssuer"
  2703. fi
  2704. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2705. if [ "$Le_LinkIssuer" ]; then
  2706. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  2707. _get "$Le_LinkIssuer" | _base64 "multiline" >>"$CA_CERT_PATH"
  2708. echo "$END_CERT" >>"$CA_CERT_PATH"
  2709. _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  2710. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  2711. _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  2712. fi
  2713. Le_CertCreateTime=$(_time)
  2714. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2715. Le_CertCreateTimeStr=$(date -u)
  2716. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2717. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
  2718. Le_RenewalDays="$MAX_RENEW"
  2719. else
  2720. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2721. fi
  2722. if [ "$CA_BUNDLE" ]; then
  2723. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2724. else
  2725. _clearaccountconf "CA_BUNDLE"
  2726. fi
  2727. if [ "$HTTPS_INSECURE" ]; then
  2728. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2729. else
  2730. _clearaccountconf "HTTPS_INSECURE"
  2731. fi
  2732. if [ "$Le_Listen_V4" ]; then
  2733. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2734. _cleardomainconf Le_Listen_V6
  2735. elif [ "$Le_Listen_V6" ]; then
  2736. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2737. _cleardomainconf Le_Listen_V4
  2738. fi
  2739. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  2740. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  2741. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2742. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  2743. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2744. _on_issue_success
  2745. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ]; then
  2746. _installcert
  2747. fi
  2748. }
  2749. #domain [isEcc]
  2750. renew() {
  2751. Le_Domain="$1"
  2752. if [ -z "$Le_Domain" ]; then
  2753. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2754. return 1
  2755. fi
  2756. _isEcc="$2"
  2757. _initpath "$Le_Domain" "$_isEcc"
  2758. _info "$(__green "Renew: '$Le_Domain'")"
  2759. if [ ! -f "$DOMAIN_CONF" ]; then
  2760. _info "'$Le_Domain' is not a issued domain, skip."
  2761. return 0
  2762. fi
  2763. if [ "$Le_RenewalDays" ]; then
  2764. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2765. fi
  2766. . "$DOMAIN_CONF"
  2767. if [ "$Le_API" ]; then
  2768. API="$Le_API"
  2769. #reload ca configs
  2770. ACCOUNT_KEY_PATH=""
  2771. ACCOUNT_JSON_PATH=""
  2772. CA_CONF=""
  2773. _debug3 "initpath again."
  2774. _initpath "$Le_Domain" "$_isEcc"
  2775. fi
  2776. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2777. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2778. _info "Add '$(__red '--force')' to force to renew."
  2779. return "$RENEW_SKIP"
  2780. fi
  2781. IS_RENEW="1"
  2782. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress"
  2783. res="$?"
  2784. if [ "$res" != "0" ]; then
  2785. return "$res"
  2786. fi
  2787. if [ "$Le_DeployHook" ]; then
  2788. deploy "$Le_Domain" "$Le_DeployHook" "$Le_Keylength"
  2789. res="$?"
  2790. fi
  2791. IS_RENEW=""
  2792. return "$res"
  2793. }
  2794. #renewAll [stopRenewOnError]
  2795. renewAll() {
  2796. _initpath
  2797. _stopRenewOnError="$1"
  2798. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2799. _ret="0"
  2800. for di in "${CERT_HOME}"/*.*/; do
  2801. _debug di "$di"
  2802. if ! [ -d "$di" ]; then
  2803. _debug "Not directory, skip: $di"
  2804. continue
  2805. fi
  2806. d=$(basename "$di")
  2807. _debug d "$d"
  2808. (
  2809. if _endswith "$d" "$ECC_SUFFIX"; then
  2810. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2811. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2812. fi
  2813. renew "$d" "$_isEcc"
  2814. )
  2815. rc="$?"
  2816. _debug "Return code: $rc"
  2817. if [ "$rc" != "0" ]; then
  2818. if [ "$rc" = "$RENEW_SKIP" ]; then
  2819. _info "Skipped $d"
  2820. elif [ "$_stopRenewOnError" ]; then
  2821. _err "Error renew $d, stop now."
  2822. return "$rc"
  2823. else
  2824. _ret="$rc"
  2825. _err "Error renew $d, Go ahead to next one."
  2826. fi
  2827. fi
  2828. done
  2829. return "$_ret"
  2830. }
  2831. #csr webroot
  2832. signcsr() {
  2833. _csrfile="$1"
  2834. _csrW="$2"
  2835. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2836. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2837. return 1
  2838. fi
  2839. _initpath
  2840. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2841. if [ "$?" != "0" ]; then
  2842. _err "Can not read subject from csr: $_csrfile"
  2843. return 1
  2844. fi
  2845. _debug _csrsubj "$_csrsubj"
  2846. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2847. if [ "$?" != "0" ]; then
  2848. _err "Can not read domain list from csr: $_csrfile"
  2849. return 1
  2850. fi
  2851. _debug "_csrdomainlist" "$_csrdomainlist"
  2852. if [ -z "$_csrsubj" ]; then
  2853. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2854. _debug _csrsubj "$_csrsubj"
  2855. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2856. _debug "_csrdomainlist" "$_csrdomainlist"
  2857. fi
  2858. if [ -z "$_csrsubj" ]; then
  2859. _err "Can not read subject from csr: $_csrfile"
  2860. return 1
  2861. fi
  2862. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2863. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2864. _err "Can not read key length from csr: $_csrfile"
  2865. return 1
  2866. fi
  2867. _initpath "$_csrsubj" "$_csrkeylength"
  2868. mkdir -p "$DOMAIN_PATH"
  2869. _info "Copy csr to: $CSR_PATH"
  2870. cp "$_csrfile" "$CSR_PATH"
  2871. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2872. }
  2873. showcsr() {
  2874. _csrfile="$1"
  2875. _csrd="$2"
  2876. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2877. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2878. return 1
  2879. fi
  2880. _initpath
  2881. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2882. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  2883. _err "Can not read subject from csr: $_csrfile"
  2884. return 1
  2885. fi
  2886. _info "Subject=$_csrsubj"
  2887. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2888. if [ "$?" != "0" ]; then
  2889. _err "Can not read domain list from csr: $_csrfile"
  2890. return 1
  2891. fi
  2892. _debug "_csrdomainlist" "$_csrdomainlist"
  2893. _info "SubjectAltNames=$_csrdomainlist"
  2894. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2895. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  2896. _err "Can not read key length from csr: $_csrfile"
  2897. return 1
  2898. fi
  2899. _info "KeyLength=$_csrkeylength"
  2900. }
  2901. list() {
  2902. _raw="$1"
  2903. _initpath
  2904. _sep="|"
  2905. if [ "$_raw" ]; then
  2906. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  2907. for di in "${CERT_HOME}"/*.*/; do
  2908. if ! [ -d "$di" ]; then
  2909. _debug "Not directory, skip: $di"
  2910. continue
  2911. fi
  2912. d=$(basename "$di")
  2913. _debug d "$d"
  2914. (
  2915. if _endswith "$d" "$ECC_SUFFIX"; then
  2916. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  2917. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  2918. fi
  2919. _initpath "$d" "$_isEcc"
  2920. if [ -f "$DOMAIN_CONF" ]; then
  2921. . "$DOMAIN_CONF"
  2922. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  2923. fi
  2924. )
  2925. done
  2926. else
  2927. if _exists column; then
  2928. list "raw" | column -t -s "$_sep"
  2929. else
  2930. list "raw" | tr "$_sep" '\t'
  2931. fi
  2932. fi
  2933. }
  2934. deploy() {
  2935. Le_Domain="$1"
  2936. Le_DeployHook="$2"
  2937. _isEcc="$3"
  2938. if [ -z "$Le_DeployHook" ]; then
  2939. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  2940. return 1
  2941. fi
  2942. _initpath "$Le_Domain" "$_isEcc"
  2943. if [ ! -d "$DOMAIN_PATH" ]; then
  2944. _err "Domain is not valid:'$Le_Domain'"
  2945. return 1
  2946. fi
  2947. _deployApi="$(_findHook "$Le_Domain" deploy "$Le_DeployHook")"
  2948. if [ -z "$_deployApi" ]; then
  2949. _err "The deploy hook $Le_DeployHook is not found."
  2950. return 1
  2951. fi
  2952. _debug _deployApi "$_deployApi"
  2953. _savedomainconf Le_DeployHook "$Le_DeployHook"
  2954. if ! (
  2955. if ! . "$_deployApi"; then
  2956. _err "Load file $_deployApi error. Please check your api file and try again."
  2957. return 1
  2958. fi
  2959. d_command="${Le_DeployHook}_deploy"
  2960. if ! _exists "$d_command"; then
  2961. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  2962. return 1
  2963. fi
  2964. if ! $d_command "$Le_Domain" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  2965. _err "Error deploy for domain:$Le_Domain"
  2966. _on_issue_err
  2967. return 1
  2968. fi
  2969. ); then
  2970. _err "Deploy error."
  2971. return 1
  2972. else
  2973. _info "$(__green Success)"
  2974. fi
  2975. }
  2976. installcert() {
  2977. Le_Domain="$1"
  2978. if [ -z "$Le_Domain" ]; then
  2979. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  2980. return 1
  2981. fi
  2982. Le_RealCertPath="$2"
  2983. Le_RealKeyPath="$3"
  2984. Le_RealCACertPath="$4"
  2985. Le_ReloadCmd="$5"
  2986. Le_RealFullChainPath="$6"
  2987. _isEcc="$7"
  2988. _initpath "$Le_Domain" "$_isEcc"
  2989. if [ ! -d "$DOMAIN_PATH" ]; then
  2990. _err "Domain is not valid:'$Le_Domain'"
  2991. return 1
  2992. fi
  2993. _installcert
  2994. }
  2995. _installcert() {
  2996. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2997. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2998. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2999. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  3000. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  3001. if [ "$Le_RealCertPath" = "$NO_VALUE" ]; then
  3002. Le_RealCertPath=""
  3003. fi
  3004. if [ "$Le_RealKeyPath" = "$NO_VALUE" ]; then
  3005. Le_RealKeyPath=""
  3006. fi
  3007. if [ "$Le_RealCACertPath" = "$NO_VALUE" ]; then
  3008. Le_RealCACertPath=""
  3009. fi
  3010. if [ "$Le_ReloadCmd" = "$NO_VALUE" ]; then
  3011. Le_ReloadCmd=""
  3012. fi
  3013. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ]; then
  3014. Le_RealFullChainPath=""
  3015. fi
  3016. if [ "$Le_RealCertPath" ]; then
  3017. _info "Installing cert to:$Le_RealCertPath"
  3018. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ]; then
  3019. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  3020. fi
  3021. cat "$CERT_PATH" >"$Le_RealCertPath"
  3022. fi
  3023. if [ "$Le_RealCACertPath" ]; then
  3024. _info "Installing CA to:$Le_RealCACertPath"
  3025. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ]; then
  3026. echo "" >>"$Le_RealCACertPath"
  3027. cat "$CA_CERT_PATH" >>"$Le_RealCACertPath"
  3028. else
  3029. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ]; then
  3030. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  3031. fi
  3032. cat "$CA_CERT_PATH" >"$Le_RealCACertPath"
  3033. fi
  3034. fi
  3035. if [ "$Le_RealKeyPath" ]; then
  3036. _info "Installing key to:$Le_RealKeyPath"
  3037. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ]; then
  3038. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  3039. fi
  3040. cat "$CERT_KEY_PATH" >"$Le_RealKeyPath"
  3041. fi
  3042. if [ "$Le_RealFullChainPath" ]; then
  3043. _info "Installing full chain to:$Le_RealFullChainPath"
  3044. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ]; then
  3045. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  3046. fi
  3047. cat "$CERT_FULLCHAIN_PATH" >"$Le_RealFullChainPath"
  3048. fi
  3049. if [ "$Le_ReloadCmd" ]; then
  3050. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  3051. if (
  3052. export CERT_PATH
  3053. export CERT_KEY_PATH
  3054. export CA_CERT_PATH
  3055. export CERT_FULLCHAIN_PATH
  3056. cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd"
  3057. ); then
  3058. _info "$(__green "Reload success")"
  3059. else
  3060. _err "Reload error for :$Le_Domain"
  3061. fi
  3062. fi
  3063. }
  3064. #confighome
  3065. installcronjob() {
  3066. _c_home="$1"
  3067. _initpath
  3068. if ! _exists "crontab"; then
  3069. _err "crontab doesn't exist, so, we can not install cron jobs."
  3070. _err "All your certs will not be renewed automatically."
  3071. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  3072. return 1
  3073. fi
  3074. _info "Installing cron job"
  3075. if ! crontab -l | grep "$PROJECT_ENTRY --cron"; then
  3076. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  3077. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  3078. else
  3079. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  3080. return 1
  3081. fi
  3082. if [ "$_c_home" ]; then
  3083. _c_entry="--config-home \"$_c_home\" "
  3084. fi
  3085. _t=$(_time)
  3086. random_minute=$(_math $_t % 60)
  3087. if _exists uname && uname -a | grep SunOS >/dev/null; then
  3088. crontab -l | {
  3089. cat
  3090. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  3091. } | crontab --
  3092. else
  3093. crontab -l | {
  3094. cat
  3095. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  3096. } | crontab -
  3097. fi
  3098. fi
  3099. if [ "$?" != "0" ]; then
  3100. _err "Install cron job failed. You need to manually renew your certs."
  3101. _err "Or you can add cronjob by yourself:"
  3102. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  3103. return 1
  3104. fi
  3105. }
  3106. uninstallcronjob() {
  3107. if ! _exists "crontab"; then
  3108. return
  3109. fi
  3110. _info "Removing cron job"
  3111. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  3112. if [ "$cr" ]; then
  3113. if _exists uname && uname -a | grep solaris >/dev/null; then
  3114. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  3115. else
  3116. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  3117. fi
  3118. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  3119. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  3120. if _contains "$cr" "--config-home"; then
  3121. LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
  3122. _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
  3123. fi
  3124. fi
  3125. _initpath
  3126. }
  3127. revoke() {
  3128. Le_Domain="$1"
  3129. if [ -z "$Le_Domain" ]; then
  3130. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com [--ecc]"
  3131. return 1
  3132. fi
  3133. _isEcc="$2"
  3134. _initpath "$Le_Domain" "$_isEcc"
  3135. if [ ! -f "$DOMAIN_CONF" ]; then
  3136. _err "$Le_Domain is not a issued domain, skip."
  3137. return 1
  3138. fi
  3139. if [ ! -f "$CERT_PATH" ]; then
  3140. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  3141. return 1
  3142. fi
  3143. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
  3144. if [ -z "$cert" ]; then
  3145. _err "Cert for $Le_Domain is empty found, skip."
  3146. return 1
  3147. fi
  3148. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  3149. uri="$API/acme/revoke-cert"
  3150. if [ -f "$CERT_KEY_PATH" ]; then
  3151. _info "Try domain key first."
  3152. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  3153. if [ -z "$response" ]; then
  3154. _info "Revoke success."
  3155. rm -f "$CERT_PATH"
  3156. return 0
  3157. else
  3158. _err "Revoke error by domain key."
  3159. _err "$response"
  3160. fi
  3161. fi
  3162. else
  3163. _info "Domain key file doesn't exists."
  3164. fi
  3165. _info "Try account key."
  3166. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  3167. if [ -z "$response" ]; then
  3168. _info "Revoke success."
  3169. rm -f "$CERT_PATH"
  3170. return 0
  3171. else
  3172. _err "Revoke error."
  3173. _debug "$response"
  3174. fi
  3175. fi
  3176. return 1
  3177. }
  3178. #domain ecc
  3179. remove() {
  3180. Le_Domain="$1"
  3181. if [ -z "$Le_Domain" ]; then
  3182. _usage "Usage: $PROJECT_ENTRY --remove -d domain.com [--ecc]"
  3183. return 1
  3184. fi
  3185. _isEcc="$2"
  3186. _initpath "$Le_Domain" "$_isEcc"
  3187. _removed_conf="$DOMAIN_CONF.removed"
  3188. if [ ! -f "$DOMAIN_CONF" ]; then
  3189. if [ -f "$_removed_conf" ]; then
  3190. _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
  3191. else
  3192. _err "$Le_Domain is not a issued domain, skip."
  3193. fi
  3194. return 1
  3195. fi
  3196. if mv "$DOMAIN_CONF" "$_removed_conf"; then
  3197. _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
  3198. _info "You can remove them by yourself."
  3199. return 0
  3200. else
  3201. _err "Remove $Le_Domain failed."
  3202. return 1
  3203. fi
  3204. }
  3205. #domain vtype
  3206. _deactivate() {
  3207. _d_domain="$1"
  3208. _d_type="$2"
  3209. _initpath
  3210. _d_i=0
  3211. _d_max_retry=9
  3212. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  3213. _info "Deactivate: $_d_domain"
  3214. _d_i="$(_math $_d_i + 1)"
  3215. if ! __get_domain_new_authz "$_d_domain"; then
  3216. _err "Can not get domain new authz token."
  3217. return 1
  3218. fi
  3219. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  3220. _debug "authzUri" "$authzUri"
  3221. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  3222. _err "new-authz error: $response"
  3223. return 1
  3224. fi
  3225. entry="$(printf "%s\n" "$response" | _egrep_o '{"type":"[^"]*","status":"valid","uri"[^}]*')"
  3226. _debug entry "$entry"
  3227. if [ -z "$entry" ]; then
  3228. _info "No more valid entry found."
  3229. break
  3230. fi
  3231. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  3232. _debug _vtype "$_vtype"
  3233. _info "Found $_vtype"
  3234. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d : -f 2,3 | tr -d '"')"
  3235. _debug uri "$uri"
  3236. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  3237. _info "Skip $_vtype"
  3238. continue
  3239. fi
  3240. _info "Deactivate: $_vtype"
  3241. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}"; then
  3242. _err "Can not deactivate $_vtype."
  3243. return 1
  3244. fi
  3245. _info "Deactivate: $_vtype success."
  3246. done
  3247. _debug "$_d_i"
  3248. if [ "$_d_i" -lt "$_d_max_retry" ]; then
  3249. _info "Deactivated success!"
  3250. else
  3251. _err "Deactivate failed."
  3252. fi
  3253. }
  3254. deactivate() {
  3255. _d_domain_list="$1"
  3256. _d_type="$2"
  3257. _initpath
  3258. _debug _d_domain_list "$_d_domain_list"
  3259. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  3260. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  3261. return 1
  3262. fi
  3263. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  3264. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  3265. continue
  3266. fi
  3267. if ! _deactivate "$_d_dm" "$_d_type"; then
  3268. return 1
  3269. fi
  3270. done
  3271. }
  3272. # Detect profile file if not specified as environment variable
  3273. _detect_profile() {
  3274. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  3275. echo "$PROFILE"
  3276. return
  3277. fi
  3278. DETECTED_PROFILE=''
  3279. SHELLTYPE="$(basename "/$SHELL")"
  3280. if [ "$SHELLTYPE" = "bash" ]; then
  3281. if [ -f "$HOME/.bashrc" ]; then
  3282. DETECTED_PROFILE="$HOME/.bashrc"
  3283. elif [ -f "$HOME/.bash_profile" ]; then
  3284. DETECTED_PROFILE="$HOME/.bash_profile"
  3285. fi
  3286. elif [ "$SHELLTYPE" = "zsh" ]; then
  3287. DETECTED_PROFILE="$HOME/.zshrc"
  3288. fi
  3289. if [ -z "$DETECTED_PROFILE" ]; then
  3290. if [ -f "$HOME/.profile" ]; then
  3291. DETECTED_PROFILE="$HOME/.profile"
  3292. elif [ -f "$HOME/.bashrc" ]; then
  3293. DETECTED_PROFILE="$HOME/.bashrc"
  3294. elif [ -f "$HOME/.bash_profile" ]; then
  3295. DETECTED_PROFILE="$HOME/.bash_profile"
  3296. elif [ -f "$HOME/.zshrc" ]; then
  3297. DETECTED_PROFILE="$HOME/.zshrc"
  3298. fi
  3299. fi
  3300. if [ ! -z "$DETECTED_PROFILE" ]; then
  3301. echo "$DETECTED_PROFILE"
  3302. fi
  3303. }
  3304. _initconf() {
  3305. _initpath
  3306. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3307. echo "#ACCOUNT_CONF_PATH=xxxx
  3308. #ACCOUNT_EMAIL=aaa@example.com # the account email used to register account.
  3309. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  3310. #CERT_HOME=\"/path/to/cert/home\"
  3311. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  3312. #LOG_LEVEL=1
  3313. #AUTO_UPGRADE=\"1\"
  3314. #NO_TIMESTAMP=1
  3315. #OPENSSL_BIN=openssl
  3316. #USER_AGENT=\"$USER_AGENT\"
  3317. #USER_PATH=
  3318. " >"$ACCOUNT_CONF_PATH"
  3319. fi
  3320. }
  3321. # nocron
  3322. _precheck() {
  3323. _nocron="$1"
  3324. if ! _exists "curl" && ! _exists "wget"; then
  3325. _err "Please install curl or wget first, we need to access http resources."
  3326. return 1
  3327. fi
  3328. if [ -z "$_nocron" ]; then
  3329. if ! _exists "crontab"; then
  3330. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  3331. _err "We need to set cron job to renew the certs automatically."
  3332. _err "Otherwise, your certs will not be able to be renewed automatically."
  3333. if [ -z "$FORCE" ]; then
  3334. _err "Please add '--force' and try install again to go without crontab."
  3335. _err "./$PROJECT_ENTRY --install --force"
  3336. return 1
  3337. fi
  3338. fi
  3339. fi
  3340. if ! _exists "$OPENSSL_BIN"; then
  3341. _err "Please install openssl first."
  3342. _err "We need openssl to generate keys."
  3343. return 1
  3344. fi
  3345. if ! _exists "nc"; then
  3346. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  3347. _err "We use nc for standalone server if you use standalone mode."
  3348. _err "If you don't use standalone mode, just ignore this warning."
  3349. fi
  3350. return 0
  3351. }
  3352. _setShebang() {
  3353. _file="$1"
  3354. _shebang="$2"
  3355. if [ -z "$_shebang" ]; then
  3356. _usage "Usage: file shebang"
  3357. return 1
  3358. fi
  3359. cp "$_file" "$_file.tmp"
  3360. echo "$_shebang" >"$_file"
  3361. sed -n 2,99999p "$_file.tmp" >>"$_file"
  3362. rm -f "$_file.tmp"
  3363. }
  3364. #confighome
  3365. _installalias() {
  3366. _c_home="$1"
  3367. _initpath
  3368. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3369. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  3370. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  3371. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  3372. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  3373. fi
  3374. if [ "$_c_home" ]; then
  3375. _c_entry=" --config-home '$_c_home'"
  3376. fi
  3377. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  3378. if [ "$_c_home" ]; then
  3379. _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
  3380. fi
  3381. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  3382. _profile="$(_detect_profile)"
  3383. if [ "$_profile" ]; then
  3384. _debug "Found profile: $_profile"
  3385. _info "Installing alias to '$_profile'"
  3386. _setopt "$_profile" ". \"$_envfile\""
  3387. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  3388. else
  3389. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  3390. fi
  3391. #for csh
  3392. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  3393. _csh_profile="$HOME/.cshrc"
  3394. if [ -f "$_csh_profile" ]; then
  3395. _info "Installing alias to '$_csh_profile'"
  3396. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3397. if [ "$_c_home" ]; then
  3398. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  3399. fi
  3400. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  3401. _setopt "$_csh_profile" "source \"$_cshfile\""
  3402. fi
  3403. #for tcsh
  3404. _tcsh_profile="$HOME/.tcshrc"
  3405. if [ -f "$_tcsh_profile" ]; then
  3406. _info "Installing alias to '$_tcsh_profile'"
  3407. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  3408. if [ "$_c_home" ]; then
  3409. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  3410. fi
  3411. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  3412. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  3413. fi
  3414. }
  3415. # nocron confighome
  3416. install() {
  3417. if [ -z "$LE_WORKING_DIR" ]; then
  3418. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  3419. fi
  3420. _nocron="$1"
  3421. _c_home="$2"
  3422. if ! _initpath; then
  3423. _err "Install failed."
  3424. return 1
  3425. fi
  3426. if [ "$_nocron" ]; then
  3427. _debug "Skip install cron job"
  3428. fi
  3429. if ! _precheck "$_nocron"; then
  3430. _err "Pre-check failed, can not install."
  3431. return 1
  3432. fi
  3433. #convert from le
  3434. if [ -d "$HOME/.le" ]; then
  3435. for envfile in "le.env" "le.sh.env"; do
  3436. if [ -f "$HOME/.le/$envfile" ]; then
  3437. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  3438. _upgrading="1"
  3439. _info "You are upgrading from le.sh"
  3440. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  3441. mv "$HOME/.le" "$LE_WORKING_DIR"
  3442. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  3443. break
  3444. fi
  3445. fi
  3446. done
  3447. fi
  3448. _info "Installing to $LE_WORKING_DIR"
  3449. if ! mkdir -p "$LE_WORKING_DIR"; then
  3450. _err "Can not create working dir: $LE_WORKING_DIR"
  3451. return 1
  3452. fi
  3453. chmod 700 "$LE_WORKING_DIR"
  3454. if ! mkdir -p "$LE_CONFIG_HOME"; then
  3455. _err "Can not create config dir: $LE_CONFIG_HOME"
  3456. return 1
  3457. fi
  3458. chmod 700 "$LE_CONFIG_HOME"
  3459. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3460. if [ "$?" != "0" ]; then
  3461. _err "Install failed, can not copy $PROJECT_ENTRY"
  3462. return 1
  3463. fi
  3464. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  3465. _installalias "$_c_home"
  3466. for subf in $_SUB_FOLDERS; do
  3467. if [ -d "$subf" ]; then
  3468. mkdir -p "$LE_WORKING_DIR/$subf"
  3469. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  3470. fi
  3471. done
  3472. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  3473. _initconf
  3474. fi
  3475. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  3476. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  3477. fi
  3478. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  3479. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  3480. fi
  3481. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  3482. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  3483. fi
  3484. if [ -z "$_nocron" ]; then
  3485. installcronjob "$_c_home"
  3486. fi
  3487. if [ -z "$NO_DETECT_SH" ]; then
  3488. #Modify shebang
  3489. if _exists bash; then
  3490. _info "Good, bash is found, so change the shebang to use bash as preferred."
  3491. _shebang='#!/usr/bin/env bash'
  3492. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  3493. for subf in $_SUB_FOLDERS; do
  3494. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  3495. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  3496. _setShebang "$_apifile" "$_shebang"
  3497. done
  3498. fi
  3499. done
  3500. fi
  3501. fi
  3502. _info OK
  3503. }
  3504. # nocron
  3505. uninstall() {
  3506. _nocron="$1"
  3507. if [ -z "$_nocron" ]; then
  3508. uninstallcronjob
  3509. fi
  3510. _initpath
  3511. _uninstallalias
  3512. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  3513. _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
  3514. }
  3515. _uninstallalias() {
  3516. _initpath
  3517. _profile="$(_detect_profile)"
  3518. if [ "$_profile" ]; then
  3519. _info "Uninstalling alias from: '$_profile'"
  3520. text="$(cat "$_profile")"
  3521. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  3522. fi
  3523. _csh_profile="$HOME/.cshrc"
  3524. if [ -f "$_csh_profile" ]; then
  3525. _info "Uninstalling alias from: '$_csh_profile'"
  3526. text="$(cat "$_csh_profile")"
  3527. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  3528. fi
  3529. _tcsh_profile="$HOME/.tcshrc"
  3530. if [ -f "$_tcsh_profile" ]; then
  3531. _info "Uninstalling alias from: '$_csh_profile'"
  3532. text="$(cat "$_tcsh_profile")"
  3533. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  3534. fi
  3535. }
  3536. cron() {
  3537. IN_CRON=1
  3538. _initpath
  3539. if [ "$AUTO_UPGRADE" = "1" ]; then
  3540. export LE_WORKING_DIR
  3541. (
  3542. if ! upgrade; then
  3543. _err "Cron:Upgrade failed!"
  3544. return 1
  3545. fi
  3546. )
  3547. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  3548. if [ -t 1 ]; then
  3549. __INTERACTIVE="1"
  3550. fi
  3551. _info "Auto upgraded to: $VER"
  3552. fi
  3553. renewAll
  3554. _ret="$?"
  3555. IN_CRON=""
  3556. exit $_ret
  3557. }
  3558. version() {
  3559. echo "$PROJECT"
  3560. echo "v$VER"
  3561. }
  3562. showhelp() {
  3563. _initpath
  3564. version
  3565. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  3566. Commands:
  3567. --help, -h Show this help message.
  3568. --version, -v Show version info.
  3569. --install Install $PROJECT_NAME to your system.
  3570. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  3571. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  3572. --issue Issue a cert.
  3573. --signcsr Issue a cert from an existing csr.
  3574. --deploy Deploy the cert to your server.
  3575. --install-cert Install the issued cert to apache/nginx or any other server.
  3576. --renew, -r Renew a cert.
  3577. --renew-all Renew all the certs.
  3578. --revoke Revoke a cert.
  3579. --remove Remove the cert from $PROJECT
  3580. --list List all the certs.
  3581. --showcsr Show the content of a csr.
  3582. --install-cronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  3583. --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  3584. --cron Run cron job to renew all the certs.
  3585. --toPkcs Export the certificate and key to a pfx file.
  3586. --update-account Update account info.
  3587. --register-account Register account key.
  3588. --createAccountKey, -cak Create an account private key, professional use.
  3589. --createDomainKey, -cdk Create an domain private key, professional use.
  3590. --createCSR, -ccsr Create CSR , professional use.
  3591. --deactivate Deactivate the domain authz, professional use.
  3592. Parameters:
  3593. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  3594. --force, -f Used to force to install or force to renew a cert immediately.
  3595. --staging, --test Use staging server, just for test.
  3596. --debug Output debug info.
  3597. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  3598. --standalone Use standalone mode.
  3599. --tls Use standalone tls mode.
  3600. --apache Use apache mode.
  3601. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  3602. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  3603. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  3604. --accountkeylength, -ak [2048] Specifies the account key length.
  3605. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  3606. --log-level 1|2 Specifies the log level, default is 1.
  3607. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  3608. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  3609. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  3610. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  3611. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  3612. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  3613. --accountconf Specifies a customized account config file.
  3614. --home Specifies the home dir for $PROJECT_NAME .
  3615. --cert-home Specifies the home dir to save all the certs, only valid for '--install' command.
  3616. --config-home Specifies the home dir to save all the configurations.
  3617. --useragent Specifies the user agent string. it will be saved for future use too.
  3618. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  3619. --accountkey Specifies the account key path, Only valid for the '--install' command.
  3620. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  3621. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3622. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  3623. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  3624. --listraw Only used for '--list' command, list the certs in raw format.
  3625. --stopRenewOnError, -se Only valid for '--renew-all' command. Stop if one cert has error in renewal.
  3626. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  3627. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  3628. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  3629. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  3630. --csr Specifies the input csr.
  3631. --pre-hook Command to be run before obtaining any certificates.
  3632. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  3633. --renew-hook Command to be run once for each successfully renewed certificate.
  3634. --deploy-hook The hook file to deploy cert
  3635. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  3636. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  3637. --listen-v4 Force standalone/tls server to listen at ipv4.
  3638. --listen-v6 Force standalone/tls server to listen at ipv6.
  3639. --openssl-bin Specifies a custom openssl bin location.
  3640. "
  3641. }
  3642. # nocron
  3643. _installOnline() {
  3644. _info "Installing from online archive."
  3645. _nocron="$1"
  3646. if [ ! "$BRANCH" ]; then
  3647. BRANCH="master"
  3648. fi
  3649. target="$PROJECT/archive/$BRANCH.tar.gz"
  3650. _info "Downloading $target"
  3651. localname="$BRANCH.tar.gz"
  3652. if ! _get "$target" >$localname; then
  3653. _err "Download error."
  3654. return 1
  3655. fi
  3656. (
  3657. _info "Extracting $localname"
  3658. if ! (tar xzf $localname || gtar xzf $localname); then
  3659. _err "Extraction error."
  3660. exit 1
  3661. fi
  3662. cd "$PROJECT_NAME-$BRANCH"
  3663. chmod +x $PROJECT_ENTRY
  3664. if ./$PROJECT_ENTRY install "$_nocron"; then
  3665. _info "Install success!"
  3666. fi
  3667. cd ..
  3668. rm -rf "$PROJECT_NAME-$BRANCH"
  3669. rm -f "$localname"
  3670. )
  3671. }
  3672. upgrade() {
  3673. if (
  3674. _initpath
  3675. export LE_WORKING_DIR
  3676. cd "$LE_WORKING_DIR"
  3677. _installOnline "nocron"
  3678. ); then
  3679. _info "Upgrade success!"
  3680. exit 0
  3681. else
  3682. _err "Upgrade failed!"
  3683. exit 1
  3684. fi
  3685. }
  3686. _processAccountConf() {
  3687. if [ "$_useragent" ]; then
  3688. _saveaccountconf "USER_AGENT" "$_useragent"
  3689. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  3690. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3691. fi
  3692. if [ "$_accountemail" ]; then
  3693. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3694. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  3695. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3696. fi
  3697. if [ "$_openssl_bin" ]; then
  3698. _saveaccountconf "OPENSSL_BIN" "$_openssl_bin"
  3699. elif [ "$OPENSSL_BIN" ] && [ "$OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  3700. _saveaccountconf "OPENSSL_BIN" "$OPENSSL_BIN"
  3701. fi
  3702. if [ "$_auto_upgrade" ]; then
  3703. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3704. elif [ "$AUTO_UPGRADE" ]; then
  3705. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3706. fi
  3707. }
  3708. _process() {
  3709. _CMD=""
  3710. _domain=""
  3711. _altdomains="$NO_VALUE"
  3712. _webroot=""
  3713. _keylength=""
  3714. _accountkeylength=""
  3715. _certpath=""
  3716. _keypath=""
  3717. _capath=""
  3718. _fullchainpath=""
  3719. _reloadcmd=""
  3720. _password=""
  3721. _accountconf=""
  3722. _useragent=""
  3723. _accountemail=""
  3724. _accountkey=""
  3725. _certhome=""
  3726. _confighome=""
  3727. _httpport=""
  3728. _tlsport=""
  3729. _dnssleep=""
  3730. _listraw=""
  3731. _stopRenewOnError=""
  3732. #_insecure=""
  3733. _ca_bundle=""
  3734. _nocron=""
  3735. _ecc=""
  3736. _csr=""
  3737. _pre_hook=""
  3738. _post_hook=""
  3739. _renew_hook=""
  3740. _deploy_hook=""
  3741. _logfile=""
  3742. _log=""
  3743. _local_address=""
  3744. _log_level=""
  3745. _auto_upgrade=""
  3746. _listen_v4=""
  3747. _listen_v6=""
  3748. _openssl_bin=""
  3749. while [ ${#} -gt 0 ]; do
  3750. case "${1}" in
  3751. --help | -h)
  3752. showhelp
  3753. return
  3754. ;;
  3755. --version | -v)
  3756. version
  3757. return
  3758. ;;
  3759. --install)
  3760. _CMD="install"
  3761. ;;
  3762. --uninstall)
  3763. _CMD="uninstall"
  3764. ;;
  3765. --upgrade)
  3766. _CMD="upgrade"
  3767. ;;
  3768. --issue)
  3769. _CMD="issue"
  3770. ;;
  3771. --deploy)
  3772. _CMD="deploy"
  3773. ;;
  3774. --signcsr)
  3775. _CMD="signcsr"
  3776. ;;
  3777. --showcsr)
  3778. _CMD="showcsr"
  3779. ;;
  3780. --installcert | -i | --install-cert)
  3781. _CMD="installcert"
  3782. ;;
  3783. --renew | -r)
  3784. _CMD="renew"
  3785. ;;
  3786. --renewAll | --renewall | --renew-all)
  3787. _CMD="renewAll"
  3788. ;;
  3789. --revoke)
  3790. _CMD="revoke"
  3791. ;;
  3792. --remove)
  3793. _CMD="remove"
  3794. ;;
  3795. --list)
  3796. _CMD="list"
  3797. ;;
  3798. --installcronjob | --install-cronjob)
  3799. _CMD="installcronjob"
  3800. ;;
  3801. --uninstallcronjob | --uninstall-cronjob)
  3802. _CMD="uninstallcronjob"
  3803. ;;
  3804. --cron)
  3805. _CMD="cron"
  3806. ;;
  3807. --toPkcs)
  3808. _CMD="toPkcs"
  3809. ;;
  3810. --createAccountKey | --createaccountkey | -cak)
  3811. _CMD="createAccountKey"
  3812. ;;
  3813. --createDomainKey | --createdomainkey | -cdk)
  3814. _CMD="createDomainKey"
  3815. ;;
  3816. --createCSR | --createcsr | -ccr)
  3817. _CMD="createCSR"
  3818. ;;
  3819. --deactivate)
  3820. _CMD="deactivate"
  3821. ;;
  3822. --updateaccount | --update-account)
  3823. _CMD="updateaccount"
  3824. ;;
  3825. --registeraccount | --register-account)
  3826. _CMD="registeraccount"
  3827. ;;
  3828. --domain | -d)
  3829. _dvalue="$2"
  3830. if [ "$_dvalue" ]; then
  3831. if _startswith "$_dvalue" "-"; then
  3832. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3833. return 1
  3834. fi
  3835. if _is_idn "$_dvalue" && ! _exists idn; then
  3836. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  3837. return 1
  3838. fi
  3839. if [ -z "$_domain" ]; then
  3840. _domain="$_dvalue"
  3841. else
  3842. if [ "$_altdomains" = "$NO_VALUE" ]; then
  3843. _altdomains="$_dvalue"
  3844. else
  3845. _altdomains="$_altdomains,$_dvalue"
  3846. fi
  3847. fi
  3848. fi
  3849. shift
  3850. ;;
  3851. --force | -f)
  3852. FORCE="1"
  3853. ;;
  3854. --staging | --test)
  3855. STAGE="1"
  3856. ;;
  3857. --debug)
  3858. if [ -z "$2" ] || _startswith "$2" "-"; then
  3859. DEBUG="1"
  3860. else
  3861. DEBUG="$2"
  3862. shift
  3863. fi
  3864. ;;
  3865. --webroot | -w)
  3866. wvalue="$2"
  3867. if [ -z "$_webroot" ]; then
  3868. _webroot="$wvalue"
  3869. else
  3870. _webroot="$_webroot,$wvalue"
  3871. fi
  3872. shift
  3873. ;;
  3874. --standalone)
  3875. wvalue="$NO_VALUE"
  3876. if [ -z "$_webroot" ]; then
  3877. _webroot="$wvalue"
  3878. else
  3879. _webroot="$_webroot,$wvalue"
  3880. fi
  3881. ;;
  3882. --local-address)
  3883. lvalue="$2"
  3884. _local_address="$_local_address$lvalue,"
  3885. shift
  3886. ;;
  3887. --apache)
  3888. wvalue="apache"
  3889. if [ -z "$_webroot" ]; then
  3890. _webroot="$wvalue"
  3891. else
  3892. _webroot="$_webroot,$wvalue"
  3893. fi
  3894. ;;
  3895. --tls)
  3896. wvalue="$W_TLS"
  3897. if [ -z "$_webroot" ]; then
  3898. _webroot="$wvalue"
  3899. else
  3900. _webroot="$_webroot,$wvalue"
  3901. fi
  3902. ;;
  3903. --dns)
  3904. wvalue="dns"
  3905. if ! _startswith "$2" "-"; then
  3906. wvalue="$2"
  3907. shift
  3908. fi
  3909. if [ -z "$_webroot" ]; then
  3910. _webroot="$wvalue"
  3911. else
  3912. _webroot="$_webroot,$wvalue"
  3913. fi
  3914. ;;
  3915. --dnssleep)
  3916. _dnssleep="$2"
  3917. Le_DNSSleep="$_dnssleep"
  3918. shift
  3919. ;;
  3920. --keylength | -k)
  3921. _keylength="$2"
  3922. shift
  3923. ;;
  3924. --accountkeylength | -ak)
  3925. _accountkeylength="$2"
  3926. shift
  3927. ;;
  3928. --certpath)
  3929. _certpath="$2"
  3930. shift
  3931. ;;
  3932. --keypath)
  3933. _keypath="$2"
  3934. shift
  3935. ;;
  3936. --capath)
  3937. _capath="$2"
  3938. shift
  3939. ;;
  3940. --fullchainpath)
  3941. _fullchainpath="$2"
  3942. shift
  3943. ;;
  3944. --reloadcmd | --reloadCmd)
  3945. _reloadcmd="$2"
  3946. shift
  3947. ;;
  3948. --password)
  3949. _password="$2"
  3950. shift
  3951. ;;
  3952. --accountconf)
  3953. _accountconf="$2"
  3954. ACCOUNT_CONF_PATH="$_accountconf"
  3955. shift
  3956. ;;
  3957. --home)
  3958. LE_WORKING_DIR="$2"
  3959. shift
  3960. ;;
  3961. --certhome | --cert-home)
  3962. _certhome="$2"
  3963. CERT_HOME="$_certhome"
  3964. shift
  3965. ;;
  3966. --config-home)
  3967. _confighome="$2"
  3968. LE_CONFIG_HOME="$_confighome"
  3969. shift
  3970. ;;
  3971. --useragent)
  3972. _useragent="$2"
  3973. USER_AGENT="$_useragent"
  3974. shift
  3975. ;;
  3976. --accountemail)
  3977. _accountemail="$2"
  3978. ACCOUNT_EMAIL="$_accountemail"
  3979. shift
  3980. ;;
  3981. --accountkey)
  3982. _accountkey="$2"
  3983. ACCOUNT_KEY_PATH="$_accountkey"
  3984. shift
  3985. ;;
  3986. --days)
  3987. _days="$2"
  3988. Le_RenewalDays="$_days"
  3989. shift
  3990. ;;
  3991. --httpport)
  3992. _httpport="$2"
  3993. Le_HTTPPort="$_httpport"
  3994. shift
  3995. ;;
  3996. --tlsport)
  3997. _tlsport="$2"
  3998. Le_TLSPort="$_tlsport"
  3999. shift
  4000. ;;
  4001. --listraw)
  4002. _listraw="raw"
  4003. ;;
  4004. --stopRenewOnError | --stoprenewonerror | -se)
  4005. _stopRenewOnError="1"
  4006. ;;
  4007. --insecure)
  4008. #_insecure="1"
  4009. HTTPS_INSECURE="1"
  4010. ;;
  4011. --ca-bundle)
  4012. _ca_bundle="$(readlink -f "$2")"
  4013. CA_BUNDLE="$_ca_bundle"
  4014. shift
  4015. ;;
  4016. --nocron)
  4017. _nocron="1"
  4018. ;;
  4019. --ecc)
  4020. _ecc="isEcc"
  4021. ;;
  4022. --csr)
  4023. _csr="$2"
  4024. shift
  4025. ;;
  4026. --pre-hook)
  4027. _pre_hook="$2"
  4028. shift
  4029. ;;
  4030. --post-hook)
  4031. _post_hook="$2"
  4032. shift
  4033. ;;
  4034. --renew-hook)
  4035. _renew_hook="$2"
  4036. shift
  4037. ;;
  4038. --deploy-hook)
  4039. _deploy_hook="$2"
  4040. shift
  4041. ;;
  4042. --ocsp-must-staple | --ocsp)
  4043. Le_OCSP_Staple="1"
  4044. ;;
  4045. --log | --logfile)
  4046. _log="1"
  4047. _logfile="$2"
  4048. if _startswith "$_logfile" '-'; then
  4049. _logfile=""
  4050. else
  4051. shift
  4052. fi
  4053. LOG_FILE="$_logfile"
  4054. if [ -z "$LOG_LEVEL" ]; then
  4055. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  4056. fi
  4057. ;;
  4058. --log-level)
  4059. _log_level="$2"
  4060. LOG_LEVEL="$_log_level"
  4061. shift
  4062. ;;
  4063. --auto-upgrade)
  4064. _auto_upgrade="$2"
  4065. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  4066. _auto_upgrade="1"
  4067. else
  4068. shift
  4069. fi
  4070. AUTO_UPGRADE="$_auto_upgrade"
  4071. ;;
  4072. --listen-v4)
  4073. _listen_v4="1"
  4074. Le_Listen_V4="$_listen_v4"
  4075. ;;
  4076. --listen-v6)
  4077. _listen_v6="1"
  4078. Le_Listen_V6="$_listen_v6"
  4079. ;;
  4080. --openssl-bin)
  4081. _openssl_bin="$2"
  4082. OPENSSL_BIN="$_openssl_bin"
  4083. ;;
  4084. *)
  4085. _err "Unknown parameter : $1"
  4086. return 1
  4087. ;;
  4088. esac
  4089. shift 1
  4090. done
  4091. if [ "${_CMD}" != "install" ]; then
  4092. __initHome
  4093. if [ "$_log" ]; then
  4094. if [ -z "$_logfile" ]; then
  4095. _logfile="$DEFAULT_LOG_FILE"
  4096. fi
  4097. fi
  4098. if [ "$_logfile" ]; then
  4099. _saveaccountconf "LOG_FILE" "$_logfile"
  4100. LOG_FILE="$_logfile"
  4101. fi
  4102. if [ "$_log_level" ]; then
  4103. _saveaccountconf "LOG_LEVEL" "$_log_level"
  4104. LOG_LEVEL="$_log_level"
  4105. fi
  4106. _processAccountConf
  4107. fi
  4108. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  4109. if [ "$DEBUG" ]; then
  4110. version
  4111. fi
  4112. case "${_CMD}" in
  4113. install) install "$_nocron" "$_confighome" ;;
  4114. uninstall) uninstall "$_nocron" ;;
  4115. upgrade) upgrade ;;
  4116. issue)
  4117. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  4118. ;;
  4119. deploy)
  4120. deploy "$_domain" "$_deploy_hook" "$_ecc"
  4121. ;;
  4122. signcsr)
  4123. signcsr "$_csr" "$_webroot"
  4124. ;;
  4125. showcsr)
  4126. showcsr "$_csr" "$_domain"
  4127. ;;
  4128. installcert)
  4129. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  4130. ;;
  4131. renew)
  4132. renew "$_domain" "$_ecc"
  4133. ;;
  4134. renewAll)
  4135. renewAll "$_stopRenewOnError"
  4136. ;;
  4137. revoke)
  4138. revoke "$_domain" "$_ecc"
  4139. ;;
  4140. remove)
  4141. remove "$_domain" "$_ecc"
  4142. ;;
  4143. deactivate)
  4144. deactivate "$_domain,$_altdomains"
  4145. ;;
  4146. registeraccount)
  4147. registeraccount "$_accountkeylength"
  4148. ;;
  4149. updateaccount)
  4150. updateaccount
  4151. ;;
  4152. list)
  4153. list "$_listraw"
  4154. ;;
  4155. installcronjob) installcronjob "$_confighome" ;;
  4156. uninstallcronjob) uninstallcronjob ;;
  4157. cron) cron ;;
  4158. toPkcs)
  4159. toPkcs "$_domain" "$_password" "$_ecc"
  4160. ;;
  4161. createAccountKey)
  4162. createAccountKey "$_accountkeylength"
  4163. ;;
  4164. createDomainKey)
  4165. createDomainKey "$_domain" "$_keylength"
  4166. ;;
  4167. createCSR)
  4168. createCSR "$_domain" "$_altdomains" "$_ecc"
  4169. ;;
  4170. *)
  4171. if [ "$_CMD" ]; then
  4172. _err "Invalid command: $_CMD"
  4173. fi
  4174. showhelp
  4175. return 1
  4176. ;;
  4177. esac
  4178. _ret="$?"
  4179. if [ "$_ret" != "0" ]; then
  4180. return $_ret
  4181. fi
  4182. if [ "${_CMD}" = "install" ]; then
  4183. if [ "$_log" ]; then
  4184. if [ -z "$LOG_FILE" ]; then
  4185. LOG_FILE="$DEFAULT_LOG_FILE"
  4186. fi
  4187. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  4188. fi
  4189. if [ "$_log_level" ]; then
  4190. _saveaccountconf "LOG_LEVEL" "$_log_level"
  4191. fi
  4192. _processAccountConf
  4193. fi
  4194. }
  4195. if [ "$INSTALLONLINE" ]; then
  4196. INSTALLONLINE=""
  4197. _installOnline
  4198. exit
  4199. fi
  4200. main() {
  4201. [ -z "$1" ] && showhelp && return
  4202. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  4203. }
  4204. main "$@"