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.

6244 lines
165 KiB

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