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.

5448 lines
136 KiB

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