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.

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