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.

6210 lines
163 KiB

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