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.

5832 lines
149 KiB

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