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.

5485 lines
137 KiB

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