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.

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