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.

5792 lines
148 KiB

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