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.

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