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.

5672 lines
143 KiB

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