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.

6234 lines
164 KiB

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