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.

6287 lines
166 KiB

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