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.

6259 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
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
7 years ago
7 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
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
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
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
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
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 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
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. _debug2 original "$response"
  1640. response="$(echo "$response" | _normalizeJson)"
  1641. responseHeaders="$(cat "$HTTP_HEADER")"
  1642. _debug2 responseHeaders "$responseHeaders"
  1643. _debug2 response "$response"
  1644. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1645. _debug code "$code"
  1646. _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1647. _body="$response"
  1648. if [ "$needbase64" ]; then
  1649. _body="$(echo "$_body" | _dbase64 | tr -d '\0')"
  1650. _debug3 _body "$_body"
  1651. fi
  1652. if _contains "$_body" "JWS has invalid anti-replay nonce" || _contains "$_body" "JWS has an invalid anti-replay nonce"; then
  1653. _info "It seems the CA server is busy now, let's wait and retry. Sleeping $_sleep_retry_sec seconds."
  1654. _CACHED_NONCE=""
  1655. _sleep $_sleep_retry_sec
  1656. continue
  1657. fi
  1658. break
  1659. done
  1660. }
  1661. #setopt "file" "opt" "=" "value" [";"]
  1662. _setopt() {
  1663. __conf="$1"
  1664. __opt="$2"
  1665. __sep="$3"
  1666. __val="$4"
  1667. __end="$5"
  1668. if [ -z "$__opt" ]; then
  1669. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1670. return
  1671. fi
  1672. if [ ! -f "$__conf" ]; then
  1673. touch "$__conf"
  1674. fi
  1675. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1676. _debug3 OK
  1677. if _contains "$__val" "&"; then
  1678. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1679. fi
  1680. text="$(cat "$__conf")"
  1681. printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1682. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1683. if _contains "$__val" "&"; then
  1684. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1685. fi
  1686. text="$(cat "$__conf")"
  1687. printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1688. else
  1689. _debug3 APP
  1690. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1691. fi
  1692. _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
  1693. }
  1694. #_save_conf file key value
  1695. #save to conf
  1696. _save_conf() {
  1697. _s_c_f="$1"
  1698. _sdkey="$2"
  1699. _sdvalue="$3"
  1700. if [ "$_s_c_f" ]; then
  1701. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1702. else
  1703. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1704. fi
  1705. }
  1706. #_clear_conf file key
  1707. _clear_conf() {
  1708. _c_c_f="$1"
  1709. _sdkey="$2"
  1710. if [ "$_c_c_f" ]; then
  1711. _conf_data="$(cat "$_c_c_f")"
  1712. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1713. else
  1714. _err "config file is empty, can not clear"
  1715. fi
  1716. }
  1717. #_read_conf file key
  1718. _read_conf() {
  1719. _r_c_f="$1"
  1720. _sdkey="$2"
  1721. if [ -f "$_r_c_f" ]; then
  1722. (
  1723. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1724. eval "printf \"%s\" \"\$$_sdkey\""
  1725. )
  1726. else
  1727. _debug "config file is empty, can not read $_sdkey"
  1728. fi
  1729. }
  1730. #_savedomainconf key value
  1731. #save to domain.conf
  1732. _savedomainconf() {
  1733. _save_conf "$DOMAIN_CONF" "$1" "$2"
  1734. }
  1735. #_cleardomainconf key
  1736. _cleardomainconf() {
  1737. _clear_conf "$DOMAIN_CONF" "$1"
  1738. }
  1739. #_readdomainconf key
  1740. _readdomainconf() {
  1741. _read_conf "$DOMAIN_CONF" "$1"
  1742. }
  1743. #_saveaccountconf key value
  1744. _saveaccountconf() {
  1745. _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
  1746. }
  1747. #key value
  1748. _saveaccountconf_mutable() {
  1749. _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2"
  1750. #remove later
  1751. _clearaccountconf "$1"
  1752. }
  1753. #key
  1754. _readaccountconf() {
  1755. _read_conf "$ACCOUNT_CONF_PATH" "$1"
  1756. }
  1757. #key
  1758. _readaccountconf_mutable() {
  1759. _rac_key="$1"
  1760. _readaccountconf "SAVED_$_rac_key"
  1761. }
  1762. #_clearaccountconf key
  1763. _clearaccountconf() {
  1764. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1765. }
  1766. #_savecaconf key value
  1767. _savecaconf() {
  1768. _save_conf "$CA_CONF" "$1" "$2"
  1769. }
  1770. #_readcaconf key
  1771. _readcaconf() {
  1772. _read_conf "$CA_CONF" "$1"
  1773. }
  1774. #_clearaccountconf key
  1775. _clearcaconf() {
  1776. _clear_conf "$CA_CONF" "$1"
  1777. }
  1778. # content localaddress
  1779. _startserver() {
  1780. content="$1"
  1781. ncaddr="$2"
  1782. _debug "ncaddr" "$ncaddr"
  1783. _debug "startserver: $$"
  1784. _debug Le_HTTPPort "$Le_HTTPPort"
  1785. _debug Le_Listen_V4 "$Le_Listen_V4"
  1786. _debug Le_Listen_V6 "$Le_Listen_V6"
  1787. _NC="socat"
  1788. if [ "$Le_Listen_V4" ]; then
  1789. _NC="$_NC -4"
  1790. elif [ "$Le_Listen_V6" ]; then
  1791. _NC="$_NC -6"
  1792. fi
  1793. if [ "$DEBUG" ] && [ "$DEBUG" -gt "1" ]; then
  1794. _NC="$_NC -d -d -v"
  1795. fi
  1796. SOCAT_OPTIONS=TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork
  1797. #Adding bind to local-address
  1798. if [ "$ncaddr" ]; then
  1799. SOCAT_OPTIONS="$SOCAT_OPTIONS,bind=${ncaddr}"
  1800. fi
  1801. _debug "_NC" "$_NC $SOCAT_OPTIONS"
  1802. $_NC $SOCAT_OPTIONS SYSTEM:"sleep 1; echo HTTP/1.0 200 OK; echo ; echo $content; echo;" &
  1803. serverproc="$!"
  1804. }
  1805. _stopserver() {
  1806. pid="$1"
  1807. _debug "pid" "$pid"
  1808. if [ -z "$pid" ]; then
  1809. return
  1810. fi
  1811. kill $pid
  1812. }
  1813. # sleep sec
  1814. _sleep() {
  1815. _sleep_sec="$1"
  1816. if [ "$__INTERACTIVE" ]; then
  1817. _sleep_c="$_sleep_sec"
  1818. while [ "$_sleep_c" -ge "0" ]; do
  1819. printf "\r \r"
  1820. __green "$_sleep_c"
  1821. _sleep_c="$(_math "$_sleep_c" - 1)"
  1822. sleep 1
  1823. done
  1824. printf "\r"
  1825. else
  1826. sleep "$_sleep_sec"
  1827. fi
  1828. }
  1829. # _starttlsserver san_a san_b port content _ncaddr acmeValidationv1
  1830. _starttlsserver() {
  1831. _info "Starting tls server."
  1832. san_a="$1"
  1833. san_b="$2"
  1834. port="$3"
  1835. content="$4"
  1836. opaddr="$5"
  1837. acmeValidationv1="$6"
  1838. _debug san_a "$san_a"
  1839. _debug san_b "$san_b"
  1840. _debug port "$port"
  1841. _debug acmeValidationv1 "$acmeValidationv1"
  1842. #create key TLS_KEY
  1843. if ! _createkey "2048" "$TLS_KEY"; then
  1844. _err "Create tls validation key error."
  1845. return 1
  1846. fi
  1847. #create csr
  1848. alt="$san_a"
  1849. if [ "$san_b" ]; then
  1850. alt="$alt,$san_b"
  1851. fi
  1852. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$acmeValidationv1"; then
  1853. _err "Create tls validation csr error."
  1854. return 1
  1855. fi
  1856. #self signed
  1857. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1858. _err "Create tls validation cert error."
  1859. return 1
  1860. fi
  1861. __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
  1862. if [ "$opaddr" ]; then
  1863. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1864. else
  1865. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1866. fi
  1867. _debug Le_Listen_V4 "$Le_Listen_V4"
  1868. _debug Le_Listen_V6 "$Le_Listen_V6"
  1869. if [ "$Le_Listen_V4" ]; then
  1870. __S_OPENSSL="$__S_OPENSSL -4"
  1871. elif [ "$Le_Listen_V6" ]; then
  1872. __S_OPENSSL="$__S_OPENSSL -6"
  1873. fi
  1874. if [ "$acmeValidationv1" ]; then
  1875. __S_OPENSSL="$__S_OPENSSL -alpn acme-tls/1"
  1876. fi
  1877. _debug "$__S_OPENSSL"
  1878. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1879. $__S_OPENSSL -tlsextdebug &
  1880. else
  1881. $__S_OPENSSL >/dev/null 2>&1 &
  1882. fi
  1883. serverproc="$!"
  1884. sleep 1
  1885. _debug serverproc "$serverproc"
  1886. }
  1887. #file
  1888. _readlink() {
  1889. _rf="$1"
  1890. if ! readlink -f "$_rf" 2>/dev/null; then
  1891. if _startswith "$_rf" "/"; then
  1892. echo "$_rf"
  1893. return 0
  1894. fi
  1895. echo "$(pwd)/$_rf" | _conapath
  1896. fi
  1897. }
  1898. _conapath() {
  1899. sed "s#/\./#/#g"
  1900. }
  1901. __initHome() {
  1902. if [ -z "$_SCRIPT_HOME" ]; then
  1903. if _exists readlink && _exists dirname; then
  1904. _debug "Lets find script dir."
  1905. _debug "_SCRIPT_" "$_SCRIPT_"
  1906. _script="$(_readlink "$_SCRIPT_")"
  1907. _debug "_script" "$_script"
  1908. _script_home="$(dirname "$_script")"
  1909. _debug "_script_home" "$_script_home"
  1910. if [ -d "$_script_home" ]; then
  1911. _SCRIPT_HOME="$_script_home"
  1912. else
  1913. _err "It seems the script home is not correct:$_script_home"
  1914. fi
  1915. fi
  1916. fi
  1917. # if [ -z "$LE_WORKING_DIR" ]; then
  1918. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1919. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1920. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1921. # else
  1922. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1923. # fi
  1924. # fi
  1925. if [ -z "$LE_WORKING_DIR" ]; then
  1926. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1927. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1928. fi
  1929. export LE_WORKING_DIR
  1930. if [ -z "$LE_CONFIG_HOME" ]; then
  1931. LE_CONFIG_HOME="$LE_WORKING_DIR"
  1932. fi
  1933. _debug "Using config home:$LE_CONFIG_HOME"
  1934. export LE_CONFIG_HOME
  1935. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  1936. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1937. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1938. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1939. fi
  1940. fi
  1941. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1942. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1943. fi
  1944. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  1945. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  1946. if [ -z "$LE_TEMP_DIR" ]; then
  1947. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  1948. fi
  1949. }
  1950. #server
  1951. _initAPI() {
  1952. _api_server="${1:-$ACME_DIRECTORY}"
  1953. _debug "_init api for server: $_api_server"
  1954. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1955. response=$(_get "$_api_server")
  1956. if [ "$?" != "0" ]; then
  1957. _debug2 "response" "$response"
  1958. _err "Can not init api."
  1959. return 1
  1960. fi
  1961. _debug2 "response" "$response"
  1962. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'key-change" *: *"[^"]*"' | cut -d '"' -f 3)
  1963. if [ -z "$ACME_KEY_CHANGE" ]; then
  1964. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
  1965. fi
  1966. export ACME_KEY_CHANGE
  1967. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'new-authz" *: *"[^"]*"' | cut -d '"' -f 3)
  1968. if [ -z "$ACME_NEW_AUTHZ" ]; then
  1969. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
  1970. fi
  1971. export ACME_NEW_AUTHZ
  1972. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  1973. ACME_NEW_ORDER_RES="new-cert"
  1974. if [ -z "$ACME_NEW_ORDER" ]; then
  1975. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-order" *: *"[^"]*"' | cut -d '"' -f 3)
  1976. ACME_NEW_ORDER_RES="new-order"
  1977. if [ -z "$ACME_NEW_ORDER" ]; then
  1978. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
  1979. fi
  1980. fi
  1981. export ACME_NEW_ORDER
  1982. export ACME_NEW_ORDER_RES
  1983. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-reg" *: *"[^"]*"' | cut -d '"' -f 3)
  1984. ACME_NEW_ACCOUNT_RES="new-reg"
  1985. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1986. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-account" *: *"[^"]*"' | cut -d '"' -f 3)
  1987. ACME_NEW_ACCOUNT_RES="new-account"
  1988. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1989. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
  1990. if [ "$ACME_NEW_ACCOUNT" ]; then
  1991. export ACME_VERSION=2
  1992. fi
  1993. fi
  1994. fi
  1995. export ACME_NEW_ACCOUNT
  1996. export ACME_NEW_ACCOUNT_RES
  1997. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revoke-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  1998. if [ -z "$ACME_REVOKE_CERT" ]; then
  1999. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
  2000. fi
  2001. export ACME_REVOKE_CERT
  2002. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'new-nonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2003. if [ -z "$ACME_NEW_NONCE" ]; then
  2004. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2005. fi
  2006. export ACME_NEW_NONCE
  2007. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'terms-of-service" *: *"[^"]*"' | cut -d '"' -f 3)
  2008. if [ -z "$ACME_AGREEMENT" ]; then
  2009. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
  2010. fi
  2011. export ACME_AGREEMENT
  2012. _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
  2013. _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
  2014. _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
  2015. _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
  2016. _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
  2017. _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
  2018. _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  2019. _debug "ACME_VERSION" "$ACME_VERSION"
  2020. fi
  2021. }
  2022. #[domain] [keylength or isEcc flag]
  2023. _initpath() {
  2024. domain="$1"
  2025. _ilength="$2"
  2026. __initHome
  2027. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  2028. . "$ACCOUNT_CONF_PATH"
  2029. fi
  2030. if [ "$IN_CRON" ]; then
  2031. if [ ! "$_USER_PATH_EXPORTED" ]; then
  2032. _USER_PATH_EXPORTED=1
  2033. export PATH="$USER_PATH:$PATH"
  2034. fi
  2035. fi
  2036. if [ -z "$CA_HOME" ]; then
  2037. CA_HOME="$DEFAULT_CA_HOME"
  2038. fi
  2039. if [ "$ACME_VERSION" = "2" ]; then
  2040. DEFAULT_CA="$LETSENCRYPT_CA_V2"
  2041. DEFAULT_STAGING_CA="$LETSENCRYPT_STAGING_CA_V2"
  2042. fi
  2043. if [ -z "$ACME_DIRECTORY" ]; then
  2044. if [ -z "$STAGE" ]; then
  2045. ACME_DIRECTORY="$DEFAULT_CA"
  2046. else
  2047. ACME_DIRECTORY="$DEFAULT_STAGING_CA"
  2048. _info "Using stage ACME_DIRECTORY: $ACME_DIRECTORY"
  2049. fi
  2050. fi
  2051. _debug ACME_DIRECTORY "$ACME_DIRECTORY"
  2052. _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
  2053. _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
  2054. CA_DIR="$CA_HOME/$_ACME_SERVER_HOST"
  2055. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  2056. if [ -z "$CA_CONF" ]; then
  2057. CA_CONF="$_DEFAULT_CA_CONF"
  2058. fi
  2059. _debug3 CA_CONF "$CA_CONF"
  2060. if [ -f "$CA_CONF" ]; then
  2061. . "$CA_CONF"
  2062. fi
  2063. if [ -z "$ACME_DIR" ]; then
  2064. ACME_DIR="/home/.acme"
  2065. fi
  2066. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  2067. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  2068. fi
  2069. if [ -z "$USER_AGENT" ]; then
  2070. USER_AGENT="$DEFAULT_USER_AGENT"
  2071. fi
  2072. if [ -z "$HTTP_HEADER" ]; then
  2073. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  2074. fi
  2075. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  2076. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  2077. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  2078. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  2079. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  2080. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  2081. fi
  2082. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  2083. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  2084. fi
  2085. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  2086. if [ -z "$CERT_HOME" ]; then
  2087. CERT_HOME="$_DEFAULT_CERT_HOME"
  2088. fi
  2089. if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
  2090. ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  2091. fi
  2092. if [ -z "$domain" ]; then
  2093. return 0
  2094. fi
  2095. if [ -z "$DOMAIN_PATH" ]; then
  2096. domainhome="$CERT_HOME/$domain"
  2097. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  2098. DOMAIN_PATH="$domainhome"
  2099. if _isEccKey "$_ilength"; then
  2100. DOMAIN_PATH="$domainhomeecc"
  2101. else
  2102. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  2103. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  2104. fi
  2105. fi
  2106. _debug DOMAIN_PATH "$DOMAIN_PATH"
  2107. fi
  2108. if [ -z "$DOMAIN_BACKUP_PATH" ]; then
  2109. DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
  2110. fi
  2111. if [ -z "$DOMAIN_CONF" ]; then
  2112. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  2113. fi
  2114. if [ -z "$DOMAIN_SSL_CONF" ]; then
  2115. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  2116. fi
  2117. if [ -z "$CSR_PATH" ]; then
  2118. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  2119. fi
  2120. if [ -z "$CERT_KEY_PATH" ]; then
  2121. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  2122. fi
  2123. if [ -z "$CERT_PATH" ]; then
  2124. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  2125. fi
  2126. if [ -z "$CA_CERT_PATH" ]; then
  2127. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  2128. fi
  2129. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  2130. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  2131. fi
  2132. if [ -z "$CERT_PFX_PATH" ]; then
  2133. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  2134. fi
  2135. if [ -z "$CERT_PKCS8_PATH" ]; then
  2136. CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
  2137. fi
  2138. if [ -z "$TLS_CONF" ]; then
  2139. TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
  2140. fi
  2141. if [ -z "$TLS_CERT" ]; then
  2142. TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
  2143. fi
  2144. if [ -z "$TLS_KEY" ]; then
  2145. TLS_KEY="$DOMAIN_PATH/tls.validation.key"
  2146. fi
  2147. if [ -z "$TLS_CSR" ]; then
  2148. TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
  2149. fi
  2150. }
  2151. _exec() {
  2152. if [ -z "$_EXEC_TEMP_ERR" ]; then
  2153. _EXEC_TEMP_ERR="$(_mktemp)"
  2154. fi
  2155. if [ "$_EXEC_TEMP_ERR" ]; then
  2156. eval "$@ 2>>$_EXEC_TEMP_ERR"
  2157. else
  2158. eval "$@"
  2159. fi
  2160. }
  2161. _exec_err() {
  2162. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  2163. }
  2164. _apachePath() {
  2165. _APACHECTL="apachectl"
  2166. if ! _exists apachectl; then
  2167. if _exists apache2ctl; then
  2168. _APACHECTL="apache2ctl"
  2169. else
  2170. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  2171. _err "Please use webroot mode to try again."
  2172. return 1
  2173. fi
  2174. fi
  2175. if ! _exec $_APACHECTL -V >/dev/null; then
  2176. _exec_err
  2177. return 1
  2178. fi
  2179. if [ "$APACHE_HTTPD_CONF" ]; then
  2180. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  2181. httpdconf="$APACHE_HTTPD_CONF"
  2182. httpdconfname="$(basename "$httpdconfname")"
  2183. else
  2184. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  2185. _debug httpdconfname "$httpdconfname"
  2186. if [ -z "$httpdconfname" ]; then
  2187. _err "Can not read apache config file."
  2188. return 1
  2189. fi
  2190. if _startswith "$httpdconfname" '/'; then
  2191. httpdconf="$httpdconfname"
  2192. httpdconfname="$(basename "$httpdconfname")"
  2193. else
  2194. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  2195. _debug httpdroot "$httpdroot"
  2196. httpdconf="$httpdroot/$httpdconfname"
  2197. httpdconfname="$(basename "$httpdconfname")"
  2198. fi
  2199. fi
  2200. _debug httpdconf "$httpdconf"
  2201. _debug httpdconfname "$httpdconfname"
  2202. if [ ! -f "$httpdconf" ]; then
  2203. _err "Apache Config file not found" "$httpdconf"
  2204. return 1
  2205. fi
  2206. return 0
  2207. }
  2208. _restoreApache() {
  2209. if [ -z "$usingApache" ]; then
  2210. return 0
  2211. fi
  2212. _initpath
  2213. if ! _apachePath; then
  2214. return 1
  2215. fi
  2216. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  2217. _debug "No config file to restore."
  2218. return 0
  2219. fi
  2220. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  2221. _debug "Restored: $httpdconf."
  2222. if ! _exec $_APACHECTL -t; then
  2223. _exec_err
  2224. _err "Sorry, restore apache config error, please contact me."
  2225. return 1
  2226. fi
  2227. _debug "Restored successfully."
  2228. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2229. return 0
  2230. }
  2231. _setApache() {
  2232. _initpath
  2233. if ! _apachePath; then
  2234. return 1
  2235. fi
  2236. #test the conf first
  2237. _info "Checking if there is an error in the apache config file before starting."
  2238. if ! _exec "$_APACHECTL" -t >/dev/null; then
  2239. _exec_err
  2240. _err "The apache config file has error, please fix it first, then try again."
  2241. _err "Don't worry, there is nothing changed to your system."
  2242. return 1
  2243. else
  2244. _info "OK"
  2245. fi
  2246. #backup the conf
  2247. _debug "Backup apache config file" "$httpdconf"
  2248. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  2249. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  2250. _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
  2251. return 1
  2252. fi
  2253. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2254. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  2255. _info "The backup file will be deleted on success, just forget it."
  2256. #add alias
  2257. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  2258. _debug "apacheVer" "$apacheVer"
  2259. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  2260. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  2261. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  2262. echo "
  2263. Alias /.well-known/acme-challenge $ACME_DIR
  2264. <Directory $ACME_DIR >
  2265. Require all granted
  2266. </Directory>
  2267. " >>"$httpdconf"
  2268. else
  2269. echo "
  2270. Alias /.well-known/acme-challenge $ACME_DIR
  2271. <Directory $ACME_DIR >
  2272. Order allow,deny
  2273. Allow from all
  2274. </Directory>
  2275. " >>"$httpdconf"
  2276. fi
  2277. _msg="$($_APACHECTL -t 2>&1)"
  2278. if [ "$?" != "0" ]; then
  2279. _err "Sorry, apache config error"
  2280. if _restoreApache; then
  2281. _err "The apache config file is restored."
  2282. else
  2283. _err "Sorry, The apache config file can not be restored, please report bug."
  2284. fi
  2285. return 1
  2286. fi
  2287. if [ ! -d "$ACME_DIR" ]; then
  2288. mkdir -p "$ACME_DIR"
  2289. chmod 755 "$ACME_DIR"
  2290. fi
  2291. if ! _exec "$_APACHECTL" graceful; then
  2292. _exec_err
  2293. _err "$_APACHECTL graceful error, please contact me."
  2294. _restoreApache
  2295. return 1
  2296. fi
  2297. usingApache="1"
  2298. return 0
  2299. }
  2300. #find the real nginx conf file
  2301. #backup
  2302. #set the nginx conf
  2303. #returns the real nginx conf file
  2304. _setNginx() {
  2305. _d="$1"
  2306. _croot="$2"
  2307. _thumbpt="$3"
  2308. FOUND_REAL_NGINX_CONF=""
  2309. FOUND_REAL_NGINX_CONF_LN=""
  2310. BACKUP_NGINX_CONF=""
  2311. _debug _croot "$_croot"
  2312. _start_f="$(echo "$_croot" | cut -d : -f 2)"
  2313. _debug _start_f "$_start_f"
  2314. if [ -z "$_start_f" ]; then
  2315. _debug "find start conf from nginx command"
  2316. if [ -z "$NGINX_CONF" ]; then
  2317. if ! _exists "nginx"; then
  2318. _err "nginx command is not found."
  2319. return 1
  2320. fi
  2321. NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
  2322. _debug NGINX_CONF "$NGINX_CONF"
  2323. NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
  2324. _debug NGINX_CONF "$NGINX_CONF"
  2325. if [ ! -f "$NGINX_CONF" ]; then
  2326. _err "'$NGINX_CONF' doesn't exist."
  2327. NGINX_CONF=""
  2328. return 1
  2329. fi
  2330. _debug "Found nginx conf file:$NGINX_CONF"
  2331. fi
  2332. _start_f="$NGINX_CONF"
  2333. fi
  2334. _debug "Start detect nginx conf for $_d from:$_start_f"
  2335. if ! _checkConf "$_d" "$_start_f"; then
  2336. _err "Can not find conf file for domain $d"
  2337. return 1
  2338. fi
  2339. _info "Found conf file: $FOUND_REAL_NGINX_CONF"
  2340. _ln=$FOUND_REAL_NGINX_CONF_LN
  2341. _debug "_ln" "$_ln"
  2342. _lnn=$(_math $_ln + 1)
  2343. _debug _lnn "$_lnn"
  2344. _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
  2345. _debug "_start_tag" "$_start_tag"
  2346. if [ "$_start_tag" = "$NGINX_START" ]; then
  2347. _info "The domain $_d is already configured, skip"
  2348. FOUND_REAL_NGINX_CONF=""
  2349. return 0
  2350. fi
  2351. mkdir -p "$DOMAIN_BACKUP_PATH"
  2352. _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
  2353. _debug _backup_conf "$_backup_conf"
  2354. BACKUP_NGINX_CONF="$_backup_conf"
  2355. _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
  2356. if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
  2357. _err "backup error."
  2358. FOUND_REAL_NGINX_CONF=""
  2359. return 1
  2360. fi
  2361. if ! _exists "nginx"; then
  2362. _err "nginx command is not found."
  2363. return 1
  2364. fi
  2365. _info "Check the nginx conf before setting up."
  2366. if ! _exec "nginx -t" >/dev/null; then
  2367. _exec_err
  2368. return 1
  2369. fi
  2370. _info "OK, Set up nginx config file"
  2371. if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
  2372. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2373. _err "write nginx conf error, but don't worry, the file is restored to the original version."
  2374. return 1
  2375. fi
  2376. echo "$NGINX_START
  2377. location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
  2378. default_type text/plain;
  2379. return 200 \"\$1.$_thumbpt\";
  2380. }
  2381. #NGINX_START
  2382. " >>"$FOUND_REAL_NGINX_CONF"
  2383. if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
  2384. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2385. _err "write nginx conf error, but don't worry, the file is restored."
  2386. return 1
  2387. fi
  2388. _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
  2389. _info "nginx conf is done, let's check it again."
  2390. if ! _exec "nginx -t" >/dev/null; then
  2391. _exec_err
  2392. _err "It seems that nginx conf was broken, let's restore."
  2393. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2394. return 1
  2395. fi
  2396. _info "Reload nginx"
  2397. if ! _exec "nginx -s reload" >/dev/null; then
  2398. _exec_err
  2399. _err "It seems that nginx reload error, let's restore."
  2400. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2401. return 1
  2402. fi
  2403. return 0
  2404. }
  2405. #d , conf
  2406. _checkConf() {
  2407. _d="$1"
  2408. _c_file="$2"
  2409. _debug "Start _checkConf from:$_c_file"
  2410. if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
  2411. _debug "wildcard"
  2412. for _w_f in $2; do
  2413. if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
  2414. return 0
  2415. fi
  2416. done
  2417. #not found
  2418. return 1
  2419. elif [ -f "$2" ]; then
  2420. _debug "single"
  2421. if _isRealNginxConf "$1" "$2"; then
  2422. _debug "$2 is found."
  2423. FOUND_REAL_NGINX_CONF="$2"
  2424. return 0
  2425. fi
  2426. if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
  2427. _debug "Try include files"
  2428. for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
  2429. _debug "check included $included"
  2430. if _checkConf "$1" "$included"; then
  2431. return 0
  2432. fi
  2433. done
  2434. fi
  2435. return 1
  2436. else
  2437. _debug "$2 not found."
  2438. return 1
  2439. fi
  2440. return 1
  2441. }
  2442. #d , conf
  2443. _isRealNginxConf() {
  2444. _debug "_isRealNginxConf $1 $2"
  2445. if [ -f "$2" ]; then
  2446. for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
  2447. _debug _fln "$_fln"
  2448. if [ "$_fln" ]; then
  2449. _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *" | grep -v server_name | _tail_n 1)
  2450. _debug "_start" "$_start"
  2451. _start_n=$(echo "$_start" | cut -d : -f 1)
  2452. _start_nn=$(_math $_start_n + 1)
  2453. _debug "_start_n" "$_start_n"
  2454. _debug "_start_nn" "$_start_nn"
  2455. _left="$(sed -n "${_start_nn},99999p" "$2")"
  2456. _debug2 _left "$_left"
  2457. _end="$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *" | grep -v server_name | _head_n 1)"
  2458. _debug "_end" "$_end"
  2459. if [ "$_end" ]; then
  2460. _end_n=$(echo "$_end" | cut -d : -f 1)
  2461. _debug "_end_n" "$_end_n"
  2462. _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
  2463. else
  2464. _seg_n="$_left"
  2465. fi
  2466. _debug "_seg_n" "$_seg_n"
  2467. _skip_ssl=1
  2468. for _listen_i in $(echo "$_seg_n" | tr "\t" ' ' | grep "^ *listen" | tr -d " "); do
  2469. if [ "$_listen_i" ]; then
  2470. if [ "$(echo "$_listen_i" | _egrep_o "listen.*ssl")" ]; then
  2471. _debug2 "$_listen_i is ssl"
  2472. else
  2473. _debug2 "$_listen_i is plain text"
  2474. _skip_ssl=""
  2475. break
  2476. fi
  2477. fi
  2478. done
  2479. if [ "$_skip_ssl" = "1" ]; then
  2480. _debug "ssl on, skip"
  2481. else
  2482. FOUND_REAL_NGINX_CONF_LN=$_fln
  2483. _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
  2484. return 0
  2485. fi
  2486. fi
  2487. done
  2488. fi
  2489. return 1
  2490. }
  2491. #restore all the nginx conf
  2492. _restoreNginx() {
  2493. if [ -z "$NGINX_RESTORE_VLIST" ]; then
  2494. _debug "No need to restore nginx, skip."
  2495. return
  2496. fi
  2497. _debug "_restoreNginx"
  2498. _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
  2499. for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
  2500. _debug "ng_entry" "$ng_entry"
  2501. _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
  2502. _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
  2503. _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
  2504. _info "Restoring from $_ngbackupconf to $_ngconf"
  2505. cat "$_ngbackupconf" >"$_ngconf"
  2506. done
  2507. _info "Reload nginx"
  2508. if ! _exec "nginx -s reload" >/dev/null; then
  2509. _exec_err
  2510. _err "It seems that nginx reload error, please report bug."
  2511. return 1
  2512. fi
  2513. return 0
  2514. }
  2515. _clearup() {
  2516. _stopserver "$serverproc"
  2517. serverproc=""
  2518. _restoreApache
  2519. _restoreNginx
  2520. _clearupdns
  2521. if [ -z "$DEBUG" ]; then
  2522. rm -f "$TLS_CONF"
  2523. rm -f "$TLS_CERT"
  2524. rm -f "$TLS_KEY"
  2525. rm -f "$TLS_CSR"
  2526. fi
  2527. }
  2528. _clearupdns() {
  2529. _debug "_clearupdns"
  2530. _debug "dnsadded" "$dnsadded"
  2531. _debug "vlist" "$vlist"
  2532. #dnsadded is "0" or "1" means dns-01 method was used for at least one domain
  2533. if [ -z "$dnsadded" ] || [ -z "$vlist" ]; then
  2534. _debug "skip dns."
  2535. return
  2536. fi
  2537. _info "Removing DNS records."
  2538. ventries=$(echo "$vlist" | tr ',' ' ')
  2539. _alias_index=1
  2540. for ventry in $ventries; do
  2541. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2542. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2543. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2544. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2545. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  2546. _debug txt "$txt"
  2547. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2548. _debug "$d is already verified, skip $vtype."
  2549. _alias_index="$(_math "$_alias_index" + 1)"
  2550. continue
  2551. fi
  2552. if [ "$vtype" != "$VTYPE_DNS" ]; then
  2553. _debug "Skip $d for $vtype"
  2554. continue
  2555. fi
  2556. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2557. _debug d_api "$d_api"
  2558. if [ -z "$d_api" ]; then
  2559. _info "Not Found domain api file: $d_api"
  2560. continue
  2561. fi
  2562. (
  2563. if ! . "$d_api"; then
  2564. _err "Load file $d_api error. Please check your api file and try again."
  2565. return 1
  2566. fi
  2567. rmcommand="${_currentRoot}_rm"
  2568. if ! _exists "$rmcommand"; then
  2569. _err "It seems that your api file doesn't define $rmcommand"
  2570. return 1
  2571. fi
  2572. _dns_root_d="$d"
  2573. if _startswith "$_dns_root_d" "*."; then
  2574. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  2575. fi
  2576. _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
  2577. _alias_index="$(_math "$_alias_index" + 1)"
  2578. _debug "_d_alias" "$_d_alias"
  2579. if [ "$_d_alias" ]; then
  2580. if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
  2581. txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
  2582. else
  2583. txtdomain="_acme-challenge.$_d_alias"
  2584. fi
  2585. else
  2586. txtdomain="_acme-challenge.$_dns_root_d"
  2587. fi
  2588. if ! $rmcommand "$txtdomain" "$txt"; then
  2589. _err "Error removing txt for domain:$txtdomain"
  2590. return 1
  2591. fi
  2592. )
  2593. done
  2594. }
  2595. # webroot removelevel tokenfile
  2596. _clearupwebbroot() {
  2597. __webroot="$1"
  2598. if [ -z "$__webroot" ]; then
  2599. _debug "no webroot specified, skip"
  2600. return 0
  2601. fi
  2602. _rmpath=""
  2603. if [ "$2" = '1' ]; then
  2604. _rmpath="$__webroot/.well-known"
  2605. elif [ "$2" = '2' ]; then
  2606. _rmpath="$__webroot/.well-known/acme-challenge"
  2607. elif [ "$2" = '3' ]; then
  2608. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  2609. else
  2610. _debug "Skip for removelevel:$2"
  2611. fi
  2612. if [ "$_rmpath" ]; then
  2613. if [ "$DEBUG" ]; then
  2614. _debug "Debugging, skip removing: $_rmpath"
  2615. else
  2616. rm -rf "$_rmpath"
  2617. fi
  2618. fi
  2619. return 0
  2620. }
  2621. _on_before_issue() {
  2622. _chk_web_roots="$1"
  2623. _chk_main_domain="$2"
  2624. _chk_alt_domains="$3"
  2625. _chk_pre_hook="$4"
  2626. _chk_local_addr="$5"
  2627. _debug _on_before_issue
  2628. _debug _chk_main_domain "$_chk_main_domain"
  2629. _debug _chk_alt_domains "$_chk_alt_domains"
  2630. #run pre hook
  2631. if [ "$_chk_pre_hook" ]; then
  2632. _info "Run pre hook:'$_chk_pre_hook'"
  2633. if ! (
  2634. cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
  2635. ); then
  2636. _err "Error when run pre hook."
  2637. return 1
  2638. fi
  2639. fi
  2640. if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
  2641. if ! _exists "socat"; then
  2642. _err "Please install socat tools first."
  2643. return 1
  2644. fi
  2645. fi
  2646. _debug Le_LocalAddress "$_chk_local_addr"
  2647. _index=1
  2648. _currentRoot=""
  2649. _addrIndex=1
  2650. _w_index=1
  2651. while true; do
  2652. d="$(echo "$_chk_main_domain,$_chk_alt_domains," | cut -d , -f "$_w_index")"
  2653. _w_index="$(_math "$_w_index" + 1)"
  2654. _debug d "$d"
  2655. if [ -z "$d" ]; then
  2656. break
  2657. fi
  2658. _debug "Check for domain" "$d"
  2659. _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
  2660. _debug "_currentRoot" "$_currentRoot"
  2661. _index=$(_math $_index + 1)
  2662. _checkport=""
  2663. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2664. _info "Standalone mode."
  2665. if [ -z "$Le_HTTPPort" ]; then
  2666. Le_HTTPPort=80
  2667. else
  2668. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  2669. fi
  2670. _checkport="$Le_HTTPPort"
  2671. elif [ "$_currentRoot" = "$W_ALPN" ]; then
  2672. _info "Standalone alpn mode."
  2673. if [ -z "$Le_TLSPort" ]; then
  2674. Le_TLSPort=443
  2675. else
  2676. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  2677. fi
  2678. _checkport="$Le_TLSPort"
  2679. fi
  2680. if [ "$_checkport" ]; then
  2681. _debug _checkport "$_checkport"
  2682. _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
  2683. _debug _checkaddr "$_checkaddr"
  2684. _addrIndex="$(_math $_addrIndex + 1)"
  2685. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  2686. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  2687. if [ -z "$netprc" ]; then
  2688. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  2689. fi
  2690. if [ "$netprc" ]; then
  2691. _err "$netprc"
  2692. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  2693. _err "Please stop it first"
  2694. return 1
  2695. fi
  2696. fi
  2697. done
  2698. if _hasfield "$_chk_web_roots" "apache"; then
  2699. if ! _setApache; then
  2700. _err "set up apache error. Report error to me."
  2701. return 1
  2702. fi
  2703. else
  2704. usingApache=""
  2705. fi
  2706. }
  2707. _on_issue_err() {
  2708. _chk_post_hook="$1"
  2709. _chk_vlist="$2"
  2710. _debug _on_issue_err
  2711. if [ "$LOG_FILE" ]; then
  2712. _err "Please check log file for more details: $LOG_FILE"
  2713. else
  2714. _err "Please add '--debug' or '--log' to check more details."
  2715. _err "See: $_DEBUG_WIKI"
  2716. fi
  2717. #run the post hook
  2718. if [ "$_chk_post_hook" ]; then
  2719. _info "Run post hook:'$_chk_post_hook'"
  2720. if ! (
  2721. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2722. ); then
  2723. _err "Error when run post hook."
  2724. return 1
  2725. fi
  2726. fi
  2727. #trigger the validation to flush the pending authz
  2728. _debug2 "_chk_vlist" "$_chk_vlist"
  2729. if [ "$_chk_vlist" ]; then
  2730. (
  2731. _debug2 "start to deactivate authz"
  2732. ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
  2733. for ventry in $ventries; do
  2734. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2735. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2736. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2737. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2738. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2739. __trigger_validation "$uri" "$keyauthorization"
  2740. done
  2741. )
  2742. fi
  2743. if [ "$IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "$W_DNS"; then
  2744. _err "$_DNS_MANUAL_ERR"
  2745. fi
  2746. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  2747. _debug "$(_dlg_versions)"
  2748. fi
  2749. }
  2750. _on_issue_success() {
  2751. _chk_post_hook="$1"
  2752. _chk_renew_hook="$2"
  2753. _debug _on_issue_success
  2754. #run the post hook
  2755. if [ "$_chk_post_hook" ]; then
  2756. _info "Run post hook:'$_chk_post_hook'"
  2757. if ! (
  2758. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2759. ); then
  2760. _err "Error when run post hook."
  2761. return 1
  2762. fi
  2763. fi
  2764. #run renew hook
  2765. if [ "$IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
  2766. _info "Run renew hook:'$_chk_renew_hook'"
  2767. if ! (
  2768. cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
  2769. ); then
  2770. _err "Error when run renew hook."
  2771. return 1
  2772. fi
  2773. fi
  2774. if _hasfield "$Le_Webroot" "$W_DNS"; then
  2775. _err "$_DNS_MANUAL_WARN"
  2776. fi
  2777. }
  2778. updateaccount() {
  2779. _initpath
  2780. _regAccount
  2781. }
  2782. registeraccount() {
  2783. _reg_length="$1"
  2784. _initpath
  2785. _regAccount "$_reg_length"
  2786. }
  2787. __calcAccountKeyHash() {
  2788. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  2789. }
  2790. __calc_account_thumbprint() {
  2791. printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
  2792. }
  2793. #keylength
  2794. _regAccount() {
  2795. _initpath
  2796. _reg_length="$1"
  2797. _debug3 _regAccount "$_regAccount"
  2798. _initAPI
  2799. mkdir -p "$CA_DIR"
  2800. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2801. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2802. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2803. fi
  2804. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2805. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2806. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2807. fi
  2808. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2809. if ! _create_account_key "$_reg_length"; then
  2810. _err "Create account key error."
  2811. return 1
  2812. fi
  2813. fi
  2814. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2815. return 1
  2816. fi
  2817. if [ "$ACME_VERSION" = "2" ]; then
  2818. regjson='{"termsOfServiceAgreed": true}'
  2819. if [ "$ACCOUNT_EMAIL" ]; then
  2820. regjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"], "termsOfServiceAgreed": true}'
  2821. fi
  2822. else
  2823. _reg_res="$ACME_NEW_ACCOUNT_RES"
  2824. regjson='{"resource": "'$_reg_res'", "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2825. if [ "$ACCOUNT_EMAIL" ]; then
  2826. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2827. fi
  2828. fi
  2829. _info "Registering account"
  2830. if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
  2831. _err "Register account Error: $response"
  2832. return 1
  2833. fi
  2834. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  2835. echo "$response" >"$ACCOUNT_JSON_PATH"
  2836. _info "Registered"
  2837. elif [ "$code" = '409' ] || [ "$code" = '200' ]; then
  2838. _info "Already registered"
  2839. else
  2840. _err "Register account Error: $response"
  2841. return 1
  2842. fi
  2843. _debug2 responseHeaders "$responseHeaders"
  2844. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2845. _debug "_accUri" "$_accUri"
  2846. if [ -z "$_accUri" ]; then
  2847. _err "Can not find account id url."
  2848. _err "$responseHeaders"
  2849. return 1
  2850. fi
  2851. _savecaconf "ACCOUNT_URL" "$_accUri"
  2852. export ACCOUNT_URL="$_accUri"
  2853. CA_KEY_HASH="$(__calcAccountKeyHash)"
  2854. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  2855. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  2856. if [ "$code" = '403' ]; then
  2857. _err "It seems that the account key is already deactivated, please use a new account key."
  2858. return 1
  2859. fi
  2860. ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
  2861. _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
  2862. }
  2863. #Implement deactivate account
  2864. deactivateaccount() {
  2865. _initpath
  2866. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2867. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2868. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2869. fi
  2870. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2871. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2872. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2873. fi
  2874. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2875. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  2876. return 1
  2877. fi
  2878. _accUri=$(_readcaconf "ACCOUNT_URL")
  2879. _debug _accUri "$_accUri"
  2880. if [ -z "$_accUri" ]; then
  2881. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  2882. _err "Then try again."
  2883. return 1
  2884. fi
  2885. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2886. return 1
  2887. fi
  2888. _initAPI
  2889. if [ "$ACME_VERSION" = "2" ]; then
  2890. _djson="{\"status\":\"deactivated\"}"
  2891. else
  2892. _djson="{\"resource\": \"reg\", \"status\":\"deactivated\"}"
  2893. fi
  2894. if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
  2895. _info "Deactivate account success for $_accUri."
  2896. _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
  2897. elif [ "$code" = "403" ]; then
  2898. _info "The account is already deactivated."
  2899. _accid=$(_getfield "$_accUri" "999" "/")
  2900. else
  2901. _err "Deactivate: account failed for $_accUri."
  2902. return 1
  2903. fi
  2904. _debug "Account id: $_accid"
  2905. if [ "$_accid" ]; then
  2906. _deactivated_account_path="$CA_DIR/deactivated/$_accid"
  2907. _debug _deactivated_account_path "$_deactivated_account_path"
  2908. if mkdir -p "$_deactivated_account_path"; then
  2909. _info "Moving deactivated account info to $_deactivated_account_path/"
  2910. mv "$CA_CONF" "$_deactivated_account_path/"
  2911. mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
  2912. mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
  2913. else
  2914. _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
  2915. rm -f "$CA_CONF"
  2916. rm -f "$ACCOUNT_JSON_PATH"
  2917. rm -f "$ACCOUNT_KEY_PATH"
  2918. fi
  2919. fi
  2920. }
  2921. # domain folder file
  2922. _findHook() {
  2923. _hookdomain="$1"
  2924. _hookcat="$2"
  2925. _hookname="$3"
  2926. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  2927. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  2928. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  2929. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  2930. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  2931. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  2932. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  2933. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  2934. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  2935. d_api="$LE_WORKING_DIR/$_hookname"
  2936. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  2937. d_api="$LE_WORKING_DIR/$_hookname.sh"
  2938. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  2939. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  2940. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  2941. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  2942. fi
  2943. printf "%s" "$d_api"
  2944. }
  2945. #domain
  2946. __get_domain_new_authz() {
  2947. _gdnd="$1"
  2948. _info "Getting new-authz for domain" "$_gdnd"
  2949. _initAPI
  2950. _Max_new_authz_retry_times=5
  2951. _authz_i=0
  2952. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  2953. _debug "Try new-authz for the $_authz_i time."
  2954. if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  2955. _err "Can not get domain new authz."
  2956. return 1
  2957. fi
  2958. if _contains "$response" "No registration exists matching provided key"; then
  2959. _err "It seems there is an error, but it's recovered now, please try again."
  2960. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  2961. _clearcaconf "CA_KEY_HASH"
  2962. break
  2963. fi
  2964. if ! _contains "$response" "An error occurred while processing your request"; then
  2965. _info "The new-authz request is ok."
  2966. break
  2967. fi
  2968. _authz_i="$(_math "$_authz_i" + 1)"
  2969. _info "The server is busy, Sleep $_authz_i to retry."
  2970. _sleep "$_authz_i"
  2971. done
  2972. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  2973. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2974. fi
  2975. if [ "$code" ] && [ "$code" != '201' ]; then
  2976. _err "new-authz error: $response"
  2977. return 1
  2978. fi
  2979. }
  2980. #uri keyAuthorization
  2981. __trigger_validation() {
  2982. _debug2 "Trigger domain validation."
  2983. _t_url="$1"
  2984. _debug2 _t_url "$_t_url"
  2985. _t_key_authz="$2"
  2986. _debug2 _t_key_authz "$_t_key_authz"
  2987. _t_vtype="$3"
  2988. _debug2 _t_vtype "$_t_vtype"
  2989. if [ "$ACME_VERSION" = "2" ]; then
  2990. _send_signed_request "$_t_url" "{\"keyAuthorization\": \"$_t_key_authz\"}"
  2991. else
  2992. _send_signed_request "$_t_url" "{\"resource\": \"challenge\", \"type\": \"$_t_vtype\", \"keyAuthorization\": \"$_t_key_authz\"}"
  2993. fi
  2994. }
  2995. #webroot, domain domainlist keylength
  2996. issue() {
  2997. if [ -z "$2" ]; then
  2998. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2999. return 1
  3000. fi
  3001. if [ -z "$1" ]; then
  3002. _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
  3003. return 1
  3004. fi
  3005. _web_roots="$1"
  3006. _main_domain="$2"
  3007. _alt_domains="$3"
  3008. if _contains "$_main_domain" ","; then
  3009. _main_domain=$(echo "$2,$3" | cut -d , -f 1)
  3010. _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  3011. fi
  3012. _debug _main_domain "$_main_domain"
  3013. _debug _alt_domains "$_alt_domains"
  3014. _key_length="$4"
  3015. _real_cert="$5"
  3016. _real_key="$6"
  3017. _real_ca="$7"
  3018. _reload_cmd="$8"
  3019. _real_fullchain="$9"
  3020. _pre_hook="${10}"
  3021. _post_hook="${11}"
  3022. _renew_hook="${12}"
  3023. _local_addr="${13}"
  3024. _challenge_alias="${14}"
  3025. #remove these later.
  3026. if [ "$_web_roots" = "dns-cf" ]; then
  3027. _web_roots="dns_cf"
  3028. fi
  3029. if [ "$_web_roots" = "dns-dp" ]; then
  3030. _web_roots="dns_dp"
  3031. fi
  3032. if [ "$_web_roots" = "dns-cx" ]; then
  3033. _web_roots="dns_cx"
  3034. fi
  3035. if [ ! "$IS_RENEW" ]; then
  3036. _initpath "$_main_domain" "$_key_length"
  3037. mkdir -p "$DOMAIN_PATH"
  3038. fi
  3039. if _hasfield "$_web_roots" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
  3040. _err "$_DNS_MANUAL_ERROR"
  3041. return 1
  3042. fi
  3043. _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
  3044. _initAPI
  3045. if [ -f "$DOMAIN_CONF" ]; then
  3046. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  3047. _debug Le_NextRenewTime "$Le_NextRenewTime"
  3048. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3049. _saved_domain=$(_readdomainconf Le_Domain)
  3050. _debug _saved_domain "$_saved_domain"
  3051. _saved_alt=$(_readdomainconf Le_Alt)
  3052. _debug _saved_alt "$_saved_alt"
  3053. if [ "$_saved_domain,$_saved_alt" = "$_main_domain,$_alt_domains" ]; then
  3054. _info "Domains not changed."
  3055. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  3056. _info "Add '$(__red '--force')' to force to renew."
  3057. return $RENEW_SKIP
  3058. else
  3059. _info "Domains have changed."
  3060. fi
  3061. fi
  3062. fi
  3063. _savedomainconf "Le_Domain" "$_main_domain"
  3064. _savedomainconf "Le_Alt" "$_alt_domains"
  3065. _savedomainconf "Le_Webroot" "$_web_roots"
  3066. _savedomainconf "Le_PreHook" "$_pre_hook"
  3067. _savedomainconf "Le_PostHook" "$_post_hook"
  3068. _savedomainconf "Le_RenewHook" "$_renew_hook"
  3069. if [ "$_local_addr" ]; then
  3070. _savedomainconf "Le_LocalAddress" "$_local_addr"
  3071. else
  3072. _cleardomainconf "Le_LocalAddress"
  3073. fi
  3074. if [ "$_challenge_alias" ]; then
  3075. _savedomainconf "Le_ChallengeAlias" "$_challenge_alias"
  3076. else
  3077. _cleardomainconf "Le_ChallengeAlias"
  3078. fi
  3079. Le_API="$ACME_DIRECTORY"
  3080. _savedomainconf "Le_API" "$Le_API"
  3081. if [ "$_alt_domains" = "$NO_VALUE" ]; then
  3082. _alt_domains=""
  3083. fi
  3084. if [ "$_key_length" = "$NO_VALUE" ]; then
  3085. _key_length=""
  3086. fi
  3087. if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
  3088. _err "_on_before_issue."
  3089. return 1
  3090. fi
  3091. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  3092. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  3093. if [ -z "$ACCOUNT_URL" ] || [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  3094. if ! _regAccount "$_accountkeylength"; then
  3095. _on_issue_err "$_post_hook"
  3096. return 1
  3097. fi
  3098. else
  3099. _debug "_saved_account_key_hash is not changed, skip register account."
  3100. fi
  3101. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  3102. _info "Signing from existing CSR."
  3103. else
  3104. _key=$(_readdomainconf Le_Keylength)
  3105. _debug "Read key length:$_key"
  3106. if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
  3107. if ! createDomainKey "$_main_domain" "$_key_length"; then
  3108. _err "Create domain key error."
  3109. _clearup
  3110. _on_issue_err "$_post_hook"
  3111. return 1
  3112. fi
  3113. fi
  3114. if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  3115. _err "Create CSR error."
  3116. _clearup
  3117. _on_issue_err "$_post_hook"
  3118. return 1
  3119. fi
  3120. fi
  3121. _savedomainconf "Le_Keylength" "$_key_length"
  3122. vlist="$Le_Vlist"
  3123. _info "Getting domain auth token for each domain"
  3124. sep='#'
  3125. dvsep=','
  3126. if [ -z "$vlist" ]; then
  3127. if [ "$ACME_VERSION" = "2" ]; then
  3128. #make new order request
  3129. _identifiers="{\"type\":\"dns\",\"value\":\"$_main_domain\"}"
  3130. _w_index=1
  3131. while true; do
  3132. d="$(echo "$_alt_domains," | cut -d , -f "$_w_index")"
  3133. _w_index="$(_math "$_w_index" + 1)"
  3134. _debug d "$d"
  3135. if [ -z "$d" ]; then
  3136. break
  3137. fi
  3138. _identifiers="$_identifiers,{\"type\":\"dns\",\"value\":\"$d\"}"
  3139. done
  3140. _debug2 _identifiers "$_identifiers"
  3141. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  3142. _err "Create new order error."
  3143. _clearup
  3144. _on_issue_err "$_post_hook"
  3145. return 1
  3146. fi
  3147. Le_OrderFinalize="$(echo "$response" | tr -d '\r\n' | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
  3148. _debug Le_OrderFinalize "$Le_OrderFinalize"
  3149. if [ -z "$Le_OrderFinalize" ]; then
  3150. _err "Create new order error. Le_OrderFinalize not found. $response"
  3151. _clearup
  3152. _on_issue_err "$_post_hook"
  3153. return 1
  3154. fi
  3155. #for dns manual mode
  3156. _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
  3157. _authorizations_seg="$(echo "$response" | tr -d '\r\n' | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  3158. _debug2 _authorizations_seg "$_authorizations_seg"
  3159. if [ -z "$_authorizations_seg" ]; then
  3160. _err "_authorizations_seg not found."
  3161. _clearup
  3162. _on_issue_err "$_post_hook"
  3163. return 1
  3164. fi
  3165. #domain and authz map
  3166. _authorizations_map=""
  3167. for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
  3168. _debug2 "_authz_url" "$_authz_url"
  3169. if ! _send_signed_request "$_authz_url"; then
  3170. _err "get to authz error."
  3171. _err "_authorizations_seg" "$_authorizations_seg"
  3172. _err "_authz_url" "$_authz_url"
  3173. _clearup
  3174. _on_issue_err "$_post_hook"
  3175. return 1
  3176. fi
  3177. response="$(echo "$response" | _normalizeJson)"
  3178. _debug2 response "$response"
  3179. _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2 | tr -d ' "')"
  3180. if _contains "$response" "\"wildcard\" *: *true"; then
  3181. _d="*.$_d"
  3182. fi
  3183. _debug2 _d "$_d"
  3184. _authorizations_map="$_d,$response
  3185. $_authorizations_map"
  3186. done
  3187. _debug2 _authorizations_map "$_authorizations_map"
  3188. fi
  3189. _index=0
  3190. _currentRoot=""
  3191. _w_index=1
  3192. while true; do
  3193. d="$(echo "$_main_domain,$_alt_domains," | cut -d , -f "$_w_index")"
  3194. _w_index="$(_math "$_w_index" + 1)"
  3195. _debug d "$d"
  3196. if [ -z "$d" ]; then
  3197. break
  3198. fi
  3199. _info "Getting webroot for domain" "$d"
  3200. _index=$(_math $_index + 1)
  3201. _w="$(echo $_web_roots | cut -d , -f $_index)"
  3202. _debug _w "$_w"
  3203. if [ "$_w" ]; then
  3204. _currentRoot="$_w"
  3205. fi
  3206. _debug "_currentRoot" "$_currentRoot"
  3207. vtype="$VTYPE_HTTP"
  3208. #todo, v2 wildcard force to use dns
  3209. if _startswith "$_currentRoot" "$W_DNS"; then
  3210. vtype="$VTYPE_DNS"
  3211. fi
  3212. if [ "$_currentRoot" = "$W_ALPN" ]; then
  3213. vtype="$VTYPE_ALPN"
  3214. fi
  3215. if [ "$ACME_VERSION" = "2" ]; then
  3216. response="$(echo "$_authorizations_map" | grep "^$d," | sed "s/$d,//")"
  3217. _debug2 "response" "$response"
  3218. if [ -z "$response" ]; then
  3219. _err "get to authz error."
  3220. _err "_authorizations_map" "$_authorizations_map"
  3221. _clearup
  3222. _on_issue_err "$_post_hook"
  3223. return 1
  3224. fi
  3225. else
  3226. if ! __get_domain_new_authz "$d"; then
  3227. _clearup
  3228. _on_issue_err "$_post_hook"
  3229. return 1
  3230. fi
  3231. fi
  3232. if [ -z "$thumbprint" ]; then
  3233. thumbprint="$(__calc_account_thumbprint)"
  3234. fi
  3235. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  3236. _debug entry "$entry"
  3237. if [ -z "$entry" ]; then
  3238. _err "Error, can not get domain token entry $d"
  3239. _supported_vtypes="$(echo "$response" | _egrep_o "\"challenges\":\[[^]]*]" | tr '{' "\n" | grep type | cut -d '"' -f 4 | tr "\n" ' ')"
  3240. if [ "$_supported_vtypes" ]; then
  3241. _err "The supported validation types are: $_supported_vtypes, but you specified: $vtype"
  3242. fi
  3243. _clearup
  3244. _on_issue_err "$_post_hook"
  3245. return 1
  3246. fi
  3247. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  3248. _debug token "$token"
  3249. if [ -z "$token" ]; then
  3250. _err "Error, can not get domain token $entry"
  3251. _clearup
  3252. _on_issue_err "$_post_hook"
  3253. return 1
  3254. fi
  3255. if [ "$ACME_VERSION" = "2" ]; then
  3256. uri="$(printf "%s\n" "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
  3257. else
  3258. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d '"' -f 4)"
  3259. fi
  3260. _debug uri "$uri"
  3261. if [ -z "$uri" ]; then
  3262. _err "Error, can not get domain uri. $entry"
  3263. _clearup
  3264. _on_issue_err "$_post_hook"
  3265. return 1
  3266. fi
  3267. keyauthorization="$token.$thumbprint"
  3268. _debug keyauthorization "$keyauthorization"
  3269. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  3270. _debug "$d is already verified."
  3271. keyauthorization="$STATE_VERIFIED"
  3272. _debug keyauthorization "$keyauthorization"
  3273. fi
  3274. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  3275. _debug dvlist "$dvlist"
  3276. vlist="$vlist$dvlist$dvsep"
  3277. done
  3278. _debug vlist "$vlist"
  3279. #add entry
  3280. dnsadded=""
  3281. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3282. _alias_index=1
  3283. for ventry in $ventries; do
  3284. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3285. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3286. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3287. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3288. _debug d "$d"
  3289. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3290. _debug "$d is already verified, skip $vtype."
  3291. _alias_index="$(_math "$_alias_index" + 1)"
  3292. continue
  3293. fi
  3294. if [ "$vtype" = "$VTYPE_DNS" ]; then
  3295. dnsadded='0'
  3296. _dns_root_d="$d"
  3297. if _startswith "$_dns_root_d" "*."; then
  3298. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  3299. fi
  3300. _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
  3301. _alias_index="$(_math "$_alias_index" + 1)"
  3302. _debug "_d_alias" "$_d_alias"
  3303. if [ "$_d_alias" ]; then
  3304. if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
  3305. txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
  3306. else
  3307. txtdomain="_acme-challenge.$_d_alias"
  3308. fi
  3309. else
  3310. txtdomain="_acme-challenge.$_dns_root_d"
  3311. fi
  3312. _debug txtdomain "$txtdomain"
  3313. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  3314. _debug txt "$txt"
  3315. d_api="$(_findHook "$_dns_root_d" dnsapi "$_currentRoot")"
  3316. _debug d_api "$d_api"
  3317. if [ "$d_api" ]; then
  3318. _info "Found domain api file: $d_api"
  3319. else
  3320. if [ "$_currentRoot" != "$W_DNS" ]; then
  3321. _err "Can not find dns api hook for: $_currentRoot"
  3322. _info "You need to add the txt record manually."
  3323. fi
  3324. _info "$(__red "Add the following TXT record:")"
  3325. _info "$(__red "Domain: '$(__green "$txtdomain")'")"
  3326. _info "$(__red "TXT value: '$(__green "$txt")'")"
  3327. _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
  3328. _info "$(__red "so the resulting subdomain will be: $txtdomain")"
  3329. continue
  3330. fi
  3331. (
  3332. if ! . "$d_api"; then
  3333. _err "Load file $d_api error. Please check your api file and try again."
  3334. return 1
  3335. fi
  3336. addcommand="${_currentRoot}_add"
  3337. if ! _exists "$addcommand"; then
  3338. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  3339. return 1
  3340. fi
  3341. if ! $addcommand "$txtdomain" "$txt"; then
  3342. _err "Error add txt for domain:$txtdomain"
  3343. return 1
  3344. fi
  3345. )
  3346. if [ "$?" != "0" ]; then
  3347. _on_issue_err "$_post_hook" "$vlist"
  3348. _clearup
  3349. return 1
  3350. fi
  3351. dnsadded='1'
  3352. fi
  3353. done
  3354. if [ "$dnsadded" = '0' ]; then
  3355. _savedomainconf "Le_Vlist" "$vlist"
  3356. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  3357. _err "Please add the TXT records to the domains, and re-run with --renew."
  3358. _on_issue_err "$_post_hook"
  3359. _clearup
  3360. return 1
  3361. fi
  3362. fi
  3363. if [ "$dnsadded" = '1' ]; then
  3364. if [ -z "$Le_DNSSleep" ]; then
  3365. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  3366. else
  3367. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  3368. fi
  3369. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  3370. _sleep "$Le_DNSSleep"
  3371. fi
  3372. NGINX_RESTORE_VLIST=""
  3373. _debug "ok, let's start to verify"
  3374. _ncIndex=1
  3375. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3376. for ventry in $ventries; do
  3377. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3378. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3379. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  3380. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3381. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3382. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3383. _info "$d is already verified, skip $vtype."
  3384. continue
  3385. fi
  3386. _info "Verifying: $d"
  3387. _debug "d" "$d"
  3388. _debug "keyauthorization" "$keyauthorization"
  3389. _debug "uri" "$uri"
  3390. removelevel=""
  3391. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  3392. _debug "_currentRoot" "$_currentRoot"
  3393. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3394. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  3395. _info "Standalone mode server"
  3396. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3397. _ncIndex="$(_math $_ncIndex + 1)"
  3398. _startserver "$keyauthorization" "$_ncaddr"
  3399. if [ "$?" != "0" ]; then
  3400. _clearup
  3401. _on_issue_err "$_post_hook" "$vlist"
  3402. return 1
  3403. fi
  3404. sleep 1
  3405. _debug serverproc "$serverproc"
  3406. elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
  3407. _info "Stateless mode for domain:$d"
  3408. _sleep 1
  3409. elif _startswith "$_currentRoot" "$NGINX"; then
  3410. _info "Nginx mode for domain:$d"
  3411. #set up nginx server
  3412. FOUND_REAL_NGINX_CONF=""
  3413. BACKUP_NGINX_CONF=""
  3414. if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
  3415. _clearup
  3416. _on_issue_err "$_post_hook" "$vlist"
  3417. return 1
  3418. fi
  3419. if [ "$FOUND_REAL_NGINX_CONF" ]; then
  3420. _realConf="$FOUND_REAL_NGINX_CONF"
  3421. _backup="$BACKUP_NGINX_CONF"
  3422. _debug _realConf "$_realConf"
  3423. NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
  3424. fi
  3425. _sleep 1
  3426. else
  3427. if [ "$_currentRoot" = "apache" ]; then
  3428. wellknown_path="$ACME_DIR"
  3429. else
  3430. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  3431. if [ ! -d "$_currentRoot/.well-known" ]; then
  3432. removelevel='1'
  3433. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  3434. removelevel='2'
  3435. else
  3436. removelevel='3'
  3437. fi
  3438. fi
  3439. _debug wellknown_path "$wellknown_path"
  3440. _debug "writing token:$token to $wellknown_path/$token"
  3441. mkdir -p "$wellknown_path"
  3442. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  3443. _err "$d:Can not write token to file : $wellknown_path/$token"
  3444. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3445. _clearup
  3446. _on_issue_err "$_post_hook" "$vlist"
  3447. return 1
  3448. fi
  3449. if [ ! "$usingApache" ]; then
  3450. if webroot_owner=$(_stat "$_currentRoot"); then
  3451. _debug "Changing owner/group of .well-known to $webroot_owner"
  3452. if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
  3453. _debug "$(cat "$_EXEC_TEMP_ERR")"
  3454. _exec_err >/dev/null 2>&1
  3455. fi
  3456. else
  3457. _debug "not changing owner/group of webroot"
  3458. fi
  3459. fi
  3460. fi
  3461. elif [ "$vtype" = "$VTYPE_ALPN" ]; then
  3462. acmevalidationv1="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  3463. _debug acmevalidationv1 "$acmevalidationv1"
  3464. if ! _starttlsserver "$d" "" "$Le_TLSPort" "$keyauthorization" "$_ncaddr" "$acmevalidationv1"; then
  3465. _err "Start tls server error."
  3466. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3467. _clearup
  3468. _on_issue_err "$_post_hook" "$vlist"
  3469. return 1
  3470. fi
  3471. fi
  3472. if ! __trigger_validation "$uri" "$keyauthorization" "$vtype"; then
  3473. _err "$d:Can not get challenge: $response"
  3474. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3475. _clearup
  3476. _on_issue_err "$_post_hook" "$vlist"
  3477. return 1
  3478. fi
  3479. if [ "$code" ] && [ "$code" != '202' ]; then
  3480. if [ "$code" = '200' ]; then
  3481. _debug "trigger validation code: $code"
  3482. else
  3483. _err "$d:Challenge error: $response"
  3484. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3485. _clearup
  3486. _on_issue_err "$_post_hook" "$vlist"
  3487. return 1
  3488. fi
  3489. fi
  3490. waittimes=0
  3491. if [ -z "$MAX_RETRY_TIMES" ]; then
  3492. MAX_RETRY_TIMES=30
  3493. fi
  3494. while true; do
  3495. waittimes=$(_math "$waittimes" + 1)
  3496. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  3497. _err "$d:Timeout"
  3498. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3499. _clearup
  3500. _on_issue_err "$_post_hook" "$vlist"
  3501. return 1
  3502. fi
  3503. _debug "sleep 2 secs to verify"
  3504. sleep 2
  3505. _debug "checking"
  3506. if [ "$ACME_VERSION" = "2" ]; then
  3507. _send_signed_request "$uri"
  3508. else
  3509. response="$(_get "$uri")"
  3510. fi
  3511. if [ "$?" != "0" ]; then
  3512. _err "$d:Verify error:$response"
  3513. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3514. _clearup
  3515. _on_issue_err "$_post_hook" "$vlist"
  3516. return 1
  3517. fi
  3518. _debug2 original "$response"
  3519. response="$(echo "$response" | _normalizeJson)"
  3520. _debug2 response "$response"
  3521. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  3522. if [ "$status" = "valid" ]; then
  3523. _info "$(__green Success)"
  3524. _stopserver "$serverproc"
  3525. serverproc=""
  3526. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3527. break
  3528. fi
  3529. if [ "$status" = "invalid" ]; then
  3530. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  3531. _debug2 error "$error"
  3532. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  3533. _debug2 errordetail "$errordetail"
  3534. if [ "$errordetail" ]; then
  3535. _err "$d:Verify error:$errordetail"
  3536. else
  3537. _err "$d:Verify error:$error"
  3538. fi
  3539. if [ "$DEBUG" ]; then
  3540. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3541. _debug "Debug: get token url."
  3542. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  3543. fi
  3544. fi
  3545. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3546. _clearup
  3547. _on_issue_err "$_post_hook" "$vlist"
  3548. return 1
  3549. fi
  3550. if [ "$status" = "pending" ]; then
  3551. _info "Pending"
  3552. else
  3553. _err "$d:Verify error:$response"
  3554. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3555. _clearup
  3556. _on_issue_err "$_post_hook" "$vlist"
  3557. return 1
  3558. fi
  3559. done
  3560. done
  3561. _clearup
  3562. _info "Verify finished, start to sign."
  3563. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
  3564. if [ "$ACME_VERSION" = "2" ]; then
  3565. if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
  3566. _err "Sign failed."
  3567. _on_issue_err "$_post_hook"
  3568. return 1
  3569. fi
  3570. if [ "$code" != "200" ]; then
  3571. _err "Sign failed, code is not 200."
  3572. _err "$response"
  3573. _on_issue_err "$_post_hook"
  3574. return 1
  3575. fi
  3576. Le_LinkCert="$(echo "$response" | tr -d '\r\n' | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
  3577. _tempSignedResponse="$response"
  3578. if ! _send_signed_request "$Le_LinkCert" "" "needbase64"; then
  3579. _err "Sign failed, can not download cert:$Le_LinkCert."
  3580. _err "$response"
  3581. _on_issue_err "$_post_hook"
  3582. return 1
  3583. fi
  3584. echo "$response" | _dbase64 "multiline" >"$CERT_PATH"
  3585. if [ "$(grep -- "$BEGIN_CERT" "$CERT_PATH" | wc -l)" -gt "1" ]; then
  3586. _debug "Found cert chain"
  3587. cat "$CERT_PATH" >"$CERT_FULLCHAIN_PATH"
  3588. _end_n="$(grep -n -- "$END_CERT" "$CERT_FULLCHAIN_PATH" | _head_n 1 | cut -d : -f 1)"
  3589. _debug _end_n "$_end_n"
  3590. sed -n "1,${_end_n}p" "$CERT_FULLCHAIN_PATH" >"$CERT_PATH"
  3591. _end_n="$(_math $_end_n + 1)"
  3592. sed -n "${_end_n},9999p" "$CERT_FULLCHAIN_PATH" >"$CA_CERT_PATH"
  3593. fi
  3594. response="$_tempSignedResponse"
  3595. else
  3596. if ! _send_signed_request "${ACME_NEW_ORDER}" "{\"resource\": \"$ACME_NEW_ORDER_RES\", \"csr\": \"$der\"}" "needbase64"; then
  3597. _err "Sign failed. $response"
  3598. _on_issue_err "$_post_hook"
  3599. return 1
  3600. fi
  3601. _rcert="$response"
  3602. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3603. echo "$BEGIN_CERT" >"$CERT_PATH"
  3604. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  3605. # _debug "Get cert failed. Let's try last response."
  3606. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  3607. #fi
  3608. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  3609. _debug "Try cert link."
  3610. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  3611. fi
  3612. echo "$END_CERT" >>"$CERT_PATH"
  3613. fi
  3614. _debug "Le_LinkCert" "$Le_LinkCert"
  3615. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  3616. if [ -z "$Le_LinkCert" ] || ! _checkcert "$CERT_PATH"; then
  3617. response="$(echo "$response" | _dbase64 "multiline" | tr -d '\0' | _normalizeJson)"
  3618. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  3619. _on_issue_err "$_post_hook"
  3620. return 1
  3621. fi
  3622. if [ "$Le_LinkCert" ]; then
  3623. _info "$(__green "Cert success.")"
  3624. cat "$CERT_PATH"
  3625. _info "Your cert is in $(__green " $CERT_PATH ")"
  3626. if [ -f "$CERT_KEY_PATH" ]; then
  3627. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  3628. fi
  3629. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  3630. USER_PATH="$PATH"
  3631. _saveaccountconf "USER_PATH" "$USER_PATH"
  3632. fi
  3633. fi
  3634. _cleardomainconf "Le_Vlist"
  3635. if [ "$ACME_VERSION" = "2" ]; then
  3636. _debug "v2 chain."
  3637. else
  3638. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  3639. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  3640. if [ "$Le_LinkIssuer" ]; then
  3641. if ! _contains "$Le_LinkIssuer" ":"; then
  3642. _info "$(__red "Relative issuer link found.")"
  3643. Le_LinkIssuer="$_ACME_SERVER_HOST$Le_LinkIssuer"
  3644. fi
  3645. _debug Le_LinkIssuer "$Le_LinkIssuer"
  3646. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  3647. _link_issuer_retry=0
  3648. _MAX_ISSUER_RETRY=5
  3649. while [ "$_link_issuer_retry" -lt "$_MAX_ISSUER_RETRY" ]; do
  3650. _debug _link_issuer_retry "$_link_issuer_retry"
  3651. if [ "$ACME_VERSION" = "2" ]; then
  3652. if _send_signed_request "$Le_LinkIssuer"; then
  3653. echo "$response" >"$CA_CERT_PATH"
  3654. break
  3655. fi
  3656. else
  3657. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH.der"; then
  3658. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  3659. _base64 "multiline" <"$CA_CERT_PATH.der" >>"$CA_CERT_PATH"
  3660. echo "$END_CERT" >>"$CA_CERT_PATH"
  3661. if ! _checkcert "$CA_CERT_PATH"; then
  3662. _err "Can not get the ca cert."
  3663. break
  3664. fi
  3665. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  3666. rm -f "$CA_CERT_PATH.der"
  3667. break
  3668. fi
  3669. fi
  3670. _link_issuer_retry=$(_math $_link_issuer_retry + 1)
  3671. _sleep "$_link_issuer_retry"
  3672. done
  3673. if [ "$_link_issuer_retry" = "$_MAX_ISSUER_RETRY" ]; then
  3674. _err "Max retry for issuer ca cert is reached."
  3675. fi
  3676. else
  3677. _debug "No Le_LinkIssuer header found."
  3678. fi
  3679. fi
  3680. [ -f "$CA_CERT_PATH" ] && _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  3681. [ -f "$CERT_FULLCHAIN_PATH" ] && _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  3682. Le_CertCreateTime=$(_time)
  3683. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  3684. Le_CertCreateTimeStr=$(date -u)
  3685. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  3686. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ]; then
  3687. Le_RenewalDays="$DEFAULT_RENEW"
  3688. else
  3689. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  3690. fi
  3691. if [ "$CA_BUNDLE" ]; then
  3692. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  3693. else
  3694. _clearaccountconf "CA_BUNDLE"
  3695. fi
  3696. if [ "$CA_PATH" ]; then
  3697. _saveaccountconf CA_PATH "$CA_PATH"
  3698. else
  3699. _clearaccountconf "CA_PATH"
  3700. fi
  3701. if [ "$HTTPS_INSECURE" ]; then
  3702. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  3703. else
  3704. _clearaccountconf "HTTPS_INSECURE"
  3705. fi
  3706. if [ "$Le_Listen_V4" ]; then
  3707. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  3708. _cleardomainconf Le_Listen_V6
  3709. elif [ "$Le_Listen_V6" ]; then
  3710. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  3711. _cleardomainconf Le_Listen_V4
  3712. fi
  3713. if [ "$Le_ForceNewDomainKey" = "1" ]; then
  3714. _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
  3715. else
  3716. _cleardomainconf Le_ForceNewDomainKey
  3717. fi
  3718. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  3719. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  3720. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  3721. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  3722. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  3723. if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
  3724. _savedomainconf "Le_RealCertPath" "$_real_cert"
  3725. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  3726. _savedomainconf "Le_RealKeyPath" "$_real_key"
  3727. _savedomainconf "Le_ReloadCmd" "$_reload_cmd"
  3728. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  3729. if ! _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"; then
  3730. return 1
  3731. fi
  3732. fi
  3733. if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
  3734. _err "Call hook error."
  3735. return 1
  3736. fi
  3737. }
  3738. #domain [isEcc]
  3739. renew() {
  3740. Le_Domain="$1"
  3741. if [ -z "$Le_Domain" ]; then
  3742. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  3743. return 1
  3744. fi
  3745. _isEcc="$2"
  3746. _initpath "$Le_Domain" "$_isEcc"
  3747. _info "$(__green "Renew: '$Le_Domain'")"
  3748. if [ ! -f "$DOMAIN_CONF" ]; then
  3749. _info "'$Le_Domain' is not a issued domain, skip."
  3750. return 0
  3751. fi
  3752. if [ "$Le_RenewalDays" ]; then
  3753. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  3754. fi
  3755. . "$DOMAIN_CONF"
  3756. _debug Le_API "$Le_API"
  3757. if [ "$Le_API" ]; then
  3758. if [ "$_OLD_CA_HOST" = "$Le_API" ]; then
  3759. export Le_API="$DEFAULT_CA"
  3760. _savedomainconf Le_API "$Le_API"
  3761. fi
  3762. if [ "$_OLD_STAGE_CA_HOST" = "$Le_API" ]; then
  3763. export Le_API="$DEFAULT_STAGING_CA"
  3764. _savedomainconf Le_API "$Le_API"
  3765. fi
  3766. export ACME_DIRECTORY="$Le_API"
  3767. #reload ca configs
  3768. ACCOUNT_KEY_PATH=""
  3769. ACCOUNT_JSON_PATH=""
  3770. CA_CONF=""
  3771. _debug3 "initpath again."
  3772. _initpath "$Le_Domain" "$_isEcc"
  3773. fi
  3774. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3775. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  3776. _info "Add '$(__red '--force')' to force to renew."
  3777. return "$RENEW_SKIP"
  3778. fi
  3779. if [ "$IN_CRON" = "1" ] && [ -z "$Le_CertCreateTime" ]; then
  3780. _info "Skip invalid cert for: $Le_Domain"
  3781. return 0
  3782. fi
  3783. IS_RENEW="1"
  3784. 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"
  3785. res="$?"
  3786. if [ "$res" != "0" ]; then
  3787. return "$res"
  3788. fi
  3789. if [ "$Le_DeployHook" ]; then
  3790. _deploy "$Le_Domain" "$Le_DeployHook"
  3791. res="$?"
  3792. fi
  3793. IS_RENEW=""
  3794. return "$res"
  3795. }
  3796. #renewAll [stopRenewOnError]
  3797. renewAll() {
  3798. _initpath
  3799. _stopRenewOnError="$1"
  3800. _debug "_stopRenewOnError" "$_stopRenewOnError"
  3801. _ret="0"
  3802. for di in "${CERT_HOME}"/*.*/; do
  3803. _debug di "$di"
  3804. if ! [ -d "$di" ]; then
  3805. _debug "Not directory, skip: $di"
  3806. continue
  3807. fi
  3808. d=$(basename "$di")
  3809. _debug d "$d"
  3810. (
  3811. if _endswith "$d" "$ECC_SUFFIX"; then
  3812. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  3813. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  3814. fi
  3815. renew "$d" "$_isEcc"
  3816. )
  3817. rc="$?"
  3818. _debug "Return code: $rc"
  3819. if [ "$rc" != "0" ]; then
  3820. if [ "$rc" = "$RENEW_SKIP" ]; then
  3821. _info "Skipped $d"
  3822. elif [ "$_stopRenewOnError" ]; then
  3823. _err "Error renew $d, stop now."
  3824. return "$rc"
  3825. else
  3826. _ret="$rc"
  3827. _err "Error renew $d."
  3828. fi
  3829. fi
  3830. done
  3831. return "$_ret"
  3832. }
  3833. #csr webroot
  3834. signcsr() {
  3835. _csrfile="$1"
  3836. _csrW="$2"
  3837. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  3838. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  3839. return 1
  3840. fi
  3841. _real_cert="$3"
  3842. _real_key="$4"
  3843. _real_ca="$5"
  3844. _reload_cmd="$6"
  3845. _real_fullchain="$7"
  3846. _pre_hook="${8}"
  3847. _post_hook="${9}"
  3848. _renew_hook="${10}"
  3849. _local_addr="${11}"
  3850. _challenge_alias="${12}"
  3851. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  3852. if [ "$?" != "0" ]; then
  3853. _err "Can not read subject from csr: $_csrfile"
  3854. return 1
  3855. fi
  3856. _debug _csrsubj "$_csrsubj"
  3857. if _contains "$_csrsubj" ' ' || ! _contains "$_csrsubj" '.'; then
  3858. _info "It seems that the subject: $_csrsubj is not a valid domain name. Drop it."
  3859. _csrsubj=""
  3860. fi
  3861. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  3862. if [ "$?" != "0" ]; then
  3863. _err "Can not read domain list from csr: $_csrfile"
  3864. return 1
  3865. fi
  3866. _debug "_csrdomainlist" "$_csrdomainlist"
  3867. if [ -z "$_csrsubj" ]; then
  3868. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  3869. _debug _csrsubj "$_csrsubj"
  3870. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  3871. _debug "_csrdomainlist" "$_csrdomainlist"
  3872. fi
  3873. if [ -z "$_csrsubj" ]; then
  3874. _err "Can not read subject from csr: $_csrfile"
  3875. return 1
  3876. fi
  3877. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  3878. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  3879. _err "Can not read key length from csr: $_csrfile"
  3880. return 1
  3881. fi
  3882. if [ -z "$ACME_VERSION" ] && _contains "$_csrsubj,$_csrdomainlist" "*."; then
  3883. export ACME_VERSION=2
  3884. fi
  3885. _initpath "$_csrsubj" "$_csrkeylength"
  3886. mkdir -p "$DOMAIN_PATH"
  3887. _info "Copy csr to: $CSR_PATH"
  3888. cp "$_csrfile" "$CSR_PATH"
  3889. 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"
  3890. }
  3891. showcsr() {
  3892. _csrfile="$1"
  3893. _csrd="$2"
  3894. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  3895. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  3896. return 1
  3897. fi
  3898. _initpath
  3899. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  3900. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  3901. _err "Can not read subject from csr: $_csrfile"
  3902. return 1
  3903. fi
  3904. _info "Subject=$_csrsubj"
  3905. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  3906. if [ "$?" != "0" ]; then
  3907. _err "Can not read domain list from csr: $_csrfile"
  3908. return 1
  3909. fi
  3910. _debug "_csrdomainlist" "$_csrdomainlist"
  3911. _info "SubjectAltNames=$_csrdomainlist"
  3912. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  3913. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  3914. _err "Can not read key length from csr: $_csrfile"
  3915. return 1
  3916. fi
  3917. _info "KeyLength=$_csrkeylength"
  3918. }
  3919. list() {
  3920. _raw="$1"
  3921. _initpath
  3922. _sep="|"
  3923. if [ "$_raw" ]; then
  3924. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  3925. for di in "${CERT_HOME}"/*.*/; do
  3926. if ! [ -d "$di" ]; then
  3927. _debug "Not directory, skip: $di"
  3928. continue
  3929. fi
  3930. d=$(basename "$di")
  3931. _debug d "$d"
  3932. (
  3933. if _endswith "$d" "$ECC_SUFFIX"; then
  3934. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  3935. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  3936. fi
  3937. _initpath "$d" "$_isEcc"
  3938. if [ -f "$DOMAIN_CONF" ]; then
  3939. . "$DOMAIN_CONF"
  3940. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  3941. fi
  3942. )
  3943. done
  3944. else
  3945. if _exists column; then
  3946. list "raw" | column -t -s "$_sep"
  3947. else
  3948. list "raw" | tr "$_sep" '\t'
  3949. fi
  3950. fi
  3951. }
  3952. _deploy() {
  3953. _d="$1"
  3954. _hooks="$2"
  3955. for _d_api in $(echo "$_hooks" | tr ',' " "); do
  3956. _deployApi="$(_findHook "$_d" deploy "$_d_api")"
  3957. if [ -z "$_deployApi" ]; then
  3958. _err "The deploy hook $_d_api is not found."
  3959. return 1
  3960. fi
  3961. _debug _deployApi "$_deployApi"
  3962. if ! (
  3963. if ! . "$_deployApi"; then
  3964. _err "Load file $_deployApi error. Please check your api file and try again."
  3965. return 1
  3966. fi
  3967. d_command="${_d_api}_deploy"
  3968. if ! _exists "$d_command"; then
  3969. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  3970. return 1
  3971. fi
  3972. if ! $d_command "$_d" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  3973. _err "Error deploy for domain:$_d"
  3974. return 1
  3975. fi
  3976. ); then
  3977. _err "Deploy error."
  3978. return 1
  3979. else
  3980. _info "$(__green Success)"
  3981. fi
  3982. done
  3983. }
  3984. #domain hooks
  3985. deploy() {
  3986. _d="$1"
  3987. _hooks="$2"
  3988. _isEcc="$3"
  3989. if [ -z "$_hooks" ]; then
  3990. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  3991. return 1
  3992. fi
  3993. _initpath "$_d" "$_isEcc"
  3994. if [ ! -d "$DOMAIN_PATH" ]; then
  3995. _err "The domain '$_d' is not a cert name. You must use the cert name to specify the cert to install."
  3996. _err "Can not find path:'$DOMAIN_PATH'"
  3997. return 1
  3998. fi
  3999. . "$DOMAIN_CONF"
  4000. _savedomainconf Le_DeployHook "$_hooks"
  4001. _deploy "$_d" "$_hooks"
  4002. }
  4003. installcert() {
  4004. _main_domain="$1"
  4005. if [ -z "$_main_domain" ]; then
  4006. _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]"
  4007. return 1
  4008. fi
  4009. _real_cert="$2"
  4010. _real_key="$3"
  4011. _real_ca="$4"
  4012. _reload_cmd="$5"
  4013. _real_fullchain="$6"
  4014. _isEcc="$7"
  4015. _initpath "$_main_domain" "$_isEcc"
  4016. if [ ! -d "$DOMAIN_PATH" ]; then
  4017. _err "The domain '$_main_domain' is not a cert name. You must use the cert name to specify the cert to install."
  4018. _err "Can not find path:'$DOMAIN_PATH'"
  4019. return 1
  4020. fi
  4021. _savedomainconf "Le_RealCertPath" "$_real_cert"
  4022. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  4023. _savedomainconf "Le_RealKeyPath" "$_real_key"
  4024. _savedomainconf "Le_ReloadCmd" "$_reload_cmd"
  4025. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  4026. _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
  4027. }
  4028. #domain cert key ca fullchain reloadcmd backup-prefix
  4029. _installcert() {
  4030. _main_domain="$1"
  4031. _real_cert="$2"
  4032. _real_key="$3"
  4033. _real_ca="$4"
  4034. _real_fullchain="$5"
  4035. _reload_cmd="$6"
  4036. _backup_prefix="$7"
  4037. if [ "$_real_cert" = "$NO_VALUE" ]; then
  4038. _real_cert=""
  4039. fi
  4040. if [ "$_real_key" = "$NO_VALUE" ]; then
  4041. _real_key=""
  4042. fi
  4043. if [ "$_real_ca" = "$NO_VALUE" ]; then
  4044. _real_ca=""
  4045. fi
  4046. if [ "$_reload_cmd" = "$NO_VALUE" ]; then
  4047. _reload_cmd=""
  4048. fi
  4049. if [ "$_real_fullchain" = "$NO_VALUE" ]; then
  4050. _real_fullchain=""
  4051. fi
  4052. _backup_path="$DOMAIN_BACKUP_PATH/$_backup_prefix"
  4053. mkdir -p "$_backup_path"
  4054. if [ "$_real_cert" ]; then
  4055. _info "Installing cert to:$_real_cert"
  4056. if [ -f "$_real_cert" ] && [ ! "$IS_RENEW" ]; then
  4057. cp "$_real_cert" "$_backup_path/cert.bak"
  4058. fi
  4059. cat "$CERT_PATH" >"$_real_cert" || return 1
  4060. fi
  4061. if [ "$_real_ca" ]; then
  4062. _info "Installing CA to:$_real_ca"
  4063. if [ "$_real_ca" = "$_real_cert" ]; then
  4064. echo "" >>"$_real_ca"
  4065. cat "$CA_CERT_PATH" >>"$_real_ca" || return 1
  4066. else
  4067. if [ -f "$_real_ca" ] && [ ! "$IS_RENEW" ]; then
  4068. cp "$_real_ca" "$_backup_path/ca.bak"
  4069. fi
  4070. cat "$CA_CERT_PATH" >"$_real_ca" || return 1
  4071. fi
  4072. fi
  4073. if [ "$_real_key" ]; then
  4074. _info "Installing key to:$_real_key"
  4075. if [ -f "$_real_key" ] && [ ! "$IS_RENEW" ]; then
  4076. cp "$_real_key" "$_backup_path/key.bak"
  4077. fi
  4078. if [ -f "$_real_key" ]; then
  4079. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4080. else
  4081. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4082. chmod 600 "$_real_key"
  4083. fi
  4084. fi
  4085. if [ "$_real_fullchain" ]; then
  4086. _info "Installing full chain to:$_real_fullchain"
  4087. if [ -f "$_real_fullchain" ] && [ ! "$IS_RENEW" ]; then
  4088. cp "$_real_fullchain" "$_backup_path/fullchain.bak"
  4089. fi
  4090. cat "$CERT_FULLCHAIN_PATH" >"$_real_fullchain" || return 1
  4091. fi
  4092. if [ "$_reload_cmd" ]; then
  4093. _info "Run reload cmd: $_reload_cmd"
  4094. if (
  4095. export CERT_PATH
  4096. export CERT_KEY_PATH
  4097. export CA_CERT_PATH
  4098. export CERT_FULLCHAIN_PATH
  4099. export Le_Domain
  4100. cd "$DOMAIN_PATH" && eval "$_reload_cmd"
  4101. ); then
  4102. _info "$(__green "Reload success")"
  4103. else
  4104. _err "Reload error for :$Le_Domain"
  4105. fi
  4106. fi
  4107. }
  4108. #confighome
  4109. installcronjob() {
  4110. _c_home="$1"
  4111. _initpath
  4112. _CRONTAB="crontab"
  4113. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4114. _CRONTAB="fcrontab"
  4115. fi
  4116. if ! _exists "$_CRONTAB"; then
  4117. _err "crontab/fcrontab doesn't exist, so, we can not install cron jobs."
  4118. _err "All your certs will not be renewed automatically."
  4119. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  4120. return 1
  4121. fi
  4122. _info "Installing cron job"
  4123. if ! $_CRONTAB -l | grep "$PROJECT_ENTRY --cron"; then
  4124. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  4125. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  4126. else
  4127. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  4128. return 1
  4129. fi
  4130. if [ "$_c_home" ]; then
  4131. _c_entry="--config-home \"$_c_home\" "
  4132. fi
  4133. _t=$(_time)
  4134. random_minute=$(_math $_t % 60)
  4135. if _exists uname && uname -a | grep SunOS >/dev/null; then
  4136. $_CRONTAB -l | {
  4137. cat
  4138. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4139. } | $_CRONTAB --
  4140. else
  4141. $_CRONTAB -l | {
  4142. cat
  4143. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4144. } | $_CRONTAB -
  4145. fi
  4146. fi
  4147. if [ "$?" != "0" ]; then
  4148. _err "Install cron job failed. You need to manually renew your certs."
  4149. _err "Or you can add cronjob by yourself:"
  4150. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  4151. return 1
  4152. fi
  4153. }
  4154. uninstallcronjob() {
  4155. _CRONTAB="crontab"
  4156. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4157. _CRONTAB="fcrontab"
  4158. fi
  4159. if ! _exists "$_CRONTAB"; then
  4160. return
  4161. fi
  4162. _info "Removing cron job"
  4163. cr="$($_CRONTAB -l | grep "$PROJECT_ENTRY --cron")"
  4164. if [ "$cr" ]; then
  4165. if _exists uname && uname -a | grep solaris >/dev/null; then
  4166. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB --
  4167. else
  4168. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB -
  4169. fi
  4170. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  4171. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  4172. if _contains "$cr" "--config-home"; then
  4173. LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
  4174. _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
  4175. fi
  4176. fi
  4177. _initpath
  4178. }
  4179. revoke() {
  4180. Le_Domain="$1"
  4181. if [ -z "$Le_Domain" ]; then
  4182. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com [--ecc]"
  4183. return 1
  4184. fi
  4185. _isEcc="$2"
  4186. _initpath "$Le_Domain" "$_isEcc"
  4187. if [ ! -f "$DOMAIN_CONF" ]; then
  4188. _err "$Le_Domain is not a issued domain, skip."
  4189. return 1
  4190. fi
  4191. if [ ! -f "$CERT_PATH" ]; then
  4192. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  4193. return 1
  4194. fi
  4195. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
  4196. if [ -z "$cert" ]; then
  4197. _err "Cert for $Le_Domain is empty found, skip."
  4198. return 1
  4199. fi
  4200. _initAPI
  4201. if [ "$ACME_VERSION" = "2" ]; then
  4202. data="{\"certificate\": \"$cert\"}"
  4203. else
  4204. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  4205. fi
  4206. uri="${ACME_REVOKE_CERT}"
  4207. if [ -f "$CERT_KEY_PATH" ]; then
  4208. _info "Try domain key first."
  4209. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  4210. if [ -z "$response" ]; then
  4211. _info "Revoke success."
  4212. rm -f "$CERT_PATH"
  4213. return 0
  4214. else
  4215. _err "Revoke error by domain key."
  4216. _err "$response"
  4217. fi
  4218. fi
  4219. else
  4220. _info "Domain key file doesn't exists."
  4221. fi
  4222. _info "Try account key."
  4223. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  4224. if [ -z "$response" ]; then
  4225. _info "Revoke success."
  4226. rm -f "$CERT_PATH"
  4227. return 0
  4228. else
  4229. _err "Revoke error."
  4230. _debug "$response"
  4231. fi
  4232. fi
  4233. return 1
  4234. }
  4235. #domain ecc
  4236. remove() {
  4237. Le_Domain="$1"
  4238. if [ -z "$Le_Domain" ]; then
  4239. _usage "Usage: $PROJECT_ENTRY --remove -d domain.com [--ecc]"
  4240. return 1
  4241. fi
  4242. _isEcc="$2"
  4243. _initpath "$Le_Domain" "$_isEcc"
  4244. _removed_conf="$DOMAIN_CONF.removed"
  4245. if [ ! -f "$DOMAIN_CONF" ]; then
  4246. if [ -f "$_removed_conf" ]; then
  4247. _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
  4248. else
  4249. _err "$Le_Domain is not a issued domain, skip."
  4250. fi
  4251. return 1
  4252. fi
  4253. if mv "$DOMAIN_CONF" "$_removed_conf"; then
  4254. _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
  4255. _info "You can remove them by yourself."
  4256. return 0
  4257. else
  4258. _err "Remove $Le_Domain failed."
  4259. return 1
  4260. fi
  4261. }
  4262. #domain vtype
  4263. _deactivate() {
  4264. _d_domain="$1"
  4265. _d_type="$2"
  4266. _initpath
  4267. if [ "$ACME_VERSION" = "2" ]; then
  4268. _identifiers="{\"type\":\"dns\",\"value\":\"$_d_domain\"}"
  4269. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  4270. _err "Can not get domain new order."
  4271. return 1
  4272. fi
  4273. _authorizations_seg="$(echo "$response" | tr -d '\r\n' | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  4274. _debug2 _authorizations_seg "$_authorizations_seg"
  4275. if [ -z "$_authorizations_seg" ]; then
  4276. _err "_authorizations_seg not found."
  4277. _clearup
  4278. _on_issue_err "$_post_hook"
  4279. return 1
  4280. fi
  4281. authzUri="$_authorizations_seg"
  4282. _debug2 "authzUri" "$authzUri"
  4283. if ! _send_signed_request "$authzUri"; then
  4284. _err "get to authz error."
  4285. _err "_authorizations_seg" "$_authorizations_seg"
  4286. _err "authzUri" "$authzUri"
  4287. _clearup
  4288. _on_issue_err "$_post_hook"
  4289. return 1
  4290. fi
  4291. response="$(echo "$response" | _normalizeJson)"
  4292. _debug2 response "$response"
  4293. _URL_NAME="url"
  4294. else
  4295. if ! __get_domain_new_authz "$_d_domain"; then
  4296. _err "Can not get domain new authz token."
  4297. return 1
  4298. fi
  4299. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  4300. _debug "authzUri" "$authzUri"
  4301. if [ "$code" ] && [ ! "$code" = '201' ]; then
  4302. _err "new-authz error: $response"
  4303. return 1
  4304. fi
  4305. _URL_NAME="uri"
  4306. fi
  4307. entries="$(echo "$response" | _egrep_o "{ *\"type\":\"[^\"]*\", *\"status\": *\"valid\", *\"$_URL_NAME\"[^}]*")"
  4308. if [ -z "$entries" ]; then
  4309. _info "No valid entries found."
  4310. if [ -z "$thumbprint" ]; then
  4311. thumbprint="$(__calc_account_thumbprint)"
  4312. fi
  4313. _debug "Trigger validation."
  4314. vtype="$VTYPE_DNS"
  4315. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  4316. _debug entry "$entry"
  4317. if [ -z "$entry" ]; then
  4318. _err "Error, can not get domain token $d"
  4319. return 1
  4320. fi
  4321. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  4322. _debug token "$token"
  4323. uri="$(printf "%s\n" "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4324. _debug uri "$uri"
  4325. keyauthorization="$token.$thumbprint"
  4326. _debug keyauthorization "$keyauthorization"
  4327. __trigger_validation "$uri" "$keyauthorization"
  4328. fi
  4329. _d_i=0
  4330. _d_max_retry=$(echo "$entries" | wc -l)
  4331. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  4332. _info "Deactivate: $_d_domain"
  4333. _d_i="$(_math $_d_i + 1)"
  4334. entry="$(echo "$entries" | sed -n "${_d_i}p")"
  4335. _debug entry "$entry"
  4336. if [ -z "$entry" ]; then
  4337. _info "No more valid entry found."
  4338. break
  4339. fi
  4340. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  4341. _debug _vtype "$_vtype"
  4342. _info "Found $_vtype"
  4343. uri="$(printf "%s\n" "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4344. _debug uri "$uri"
  4345. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  4346. _info "Skip $_vtype"
  4347. continue
  4348. fi
  4349. _info "Deactivate: $_vtype"
  4350. if [ "$ACME_VERSION" = "2" ]; then
  4351. _djson="{\"status\":\"deactivated\"}"
  4352. else
  4353. _djson="{\"resource\": \"authz\", \"status\":\"deactivated\"}"
  4354. fi
  4355. if _send_signed_request "$authzUri" "$_djson" && _contains "$response" '"deactivated"'; then
  4356. _info "Deactivate: $_vtype success."
  4357. else
  4358. _err "Can not deactivate $_vtype."
  4359. break
  4360. fi
  4361. done
  4362. _debug "$_d_i"
  4363. if [ "$_d_i" -eq "$_d_max_retry" ]; then
  4364. _info "Deactivated success!"
  4365. else
  4366. _err "Deactivate failed."
  4367. fi
  4368. }
  4369. deactivate() {
  4370. _d_domain_list="$1"
  4371. _d_type="$2"
  4372. _initpath
  4373. _initAPI
  4374. _debug _d_domain_list "$_d_domain_list"
  4375. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  4376. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  4377. return 1
  4378. fi
  4379. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  4380. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  4381. continue
  4382. fi
  4383. if ! _deactivate "$_d_dm" "$_d_type"; then
  4384. return 1
  4385. fi
  4386. done
  4387. }
  4388. # Detect profile file if not specified as environment variable
  4389. _detect_profile() {
  4390. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  4391. echo "$PROFILE"
  4392. return
  4393. fi
  4394. DETECTED_PROFILE=''
  4395. SHELLTYPE="$(basename "/$SHELL")"
  4396. if [ "$SHELLTYPE" = "bash" ]; then
  4397. if [ -f "$HOME/.bashrc" ]; then
  4398. DETECTED_PROFILE="$HOME/.bashrc"
  4399. elif [ -f "$HOME/.bash_profile" ]; then
  4400. DETECTED_PROFILE="$HOME/.bash_profile"
  4401. fi
  4402. elif [ "$SHELLTYPE" = "zsh" ]; then
  4403. DETECTED_PROFILE="$HOME/.zshrc"
  4404. fi
  4405. if [ -z "$DETECTED_PROFILE" ]; then
  4406. if [ -f "$HOME/.profile" ]; then
  4407. DETECTED_PROFILE="$HOME/.profile"
  4408. elif [ -f "$HOME/.bashrc" ]; then
  4409. DETECTED_PROFILE="$HOME/.bashrc"
  4410. elif [ -f "$HOME/.bash_profile" ]; then
  4411. DETECTED_PROFILE="$HOME/.bash_profile"
  4412. elif [ -f "$HOME/.zshrc" ]; then
  4413. DETECTED_PROFILE="$HOME/.zshrc"
  4414. fi
  4415. fi
  4416. echo "$DETECTED_PROFILE"
  4417. }
  4418. _initconf() {
  4419. _initpath
  4420. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  4421. echo "
  4422. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  4423. #LOG_LEVEL=1
  4424. #AUTO_UPGRADE=\"1\"
  4425. #NO_TIMESTAMP=1
  4426. " >"$ACCOUNT_CONF_PATH"
  4427. fi
  4428. }
  4429. # nocron
  4430. _precheck() {
  4431. _nocron="$1"
  4432. if ! _exists "curl" && ! _exists "wget"; then
  4433. _err "Please install curl or wget first, we need to access http resources."
  4434. return 1
  4435. fi
  4436. if [ -z "$_nocron" ]; then
  4437. if ! _exists "crontab" && ! _exists "fcrontab"; then
  4438. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  4439. _err "We need to set cron job to renew the certs automatically."
  4440. _err "Otherwise, your certs will not be able to be renewed automatically."
  4441. if [ -z "$FORCE" ]; then
  4442. _err "Please add '--force' and try install again to go without crontab."
  4443. _err "./$PROJECT_ENTRY --install --force"
  4444. return 1
  4445. fi
  4446. fi
  4447. fi
  4448. if ! _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  4449. _err "Please install openssl first. ACME_OPENSSL_BIN=$ACME_OPENSSL_BIN"
  4450. _err "We need openssl to generate keys."
  4451. return 1
  4452. fi
  4453. if ! _exists "socat"; then
  4454. _err "It is recommended to install socat first."
  4455. _err "We use socat for standalone server if you use standalone mode."
  4456. _err "If you don't use standalone mode, just ignore this warning."
  4457. fi
  4458. return 0
  4459. }
  4460. _setShebang() {
  4461. _file="$1"
  4462. _shebang="$2"
  4463. if [ -z "$_shebang" ]; then
  4464. _usage "Usage: file shebang"
  4465. return 1
  4466. fi
  4467. cp "$_file" "$_file.tmp"
  4468. echo "$_shebang" >"$_file"
  4469. sed -n 2,99999p "$_file.tmp" >>"$_file"
  4470. rm -f "$_file.tmp"
  4471. }
  4472. #confighome
  4473. _installalias() {
  4474. _c_home="$1"
  4475. _initpath
  4476. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  4477. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  4478. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  4479. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  4480. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  4481. fi
  4482. if [ "$_c_home" ]; then
  4483. _c_entry=" --config-home '$_c_home'"
  4484. fi
  4485. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  4486. if [ "$_c_home" ]; then
  4487. _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
  4488. else
  4489. _sed_i "/^export LE_CONFIG_HOME/d" "$_envfile"
  4490. fi
  4491. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4492. _profile="$(_detect_profile)"
  4493. if [ "$_profile" ]; then
  4494. _debug "Found profile: $_profile"
  4495. _info "Installing alias to '$_profile'"
  4496. _setopt "$_profile" ". \"$_envfile\""
  4497. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  4498. else
  4499. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  4500. fi
  4501. #for csh
  4502. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  4503. _csh_profile="$HOME/.cshrc"
  4504. if [ -f "$_csh_profile" ]; then
  4505. _info "Installing alias to '$_csh_profile'"
  4506. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  4507. if [ "$_c_home" ]; then
  4508. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  4509. else
  4510. _sed_i "/^setenv LE_CONFIG_HOME/d" "$_cshfile"
  4511. fi
  4512. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4513. _setopt "$_csh_profile" "source \"$_cshfile\""
  4514. fi
  4515. #for tcsh
  4516. _tcsh_profile="$HOME/.tcshrc"
  4517. if [ -f "$_tcsh_profile" ]; then
  4518. _info "Installing alias to '$_tcsh_profile'"
  4519. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  4520. if [ "$_c_home" ]; then
  4521. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  4522. fi
  4523. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4524. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  4525. fi
  4526. }
  4527. # nocron confighome noprofile
  4528. install() {
  4529. if [ -z "$LE_WORKING_DIR" ]; then
  4530. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  4531. fi
  4532. _nocron="$1"
  4533. _c_home="$2"
  4534. _noprofile="$3"
  4535. if ! _initpath; then
  4536. _err "Install failed."
  4537. return 1
  4538. fi
  4539. if [ "$_nocron" ]; then
  4540. _debug "Skip install cron job"
  4541. fi
  4542. if [ "$IN_CRON" != "1" ]; then
  4543. if ! _precheck "$_nocron"; then
  4544. _err "Pre-check failed, can not install."
  4545. return 1
  4546. fi
  4547. fi
  4548. if [ -z "$_c_home" ] && [ "$LE_CONFIG_HOME" != "$LE_WORKING_DIR" ]; then
  4549. _info "Using config home: $LE_CONFIG_HOME"
  4550. _c_home="$LE_CONFIG_HOME"
  4551. fi
  4552. #convert from le
  4553. if [ -d "$HOME/.le" ]; then
  4554. for envfile in "le.env" "le.sh.env"; do
  4555. if [ -f "$HOME/.le/$envfile" ]; then
  4556. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  4557. _upgrading="1"
  4558. _info "You are upgrading from le.sh"
  4559. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  4560. mv "$HOME/.le" "$LE_WORKING_DIR"
  4561. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  4562. break
  4563. fi
  4564. fi
  4565. done
  4566. fi
  4567. _info "Installing to $LE_WORKING_DIR"
  4568. if [ ! -d "$LE_WORKING_DIR" ]; then
  4569. if ! mkdir -p "$LE_WORKING_DIR"; then
  4570. _err "Can not create working dir: $LE_WORKING_DIR"
  4571. return 1
  4572. fi
  4573. chmod 700 "$LE_WORKING_DIR"
  4574. fi
  4575. if [ ! -d "$LE_CONFIG_HOME" ]; then
  4576. if ! mkdir -p "$LE_CONFIG_HOME"; then
  4577. _err "Can not create config dir: $LE_CONFIG_HOME"
  4578. return 1
  4579. fi
  4580. chmod 700 "$LE_CONFIG_HOME"
  4581. fi
  4582. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  4583. if [ "$?" != "0" ]; then
  4584. _err "Install failed, can not copy $PROJECT_ENTRY"
  4585. return 1
  4586. fi
  4587. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  4588. if [ "$IN_CRON" != "1" ] && [ -z "$_noprofile" ]; then
  4589. _installalias "$_c_home"
  4590. fi
  4591. for subf in $_SUB_FOLDERS; do
  4592. if [ -d "$subf" ]; then
  4593. mkdir -p "$LE_WORKING_DIR/$subf"
  4594. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  4595. fi
  4596. done
  4597. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  4598. _initconf
  4599. fi
  4600. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  4601. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  4602. fi
  4603. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  4604. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  4605. fi
  4606. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  4607. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  4608. fi
  4609. if [ -z "$_nocron" ]; then
  4610. installcronjob "$_c_home"
  4611. fi
  4612. if [ -z "$NO_DETECT_SH" ]; then
  4613. #Modify shebang
  4614. if _exists bash; then
  4615. _bash_path="$(bash -c "command -v bash 2>/dev/null")"
  4616. if [ -z "$_bash_path" ]; then
  4617. _bash_path="$(bash -c 'echo $SHELL')"
  4618. fi
  4619. fi
  4620. if [ "$_bash_path" ]; then
  4621. _info "Good, bash is found, so change the shebang to use bash as preferred."
  4622. _shebang='#!'"$_bash_path"
  4623. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  4624. for subf in $_SUB_FOLDERS; do
  4625. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  4626. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  4627. _setShebang "$_apifile" "$_shebang"
  4628. done
  4629. fi
  4630. done
  4631. fi
  4632. fi
  4633. _info OK
  4634. }
  4635. # nocron
  4636. uninstall() {
  4637. _nocron="$1"
  4638. if [ -z "$_nocron" ]; then
  4639. uninstallcronjob
  4640. fi
  4641. _initpath
  4642. _uninstallalias
  4643. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  4644. _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
  4645. }
  4646. _uninstallalias() {
  4647. _initpath
  4648. _profile="$(_detect_profile)"
  4649. if [ "$_profile" ]; then
  4650. _info "Uninstalling alias from: '$_profile'"
  4651. text="$(cat "$_profile")"
  4652. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  4653. fi
  4654. _csh_profile="$HOME/.cshrc"
  4655. if [ -f "$_csh_profile" ]; then
  4656. _info "Uninstalling alias from: '$_csh_profile'"
  4657. text="$(cat "$_csh_profile")"
  4658. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  4659. fi
  4660. _tcsh_profile="$HOME/.tcshrc"
  4661. if [ -f "$_tcsh_profile" ]; then
  4662. _info "Uninstalling alias from: '$_csh_profile'"
  4663. text="$(cat "$_tcsh_profile")"
  4664. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  4665. fi
  4666. }
  4667. cron() {
  4668. export IN_CRON=1
  4669. _initpath
  4670. _info "$(__green "===Starting cron===")"
  4671. if [ "$AUTO_UPGRADE" = "1" ]; then
  4672. export LE_WORKING_DIR
  4673. (
  4674. if ! upgrade; then
  4675. _err "Cron:Upgrade failed!"
  4676. return 1
  4677. fi
  4678. )
  4679. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  4680. if [ -t 1 ]; then
  4681. __INTERACTIVE="1"
  4682. fi
  4683. _info "Auto upgraded to: $VER"
  4684. fi
  4685. renewAll
  4686. _ret="$?"
  4687. IN_CRON=""
  4688. _info "$(__green "===End cron===")"
  4689. exit $_ret
  4690. }
  4691. version() {
  4692. echo "$PROJECT"
  4693. echo "v$VER"
  4694. }
  4695. showhelp() {
  4696. _initpath
  4697. version
  4698. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  4699. Commands:
  4700. --help, -h Show this help message.
  4701. --version, -v Show version info.
  4702. --install Install $PROJECT_NAME to your system.
  4703. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  4704. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT.
  4705. --issue Issue a cert.
  4706. --signcsr Issue a cert from an existing csr.
  4707. --deploy Deploy the cert to your server.
  4708. --install-cert Install the issued cert to apache/nginx or any other server.
  4709. --renew, -r Renew a cert.
  4710. --renew-all Renew all the certs.
  4711. --revoke Revoke a cert.
  4712. --remove Remove the cert from list of certs known to $PROJECT_NAME.
  4713. --list List all the certs.
  4714. --showcsr Show the content of a csr.
  4715. --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.
  4716. --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  4717. --cron Run cron job to renew all the certs.
  4718. --toPkcs Export the certificate and key to a pfx file.
  4719. --toPkcs8 Convert to pkcs8 format.
  4720. --update-account Update account info.
  4721. --register-account Register account key.
  4722. --deactivate-account Deactivate the account.
  4723. --create-account-key Create an account private key, professional use.
  4724. --create-domain-key Create an domain private key, professional use.
  4725. --createCSR, -ccsr Create CSR , professional use.
  4726. --deactivate Deactivate the domain authz, professional use.
  4727. Parameters:
  4728. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  4729. --challenge-alias domain.tld The challenge domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
  4730. --domain-alias domain.tld The domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
  4731. --force, -f Used to force to install or force to renew a cert immediately.
  4732. --staging, --test Use staging server, just for test.
  4733. --debug Output debug info.
  4734. --output-insecure Output all the sensitive messages. By default all the credentials/sensitive messages are hidden from the output/debug/log for secure.
  4735. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  4736. --standalone Use standalone mode.
  4737. --alpn Use standalone alpn mode.
  4738. --stateless Use stateless mode, see: $_STATELESS_WIKI
  4739. --apache Use apache mode.
  4740. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  4741. --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.
  4742. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  4743. --accountkeylength, -ak [2048] Specifies the account key length.
  4744. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  4745. --log-level 1|2 Specifies the log level, default is 1.
  4746. --syslog [0|3|6|7] Syslog level, 0: disable syslog, 3: error, 6: info, 7: debug.
  4747. These parameters are to install the cert to nginx/apache or any other server after issue/renew a cert:
  4748. --cert-file After issue/renew, the cert will be copied to this path.
  4749. --key-file After issue/renew, the key will be copied to this path.
  4750. --ca-file After issue/renew, the intermediate cert will be copied to this path.
  4751. --fullchain-file After issue/renew, the fullchain cert will be copied to this path.
  4752. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  4753. --server SERVER ACME Directory Resource URI. (default: https://acme-v01.api.letsencrypt.org/directory)
  4754. --accountconf Specifies a customized account config file.
  4755. --home Specifies the home dir for $PROJECT_NAME.
  4756. --cert-home Specifies the home dir to save all the certs, only valid for '--install' command.
  4757. --config-home Specifies the home dir to save all the configurations.
  4758. --useragent Specifies the user agent string. it will be saved for future use too.
  4759. --accountemail Specifies the account email, only valid for the '--install' and '--update-account' command.
  4760. --accountkey Specifies the account key path, only valid for the '--install' command.
  4761. --days Specifies the days to renew the cert when using '--issue' command. The default value is $DEFAULT_RENEW days.
  4762. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  4763. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  4764. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  4765. --listraw Only used for '--list' command, list the certs in raw format.
  4766. --stopRenewOnError, -se Only valid for '--renew-all' command. Stop if one cert has error in renewal.
  4767. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  4768. --ca-bundle Specifies the path to the CA certificate bundle to verify api server's certificate.
  4769. --ca-path Specifies directory containing CA certificates in PEM format, used by wget or curl.
  4770. --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.
  4771. --no-color Do not output color text.
  4772. --force-color Force output of color text. Useful for non-interactive use with the aha tool for HTML E-Mails.
  4773. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  4774. --csr Specifies the input csr.
  4775. --pre-hook Command to be run before obtaining any certificates.
  4776. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obtain/renew is success or failed.
  4777. --renew-hook Command to be run once for each successfully renewed certificate.
  4778. --deploy-hook The hook file to deploy cert
  4779. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  4780. --always-force-new-domain-key Generate new domain key when renewal. Otherwise, the domain key is not changed by default.
  4781. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  4782. --listen-v4 Force standalone/tls server to listen at ipv4.
  4783. --listen-v6 Force standalone/tls server to listen at ipv6.
  4784. --openssl-bin Specifies a custom openssl bin location.
  4785. --use-wget Force to use wget, if you have both curl and wget installed.
  4786. --yes-I-know-dns-manual-mode-enough-go-ahead-please Force to use dns manual mode: $_DNS_MANUAL_WIKI
  4787. --branch, -b Only valid for '--upgrade' command, specifies the branch name to upgrade to.
  4788. "
  4789. }
  4790. # nocron noprofile
  4791. _installOnline() {
  4792. _info "Installing from online archive."
  4793. _nocron="$1"
  4794. _noprofile="$2"
  4795. if [ ! "$BRANCH" ]; then
  4796. BRANCH="master"
  4797. fi
  4798. target="$PROJECT/archive/$BRANCH.tar.gz"
  4799. _info "Downloading $target"
  4800. localname="$BRANCH.tar.gz"
  4801. if ! _get "$target" >$localname; then
  4802. _err "Download error."
  4803. return 1
  4804. fi
  4805. (
  4806. _info "Extracting $localname"
  4807. if ! (tar xzf $localname || gtar xzf $localname); then
  4808. _err "Extraction error."
  4809. exit 1
  4810. fi
  4811. cd "$PROJECT_NAME-$BRANCH"
  4812. chmod +x $PROJECT_ENTRY
  4813. if ./$PROJECT_ENTRY install "$_nocron" "" "$_noprofile"; then
  4814. _info "Install success!"
  4815. fi
  4816. cd ..
  4817. rm -rf "$PROJECT_NAME-$BRANCH"
  4818. rm -f "$localname"
  4819. )
  4820. }
  4821. upgrade() {
  4822. if (
  4823. _initpath
  4824. export LE_WORKING_DIR
  4825. cd "$LE_WORKING_DIR"
  4826. _installOnline "nocron" "noprofile"
  4827. ); then
  4828. _info "Upgrade success!"
  4829. exit 0
  4830. else
  4831. _err "Upgrade failed!"
  4832. exit 1
  4833. fi
  4834. }
  4835. _processAccountConf() {
  4836. if [ "$_useragent" ]; then
  4837. _saveaccountconf "USER_AGENT" "$_useragent"
  4838. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  4839. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  4840. fi
  4841. if [ "$_accountemail" ]; then
  4842. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  4843. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  4844. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  4845. fi
  4846. if [ "$_openssl_bin" ]; then
  4847. _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
  4848. elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  4849. _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
  4850. fi
  4851. if [ "$_auto_upgrade" ]; then
  4852. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  4853. elif [ "$AUTO_UPGRADE" ]; then
  4854. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  4855. fi
  4856. if [ "$_use_wget" ]; then
  4857. _saveaccountconf "ACME_USE_WGET" "$_use_wget"
  4858. elif [ "$ACME_USE_WGET" ]; then
  4859. _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
  4860. fi
  4861. }
  4862. _process() {
  4863. _CMD=""
  4864. _domain=""
  4865. _altdomains="$NO_VALUE"
  4866. _webroot=""
  4867. _challenge_alias=""
  4868. _keylength=""
  4869. _accountkeylength=""
  4870. _cert_file=""
  4871. _key_file=""
  4872. _ca_file=""
  4873. _fullchain_file=""
  4874. _reloadcmd=""
  4875. _password=""
  4876. _accountconf=""
  4877. _useragent=""
  4878. _accountemail=""
  4879. _accountkey=""
  4880. _certhome=""
  4881. _confighome=""
  4882. _httpport=""
  4883. _tlsport=""
  4884. _dnssleep=""
  4885. _listraw=""
  4886. _stopRenewOnError=""
  4887. #_insecure=""
  4888. _ca_bundle=""
  4889. _ca_path=""
  4890. _nocron=""
  4891. _ecc=""
  4892. _csr=""
  4893. _pre_hook=""
  4894. _post_hook=""
  4895. _renew_hook=""
  4896. _deploy_hook=""
  4897. _logfile=""
  4898. _log=""
  4899. _local_address=""
  4900. _log_level=""
  4901. _auto_upgrade=""
  4902. _listen_v4=""
  4903. _listen_v6=""
  4904. _openssl_bin=""
  4905. _syslog=""
  4906. _use_wget=""
  4907. _server=""
  4908. while [ ${#} -gt 0 ]; do
  4909. case "${1}" in
  4910. --help | -h)
  4911. showhelp
  4912. return
  4913. ;;
  4914. --version | -v)
  4915. version
  4916. return
  4917. ;;
  4918. --install)
  4919. _CMD="install"
  4920. ;;
  4921. --uninstall)
  4922. _CMD="uninstall"
  4923. ;;
  4924. --upgrade)
  4925. _CMD="upgrade"
  4926. ;;
  4927. --issue)
  4928. _CMD="issue"
  4929. ;;
  4930. --deploy)
  4931. _CMD="deploy"
  4932. ;;
  4933. --signcsr)
  4934. _CMD="signcsr"
  4935. ;;
  4936. --showcsr)
  4937. _CMD="showcsr"
  4938. ;;
  4939. --installcert | -i | --install-cert)
  4940. _CMD="installcert"
  4941. ;;
  4942. --renew | -r)
  4943. _CMD="renew"
  4944. ;;
  4945. --renewAll | --renewall | --renew-all)
  4946. _CMD="renewAll"
  4947. ;;
  4948. --revoke)
  4949. _CMD="revoke"
  4950. ;;
  4951. --remove)
  4952. _CMD="remove"
  4953. ;;
  4954. --list)
  4955. _CMD="list"
  4956. ;;
  4957. --installcronjob | --install-cronjob)
  4958. _CMD="installcronjob"
  4959. ;;
  4960. --uninstallcronjob | --uninstall-cronjob)
  4961. _CMD="uninstallcronjob"
  4962. ;;
  4963. --cron)
  4964. _CMD="cron"
  4965. ;;
  4966. --toPkcs)
  4967. _CMD="toPkcs"
  4968. ;;
  4969. --toPkcs8)
  4970. _CMD="toPkcs8"
  4971. ;;
  4972. --createAccountKey | --createaccountkey | -cak | --create-account-key)
  4973. _CMD="createAccountKey"
  4974. ;;
  4975. --createDomainKey | --createdomainkey | -cdk | --create-domain-key)
  4976. _CMD="createDomainKey"
  4977. ;;
  4978. --createCSR | --createcsr | -ccr)
  4979. _CMD="createCSR"
  4980. ;;
  4981. --deactivate)
  4982. _CMD="deactivate"
  4983. ;;
  4984. --updateaccount | --update-account)
  4985. _CMD="updateaccount"
  4986. ;;
  4987. --registeraccount | --register-account)
  4988. _CMD="registeraccount"
  4989. ;;
  4990. --deactivate-account)
  4991. _CMD="deactivateaccount"
  4992. ;;
  4993. --domain | -d)
  4994. _dvalue="$2"
  4995. if [ "$_dvalue" ]; then
  4996. if _startswith "$_dvalue" "-"; then
  4997. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  4998. return 1
  4999. fi
  5000. if _is_idn "$_dvalue" && ! _exists idn; then
  5001. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  5002. return 1
  5003. fi
  5004. if _startswith "$_dvalue" "*."; then
  5005. _debug "Wildcard domain"
  5006. export ACME_VERSION=2
  5007. fi
  5008. if [ -z "$_domain" ]; then
  5009. _domain="$_dvalue"
  5010. else
  5011. if [ "$_altdomains" = "$NO_VALUE" ]; then
  5012. _altdomains="$_dvalue"
  5013. else
  5014. _altdomains="$_altdomains,$_dvalue"
  5015. fi
  5016. fi
  5017. fi
  5018. shift
  5019. ;;
  5020. --force | -f)
  5021. FORCE="1"
  5022. ;;
  5023. --staging | --test)
  5024. STAGE="1"
  5025. ;;
  5026. --server)
  5027. ACME_DIRECTORY="$2"
  5028. _server="$ACME_DIRECTORY"
  5029. export ACME_DIRECTORY
  5030. shift
  5031. ;;
  5032. --debug)
  5033. if [ -z "$2" ] || _startswith "$2" "-"; then
  5034. DEBUG="$DEBUG_LEVEL_DEFAULT"
  5035. else
  5036. DEBUG="$2"
  5037. shift
  5038. fi
  5039. ;;
  5040. --output-insecure)
  5041. export OUTPUT_INSECURE=1
  5042. ;;
  5043. --webroot | -w)
  5044. wvalue="$2"
  5045. if [ -z "$_webroot" ]; then
  5046. _webroot="$wvalue"
  5047. else
  5048. _webroot="$_webroot,$wvalue"
  5049. fi
  5050. shift
  5051. ;;
  5052. --challenge-alias)
  5053. cvalue="$2"
  5054. _challenge_alias="$_challenge_alias$cvalue,"
  5055. shift
  5056. ;;
  5057. --domain-alias)
  5058. cvalue="$DNS_ALIAS_PREFIX$2"
  5059. _challenge_alias="$_challenge_alias$cvalue,"
  5060. shift
  5061. ;;
  5062. --standalone)
  5063. wvalue="$NO_VALUE"
  5064. if [ -z "$_webroot" ]; then
  5065. _webroot="$wvalue"
  5066. else
  5067. _webroot="$_webroot,$wvalue"
  5068. fi
  5069. ;;
  5070. --alpn)
  5071. wvalue="$W_ALPN"
  5072. if [ -z "$_webroot" ]; then
  5073. _webroot="$wvalue"
  5074. else
  5075. _webroot="$_webroot,$wvalue"
  5076. fi
  5077. ;;
  5078. --stateless)
  5079. wvalue="$MODE_STATELESS"
  5080. if [ -z "$_webroot" ]; then
  5081. _webroot="$wvalue"
  5082. else
  5083. _webroot="$_webroot,$wvalue"
  5084. fi
  5085. ;;
  5086. --local-address)
  5087. lvalue="$2"
  5088. _local_address="$_local_address$lvalue,"
  5089. shift
  5090. ;;
  5091. --apache)
  5092. wvalue="apache"
  5093. if [ -z "$_webroot" ]; then
  5094. _webroot="$wvalue"
  5095. else
  5096. _webroot="$_webroot,$wvalue"
  5097. fi
  5098. ;;
  5099. --nginx)
  5100. wvalue="$NGINX"
  5101. if [ -z "$_webroot" ]; then
  5102. _webroot="$wvalue"
  5103. else
  5104. _webroot="$_webroot,$wvalue"
  5105. fi
  5106. ;;
  5107. --dns)
  5108. wvalue="$W_DNS"
  5109. if [ "$2" ] && ! _startswith "$2" "-"; then
  5110. wvalue="$2"
  5111. shift
  5112. fi
  5113. if [ -z "$_webroot" ]; then
  5114. _webroot="$wvalue"
  5115. else
  5116. _webroot="$_webroot,$wvalue"
  5117. fi
  5118. ;;
  5119. --dnssleep)
  5120. _dnssleep="$2"
  5121. Le_DNSSleep="$_dnssleep"
  5122. shift
  5123. ;;
  5124. --keylength | -k)
  5125. _keylength="$2"
  5126. shift
  5127. ;;
  5128. --accountkeylength | -ak)
  5129. _accountkeylength="$2"
  5130. shift
  5131. ;;
  5132. --cert-file | --certpath)
  5133. _cert_file="$2"
  5134. shift
  5135. ;;
  5136. --key-file | --keypath)
  5137. _key_file="$2"
  5138. shift
  5139. ;;
  5140. --ca-file | --capath)
  5141. _ca_file="$2"
  5142. shift
  5143. ;;
  5144. --fullchain-file | --fullchainpath)
  5145. _fullchain_file="$2"
  5146. shift
  5147. ;;
  5148. --reloadcmd | --reloadCmd)
  5149. _reloadcmd="$2"
  5150. shift
  5151. ;;
  5152. --password)
  5153. _password="$2"
  5154. shift
  5155. ;;
  5156. --accountconf)
  5157. _accountconf="$2"
  5158. ACCOUNT_CONF_PATH="$_accountconf"
  5159. shift
  5160. ;;
  5161. --home)
  5162. LE_WORKING_DIR="$2"
  5163. shift
  5164. ;;
  5165. --certhome | --cert-home)
  5166. _certhome="$2"
  5167. CERT_HOME="$_certhome"
  5168. shift
  5169. ;;
  5170. --config-home)
  5171. _confighome="$2"
  5172. LE_CONFIG_HOME="$_confighome"
  5173. shift
  5174. ;;
  5175. --useragent)
  5176. _useragent="$2"
  5177. USER_AGENT="$_useragent"
  5178. shift
  5179. ;;
  5180. --accountemail)
  5181. _accountemail="$2"
  5182. ACCOUNT_EMAIL="$_accountemail"
  5183. shift
  5184. ;;
  5185. --accountkey)
  5186. _accountkey="$2"
  5187. ACCOUNT_KEY_PATH="$_accountkey"
  5188. shift
  5189. ;;
  5190. --days)
  5191. _days="$2"
  5192. Le_RenewalDays="$_days"
  5193. shift
  5194. ;;
  5195. --httpport)
  5196. _httpport="$2"
  5197. Le_HTTPPort="$_httpport"
  5198. shift
  5199. ;;
  5200. --tlsport)
  5201. _tlsport="$2"
  5202. Le_TLSPort="$_tlsport"
  5203. shift
  5204. ;;
  5205. --listraw)
  5206. _listraw="raw"
  5207. ;;
  5208. --stopRenewOnError | --stoprenewonerror | -se)
  5209. _stopRenewOnError="1"
  5210. ;;
  5211. --insecure)
  5212. #_insecure="1"
  5213. HTTPS_INSECURE="1"
  5214. ;;
  5215. --ca-bundle)
  5216. _ca_bundle="$(_readlink "$2")"
  5217. CA_BUNDLE="$_ca_bundle"
  5218. shift
  5219. ;;
  5220. --ca-path)
  5221. _ca_path="$2"
  5222. CA_PATH="$_ca_path"
  5223. shift
  5224. ;;
  5225. --nocron)
  5226. _nocron="1"
  5227. ;;
  5228. --no-color)
  5229. export ACME_NO_COLOR=1
  5230. ;;
  5231. --force-color)
  5232. export ACME_FORCE_COLOR=1
  5233. ;;
  5234. --ecc)
  5235. _ecc="isEcc"
  5236. ;;
  5237. --csr)
  5238. _csr="$2"
  5239. shift
  5240. ;;
  5241. --pre-hook)
  5242. _pre_hook="$2"
  5243. shift
  5244. ;;
  5245. --post-hook)
  5246. _post_hook="$2"
  5247. shift
  5248. ;;
  5249. --renew-hook)
  5250. _renew_hook="$2"
  5251. shift
  5252. ;;
  5253. --deploy-hook)
  5254. if [ -z "$2" ] || _startswith "$2" "-"; then
  5255. _usage "Please specify a value for '--deploy-hook'"
  5256. return 1
  5257. fi
  5258. _deploy_hook="$_deploy_hook$2,"
  5259. shift
  5260. ;;
  5261. --ocsp-must-staple | --ocsp)
  5262. Le_OCSP_Staple="1"
  5263. ;;
  5264. --always-force-new-domain-key)
  5265. if [ -z "$2" ] || _startswith "$2" "-"; then
  5266. Le_ForceNewDomainKey=1
  5267. else
  5268. Le_ForceNewDomainKey="$2"
  5269. shift
  5270. fi
  5271. ;;
  5272. --yes-I-know-dns-manual-mode-enough-go-ahead-please)
  5273. export FORCE_DNS_MANUAL=1
  5274. ;;
  5275. --log | --logfile)
  5276. _log="1"
  5277. _logfile="$2"
  5278. if _startswith "$_logfile" '-'; then
  5279. _logfile=""
  5280. else
  5281. shift
  5282. fi
  5283. LOG_FILE="$_logfile"
  5284. if [ -z "$LOG_LEVEL" ]; then
  5285. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  5286. fi
  5287. ;;
  5288. --log-level)
  5289. _log_level="$2"
  5290. LOG_LEVEL="$_log_level"
  5291. shift
  5292. ;;
  5293. --syslog)
  5294. if ! _startswith "$2" '-'; then
  5295. _syslog="$2"
  5296. shift
  5297. fi
  5298. if [ -z "$_syslog" ]; then
  5299. _syslog="$SYSLOG_LEVEL_DEFAULT"
  5300. fi
  5301. ;;
  5302. --auto-upgrade)
  5303. _auto_upgrade="$2"
  5304. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  5305. _auto_upgrade="1"
  5306. else
  5307. shift
  5308. fi
  5309. AUTO_UPGRADE="$_auto_upgrade"
  5310. ;;
  5311. --listen-v4)
  5312. _listen_v4="1"
  5313. Le_Listen_V4="$_listen_v4"
  5314. ;;
  5315. --listen-v6)
  5316. _listen_v6="1"
  5317. Le_Listen_V6="$_listen_v6"
  5318. ;;
  5319. --openssl-bin)
  5320. _openssl_bin="$2"
  5321. ACME_OPENSSL_BIN="$_openssl_bin"
  5322. shift
  5323. ;;
  5324. --use-wget)
  5325. _use_wget="1"
  5326. ACME_USE_WGET="1"
  5327. ;;
  5328. --branch | -b)
  5329. export BRANCH="$2"
  5330. shift
  5331. ;;
  5332. *)
  5333. _err "Unknown parameter : $1"
  5334. return 1
  5335. ;;
  5336. esac
  5337. shift 1
  5338. done
  5339. if [ "${_CMD}" != "install" ]; then
  5340. __initHome
  5341. if [ "$_log" ]; then
  5342. if [ -z "$_logfile" ]; then
  5343. _logfile="$DEFAULT_LOG_FILE"
  5344. fi
  5345. fi
  5346. if [ "$_logfile" ]; then
  5347. _saveaccountconf "LOG_FILE" "$_logfile"
  5348. LOG_FILE="$_logfile"
  5349. fi
  5350. if [ "$_log_level" ]; then
  5351. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5352. LOG_LEVEL="$_log_level"
  5353. fi
  5354. if [ "$_syslog" ]; then
  5355. if _exists logger; then
  5356. if [ "$_syslog" = "0" ]; then
  5357. _clearaccountconf "SYS_LOG"
  5358. else
  5359. _saveaccountconf "SYS_LOG" "$_syslog"
  5360. fi
  5361. SYS_LOG="$_syslog"
  5362. else
  5363. _err "The 'logger' command is not found, can not enable syslog."
  5364. _clearaccountconf "SYS_LOG"
  5365. SYS_LOG=""
  5366. fi
  5367. fi
  5368. _processAccountConf
  5369. fi
  5370. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  5371. if [ "$DEBUG" ]; then
  5372. version
  5373. if [ "$_server" ]; then
  5374. _debug "Using server: $_server"
  5375. fi
  5376. fi
  5377. case "${_CMD}" in
  5378. install) install "$_nocron" "$_confighome" ;;
  5379. uninstall) uninstall "$_nocron" ;;
  5380. upgrade) upgrade ;;
  5381. issue)
  5382. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  5383. ;;
  5384. deploy)
  5385. deploy "$_domain" "$_deploy_hook" "$_ecc"
  5386. ;;
  5387. signcsr)
  5388. signcsr "$_csr" "$_webroot" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  5389. ;;
  5390. showcsr)
  5391. showcsr "$_csr" "$_domain"
  5392. ;;
  5393. installcert)
  5394. installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
  5395. ;;
  5396. renew)
  5397. renew "$_domain" "$_ecc"
  5398. ;;
  5399. renewAll)
  5400. renewAll "$_stopRenewOnError"
  5401. ;;
  5402. revoke)
  5403. revoke "$_domain" "$_ecc"
  5404. ;;
  5405. remove)
  5406. remove "$_domain" "$_ecc"
  5407. ;;
  5408. deactivate)
  5409. deactivate "$_domain,$_altdomains"
  5410. ;;
  5411. registeraccount)
  5412. registeraccount "$_accountkeylength"
  5413. ;;
  5414. updateaccount)
  5415. updateaccount
  5416. ;;
  5417. deactivateaccount)
  5418. deactivateaccount
  5419. ;;
  5420. list)
  5421. list "$_listraw"
  5422. ;;
  5423. installcronjob) installcronjob "$_confighome" ;;
  5424. uninstallcronjob) uninstallcronjob ;;
  5425. cron) cron ;;
  5426. toPkcs)
  5427. toPkcs "$_domain" "$_password" "$_ecc"
  5428. ;;
  5429. toPkcs8)
  5430. toPkcs8 "$_domain" "$_ecc"
  5431. ;;
  5432. createAccountKey)
  5433. createAccountKey "$_accountkeylength"
  5434. ;;
  5435. createDomainKey)
  5436. createDomainKey "$_domain" "$_keylength"
  5437. ;;
  5438. createCSR)
  5439. createCSR "$_domain" "$_altdomains" "$_ecc"
  5440. ;;
  5441. *)
  5442. if [ "$_CMD" ]; then
  5443. _err "Invalid command: $_CMD"
  5444. fi
  5445. showhelp
  5446. return 1
  5447. ;;
  5448. esac
  5449. _ret="$?"
  5450. if [ "$_ret" != "0" ]; then
  5451. return $_ret
  5452. fi
  5453. if [ "${_CMD}" = "install" ]; then
  5454. if [ "$_log" ]; then
  5455. if [ -z "$LOG_FILE" ]; then
  5456. LOG_FILE="$DEFAULT_LOG_FILE"
  5457. fi
  5458. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  5459. fi
  5460. if [ "$_log_level" ]; then
  5461. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5462. fi
  5463. if [ "$_syslog" ]; then
  5464. if _exists logger; then
  5465. if [ "$_syslog" = "0" ]; then
  5466. _clearaccountconf "SYS_LOG"
  5467. else
  5468. _saveaccountconf "SYS_LOG" "$_syslog"
  5469. fi
  5470. else
  5471. _err "The 'logger' command is not found, can not enable syslog."
  5472. _clearaccountconf "SYS_LOG"
  5473. SYS_LOG=""
  5474. fi
  5475. fi
  5476. _processAccountConf
  5477. fi
  5478. }
  5479. if [ "$INSTALLONLINE" ]; then
  5480. INSTALLONLINE=""
  5481. _installOnline
  5482. exit
  5483. fi
  5484. main() {
  5485. [ -z "$1" ] && showhelp && return
  5486. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  5487. }
  5488. main "$@"