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.

6243 lines
165 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
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
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
7 years ago
7 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
7 years ago
9 years ago
9 years ago
9 years ago
7 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
7 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
8 years ago
9 years ago
7 years ago
7 years ago
7 years ago
8 years ago
9 years ago
9 years ago
7 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
7 years ago
7 years ago
9 years ago
7 years ago
7 years ago
7 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 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
7 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
8 years ago
  1. #!/usr/bin/env sh
  2. VER=2.8.0
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. _SUB_FOLDERS="dnsapi deploy"
  9. LETSENCRYPT_CA_V1="https://acme-v01.api.letsencrypt.org/directory"
  10. LETSENCRYPT_STAGING_CA_V1="https://acme-staging.api.letsencrypt.org/directory"
  11. LETSENCRYPT_CA_V2="https://acme-v02.api.letsencrypt.org/directory"
  12. LETSENCRYPT_STAGING_CA_V2="https://acme-staging-v02.api.letsencrypt.org/directory"
  13. DEFAULT_CA=$LETSENCRYPT_CA_V1
  14. DEFAULT_STAGING_CA=$LETSENCRYPT_STAGING_CA_V1
  15. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  16. DEFAULT_ACCOUNT_EMAIL=""
  17. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  18. DEFAULT_DOMAIN_KEY_LENGTH=2048
  19. DEFAULT_OPENSSL_BIN="openssl"
  20. _OLD_CA_HOST="https://acme-v01.api.letsencrypt.org"
  21. _OLD_STAGE_CA_HOST="https://acme-staging.api.letsencrypt.org"
  22. VTYPE_HTTP="http-01"
  23. VTYPE_DNS="dns-01"
  24. VTYPE_TLS="tls-sni-01"
  25. VTYPE_TLS2="tls-sni-02"
  26. LOCAL_ANY_ADDRESS="0.0.0.0"
  27. MAX_RENEW=60
  28. DEFAULT_DNS_SLEEP=120
  29. NO_VALUE="no"
  30. W_TLS="tls"
  31. W_DNS="dns"
  32. DNS_ALIAS_PREFIX="="
  33. MODE_STATELESS="stateless"
  34. STATE_VERIFIED="verified_ok"
  35. NGINX="nginx:"
  36. NGINX_START="#ACME_NGINX_START"
  37. NGINX_END="#ACME_NGINX_END"
  38. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  39. END_CSR="-----END CERTIFICATE REQUEST-----"
  40. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  41. END_CERT="-----END CERTIFICATE-----"
  42. CONTENT_TYPE_JSON="application/jose+json"
  43. RENEW_SKIP=2
  44. ECC_SEP="_"
  45. ECC_SUFFIX="${ECC_SEP}ecc"
  46. LOG_LEVEL_1=1
  47. LOG_LEVEL_2=2
  48. LOG_LEVEL_3=3
  49. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  50. DEBUG_LEVEL_1=1
  51. DEBUG_LEVEL_2=2
  52. DEBUG_LEVEL_3=3
  53. DEBUG_LEVEL_DEFAULT=$DEBUG_LEVEL_1
  54. DEBUG_LEVEL_NONE=0
  55. HIDDEN_VALUE="[hidden](please add '--output-insecure' to see this value)"
  56. SYSLOG_ERROR="user.error"
  57. SYSLOG_INFO="user.info"
  58. SYSLOG_DEBUG="user.debug"
  59. #error
  60. SYSLOG_LEVEL_ERROR=3
  61. #info
  62. SYSLOG_LEVEL_INFO=6
  63. #debug
  64. SYSLOG_LEVEL_DEBUG=7
  65. #debug2
  66. SYSLOG_LEVEL_DEBUG_2=8
  67. #debug3
  68. SYSLOG_LEVEL_DEBUG_3=9
  69. SYSLOG_LEVEL_DEFAULT=$SYSLOG_LEVEL_ERROR
  70. #none
  71. SYSLOG_LEVEL_NONE=0
  72. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  73. _PREPARE_LINK="https://github.com/Neilpang/acme.sh/wiki/Install-preparations"
  74. _STATELESS_WIKI="https://github.com/Neilpang/acme.sh/wiki/Stateless-Mode"
  75. _DNS_ALIAS_WIKI="https://github.com/Neilpang/acme.sh/wiki/DNS-alias-mode"
  76. _DNS_MANUAL_WIKI="https://github.com/Neilpang/acme.sh/wiki/dns-manual-mode"
  77. _DNS_MANUAL_ERR="The dns manual mode can not renew automatically, you must issue it again manually. You'd better use the other modes instead."
  78. _DNS_MANUAL_WARN="It seems that you are using dns manual mode. please take care: $_DNS_MANUAL_ERR"
  79. _DNS_MANUAL_ERROR="It seems that you are using dns manual mode. Read this link first: $_DNS_MANUAL_WIKI"
  80. __INTERACTIVE=""
  81. if [ -t 1 ]; then
  82. __INTERACTIVE="1"
  83. fi
  84. __green() {
  85. if [ "$__INTERACTIVE${ACME_NO_COLOR}" = "1" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  86. printf '\033[1;31;32m'
  87. fi
  88. printf -- "%b" "$1"
  89. if [ "$__INTERACTIVE${ACME_NO_COLOR}" = "1" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  90. printf '\033[0m'
  91. fi
  92. }
  93. __red() {
  94. if [ "$__INTERACTIVE${ACME_NO_COLOR}" = "1" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  95. printf '\033[1;31;40m'
  96. fi
  97. printf -- "%b" "$1"
  98. if [ "$__INTERACTIVE${ACME_NO_COLOR}" = "1" -o "${ACME_FORCE_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. #BSD
  1194. if date -u -r "$1" 2>/dev/null; then
  1195. return
  1196. fi
  1197. #Linux
  1198. if date -u -d@"$1" 2>/dev/null; then
  1199. return
  1200. fi
  1201. #Solaris
  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|DELETE] [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. __request_conent_type="$CONTENT_TYPE_JSON"
  1565. payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
  1566. _debug3 payload64 "$payload64"
  1567. MAX_REQUEST_RETRY_TIMES=20
  1568. _sleep_retry_sec=1
  1569. _request_retry_times=0
  1570. while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
  1571. _request_retry_times=$(_math "$_request_retry_times" + 1)
  1572. _debug3 _request_retry_times "$_request_retry_times"
  1573. if [ -z "$_CACHED_NONCE" ]; then
  1574. _headers=""
  1575. if [ "$ACME_NEW_NONCE" ]; then
  1576. _debug2 "Get nonce. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1577. nonceurl="$ACME_NEW_NONCE"
  1578. if _post "" "$nonceurl" "" "HEAD" "$__request_conent_type"; then
  1579. _headers="$(cat "$HTTP_HEADER")"
  1580. fi
  1581. fi
  1582. if [ -z "$_headers" ]; then
  1583. _debug2 "Get nonce. ACME_DIRECTORY" "$ACME_DIRECTORY"
  1584. nonceurl="$ACME_DIRECTORY"
  1585. _headers="$(_get "$nonceurl" "onlyheader")"
  1586. fi
  1587. if [ "$?" != "0" ]; then
  1588. _err "Can not connect to $nonceurl to get nonce."
  1589. return 1
  1590. fi
  1591. _debug2 _headers "$_headers"
  1592. _CACHED_NONCE="$(echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1593. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1594. else
  1595. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1596. fi
  1597. nonce="$_CACHED_NONCE"
  1598. _debug2 nonce "$nonce"
  1599. if [ -z "$nonce" ]; then
  1600. _info "Could not get nonce, let's try again."
  1601. _sleep 2
  1602. continue
  1603. fi
  1604. if [ "$ACME_VERSION" = "2" ]; then
  1605. if [ "$url" = "$ACME_NEW_ACCOUNT" ] || [ "$url" = "$ACME_REVOKE_CERT" ]; then
  1606. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1607. else
  1608. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"kid\": \"${ACCOUNT_URL}\""'}'
  1609. fi
  1610. else
  1611. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1612. fi
  1613. _debug3 protected "$protected"
  1614. protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
  1615. _debug3 protected64 "$protected64"
  1616. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1617. _err "Sign request failed."
  1618. return 1
  1619. fi
  1620. _debug3 _sig_t "$_sig_t"
  1621. sig="$(printf "%s" "$_sig_t" | _url_replace)"
  1622. _debug3 sig "$sig"
  1623. if [ "$ACME_VERSION" = "2" ]; then
  1624. body="{\"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1625. else
  1626. body="{\"header\": $JWK_HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1627. fi
  1628. _debug3 body "$body"
  1629. response="$(_post "$body" "$url" "$needbase64" "POST" "$__request_conent_type")"
  1630. _CACHED_NONCE=""
  1631. if [ "$?" != "0" ]; then
  1632. _err "Can not post to $url"
  1633. return 1
  1634. fi
  1635. _debug2 original "$response"
  1636. response="$(echo "$response" | _normalizeJson)"
  1637. responseHeaders="$(cat "$HTTP_HEADER")"
  1638. _debug2 responseHeaders "$responseHeaders"
  1639. _debug2 response "$response"
  1640. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1641. _debug code "$code"
  1642. _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1643. _body="$response"
  1644. if [ "$needbase64" ]; then
  1645. _body="$(echo "$_body" | _dbase64 | tr -d '\0')"
  1646. _debug3 _body "$_body"
  1647. fi
  1648. if _contains "$_body" "JWS has invalid anti-replay nonce" || _contains "$_body" "JWS has an invalid anti-replay nonce"; then
  1649. _info "It seems the CA server is busy now, let's wait and retry. Sleeping $_sleep_retry_sec seconds."
  1650. _CACHED_NONCE=""
  1651. _sleep $_sleep_retry_sec
  1652. continue
  1653. fi
  1654. break
  1655. done
  1656. }
  1657. #setopt "file" "opt" "=" "value" [";"]
  1658. _setopt() {
  1659. __conf="$1"
  1660. __opt="$2"
  1661. __sep="$3"
  1662. __val="$4"
  1663. __end="$5"
  1664. if [ -z "$__opt" ]; then
  1665. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1666. return
  1667. fi
  1668. if [ ! -f "$__conf" ]; then
  1669. touch "$__conf"
  1670. fi
  1671. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1672. _debug3 OK
  1673. if _contains "$__val" "&"; then
  1674. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1675. fi
  1676. text="$(cat "$__conf")"
  1677. printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1678. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1679. if _contains "$__val" "&"; then
  1680. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1681. fi
  1682. text="$(cat "$__conf")"
  1683. printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1684. else
  1685. _debug3 APP
  1686. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1687. fi
  1688. _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
  1689. }
  1690. #_save_conf file key value
  1691. #save to conf
  1692. _save_conf() {
  1693. _s_c_f="$1"
  1694. _sdkey="$2"
  1695. _sdvalue="$3"
  1696. if [ "$_s_c_f" ]; then
  1697. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1698. else
  1699. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1700. fi
  1701. }
  1702. #_clear_conf file key
  1703. _clear_conf() {
  1704. _c_c_f="$1"
  1705. _sdkey="$2"
  1706. if [ "$_c_c_f" ]; then
  1707. _conf_data="$(cat "$_c_c_f")"
  1708. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1709. else
  1710. _err "config file is empty, can not clear"
  1711. fi
  1712. }
  1713. #_read_conf file key
  1714. _read_conf() {
  1715. _r_c_f="$1"
  1716. _sdkey="$2"
  1717. if [ -f "$_r_c_f" ]; then
  1718. (
  1719. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1720. eval "printf \"%s\" \"\$$_sdkey\""
  1721. )
  1722. else
  1723. _debug "config file is empty, can not read $_sdkey"
  1724. fi
  1725. }
  1726. #_savedomainconf key value
  1727. #save to domain.conf
  1728. _savedomainconf() {
  1729. _save_conf "$DOMAIN_CONF" "$1" "$2"
  1730. }
  1731. #_cleardomainconf key
  1732. _cleardomainconf() {
  1733. _clear_conf "$DOMAIN_CONF" "$1"
  1734. }
  1735. #_readdomainconf key
  1736. _readdomainconf() {
  1737. _read_conf "$DOMAIN_CONF" "$1"
  1738. }
  1739. #_saveaccountconf key value
  1740. _saveaccountconf() {
  1741. _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
  1742. }
  1743. #key value
  1744. _saveaccountconf_mutable() {
  1745. _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2"
  1746. #remove later
  1747. _clearaccountconf "$1"
  1748. }
  1749. #key
  1750. _readaccountconf() {
  1751. _read_conf "$ACCOUNT_CONF_PATH" "$1"
  1752. }
  1753. #key
  1754. _readaccountconf_mutable() {
  1755. _rac_key="$1"
  1756. _readaccountconf "SAVED_$_rac_key"
  1757. }
  1758. #_clearaccountconf key
  1759. _clearaccountconf() {
  1760. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1761. }
  1762. #_savecaconf key value
  1763. _savecaconf() {
  1764. _save_conf "$CA_CONF" "$1" "$2"
  1765. }
  1766. #_readcaconf key
  1767. _readcaconf() {
  1768. _read_conf "$CA_CONF" "$1"
  1769. }
  1770. #_clearaccountconf key
  1771. _clearcaconf() {
  1772. _clear_conf "$CA_CONF" "$1"
  1773. }
  1774. # content localaddress
  1775. _startserver() {
  1776. content="$1"
  1777. ncaddr="$2"
  1778. _debug "ncaddr" "$ncaddr"
  1779. _debug "startserver: $$"
  1780. _debug Le_HTTPPort "$Le_HTTPPort"
  1781. _debug Le_Listen_V4 "$Le_Listen_V4"
  1782. _debug Le_Listen_V6 "$Le_Listen_V6"
  1783. _NC="socat"
  1784. if [ "$Le_Listen_V4" ]; then
  1785. _NC="$_NC -4"
  1786. elif [ "$Le_Listen_V6" ]; then
  1787. _NC="$_NC -6"
  1788. fi
  1789. if [ "$DEBUG" ] && [ "$DEBUG" -gt "1" ]; then
  1790. _NC="$_NC -d -d -v"
  1791. fi
  1792. SOCAT_OPTIONS=TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork
  1793. #Adding bind to local-address
  1794. if [ "$ncaddr" ]; then
  1795. SOCAT_OPTIONS="$SOCAT_OPTIONS,bind=${ncaddr}"
  1796. fi
  1797. _debug "_NC" "$_NC $SOCAT_OPTIONS"
  1798. $_NC $SOCAT_OPTIONS SYSTEM:"sleep 1; echo HTTP/1.0 200 OK; echo ; echo $content; echo;" &
  1799. serverproc="$!"
  1800. }
  1801. _stopserver() {
  1802. pid="$1"
  1803. _debug "pid" "$pid"
  1804. if [ -z "$pid" ]; then
  1805. return
  1806. fi
  1807. kill $pid
  1808. }
  1809. # sleep sec
  1810. _sleep() {
  1811. _sleep_sec="$1"
  1812. if [ "$__INTERACTIVE" ]; then
  1813. _sleep_c="$_sleep_sec"
  1814. while [ "$_sleep_c" -ge "0" ]; do
  1815. printf "\r \r"
  1816. __green "$_sleep_c"
  1817. _sleep_c="$(_math "$_sleep_c" - 1)"
  1818. sleep 1
  1819. done
  1820. printf "\r"
  1821. else
  1822. sleep "$_sleep_sec"
  1823. fi
  1824. }
  1825. # _starttlsserver san_a san_b port content _ncaddr
  1826. _starttlsserver() {
  1827. _info "Starting tls server."
  1828. san_a="$1"
  1829. san_b="$2"
  1830. port="$3"
  1831. content="$4"
  1832. opaddr="$5"
  1833. _debug san_a "$san_a"
  1834. _debug san_b "$san_b"
  1835. _debug port "$port"
  1836. #create key TLS_KEY
  1837. if ! _createkey "2048" "$TLS_KEY"; then
  1838. _err "Create tls validation key error."
  1839. return 1
  1840. fi
  1841. #create csr
  1842. alt="$san_a"
  1843. if [ "$san_b" ]; then
  1844. alt="$alt,$san_b"
  1845. fi
  1846. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF"; then
  1847. _err "Create tls validation csr error."
  1848. return 1
  1849. fi
  1850. #self signed
  1851. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1852. _err "Create tls validation cert error."
  1853. return 1
  1854. fi
  1855. __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
  1856. if [ "$opaddr" ]; then
  1857. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1858. else
  1859. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1860. fi
  1861. _debug Le_Listen_V4 "$Le_Listen_V4"
  1862. _debug Le_Listen_V6 "$Le_Listen_V6"
  1863. if [ "$Le_Listen_V4" ]; then
  1864. __S_OPENSSL="$__S_OPENSSL -4"
  1865. elif [ "$Le_Listen_V6" ]; then
  1866. __S_OPENSSL="$__S_OPENSSL -6"
  1867. fi
  1868. _debug "$__S_OPENSSL"
  1869. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1870. $__S_OPENSSL -tlsextdebug &
  1871. else
  1872. $__S_OPENSSL >/dev/null 2>&1 &
  1873. fi
  1874. serverproc="$!"
  1875. sleep 1
  1876. _debug serverproc "$serverproc"
  1877. }
  1878. #file
  1879. _readlink() {
  1880. _rf="$1"
  1881. if ! readlink -f "$_rf" 2>/dev/null; then
  1882. if _startswith "$_rf" "/"; then
  1883. echo "$_rf"
  1884. return 0
  1885. fi
  1886. echo "$(pwd)/$_rf" | _conapath
  1887. fi
  1888. }
  1889. _conapath() {
  1890. sed "s#/\./#/#g"
  1891. }
  1892. __initHome() {
  1893. if [ -z "$_SCRIPT_HOME" ]; then
  1894. if _exists readlink && _exists dirname; then
  1895. _debug "Lets find script dir."
  1896. _debug "_SCRIPT_" "$_SCRIPT_"
  1897. _script="$(_readlink "$_SCRIPT_")"
  1898. _debug "_script" "$_script"
  1899. _script_home="$(dirname "$_script")"
  1900. _debug "_script_home" "$_script_home"
  1901. if [ -d "$_script_home" ]; then
  1902. _SCRIPT_HOME="$_script_home"
  1903. else
  1904. _err "It seems the script home is not correct:$_script_home"
  1905. fi
  1906. fi
  1907. fi
  1908. # if [ -z "$LE_WORKING_DIR" ]; then
  1909. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1910. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1911. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1912. # else
  1913. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1914. # fi
  1915. # fi
  1916. if [ -z "$LE_WORKING_DIR" ]; then
  1917. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1918. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1919. fi
  1920. export LE_WORKING_DIR
  1921. if [ -z "$LE_CONFIG_HOME" ]; then
  1922. LE_CONFIG_HOME="$LE_WORKING_DIR"
  1923. fi
  1924. _debug "Using config home:$LE_CONFIG_HOME"
  1925. export LE_CONFIG_HOME
  1926. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  1927. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1928. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1929. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1930. fi
  1931. fi
  1932. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1933. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1934. fi
  1935. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  1936. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  1937. if [ -z "$LE_TEMP_DIR" ]; then
  1938. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  1939. fi
  1940. }
  1941. #server
  1942. _initAPI() {
  1943. _api_server="${1:-$ACME_DIRECTORY}"
  1944. _debug "_init api for server: $_api_server"
  1945. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1946. response=$(_get "$_api_server")
  1947. if [ "$?" != "0" ]; then
  1948. _debug2 "response" "$response"
  1949. _err "Can not init api."
  1950. return 1
  1951. fi
  1952. _debug2 "response" "$response"
  1953. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'key-change" *: *"[^"]*"' | cut -d '"' -f 3)
  1954. if [ -z "$ACME_KEY_CHANGE" ]; then
  1955. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
  1956. fi
  1957. export ACME_KEY_CHANGE
  1958. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'new-authz" *: *"[^"]*"' | cut -d '"' -f 3)
  1959. if [ -z "$ACME_NEW_AUTHZ" ]; then
  1960. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
  1961. fi
  1962. export ACME_NEW_AUTHZ
  1963. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  1964. ACME_NEW_ORDER_RES="new-cert"
  1965. if [ -z "$ACME_NEW_ORDER" ]; then
  1966. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-order" *: *"[^"]*"' | cut -d '"' -f 3)
  1967. ACME_NEW_ORDER_RES="new-order"
  1968. if [ -z "$ACME_NEW_ORDER" ]; then
  1969. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
  1970. fi
  1971. fi
  1972. export ACME_NEW_ORDER
  1973. export ACME_NEW_ORDER_RES
  1974. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-reg" *: *"[^"]*"' | cut -d '"' -f 3)
  1975. ACME_NEW_ACCOUNT_RES="new-reg"
  1976. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1977. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-account" *: *"[^"]*"' | cut -d '"' -f 3)
  1978. ACME_NEW_ACCOUNT_RES="new-account"
  1979. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1980. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
  1981. if [ "$ACME_NEW_ACCOUNT" ]; then
  1982. export ACME_VERSION=2
  1983. fi
  1984. fi
  1985. fi
  1986. export ACME_NEW_ACCOUNT
  1987. export ACME_NEW_ACCOUNT_RES
  1988. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revoke-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  1989. if [ -z "$ACME_REVOKE_CERT" ]; then
  1990. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
  1991. fi
  1992. export ACME_REVOKE_CERT
  1993. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'new-nonce" *: *"[^"]*"' | cut -d '"' -f 3)
  1994. if [ -z "$ACME_NEW_NONCE" ]; then
  1995. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
  1996. fi
  1997. export ACME_NEW_NONCE
  1998. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'terms-of-service" *: *"[^"]*"' | cut -d '"' -f 3)
  1999. if [ -z "$ACME_AGREEMENT" ]; then
  2000. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
  2001. fi
  2002. export ACME_AGREEMENT
  2003. _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
  2004. _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
  2005. _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
  2006. _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
  2007. _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
  2008. _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
  2009. _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  2010. _debug "ACME_VERSION" "$ACME_VERSION"
  2011. fi
  2012. }
  2013. #[domain] [keylength or isEcc flag]
  2014. _initpath() {
  2015. domain="$1"
  2016. _ilength="$2"
  2017. __initHome
  2018. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  2019. . "$ACCOUNT_CONF_PATH"
  2020. fi
  2021. if [ "$IN_CRON" ]; then
  2022. if [ ! "$_USER_PATH_EXPORTED" ]; then
  2023. _USER_PATH_EXPORTED=1
  2024. export PATH="$USER_PATH:$PATH"
  2025. fi
  2026. fi
  2027. if [ -z "$CA_HOME" ]; then
  2028. CA_HOME="$DEFAULT_CA_HOME"
  2029. fi
  2030. if [ "$ACME_VERSION" = "2" ]; then
  2031. DEFAULT_CA="$LETSENCRYPT_CA_V2"
  2032. DEFAULT_STAGING_CA="$LETSENCRYPT_STAGING_CA_V2"
  2033. fi
  2034. if [ -z "$ACME_DIRECTORY" ]; then
  2035. if [ -z "$STAGE" ]; then
  2036. ACME_DIRECTORY="$DEFAULT_CA"
  2037. else
  2038. ACME_DIRECTORY="$DEFAULT_STAGING_CA"
  2039. _info "Using stage ACME_DIRECTORY: $ACME_DIRECTORY"
  2040. fi
  2041. fi
  2042. _debug ACME_DIRECTORY "$ACME_DIRECTORY"
  2043. _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
  2044. _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
  2045. CA_DIR="$CA_HOME/$_ACME_SERVER_HOST"
  2046. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  2047. if [ -z "$CA_CONF" ]; then
  2048. CA_CONF="$_DEFAULT_CA_CONF"
  2049. fi
  2050. _debug3 CA_CONF "$CA_CONF"
  2051. if [ -f "$CA_CONF" ]; then
  2052. . "$CA_CONF"
  2053. fi
  2054. if [ -z "$ACME_DIR" ]; then
  2055. ACME_DIR="/home/.acme"
  2056. fi
  2057. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  2058. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  2059. fi
  2060. if [ -z "$USER_AGENT" ]; then
  2061. USER_AGENT="$DEFAULT_USER_AGENT"
  2062. fi
  2063. if [ -z "$HTTP_HEADER" ]; then
  2064. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  2065. fi
  2066. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  2067. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  2068. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  2069. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  2070. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  2071. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  2072. fi
  2073. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  2074. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  2075. fi
  2076. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  2077. if [ -z "$CERT_HOME" ]; then
  2078. CERT_HOME="$_DEFAULT_CERT_HOME"
  2079. fi
  2080. if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
  2081. ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  2082. fi
  2083. if [ -z "$domain" ]; then
  2084. return 0
  2085. fi
  2086. if [ -z "$DOMAIN_PATH" ]; then
  2087. domainhome="$CERT_HOME/$domain"
  2088. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  2089. DOMAIN_PATH="$domainhome"
  2090. if _isEccKey "$_ilength"; then
  2091. DOMAIN_PATH="$domainhomeecc"
  2092. else
  2093. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  2094. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  2095. fi
  2096. fi
  2097. _debug DOMAIN_PATH "$DOMAIN_PATH"
  2098. fi
  2099. if [ -z "$DOMAIN_BACKUP_PATH" ]; then
  2100. DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
  2101. fi
  2102. if [ -z "$DOMAIN_CONF" ]; then
  2103. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  2104. fi
  2105. if [ -z "$DOMAIN_SSL_CONF" ]; then
  2106. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  2107. fi
  2108. if [ -z "$CSR_PATH" ]; then
  2109. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  2110. fi
  2111. if [ -z "$CERT_KEY_PATH" ]; then
  2112. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  2113. fi
  2114. if [ -z "$CERT_PATH" ]; then
  2115. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  2116. fi
  2117. if [ -z "$CA_CERT_PATH" ]; then
  2118. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  2119. fi
  2120. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  2121. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  2122. fi
  2123. if [ -z "$CERT_PFX_PATH" ]; then
  2124. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  2125. fi
  2126. if [ -z "$CERT_PKCS8_PATH" ]; then
  2127. CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
  2128. fi
  2129. if [ -z "$TLS_CONF" ]; then
  2130. TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
  2131. fi
  2132. if [ -z "$TLS_CERT" ]; then
  2133. TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
  2134. fi
  2135. if [ -z "$TLS_KEY" ]; then
  2136. TLS_KEY="$DOMAIN_PATH/tls.validation.key"
  2137. fi
  2138. if [ -z "$TLS_CSR" ]; then
  2139. TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
  2140. fi
  2141. }
  2142. _exec() {
  2143. if [ -z "$_EXEC_TEMP_ERR" ]; then
  2144. _EXEC_TEMP_ERR="$(_mktemp)"
  2145. fi
  2146. if [ "$_EXEC_TEMP_ERR" ]; then
  2147. eval "$@ 2>>$_EXEC_TEMP_ERR"
  2148. else
  2149. eval "$@"
  2150. fi
  2151. }
  2152. _exec_err() {
  2153. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  2154. }
  2155. _apachePath() {
  2156. _APACHECTL="apachectl"
  2157. if ! _exists apachectl; then
  2158. if _exists apache2ctl; then
  2159. _APACHECTL="apache2ctl"
  2160. else
  2161. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  2162. _err "Please use webroot mode to try again."
  2163. return 1
  2164. fi
  2165. fi
  2166. if ! _exec $_APACHECTL -V >/dev/null; then
  2167. _exec_err
  2168. return 1
  2169. fi
  2170. if [ "$APACHE_HTTPD_CONF" ]; then
  2171. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  2172. httpdconf="$APACHE_HTTPD_CONF"
  2173. httpdconfname="$(basename "$httpdconfname")"
  2174. else
  2175. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  2176. _debug httpdconfname "$httpdconfname"
  2177. if [ -z "$httpdconfname" ]; then
  2178. _err "Can not read apache config file."
  2179. return 1
  2180. fi
  2181. if _startswith "$httpdconfname" '/'; then
  2182. httpdconf="$httpdconfname"
  2183. httpdconfname="$(basename "$httpdconfname")"
  2184. else
  2185. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  2186. _debug httpdroot "$httpdroot"
  2187. httpdconf="$httpdroot/$httpdconfname"
  2188. httpdconfname="$(basename "$httpdconfname")"
  2189. fi
  2190. fi
  2191. _debug httpdconf "$httpdconf"
  2192. _debug httpdconfname "$httpdconfname"
  2193. if [ ! -f "$httpdconf" ]; then
  2194. _err "Apache Config file not found" "$httpdconf"
  2195. return 1
  2196. fi
  2197. return 0
  2198. }
  2199. _restoreApache() {
  2200. if [ -z "$usingApache" ]; then
  2201. return 0
  2202. fi
  2203. _initpath
  2204. if ! _apachePath; then
  2205. return 1
  2206. fi
  2207. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  2208. _debug "No config file to restore."
  2209. return 0
  2210. fi
  2211. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  2212. _debug "Restored: $httpdconf."
  2213. if ! _exec $_APACHECTL -t; then
  2214. _exec_err
  2215. _err "Sorry, restore apache config error, please contact me."
  2216. return 1
  2217. fi
  2218. _debug "Restored successfully."
  2219. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2220. return 0
  2221. }
  2222. _setApache() {
  2223. _initpath
  2224. if ! _apachePath; then
  2225. return 1
  2226. fi
  2227. #test the conf first
  2228. _info "Checking if there is an error in the apache config file before starting."
  2229. if ! _exec "$_APACHECTL" -t >/dev/null; then
  2230. _exec_err
  2231. _err "The apache config file has error, please fix it first, then try again."
  2232. _err "Don't worry, there is nothing changed to your system."
  2233. return 1
  2234. else
  2235. _info "OK"
  2236. fi
  2237. #backup the conf
  2238. _debug "Backup apache config file" "$httpdconf"
  2239. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  2240. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  2241. _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
  2242. return 1
  2243. fi
  2244. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2245. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  2246. _info "The backup file will be deleted on success, just forget it."
  2247. #add alias
  2248. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  2249. _debug "apacheVer" "$apacheVer"
  2250. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  2251. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  2252. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  2253. echo "
  2254. Alias /.well-known/acme-challenge $ACME_DIR
  2255. <Directory $ACME_DIR >
  2256. Require all granted
  2257. </Directory>
  2258. " >>"$httpdconf"
  2259. else
  2260. echo "
  2261. Alias /.well-known/acme-challenge $ACME_DIR
  2262. <Directory $ACME_DIR >
  2263. Order allow,deny
  2264. Allow from all
  2265. </Directory>
  2266. " >>"$httpdconf"
  2267. fi
  2268. _msg="$($_APACHECTL -t 2>&1)"
  2269. if [ "$?" != "0" ]; then
  2270. _err "Sorry, apache config error"
  2271. if _restoreApache; then
  2272. _err "The apache config file is restored."
  2273. else
  2274. _err "Sorry, The apache config file can not be restored, please report bug."
  2275. fi
  2276. return 1
  2277. fi
  2278. if [ ! -d "$ACME_DIR" ]; then
  2279. mkdir -p "$ACME_DIR"
  2280. chmod 755 "$ACME_DIR"
  2281. fi
  2282. if ! _exec "$_APACHECTL" graceful; then
  2283. _exec_err
  2284. _err "$_APACHECTL graceful error, please contact me."
  2285. _restoreApache
  2286. return 1
  2287. fi
  2288. usingApache="1"
  2289. return 0
  2290. }
  2291. #find the real nginx conf file
  2292. #backup
  2293. #set the nginx conf
  2294. #returns the real nginx conf file
  2295. _setNginx() {
  2296. _d="$1"
  2297. _croot="$2"
  2298. _thumbpt="$3"
  2299. FOUND_REAL_NGINX_CONF=""
  2300. FOUND_REAL_NGINX_CONF_LN=""
  2301. BACKUP_NGINX_CONF=""
  2302. _debug _croot "$_croot"
  2303. _start_f="$(echo "$_croot" | cut -d : -f 2)"
  2304. _debug _start_f "$_start_f"
  2305. if [ -z "$_start_f" ]; then
  2306. _debug "find start conf from nginx command"
  2307. if [ -z "$NGINX_CONF" ]; then
  2308. if ! _exists "nginx"; then
  2309. _err "nginx command is not found."
  2310. return 1
  2311. fi
  2312. NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
  2313. _debug NGINX_CONF "$NGINX_CONF"
  2314. NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
  2315. _debug NGINX_CONF "$NGINX_CONF"
  2316. if [ ! -f "$NGINX_CONF" ]; then
  2317. _err "'$NGINX_CONF' doesn't exist."
  2318. NGINX_CONF=""
  2319. return 1
  2320. fi
  2321. _debug "Found nginx conf file:$NGINX_CONF"
  2322. fi
  2323. _start_f="$NGINX_CONF"
  2324. fi
  2325. _debug "Start detect nginx conf for $_d from:$_start_f"
  2326. if ! _checkConf "$_d" "$_start_f"; then
  2327. _err "Can not find conf file for domain $d"
  2328. return 1
  2329. fi
  2330. _info "Found conf file: $FOUND_REAL_NGINX_CONF"
  2331. _ln=$FOUND_REAL_NGINX_CONF_LN
  2332. _debug "_ln" "$_ln"
  2333. _lnn=$(_math $_ln + 1)
  2334. _debug _lnn "$_lnn"
  2335. _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
  2336. _debug "_start_tag" "$_start_tag"
  2337. if [ "$_start_tag" = "$NGINX_START" ]; then
  2338. _info "The domain $_d is already configured, skip"
  2339. FOUND_REAL_NGINX_CONF=""
  2340. return 0
  2341. fi
  2342. mkdir -p "$DOMAIN_BACKUP_PATH"
  2343. _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
  2344. _debug _backup_conf "$_backup_conf"
  2345. BACKUP_NGINX_CONF="$_backup_conf"
  2346. _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
  2347. if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
  2348. _err "backup error."
  2349. FOUND_REAL_NGINX_CONF=""
  2350. return 1
  2351. fi
  2352. if ! _exists "nginx"; then
  2353. _err "nginx command is not found."
  2354. return 1
  2355. fi
  2356. _info "Check the nginx conf before setting up."
  2357. if ! _exec "nginx -t" >/dev/null; then
  2358. _exec_err
  2359. return 1
  2360. fi
  2361. _info "OK, Set up nginx config file"
  2362. if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
  2363. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2364. _err "write nginx conf error, but don't worry, the file is restored to the original version."
  2365. return 1
  2366. fi
  2367. echo "$NGINX_START
  2368. location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
  2369. default_type text/plain;
  2370. return 200 \"\$1.$_thumbpt\";
  2371. }
  2372. #NGINX_START
  2373. " >>"$FOUND_REAL_NGINX_CONF"
  2374. if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
  2375. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2376. _err "write nginx conf error, but don't worry, the file is restored."
  2377. return 1
  2378. fi
  2379. _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
  2380. _info "nginx conf is done, let's check it again."
  2381. if ! _exec "nginx -t" >/dev/null; then
  2382. _exec_err
  2383. _err "It seems that nginx conf was broken, let's restore."
  2384. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2385. return 1
  2386. fi
  2387. _info "Reload nginx"
  2388. if ! _exec "nginx -s reload" >/dev/null; then
  2389. _exec_err
  2390. _err "It seems that nginx reload error, let's restore."
  2391. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2392. return 1
  2393. fi
  2394. return 0
  2395. }
  2396. #d , conf
  2397. _checkConf() {
  2398. _d="$1"
  2399. _c_file="$2"
  2400. _debug "Start _checkConf from:$_c_file"
  2401. if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
  2402. _debug "wildcard"
  2403. for _w_f in $2; do
  2404. if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
  2405. return 0
  2406. fi
  2407. done
  2408. #not found
  2409. return 1
  2410. elif [ -f "$2" ]; then
  2411. _debug "single"
  2412. if _isRealNginxConf "$1" "$2"; then
  2413. _debug "$2 is found."
  2414. FOUND_REAL_NGINX_CONF="$2"
  2415. return 0
  2416. fi
  2417. if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
  2418. _debug "Try include files"
  2419. for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
  2420. _debug "check included $included"
  2421. if _checkConf "$1" "$included"; then
  2422. return 0
  2423. fi
  2424. done
  2425. fi
  2426. return 1
  2427. else
  2428. _debug "$2 not found."
  2429. return 1
  2430. fi
  2431. return 1
  2432. }
  2433. #d , conf
  2434. _isRealNginxConf() {
  2435. _debug "_isRealNginxConf $1 $2"
  2436. if [ -f "$2" ]; then
  2437. for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
  2438. _debug _fln "$_fln"
  2439. if [ "$_fln" ]; then
  2440. _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *" | grep -v server_name | _tail_n 1)
  2441. _debug "_start" "$_start"
  2442. _start_n=$(echo "$_start" | cut -d : -f 1)
  2443. _start_nn=$(_math $_start_n + 1)
  2444. _debug "_start_n" "$_start_n"
  2445. _debug "_start_nn" "$_start_nn"
  2446. _left="$(sed -n "${_start_nn},99999p" "$2")"
  2447. _debug2 _left "$_left"
  2448. _end="$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *" | grep -v server_name | _head_n 1)"
  2449. _debug "_end" "$_end"
  2450. if [ "$_end" ]; then
  2451. _end_n=$(echo "$_end" | cut -d : -f 1)
  2452. _debug "_end_n" "$_end_n"
  2453. _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
  2454. else
  2455. _seg_n="$_left"
  2456. fi
  2457. _debug "_seg_n" "$_seg_n"
  2458. _skip_ssl=1
  2459. for _listen_i in $(echo "$_seg_n" | tr "\t" ' ' | grep "^ *listen" | tr -d " "); do
  2460. if [ "$_listen_i" ]; then
  2461. if [ "$(echo "$_listen_i" | _egrep_o "listen.*ssl[ |;]")" ]; then
  2462. _debug2 "$_listen_i is ssl"
  2463. else
  2464. _debug2 "$_listen_i is plain text"
  2465. _skip_ssl=""
  2466. break
  2467. fi
  2468. fi
  2469. done
  2470. if [ "$_skip_ssl" = "1" ]; then
  2471. _debug "ssl on, skip"
  2472. else
  2473. FOUND_REAL_NGINX_CONF_LN=$_fln
  2474. _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
  2475. return 0
  2476. fi
  2477. fi
  2478. done
  2479. fi
  2480. return 1
  2481. }
  2482. #restore all the nginx conf
  2483. _restoreNginx() {
  2484. if [ -z "$NGINX_RESTORE_VLIST" ]; then
  2485. _debug "No need to restore nginx, skip."
  2486. return
  2487. fi
  2488. _debug "_restoreNginx"
  2489. _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
  2490. for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
  2491. _debug "ng_entry" "$ng_entry"
  2492. _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
  2493. _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
  2494. _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
  2495. _info "Restoring from $_ngbackupconf to $_ngconf"
  2496. cat "$_ngbackupconf" >"$_ngconf"
  2497. done
  2498. _info "Reload nginx"
  2499. if ! _exec "nginx -s reload" >/dev/null; then
  2500. _exec_err
  2501. _err "It seems that nginx reload error, please report bug."
  2502. return 1
  2503. fi
  2504. return 0
  2505. }
  2506. _clearup() {
  2507. _stopserver "$serverproc"
  2508. serverproc=""
  2509. _restoreApache
  2510. _restoreNginx
  2511. _clearupdns
  2512. if [ -z "$DEBUG" ]; then
  2513. rm -f "$TLS_CONF"
  2514. rm -f "$TLS_CERT"
  2515. rm -f "$TLS_KEY"
  2516. rm -f "$TLS_CSR"
  2517. fi
  2518. }
  2519. _clearupdns() {
  2520. _debug "_clearupdns"
  2521. if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
  2522. _debug "skip dns."
  2523. return
  2524. fi
  2525. _info "Removing DNS records."
  2526. ventries=$(echo "$vlist" | tr ',' ' ')
  2527. _alias_index=1
  2528. for ventry in $ventries; do
  2529. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2530. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2531. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2532. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2533. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  2534. _debug txt "$txt"
  2535. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2536. _debug "$d is already verified, skip $vtype."
  2537. continue
  2538. fi
  2539. if [ "$vtype" != "$VTYPE_DNS" ]; then
  2540. _debug "Skip $d for $vtype"
  2541. continue
  2542. fi
  2543. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2544. _debug d_api "$d_api"
  2545. if [ -z "$d_api" ]; then
  2546. _info "Not Found domain api file: $d_api"
  2547. continue
  2548. fi
  2549. (
  2550. if ! . "$d_api"; then
  2551. _err "Load file $d_api error. Please check your api file and try again."
  2552. return 1
  2553. fi
  2554. rmcommand="${_currentRoot}_rm"
  2555. if ! _exists "$rmcommand"; then
  2556. _err "It seems that your api file doesn't define $rmcommand"
  2557. return 1
  2558. fi
  2559. _dns_root_d="$d"
  2560. if _startswith "$_dns_root_d" "*."; then
  2561. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  2562. fi
  2563. _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
  2564. _alias_index="$(_math "$_alias_index" + 1)"
  2565. _debug "_d_alias" "$_d_alias"
  2566. if [ "$_d_alias" ]; then
  2567. if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
  2568. txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
  2569. else
  2570. txtdomain="_acme-challenge.$_d_alias"
  2571. fi
  2572. else
  2573. txtdomain="_acme-challenge.$_dns_root_d"
  2574. fi
  2575. if ! $rmcommand "$txtdomain" "$txt"; then
  2576. _err "Error removing txt for domain:$txtdomain"
  2577. return 1
  2578. fi
  2579. )
  2580. done
  2581. }
  2582. # webroot removelevel tokenfile
  2583. _clearupwebbroot() {
  2584. __webroot="$1"
  2585. if [ -z "$__webroot" ]; then
  2586. _debug "no webroot specified, skip"
  2587. return 0
  2588. fi
  2589. _rmpath=""
  2590. if [ "$2" = '1' ]; then
  2591. _rmpath="$__webroot/.well-known"
  2592. elif [ "$2" = '2' ]; then
  2593. _rmpath="$__webroot/.well-known/acme-challenge"
  2594. elif [ "$2" = '3' ]; then
  2595. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  2596. else
  2597. _debug "Skip for removelevel:$2"
  2598. fi
  2599. if [ "$_rmpath" ]; then
  2600. if [ "$DEBUG" ]; then
  2601. _debug "Debugging, skip removing: $_rmpath"
  2602. else
  2603. rm -rf "$_rmpath"
  2604. fi
  2605. fi
  2606. return 0
  2607. }
  2608. _on_before_issue() {
  2609. _chk_web_roots="$1"
  2610. _chk_main_domain="$2"
  2611. _chk_alt_domains="$3"
  2612. _chk_pre_hook="$4"
  2613. _chk_local_addr="$5"
  2614. _debug _on_before_issue
  2615. _debug _chk_main_domain "$_chk_main_domain"
  2616. _debug _chk_alt_domains "$_chk_alt_domains"
  2617. #run pre hook
  2618. if [ "$_chk_pre_hook" ]; then
  2619. _info "Run pre hook:'$_chk_pre_hook'"
  2620. if ! (
  2621. cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
  2622. ); then
  2623. _err "Error when run pre hook."
  2624. return 1
  2625. fi
  2626. fi
  2627. if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
  2628. if ! _exists "socat"; then
  2629. _err "Please install socat tools first."
  2630. return 1
  2631. fi
  2632. fi
  2633. _debug Le_LocalAddress "$_chk_local_addr"
  2634. _index=1
  2635. _currentRoot=""
  2636. _addrIndex=1
  2637. _w_index=1
  2638. while true; do
  2639. d="$(echo "$_chk_main_domain,$_chk_alt_domains," | cut -d , -f "$_w_index")"
  2640. _w_index="$(_math "$_w_index" + 1)"
  2641. _debug d "$d"
  2642. if [ -z "$d" ]; then
  2643. break
  2644. fi
  2645. _debug "Check for domain" "$d"
  2646. _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
  2647. _debug "_currentRoot" "$_currentRoot"
  2648. _index=$(_math $_index + 1)
  2649. _checkport=""
  2650. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2651. _info "Standalone mode."
  2652. if [ -z "$Le_HTTPPort" ]; then
  2653. Le_HTTPPort=80
  2654. else
  2655. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  2656. fi
  2657. _checkport="$Le_HTTPPort"
  2658. elif [ "$_currentRoot" = "$W_TLS" ]; then
  2659. _info "Standalone tls mode."
  2660. if [ -z "$Le_TLSPort" ]; then
  2661. Le_TLSPort=443
  2662. else
  2663. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  2664. fi
  2665. _checkport="$Le_TLSPort"
  2666. fi
  2667. if [ "$_checkport" ]; then
  2668. _debug _checkport "$_checkport"
  2669. _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
  2670. _debug _checkaddr "$_checkaddr"
  2671. _addrIndex="$(_math $_addrIndex + 1)"
  2672. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  2673. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  2674. if [ -z "$netprc" ]; then
  2675. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  2676. fi
  2677. if [ "$netprc" ]; then
  2678. _err "$netprc"
  2679. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  2680. _err "Please stop it first"
  2681. return 1
  2682. fi
  2683. fi
  2684. done
  2685. if _hasfield "$_chk_web_roots" "apache"; then
  2686. if ! _setApache; then
  2687. _err "set up apache error. Report error to me."
  2688. return 1
  2689. fi
  2690. else
  2691. usingApache=""
  2692. fi
  2693. }
  2694. _on_issue_err() {
  2695. _chk_post_hook="$1"
  2696. _chk_vlist="$2"
  2697. _debug _on_issue_err
  2698. if [ "$LOG_FILE" ]; then
  2699. _err "Please check log file for more details: $LOG_FILE"
  2700. else
  2701. _err "Please add '--debug' or '--log' to check more details."
  2702. _err "See: $_DEBUG_WIKI"
  2703. fi
  2704. #run the post hook
  2705. if [ "$_chk_post_hook" ]; then
  2706. _info "Run post hook:'$_chk_post_hook'"
  2707. if ! (
  2708. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2709. ); then
  2710. _err "Error when run post hook."
  2711. return 1
  2712. fi
  2713. fi
  2714. #trigger the validation to flush the pending authz
  2715. _debug2 "_chk_vlist" "$_chk_vlist"
  2716. if [ "$_chk_vlist" ]; then
  2717. (
  2718. _debug2 "start to deactivate authz"
  2719. ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
  2720. for ventry in $ventries; do
  2721. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2722. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2723. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2724. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2725. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2726. __trigger_validation "$uri" "$keyauthorization"
  2727. done
  2728. )
  2729. fi
  2730. if [ "$IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "$W_DNS"; then
  2731. _err "$_DNS_MANUAL_ERR"
  2732. fi
  2733. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  2734. _debug "$(_dlg_versions)"
  2735. fi
  2736. }
  2737. _on_issue_success() {
  2738. _chk_post_hook="$1"
  2739. _chk_renew_hook="$2"
  2740. _debug _on_issue_success
  2741. #run the post hook
  2742. if [ "$_chk_post_hook" ]; then
  2743. _info "Run post hook:'$_chk_post_hook'"
  2744. if ! (
  2745. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2746. ); then
  2747. _err "Error when run post hook."
  2748. return 1
  2749. fi
  2750. fi
  2751. #run renew hook
  2752. if [ "$IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
  2753. _info "Run renew hook:'$_chk_renew_hook'"
  2754. if ! (
  2755. cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
  2756. ); then
  2757. _err "Error when run renew hook."
  2758. return 1
  2759. fi
  2760. fi
  2761. if _hasfield "$Le_Webroot" "$W_DNS"; then
  2762. _err "$_DNS_MANUAL_WARN"
  2763. fi
  2764. }
  2765. updateaccount() {
  2766. _initpath
  2767. _regAccount
  2768. }
  2769. registeraccount() {
  2770. _reg_length="$1"
  2771. _initpath
  2772. _regAccount "$_reg_length"
  2773. }
  2774. __calcAccountKeyHash() {
  2775. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  2776. }
  2777. __calc_account_thumbprint() {
  2778. printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
  2779. }
  2780. #keylength
  2781. _regAccount() {
  2782. _initpath
  2783. _reg_length="$1"
  2784. _debug3 _regAccount "$_regAccount"
  2785. _initAPI
  2786. mkdir -p "$CA_DIR"
  2787. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2788. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2789. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2790. fi
  2791. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2792. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2793. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2794. fi
  2795. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2796. if ! _create_account_key "$_reg_length"; then
  2797. _err "Create account key error."
  2798. return 1
  2799. fi
  2800. fi
  2801. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2802. return 1
  2803. fi
  2804. if [ "$ACME_VERSION" = "2" ]; then
  2805. regjson='{"termsOfServiceAgreed": true}'
  2806. if [ "$ACCOUNT_EMAIL" ]; then
  2807. regjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"], "termsOfServiceAgreed": true}'
  2808. fi
  2809. else
  2810. _reg_res="$ACME_NEW_ACCOUNT_RES"
  2811. regjson='{"resource": "'$_reg_res'", "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2812. if [ "$ACCOUNT_EMAIL" ]; then
  2813. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2814. fi
  2815. fi
  2816. _info "Registering account"
  2817. if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
  2818. _err "Register account Error: $response"
  2819. return 1
  2820. fi
  2821. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  2822. echo "$response" >"$ACCOUNT_JSON_PATH"
  2823. _info "Registered"
  2824. elif [ "$code" = '409' ] || [ "$code" = '200' ]; then
  2825. _info "Already registered"
  2826. else
  2827. _err "Register account Error: $response"
  2828. return 1
  2829. fi
  2830. _debug2 responseHeaders "$responseHeaders"
  2831. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2832. _debug "_accUri" "$_accUri"
  2833. if [ -z "$_accUri" ]; then
  2834. _err "Can not find account id url."
  2835. _err "$responseHeaders"
  2836. return 1
  2837. fi
  2838. _savecaconf "ACCOUNT_URL" "$_accUri"
  2839. export ACCOUNT_URL="$_accUri"
  2840. CA_KEY_HASH="$(__calcAccountKeyHash)"
  2841. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  2842. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  2843. if [ "$code" = '403' ]; then
  2844. _err "It seems that the account key is already deactivated, please use a new account key."
  2845. return 1
  2846. fi
  2847. ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
  2848. _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
  2849. }
  2850. #Implement deactivate account
  2851. deactivateaccount() {
  2852. _initpath
  2853. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2854. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2855. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2856. fi
  2857. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2858. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2859. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2860. fi
  2861. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2862. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  2863. return 1
  2864. fi
  2865. _accUri=$(_readcaconf "ACCOUNT_URL")
  2866. _debug _accUri "$_accUri"
  2867. if [ -z "$_accUri" ]; then
  2868. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  2869. _err "Then try again."
  2870. return 1
  2871. fi
  2872. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2873. return 1
  2874. fi
  2875. _initAPI
  2876. if [ "$ACME_VERSION" = "2" ]; then
  2877. _djson="{\"status\":\"deactivated\"}"
  2878. else
  2879. _djson="{\"resource\": \"reg\", \"status\":\"deactivated\"}"
  2880. fi
  2881. if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
  2882. _info "Deactivate account success for $_accUri."
  2883. _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
  2884. elif [ "$code" = "403" ]; then
  2885. _info "The account is already deactivated."
  2886. _accid=$(_getfield "$_accUri" "999" "/")
  2887. else
  2888. _err "Deactivate: account failed for $_accUri."
  2889. return 1
  2890. fi
  2891. _debug "Account id: $_accid"
  2892. if [ "$_accid" ]; then
  2893. _deactivated_account_path="$CA_DIR/deactivated/$_accid"
  2894. _debug _deactivated_account_path "$_deactivated_account_path"
  2895. if mkdir -p "$_deactivated_account_path"; then
  2896. _info "Moving deactivated account info to $_deactivated_account_path/"
  2897. mv "$CA_CONF" "$_deactivated_account_path/"
  2898. mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
  2899. mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
  2900. else
  2901. _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
  2902. rm -f "$CA_CONF"
  2903. rm -f "$ACCOUNT_JSON_PATH"
  2904. rm -f "$ACCOUNT_KEY_PATH"
  2905. fi
  2906. fi
  2907. }
  2908. # domain folder file
  2909. _findHook() {
  2910. _hookdomain="$1"
  2911. _hookcat="$2"
  2912. _hookname="$3"
  2913. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  2914. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  2915. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  2916. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  2917. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  2918. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  2919. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  2920. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  2921. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  2922. d_api="$LE_WORKING_DIR/$_hookname"
  2923. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  2924. d_api="$LE_WORKING_DIR/$_hookname.sh"
  2925. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  2926. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  2927. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  2928. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  2929. fi
  2930. printf "%s" "$d_api"
  2931. }
  2932. #domain
  2933. __get_domain_new_authz() {
  2934. _gdnd="$1"
  2935. _info "Getting new-authz for domain" "$_gdnd"
  2936. _initAPI
  2937. _Max_new_authz_retry_times=5
  2938. _authz_i=0
  2939. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  2940. _debug "Try new-authz for the $_authz_i time."
  2941. if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  2942. _err "Can not get domain new authz."
  2943. return 1
  2944. fi
  2945. if _contains "$response" "No registration exists matching provided key"; then
  2946. _err "It seems there is an error, but it's recovered now, please try again."
  2947. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  2948. _clearcaconf "CA_KEY_HASH"
  2949. break
  2950. fi
  2951. if ! _contains "$response" "An error occurred while processing your request"; then
  2952. _info "The new-authz request is ok."
  2953. break
  2954. fi
  2955. _authz_i="$(_math "$_authz_i" + 1)"
  2956. _info "The server is busy, Sleep $_authz_i to retry."
  2957. _sleep "$_authz_i"
  2958. done
  2959. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  2960. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2961. fi
  2962. if [ "$code" ] && [ "$code" != '201' ]; then
  2963. _err "new-authz error: $response"
  2964. return 1
  2965. fi
  2966. }
  2967. #uri keyAuthorization
  2968. __trigger_validation() {
  2969. _debug2 "tigger domain validation."
  2970. _t_url="$1"
  2971. _debug2 _t_url "$_t_url"
  2972. _t_key_authz="$2"
  2973. _debug2 _t_key_authz "$_t_key_authz"
  2974. if [ "$ACME_VERSION" = "2" ]; then
  2975. _send_signed_request "$_t_url" "{\"keyAuthorization\": \"$_t_key_authz\"}"
  2976. else
  2977. _send_signed_request "$_t_url" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$_t_key_authz\"}"
  2978. fi
  2979. }
  2980. #webroot, domain domainlist keylength
  2981. issue() {
  2982. if [ -z "$2" ]; then
  2983. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2984. return 1
  2985. fi
  2986. if [ -z "$1" ]; then
  2987. _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
  2988. return 1
  2989. fi
  2990. _web_roots="$1"
  2991. _main_domain="$2"
  2992. _alt_domains="$3"
  2993. if _contains "$_main_domain" ","; then
  2994. _main_domain=$(echo "$2,$3" | cut -d , -f 1)
  2995. _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  2996. fi
  2997. _debug _main_domain "$_main_domain"
  2998. _debug _alt_domains "$_alt_domains"
  2999. _key_length="$4"
  3000. _real_cert="$5"
  3001. _real_key="$6"
  3002. _real_ca="$7"
  3003. _reload_cmd="$8"
  3004. _real_fullchain="$9"
  3005. _pre_hook="${10}"
  3006. _post_hook="${11}"
  3007. _renew_hook="${12}"
  3008. _local_addr="${13}"
  3009. _challenge_alias="${14}"
  3010. #remove these later.
  3011. if [ "$_web_roots" = "dns-cf" ]; then
  3012. _web_roots="dns_cf"
  3013. fi
  3014. if [ "$_web_roots" = "dns-dp" ]; then
  3015. _web_roots="dns_dp"
  3016. fi
  3017. if [ "$_web_roots" = "dns-cx" ]; then
  3018. _web_roots="dns_cx"
  3019. fi
  3020. if [ ! "$IS_RENEW" ]; then
  3021. _initpath "$_main_domain" "$_key_length"
  3022. mkdir -p "$DOMAIN_PATH"
  3023. fi
  3024. if _hasfield "$_web_roots" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
  3025. _err "$_DNS_MANUAL_ERROR"
  3026. return 1
  3027. fi
  3028. _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
  3029. _initAPI
  3030. if [ -f "$DOMAIN_CONF" ]; then
  3031. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  3032. _debug Le_NextRenewTime "$Le_NextRenewTime"
  3033. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3034. _saved_domain=$(_readdomainconf Le_Domain)
  3035. _debug _saved_domain "$_saved_domain"
  3036. _saved_alt=$(_readdomainconf Le_Alt)
  3037. _debug _saved_alt "$_saved_alt"
  3038. if [ "$_saved_domain,$_saved_alt" = "$_main_domain,$_alt_domains" ]; then
  3039. _info "Domains not changed."
  3040. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  3041. _info "Add '$(__red '--force')' to force to renew."
  3042. return $RENEW_SKIP
  3043. else
  3044. _info "Domains have changed."
  3045. fi
  3046. fi
  3047. fi
  3048. _savedomainconf "Le_Domain" "$_main_domain"
  3049. _savedomainconf "Le_Alt" "$_alt_domains"
  3050. _savedomainconf "Le_Webroot" "$_web_roots"
  3051. _savedomainconf "Le_PreHook" "$_pre_hook"
  3052. _savedomainconf "Le_PostHook" "$_post_hook"
  3053. _savedomainconf "Le_RenewHook" "$_renew_hook"
  3054. if [ "$_local_addr" ]; then
  3055. _savedomainconf "Le_LocalAddress" "$_local_addr"
  3056. else
  3057. _cleardomainconf "Le_LocalAddress"
  3058. fi
  3059. if [ "$_challenge_alias" ]; then
  3060. _savedomainconf "Le_ChallengeAlias" "$_challenge_alias"
  3061. else
  3062. _cleardomainconf "Le_ChallengeAlias"
  3063. fi
  3064. Le_API="$ACME_DIRECTORY"
  3065. _savedomainconf "Le_API" "$Le_API"
  3066. if [ "$_alt_domains" = "$NO_VALUE" ]; then
  3067. _alt_domains=""
  3068. fi
  3069. if [ "$_key_length" = "$NO_VALUE" ]; then
  3070. _key_length=""
  3071. fi
  3072. if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
  3073. _err "_on_before_issue."
  3074. return 1
  3075. fi
  3076. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  3077. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  3078. if [ -z "$ACCOUNT_URL" ] || [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  3079. if ! _regAccount "$_accountkeylength"; then
  3080. _on_issue_err "$_post_hook"
  3081. return 1
  3082. fi
  3083. else
  3084. _debug "_saved_account_key_hash is not changed, skip register account."
  3085. fi
  3086. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  3087. _info "Signing from existing CSR."
  3088. else
  3089. _key=$(_readdomainconf Le_Keylength)
  3090. _debug "Read key length:$_key"
  3091. if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
  3092. if ! createDomainKey "$_main_domain" "$_key_length"; then
  3093. _err "Create domain key error."
  3094. _clearup
  3095. _on_issue_err "$_post_hook"
  3096. return 1
  3097. fi
  3098. fi
  3099. if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  3100. _err "Create CSR error."
  3101. _clearup
  3102. _on_issue_err "$_post_hook"
  3103. return 1
  3104. fi
  3105. fi
  3106. _savedomainconf "Le_Keylength" "$_key_length"
  3107. vlist="$Le_Vlist"
  3108. _info "Getting domain auth token for each domain"
  3109. sep='#'
  3110. dvsep=','
  3111. if [ -z "$vlist" ]; then
  3112. if [ "$ACME_VERSION" = "2" ]; then
  3113. #make new order request
  3114. _identifiers="{\"type\":\"dns\",\"value\":\"$_main_domain\"}"
  3115. _w_index=1
  3116. while true; do
  3117. d="$(echo "$_alt_domains," | cut -d , -f "$_w_index")"
  3118. _w_index="$(_math "$_w_index" + 1)"
  3119. _debug d "$d"
  3120. if [ -z "$d" ]; then
  3121. break
  3122. fi
  3123. _identifiers="$_identifiers,{\"type\":\"dns\",\"value\":\"$d\"}"
  3124. done
  3125. _debug2 _identifiers "$_identifiers"
  3126. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  3127. _err "Create new order error."
  3128. _clearup
  3129. _on_issue_err "$_post_hook"
  3130. return 1
  3131. fi
  3132. Le_OrderFinalize="$(echo "$response" | tr -d '\r\n' | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
  3133. _debug Le_OrderFinalize "$Le_OrderFinalize"
  3134. if [ -z "$Le_OrderFinalize" ]; then
  3135. _err "Create new order error. Le_OrderFinalize not found. $response"
  3136. _clearup
  3137. _on_issue_err "$_post_hook"
  3138. return 1
  3139. fi
  3140. #for dns manual mode
  3141. _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
  3142. _authorizations_seg="$(echo "$response" | tr -d '\r\n' | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  3143. _debug2 _authorizations_seg "$_authorizations_seg"
  3144. if [ -z "$_authorizations_seg" ]; then
  3145. _err "_authorizations_seg not found."
  3146. _clearup
  3147. _on_issue_err "$_post_hook"
  3148. return 1
  3149. fi
  3150. #domain and authz map
  3151. _authorizations_map=""
  3152. for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
  3153. _debug2 "_authz_url" "$_authz_url"
  3154. if ! response="$(_get "$_authz_url")"; then
  3155. _err "get to authz error."
  3156. _err "_authorizations_seg" "$_authorizations_seg"
  3157. _err "_authz_url" "$_authz_url"
  3158. _clearup
  3159. _on_issue_err "$_post_hook"
  3160. return 1
  3161. fi
  3162. response="$(echo "$response" | _normalizeJson)"
  3163. _debug2 response "$response"
  3164. _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2 | tr -d ' "')"
  3165. if _contains "$response" "\"wildcard\" *: *true"; then
  3166. _d="*.$_d"
  3167. fi
  3168. _debug2 _d "$_d"
  3169. _authorizations_map="$_d,$response
  3170. $_authorizations_map"
  3171. done
  3172. _debug2 _authorizations_map "$_authorizations_map"
  3173. fi
  3174. _index=0
  3175. _currentRoot=""
  3176. _w_index=1
  3177. while true; do
  3178. d="$(echo "$_main_domain,$_alt_domains," | cut -d , -f "$_w_index")"
  3179. _w_index="$(_math "$_w_index" + 1)"
  3180. _debug d "$d"
  3181. if [ -z "$d" ]; then
  3182. break
  3183. fi
  3184. _info "Getting webroot for domain" "$d"
  3185. _index=$(_math $_index + 1)
  3186. _w="$(echo $_web_roots | cut -d , -f $_index)"
  3187. _debug _w "$_w"
  3188. if [ "$_w" ]; then
  3189. _currentRoot="$_w"
  3190. fi
  3191. _debug "_currentRoot" "$_currentRoot"
  3192. vtype="$VTYPE_HTTP"
  3193. #todo, v2 wildcard force to use dns
  3194. if _startswith "$_currentRoot" "$W_DNS"; then
  3195. vtype="$VTYPE_DNS"
  3196. fi
  3197. if [ "$_currentRoot" = "$W_TLS" ]; then
  3198. if [ "$ACME_VERSION" = "2" ]; then
  3199. vtype="$VTYPE_TLS2"
  3200. else
  3201. vtype="$VTYPE_TLS"
  3202. fi
  3203. fi
  3204. if [ "$ACME_VERSION" = "2" ]; then
  3205. response="$(echo "$_authorizations_map" | grep "^$d," | sed "s/$d,//")"
  3206. _debug2 "response" "$response"
  3207. if [ -z "$response" ]; then
  3208. _err "get to authz error."
  3209. _err "_authorizations_map" "$_authorizations_map"
  3210. _clearup
  3211. _on_issue_err "$_post_hook"
  3212. return 1
  3213. fi
  3214. else
  3215. if ! __get_domain_new_authz "$d"; then
  3216. _clearup
  3217. _on_issue_err "$_post_hook"
  3218. return 1
  3219. fi
  3220. fi
  3221. if [ -z "$thumbprint" ]; then
  3222. thumbprint="$(__calc_account_thumbprint)"
  3223. fi
  3224. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  3225. _debug entry "$entry"
  3226. if [ -z "$entry" ]; then
  3227. _err "Error, can not get domain token entry $d"
  3228. _supported_vtypes="$(echo "$response" | _egrep_o "\"challenges\":\[[^]]*]" | tr '{' "\n" | grep type | cut -d '"' -f 4 | tr "\n" ' ')"
  3229. if [ "$_supported_vtypes" ]; then
  3230. _err "The supported validation types are: $_supported_vtypes, but you specified: $vtype"
  3231. fi
  3232. _clearup
  3233. _on_issue_err "$_post_hook"
  3234. return 1
  3235. fi
  3236. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  3237. _debug token "$token"
  3238. if [ -z "$token" ]; then
  3239. _err "Error, can not get domain token $entry"
  3240. _clearup
  3241. _on_issue_err "$_post_hook"
  3242. return 1
  3243. fi
  3244. if [ "$ACME_VERSION" = "2" ]; then
  3245. uri="$(printf "%s\n" "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
  3246. else
  3247. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d '"' -f 4)"
  3248. fi
  3249. _debug uri "$uri"
  3250. if [ -z "$uri" ]; then
  3251. _err "Error, can not get domain uri. $entry"
  3252. _clearup
  3253. _on_issue_err "$_post_hook"
  3254. return 1
  3255. fi
  3256. keyauthorization="$token.$thumbprint"
  3257. _debug keyauthorization "$keyauthorization"
  3258. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  3259. _debug "$d is already verified."
  3260. keyauthorization="$STATE_VERIFIED"
  3261. _debug keyauthorization "$keyauthorization"
  3262. fi
  3263. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  3264. _debug dvlist "$dvlist"
  3265. vlist="$vlist$dvlist$dvsep"
  3266. done
  3267. _debug vlist "$vlist"
  3268. #add entry
  3269. dnsadded=""
  3270. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3271. _alias_index=1
  3272. for ventry in $ventries; do
  3273. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3274. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3275. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3276. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3277. _debug d "$d"
  3278. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3279. _debug "$d is already verified, skip $vtype."
  3280. continue
  3281. fi
  3282. if [ "$vtype" = "$VTYPE_DNS" ]; then
  3283. dnsadded='0'
  3284. _dns_root_d="$d"
  3285. if _startswith "$_dns_root_d" "*."; then
  3286. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  3287. fi
  3288. _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
  3289. _alias_index="$(_math "$_alias_index" + 1)"
  3290. _debug "_d_alias" "$_d_alias"
  3291. if [ "$_d_alias" ]; then
  3292. if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
  3293. txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
  3294. else
  3295. txtdomain="_acme-challenge.$_d_alias"
  3296. fi
  3297. else
  3298. txtdomain="_acme-challenge.$_dns_root_d"
  3299. fi
  3300. _debug txtdomain "$txtdomain"
  3301. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  3302. _debug txt "$txt"
  3303. d_api="$(_findHook "$_dns_root_d" dnsapi "$_currentRoot")"
  3304. _debug d_api "$d_api"
  3305. if [ "$d_api" ]; then
  3306. _info "Found domain api file: $d_api"
  3307. else
  3308. if [ "$_currentRoot" != "$W_DNS" ]; then
  3309. _err "Can not find dns api hook for: $_currentRoot"
  3310. _info "You need to add the txt record manually."
  3311. fi
  3312. _info "$(__red "Add the following TXT record:")"
  3313. _info "$(__red "Domain: '$(__green "$txtdomain")'")"
  3314. _info "$(__red "TXT value: '$(__green "$txt")'")"
  3315. _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
  3316. _info "$(__red "so the resulting subdomain will be: $txtdomain")"
  3317. continue
  3318. fi
  3319. (
  3320. if ! . "$d_api"; then
  3321. _err "Load file $d_api error. Please check your api file and try again."
  3322. return 1
  3323. fi
  3324. addcommand="${_currentRoot}_add"
  3325. if ! _exists "$addcommand"; then
  3326. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  3327. return 1
  3328. fi
  3329. if ! $addcommand "$txtdomain" "$txt"; then
  3330. _err "Error add txt for domain:$txtdomain"
  3331. return 1
  3332. fi
  3333. )
  3334. if [ "$?" != "0" ]; then
  3335. _clearup
  3336. _on_issue_err "$_post_hook" "$vlist"
  3337. return 1
  3338. fi
  3339. dnsadded='1'
  3340. fi
  3341. done
  3342. if [ "$dnsadded" = '0' ]; then
  3343. _savedomainconf "Le_Vlist" "$vlist"
  3344. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  3345. _err "Please add the TXT records to the domains, and re-run with --renew."
  3346. _clearup
  3347. _on_issue_err "$_post_hook"
  3348. return 1
  3349. fi
  3350. fi
  3351. if [ "$dnsadded" = '1' ]; then
  3352. if [ -z "$Le_DNSSleep" ]; then
  3353. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  3354. else
  3355. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  3356. fi
  3357. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  3358. _sleep "$Le_DNSSleep"
  3359. fi
  3360. NGINX_RESTORE_VLIST=""
  3361. _debug "ok, let's start to verify"
  3362. _ncIndex=1
  3363. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3364. for ventry in $ventries; do
  3365. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3366. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3367. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  3368. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3369. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3370. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3371. _info "$d is already verified, skip $vtype."
  3372. continue
  3373. fi
  3374. _info "Verifying:$d"
  3375. _debug "d" "$d"
  3376. _debug "keyauthorization" "$keyauthorization"
  3377. _debug "uri" "$uri"
  3378. removelevel=""
  3379. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  3380. _debug "_currentRoot" "$_currentRoot"
  3381. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3382. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  3383. _info "Standalone mode server"
  3384. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3385. _ncIndex="$(_math $_ncIndex + 1)"
  3386. _startserver "$keyauthorization" "$_ncaddr"
  3387. if [ "$?" != "0" ]; then
  3388. _clearup
  3389. _on_issue_err "$_post_hook" "$vlist"
  3390. return 1
  3391. fi
  3392. sleep 1
  3393. _debug serverproc "$serverproc"
  3394. elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
  3395. _info "Stateless mode for domain:$d"
  3396. _sleep 1
  3397. elif _startswith "$_currentRoot" "$NGINX"; then
  3398. _info "Nginx mode for domain:$d"
  3399. #set up nginx server
  3400. FOUND_REAL_NGINX_CONF=""
  3401. BACKUP_NGINX_CONF=""
  3402. if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
  3403. _clearup
  3404. _on_issue_err "$_post_hook" "$vlist"
  3405. return 1
  3406. fi
  3407. if [ "$FOUND_REAL_NGINX_CONF" ]; then
  3408. _realConf="$FOUND_REAL_NGINX_CONF"
  3409. _backup="$BACKUP_NGINX_CONF"
  3410. _debug _realConf "$_realConf"
  3411. NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
  3412. fi
  3413. _sleep 1
  3414. else
  3415. if [ "$_currentRoot" = "apache" ]; then
  3416. wellknown_path="$ACME_DIR"
  3417. else
  3418. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  3419. if [ ! -d "$_currentRoot/.well-known" ]; then
  3420. removelevel='1'
  3421. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  3422. removelevel='2'
  3423. else
  3424. removelevel='3'
  3425. fi
  3426. fi
  3427. _debug wellknown_path "$wellknown_path"
  3428. _debug "writing token:$token to $wellknown_path/$token"
  3429. mkdir -p "$wellknown_path"
  3430. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  3431. _err "$d:Can not write token to file : $wellknown_path/$token"
  3432. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3433. _clearup
  3434. _on_issue_err "$_post_hook" "$vlist"
  3435. return 1
  3436. fi
  3437. if [ ! "$usingApache" ]; then
  3438. if webroot_owner=$(_stat "$_currentRoot"); then
  3439. _debug "Changing owner/group of .well-known to $webroot_owner"
  3440. if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
  3441. _debug "$(cat "$_EXEC_TEMP_ERR")"
  3442. _exec_err >/dev/null 2>&1
  3443. fi
  3444. else
  3445. _debug "not changing owner/group of webroot"
  3446. fi
  3447. fi
  3448. fi
  3449. elif [ "$vtype" = "$VTYPE_TLS" ]; then
  3450. #create A
  3451. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  3452. #_debug2 _hash_A "$_hash_A"
  3453. #_x="$(echo $_hash_A | cut -c 1-32)"
  3454. #_debug2 _x "$_x"
  3455. #_y="$(echo $_hash_A | cut -c 33-64)"
  3456. #_debug2 _y "$_y"
  3457. #_SAN_A="$_x.$_y.token.acme.invalid"
  3458. #_debug2 _SAN_A "$_SAN_A"
  3459. #create B
  3460. _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  3461. _debug2 _hash_B "$_hash_B"
  3462. _x="$(echo "$_hash_B" | cut -c 1-32)"
  3463. _debug2 _x "$_x"
  3464. _y="$(echo "$_hash_B" | cut -c 33-64)"
  3465. _debug2 _y "$_y"
  3466. #_SAN_B="$_x.$_y.ka.acme.invalid"
  3467. _SAN_B="$_x.$_y.acme.invalid"
  3468. _debug2 _SAN_B "$_SAN_B"
  3469. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3470. _ncIndex="$(_math "$_ncIndex" + 1)"
  3471. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  3472. _err "Start tls server error."
  3473. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3474. _clearup
  3475. _on_issue_err "$_post_hook" "$vlist"
  3476. return 1
  3477. fi
  3478. fi
  3479. if ! __trigger_validation "$uri" "$keyauthorization"; then
  3480. _err "$d:Can not get challenge: $response"
  3481. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3482. _clearup
  3483. _on_issue_err "$_post_hook" "$vlist"
  3484. return 1
  3485. fi
  3486. if [ "$code" ] && [ "$code" != '202' ]; then
  3487. if [ "$ACME_VERSION" = "2" ] && [ "$code" = '200' ]; then
  3488. _debug "trigger validation code: $code"
  3489. else
  3490. _err "$d:Challenge error: $response"
  3491. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3492. _clearup
  3493. _on_issue_err "$_post_hook" "$vlist"
  3494. return 1
  3495. fi
  3496. fi
  3497. waittimes=0
  3498. if [ -z "$MAX_RETRY_TIMES" ]; then
  3499. MAX_RETRY_TIMES=30
  3500. fi
  3501. while true; do
  3502. waittimes=$(_math "$waittimes" + 1)
  3503. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  3504. _err "$d:Timeout"
  3505. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3506. _clearup
  3507. _on_issue_err "$_post_hook" "$vlist"
  3508. return 1
  3509. fi
  3510. _debug "sleep 2 secs to verify"
  3511. sleep 2
  3512. _debug "checking"
  3513. response="$(_get "$uri")"
  3514. if [ "$?" != "0" ]; then
  3515. _err "$d:Verify error:$response"
  3516. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3517. _clearup
  3518. _on_issue_err "$_post_hook" "$vlist"
  3519. return 1
  3520. fi
  3521. _debug2 original "$response"
  3522. response="$(echo "$response" | _normalizeJson)"
  3523. _debug2 response "$response"
  3524. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  3525. if [ "$status" = "valid" ]; then
  3526. _info "$(__green Success)"
  3527. _stopserver "$serverproc"
  3528. serverproc=""
  3529. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3530. break
  3531. fi
  3532. if [ "$status" = "invalid" ]; then
  3533. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  3534. _debug2 error "$error"
  3535. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  3536. _debug2 errordetail "$errordetail"
  3537. if [ "$errordetail" ]; then
  3538. _err "$d:Verify error:$errordetail"
  3539. else
  3540. _err "$d:Verify error:$error"
  3541. fi
  3542. if [ "$DEBUG" ]; then
  3543. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3544. _debug "Debug: get token url."
  3545. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  3546. fi
  3547. fi
  3548. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3549. _clearup
  3550. _on_issue_err "$_post_hook" "$vlist"
  3551. return 1
  3552. fi
  3553. if [ "$status" = "pending" ]; then
  3554. _info "Pending"
  3555. else
  3556. _err "$d:Verify error:$response"
  3557. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3558. _clearup
  3559. _on_issue_err "$_post_hook" "$vlist"
  3560. return 1
  3561. fi
  3562. done
  3563. done
  3564. _clearup
  3565. _info "Verify finished, start to sign."
  3566. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
  3567. if [ "$ACME_VERSION" = "2" ]; then
  3568. if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
  3569. _err "Sign failed."
  3570. _on_issue_err "$_post_hook"
  3571. return 1
  3572. fi
  3573. if [ "$code" != "200" ]; then
  3574. _err "Sign failed, code is not 200."
  3575. _err "$response"
  3576. _on_issue_err "$_post_hook"
  3577. return 1
  3578. fi
  3579. Le_LinkCert="$(echo "$response" | tr -d '\r\n' | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
  3580. if ! _get "$Le_LinkCert" >"$CERT_PATH"; then
  3581. _err "Sign failed, can not download cert:$Le_LinkCert."
  3582. _err "$response"
  3583. _on_issue_err "$_post_hook"
  3584. return 1
  3585. fi
  3586. if [ "$(grep -- "$BEGIN_CERT" "$CERT_PATH" | wc -l)" -gt "1" ]; then
  3587. _debug "Found cert chain"
  3588. cat "$CERT_PATH" >"$CERT_FULLCHAIN_PATH"
  3589. _end_n="$(grep -n -- "$END_CERT" "$CERT_FULLCHAIN_PATH" | _head_n 1 | cut -d : -f 1)"
  3590. _debug _end_n "$_end_n"
  3591. sed -n "1,${_end_n}p" "$CERT_FULLCHAIN_PATH" >"$CERT_PATH"
  3592. _end_n="$(_math $_end_n + 1)"
  3593. sed -n "${_end_n},9999p" "$CERT_FULLCHAIN_PATH" >"$CA_CERT_PATH"
  3594. fi
  3595. else
  3596. if ! _send_signed_request "${ACME_NEW_ORDER}" "{\"resource\": \"$ACME_NEW_ORDER_RES\", \"csr\": \"$der\"}" "needbase64"; then
  3597. _err "Sign failed. $response"
  3598. _on_issue_err "$_post_hook"
  3599. return 1
  3600. fi
  3601. _rcert="$response"
  3602. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3603. echo "$BEGIN_CERT" >"$CERT_PATH"
  3604. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  3605. # _debug "Get cert failed. Let's try last response."
  3606. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  3607. #fi
  3608. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  3609. _debug "Try cert link."
  3610. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  3611. fi
  3612. echo "$END_CERT" >>"$CERT_PATH"
  3613. fi
  3614. _debug "Le_LinkCert" "$Le_LinkCert"
  3615. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  3616. if [ -z "$Le_LinkCert" ] || ! _checkcert "$CERT_PATH"; then
  3617. response="$(echo "$response" | _dbase64 "multiline" | tr -d '\0' | _normalizeJson)"
  3618. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  3619. _on_issue_err "$_post_hook"
  3620. return 1
  3621. fi
  3622. if [ "$Le_LinkCert" ]; then
  3623. _info "$(__green "Cert success.")"
  3624. cat "$CERT_PATH"
  3625. _info "Your cert is in $(__green " $CERT_PATH ")"
  3626. if [ -f "$CERT_KEY_PATH" ]; then
  3627. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  3628. fi
  3629. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  3630. USER_PATH="$PATH"
  3631. _saveaccountconf "USER_PATH" "$USER_PATH"
  3632. fi
  3633. fi
  3634. _cleardomainconf "Le_Vlist"
  3635. if [ "$ACME_VERSION" = "2" ]; then
  3636. _debug "v2 chain."
  3637. else
  3638. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  3639. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  3640. if [ "$Le_LinkIssuer" ]; then
  3641. if ! _contains "$Le_LinkIssuer" ":"; then
  3642. _info "$(__red "Relative issuer link found.")"
  3643. Le_LinkIssuer="$_ACME_SERVER_HOST$Le_LinkIssuer"
  3644. fi
  3645. _debug Le_LinkIssuer "$Le_LinkIssuer"
  3646. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  3647. _link_issuer_retry=0
  3648. _MAX_ISSUER_RETRY=5
  3649. while [ "$_link_issuer_retry" -lt "$_MAX_ISSUER_RETRY" ]; do
  3650. _debug _link_issuer_retry "$_link_issuer_retry"
  3651. if [ "$ACME_VERSION" = "2" ]; then
  3652. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH"; then
  3653. break
  3654. fi
  3655. else
  3656. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH.der"; then
  3657. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  3658. _base64 "multiline" <"$CA_CERT_PATH.der" >>"$CA_CERT_PATH"
  3659. echo "$END_CERT" >>"$CA_CERT_PATH"
  3660. if ! _checkcert "$CA_CERT_PATH"; then
  3661. _err "Can not get the ca cert."
  3662. break
  3663. fi
  3664. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  3665. rm -f "$CA_CERT_PATH.der"
  3666. break
  3667. fi
  3668. fi
  3669. _link_issuer_retry=$(_math $_link_issuer_retry + 1)
  3670. _sleep "$_link_issuer_retry"
  3671. done
  3672. if [ "$_link_issuer_retry" = "$_MAX_ISSUER_RETRY" ]; then
  3673. _err "Max retry for issuer ca cert is reached."
  3674. fi
  3675. else
  3676. _debug "No Le_LinkIssuer header found."
  3677. fi
  3678. fi
  3679. [ -f "$CA_CERT_PATH" ] && _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  3680. [ -f "$CERT_FULLCHAIN_PATH" ] && _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  3681. Le_CertCreateTime=$(_time)
  3682. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  3683. Le_CertCreateTimeStr=$(date -u)
  3684. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  3685. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
  3686. Le_RenewalDays="$MAX_RENEW"
  3687. else
  3688. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  3689. fi
  3690. if [ "$CA_BUNDLE" ]; then
  3691. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  3692. else
  3693. _clearaccountconf "CA_BUNDLE"
  3694. fi
  3695. if [ "$CA_PATH" ]; then
  3696. _saveaccountconf CA_PATH "$CA_PATH"
  3697. else
  3698. _clearaccountconf "CA_PATH"
  3699. fi
  3700. if [ "$HTTPS_INSECURE" ]; then
  3701. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  3702. else
  3703. _clearaccountconf "HTTPS_INSECURE"
  3704. fi
  3705. if [ "$Le_Listen_V4" ]; then
  3706. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  3707. _cleardomainconf Le_Listen_V6
  3708. elif [ "$Le_Listen_V6" ]; then
  3709. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  3710. _cleardomainconf Le_Listen_V4
  3711. fi
  3712. if [ "$Le_ForceNewDomainKey" = "1" ]; then
  3713. _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
  3714. else
  3715. _cleardomainconf Le_ForceNewDomainKey
  3716. fi
  3717. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  3718. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  3719. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  3720. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  3721. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  3722. if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
  3723. _savedomainconf "Le_RealCertPath" "$_real_cert"
  3724. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  3725. _savedomainconf "Le_RealKeyPath" "$_real_key"
  3726. _savedomainconf "Le_ReloadCmd" "$_reload_cmd"
  3727. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  3728. if ! _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"; then
  3729. return 1
  3730. fi
  3731. fi
  3732. if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
  3733. _err "Call hook error."
  3734. return 1
  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" || return 1
  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" || return 1
  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" || return 1
  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" || return 1
  4077. else
  4078. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  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" || return 1
  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. --force-color Force output of color text. Useful for non-interactive use with the aha tool for HTML E-Mails.
  4768. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  4769. --csr Specifies the input csr.
  4770. --pre-hook Command to be run before obtaining any certificates.
  4771. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obtain/renew is success or failed.
  4772. --renew-hook Command to be run once for each successfully renewed certificate.
  4773. --deploy-hook The hook file to deploy cert
  4774. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  4775. --always-force-new-domain-key Generate new domain key when renewal. Otherwise, the domain key is not changed by default.
  4776. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  4777. --listen-v4 Force standalone/tls server to listen at ipv4.
  4778. --listen-v6 Force standalone/tls server to listen at ipv6.
  4779. --openssl-bin Specifies a custom openssl bin location.
  4780. --use-wget Force to use wget, if you have both curl and wget installed.
  4781. --yes-I-know-dns-manual-mode-enough-go-ahead-please Force to use dns manual mode: $_DNS_MANUAL_WIKI
  4782. --branch, -b Only valid for '--upgrade' command, specifies the branch name to upgrade to.
  4783. "
  4784. }
  4785. # nocron noprofile
  4786. _installOnline() {
  4787. _info "Installing from online archive."
  4788. _nocron="$1"
  4789. _noprofile="$2"
  4790. if [ ! "$BRANCH" ]; then
  4791. BRANCH="master"
  4792. fi
  4793. target="$PROJECT/archive/$BRANCH.tar.gz"
  4794. _info "Downloading $target"
  4795. localname="$BRANCH.tar.gz"
  4796. if ! _get "$target" >$localname; then
  4797. _err "Download error."
  4798. return 1
  4799. fi
  4800. (
  4801. _info "Extracting $localname"
  4802. if ! (tar xzf $localname || gtar xzf $localname); then
  4803. _err "Extraction error."
  4804. exit 1
  4805. fi
  4806. cd "$PROJECT_NAME-$BRANCH"
  4807. chmod +x $PROJECT_ENTRY
  4808. if ./$PROJECT_ENTRY install "$_nocron" "" "$_noprofile"; then
  4809. _info "Install success!"
  4810. fi
  4811. cd ..
  4812. rm -rf "$PROJECT_NAME-$BRANCH"
  4813. rm -f "$localname"
  4814. )
  4815. }
  4816. upgrade() {
  4817. if (
  4818. _initpath
  4819. export LE_WORKING_DIR
  4820. cd "$LE_WORKING_DIR"
  4821. _installOnline "nocron" "noprofile"
  4822. ); then
  4823. _info "Upgrade success!"
  4824. exit 0
  4825. else
  4826. _err "Upgrade failed!"
  4827. exit 1
  4828. fi
  4829. }
  4830. _processAccountConf() {
  4831. if [ "$_useragent" ]; then
  4832. _saveaccountconf "USER_AGENT" "$_useragent"
  4833. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  4834. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  4835. fi
  4836. if [ "$_accountemail" ]; then
  4837. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  4838. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  4839. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  4840. fi
  4841. if [ "$_openssl_bin" ]; then
  4842. _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
  4843. elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  4844. _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
  4845. fi
  4846. if [ "$_auto_upgrade" ]; then
  4847. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  4848. elif [ "$AUTO_UPGRADE" ]; then
  4849. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  4850. fi
  4851. if [ "$_use_wget" ]; then
  4852. _saveaccountconf "ACME_USE_WGET" "$_use_wget"
  4853. elif [ "$ACME_USE_WGET" ]; then
  4854. _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
  4855. fi
  4856. }
  4857. _process() {
  4858. _CMD=""
  4859. _domain=""
  4860. _altdomains="$NO_VALUE"
  4861. _webroot=""
  4862. _challenge_alias=""
  4863. _keylength=""
  4864. _accountkeylength=""
  4865. _cert_file=""
  4866. _key_file=""
  4867. _ca_file=""
  4868. _fullchain_file=""
  4869. _reloadcmd=""
  4870. _password=""
  4871. _accountconf=""
  4872. _useragent=""
  4873. _accountemail=""
  4874. _accountkey=""
  4875. _certhome=""
  4876. _confighome=""
  4877. _httpport=""
  4878. _tlsport=""
  4879. _dnssleep=""
  4880. _listraw=""
  4881. _stopRenewOnError=""
  4882. #_insecure=""
  4883. _ca_bundle=""
  4884. _ca_path=""
  4885. _nocron=""
  4886. _ecc=""
  4887. _csr=""
  4888. _pre_hook=""
  4889. _post_hook=""
  4890. _renew_hook=""
  4891. _deploy_hook=""
  4892. _logfile=""
  4893. _log=""
  4894. _local_address=""
  4895. _log_level=""
  4896. _auto_upgrade=""
  4897. _listen_v4=""
  4898. _listen_v6=""
  4899. _openssl_bin=""
  4900. _syslog=""
  4901. _use_wget=""
  4902. _server=""
  4903. while [ ${#} -gt 0 ]; do
  4904. case "${1}" in
  4905. --help | -h)
  4906. showhelp
  4907. return
  4908. ;;
  4909. --version | -v)
  4910. version
  4911. return
  4912. ;;
  4913. --install)
  4914. _CMD="install"
  4915. ;;
  4916. --uninstall)
  4917. _CMD="uninstall"
  4918. ;;
  4919. --upgrade)
  4920. _CMD="upgrade"
  4921. ;;
  4922. --issue)
  4923. _CMD="issue"
  4924. ;;
  4925. --deploy)
  4926. _CMD="deploy"
  4927. ;;
  4928. --signcsr)
  4929. _CMD="signcsr"
  4930. ;;
  4931. --showcsr)
  4932. _CMD="showcsr"
  4933. ;;
  4934. --installcert | -i | --install-cert)
  4935. _CMD="installcert"
  4936. ;;
  4937. --renew | -r)
  4938. _CMD="renew"
  4939. ;;
  4940. --renewAll | --renewall | --renew-all)
  4941. _CMD="renewAll"
  4942. ;;
  4943. --revoke)
  4944. _CMD="revoke"
  4945. ;;
  4946. --remove)
  4947. _CMD="remove"
  4948. ;;
  4949. --list)
  4950. _CMD="list"
  4951. ;;
  4952. --installcronjob | --install-cronjob)
  4953. _CMD="installcronjob"
  4954. ;;
  4955. --uninstallcronjob | --uninstall-cronjob)
  4956. _CMD="uninstallcronjob"
  4957. ;;
  4958. --cron)
  4959. _CMD="cron"
  4960. ;;
  4961. --toPkcs)
  4962. _CMD="toPkcs"
  4963. ;;
  4964. --toPkcs8)
  4965. _CMD="toPkcs8"
  4966. ;;
  4967. --createAccountKey | --createaccountkey | -cak | --create-account-key)
  4968. _CMD="createAccountKey"
  4969. ;;
  4970. --createDomainKey | --createdomainkey | -cdk | --create-domain-key)
  4971. _CMD="createDomainKey"
  4972. ;;
  4973. --createCSR | --createcsr | -ccr)
  4974. _CMD="createCSR"
  4975. ;;
  4976. --deactivate)
  4977. _CMD="deactivate"
  4978. ;;
  4979. --updateaccount | --update-account)
  4980. _CMD="updateaccount"
  4981. ;;
  4982. --registeraccount | --register-account)
  4983. _CMD="registeraccount"
  4984. ;;
  4985. --deactivate-account)
  4986. _CMD="deactivateaccount"
  4987. ;;
  4988. --domain | -d)
  4989. _dvalue="$2"
  4990. if [ "$_dvalue" ]; then
  4991. if _startswith "$_dvalue" "-"; then
  4992. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  4993. return 1
  4994. fi
  4995. if _is_idn "$_dvalue" && ! _exists idn; then
  4996. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  4997. return 1
  4998. fi
  4999. if _startswith "$_dvalue" "*."; then
  5000. _debug "Wildcard domain"
  5001. export ACME_VERSION=2
  5002. fi
  5003. if [ -z "$_domain" ]; then
  5004. _domain="$_dvalue"
  5005. else
  5006. if [ "$_altdomains" = "$NO_VALUE" ]; then
  5007. _altdomains="$_dvalue"
  5008. else
  5009. _altdomains="$_altdomains,$_dvalue"
  5010. fi
  5011. fi
  5012. fi
  5013. shift
  5014. ;;
  5015. --force | -f)
  5016. FORCE="1"
  5017. ;;
  5018. --staging | --test)
  5019. STAGE="1"
  5020. ;;
  5021. --server)
  5022. ACME_DIRECTORY="$2"
  5023. _server="$ACME_DIRECTORY"
  5024. export ACME_DIRECTORY
  5025. shift
  5026. ;;
  5027. --debug)
  5028. if [ -z "$2" ] || _startswith "$2" "-"; then
  5029. DEBUG="$DEBUG_LEVEL_DEFAULT"
  5030. else
  5031. DEBUG="$2"
  5032. shift
  5033. fi
  5034. ;;
  5035. --output-insecure)
  5036. export OUTPUT_INSECURE=1
  5037. ;;
  5038. --webroot | -w)
  5039. wvalue="$2"
  5040. if [ -z "$_webroot" ]; then
  5041. _webroot="$wvalue"
  5042. else
  5043. _webroot="$_webroot,$wvalue"
  5044. fi
  5045. shift
  5046. ;;
  5047. --challenge-alias)
  5048. cvalue="$2"
  5049. _challenge_alias="$_challenge_alias$cvalue,"
  5050. shift
  5051. ;;
  5052. --domain-alias)
  5053. cvalue="$DNS_ALIAS_PREFIX$2"
  5054. _challenge_alias="$_challenge_alias$cvalue,"
  5055. shift
  5056. ;;
  5057. --standalone)
  5058. wvalue="$NO_VALUE"
  5059. if [ -z "$_webroot" ]; then
  5060. _webroot="$wvalue"
  5061. else
  5062. _webroot="$_webroot,$wvalue"
  5063. fi
  5064. ;;
  5065. --stateless)
  5066. wvalue="$MODE_STATELESS"
  5067. if [ -z "$_webroot" ]; then
  5068. _webroot="$wvalue"
  5069. else
  5070. _webroot="$_webroot,$wvalue"
  5071. fi
  5072. ;;
  5073. --local-address)
  5074. lvalue="$2"
  5075. _local_address="$_local_address$lvalue,"
  5076. shift
  5077. ;;
  5078. --apache)
  5079. wvalue="apache"
  5080. if [ -z "$_webroot" ]; then
  5081. _webroot="$wvalue"
  5082. else
  5083. _webroot="$_webroot,$wvalue"
  5084. fi
  5085. ;;
  5086. --nginx)
  5087. wvalue="$NGINX"
  5088. if [ -z "$_webroot" ]; then
  5089. _webroot="$wvalue"
  5090. else
  5091. _webroot="$_webroot,$wvalue"
  5092. fi
  5093. ;;
  5094. --dns)
  5095. wvalue="$W_DNS"
  5096. if [ "$2" ] && ! _startswith "$2" "-"; then
  5097. wvalue="$2"
  5098. shift
  5099. fi
  5100. if [ -z "$_webroot" ]; then
  5101. _webroot="$wvalue"
  5102. else
  5103. _webroot="$_webroot,$wvalue"
  5104. fi
  5105. ;;
  5106. --dnssleep)
  5107. _dnssleep="$2"
  5108. Le_DNSSleep="$_dnssleep"
  5109. shift
  5110. ;;
  5111. --keylength | -k)
  5112. _keylength="$2"
  5113. shift
  5114. ;;
  5115. --accountkeylength | -ak)
  5116. _accountkeylength="$2"
  5117. shift
  5118. ;;
  5119. --cert-file | --certpath)
  5120. _cert_file="$2"
  5121. shift
  5122. ;;
  5123. --key-file | --keypath)
  5124. _key_file="$2"
  5125. shift
  5126. ;;
  5127. --ca-file | --capath)
  5128. _ca_file="$2"
  5129. shift
  5130. ;;
  5131. --fullchain-file | --fullchainpath)
  5132. _fullchain_file="$2"
  5133. shift
  5134. ;;
  5135. --reloadcmd | --reloadCmd)
  5136. _reloadcmd="$2"
  5137. shift
  5138. ;;
  5139. --password)
  5140. _password="$2"
  5141. shift
  5142. ;;
  5143. --accountconf)
  5144. _accountconf="$2"
  5145. ACCOUNT_CONF_PATH="$_accountconf"
  5146. shift
  5147. ;;
  5148. --home)
  5149. LE_WORKING_DIR="$2"
  5150. shift
  5151. ;;
  5152. --certhome | --cert-home)
  5153. _certhome="$2"
  5154. CERT_HOME="$_certhome"
  5155. shift
  5156. ;;
  5157. --config-home)
  5158. _confighome="$2"
  5159. LE_CONFIG_HOME="$_confighome"
  5160. shift
  5161. ;;
  5162. --useragent)
  5163. _useragent="$2"
  5164. USER_AGENT="$_useragent"
  5165. shift
  5166. ;;
  5167. --accountemail)
  5168. _accountemail="$2"
  5169. ACCOUNT_EMAIL="$_accountemail"
  5170. shift
  5171. ;;
  5172. --accountkey)
  5173. _accountkey="$2"
  5174. ACCOUNT_KEY_PATH="$_accountkey"
  5175. shift
  5176. ;;
  5177. --days)
  5178. _days="$2"
  5179. Le_RenewalDays="$_days"
  5180. shift
  5181. ;;
  5182. --httpport)
  5183. _httpport="$2"
  5184. Le_HTTPPort="$_httpport"
  5185. shift
  5186. ;;
  5187. --listraw)
  5188. _listraw="raw"
  5189. ;;
  5190. --stopRenewOnError | --stoprenewonerror | -se)
  5191. _stopRenewOnError="1"
  5192. ;;
  5193. --insecure)
  5194. #_insecure="1"
  5195. HTTPS_INSECURE="1"
  5196. ;;
  5197. --ca-bundle)
  5198. _ca_bundle="$(_readlink "$2")"
  5199. CA_BUNDLE="$_ca_bundle"
  5200. shift
  5201. ;;
  5202. --ca-path)
  5203. _ca_path="$2"
  5204. CA_PATH="$_ca_path"
  5205. shift
  5206. ;;
  5207. --nocron)
  5208. _nocron="1"
  5209. ;;
  5210. --no-color)
  5211. export ACME_NO_COLOR=1
  5212. ;;
  5213. --force-color)
  5214. export ACME_FORCE_COLOR=1
  5215. ;;
  5216. --ecc)
  5217. _ecc="isEcc"
  5218. ;;
  5219. --csr)
  5220. _csr="$2"
  5221. shift
  5222. ;;
  5223. --pre-hook)
  5224. _pre_hook="$2"
  5225. shift
  5226. ;;
  5227. --post-hook)
  5228. _post_hook="$2"
  5229. shift
  5230. ;;
  5231. --renew-hook)
  5232. _renew_hook="$2"
  5233. shift
  5234. ;;
  5235. --deploy-hook)
  5236. if [ -z "$2" ] || _startswith "$2" "-"; then
  5237. _usage "Please specify a value for '--deploy-hook'"
  5238. return 1
  5239. fi
  5240. _deploy_hook="$_deploy_hook$2,"
  5241. shift
  5242. ;;
  5243. --ocsp-must-staple | --ocsp)
  5244. Le_OCSP_Staple="1"
  5245. ;;
  5246. --always-force-new-domain-key)
  5247. if [ -z "$2" ] || _startswith "$2" "-"; then
  5248. Le_ForceNewDomainKey=1
  5249. else
  5250. Le_ForceNewDomainKey="$2"
  5251. shift
  5252. fi
  5253. ;;
  5254. --yes-I-know-dns-manual-mode-enough-go-ahead-please)
  5255. export FORCE_DNS_MANUAL=1
  5256. ;;
  5257. --log | --logfile)
  5258. _log="1"
  5259. _logfile="$2"
  5260. if _startswith "$_logfile" '-'; then
  5261. _logfile=""
  5262. else
  5263. shift
  5264. fi
  5265. LOG_FILE="$_logfile"
  5266. if [ -z "$LOG_LEVEL" ]; then
  5267. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  5268. fi
  5269. ;;
  5270. --log-level)
  5271. _log_level="$2"
  5272. LOG_LEVEL="$_log_level"
  5273. shift
  5274. ;;
  5275. --syslog)
  5276. if ! _startswith "$2" '-'; then
  5277. _syslog="$2"
  5278. shift
  5279. fi
  5280. if [ -z "$_syslog" ]; then
  5281. _syslog="$SYSLOG_LEVEL_DEFAULT"
  5282. fi
  5283. ;;
  5284. --auto-upgrade)
  5285. _auto_upgrade="$2"
  5286. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  5287. _auto_upgrade="1"
  5288. else
  5289. shift
  5290. fi
  5291. AUTO_UPGRADE="$_auto_upgrade"
  5292. ;;
  5293. --listen-v4)
  5294. _listen_v4="1"
  5295. Le_Listen_V4="$_listen_v4"
  5296. ;;
  5297. --listen-v6)
  5298. _listen_v6="1"
  5299. Le_Listen_V6="$_listen_v6"
  5300. ;;
  5301. --openssl-bin)
  5302. _openssl_bin="$2"
  5303. ACME_OPENSSL_BIN="$_openssl_bin"
  5304. shift
  5305. ;;
  5306. --use-wget)
  5307. _use_wget="1"
  5308. ACME_USE_WGET="1"
  5309. ;;
  5310. --branch | -b)
  5311. export BRANCH="$2"
  5312. shift
  5313. ;;
  5314. *)
  5315. _err "Unknown parameter : $1"
  5316. return 1
  5317. ;;
  5318. esac
  5319. shift 1
  5320. done
  5321. if [ "${_CMD}" != "install" ]; then
  5322. __initHome
  5323. if [ "$_log" ]; then
  5324. if [ -z "$_logfile" ]; then
  5325. _logfile="$DEFAULT_LOG_FILE"
  5326. fi
  5327. fi
  5328. if [ "$_logfile" ]; then
  5329. _saveaccountconf "LOG_FILE" "$_logfile"
  5330. LOG_FILE="$_logfile"
  5331. fi
  5332. if [ "$_log_level" ]; then
  5333. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5334. LOG_LEVEL="$_log_level"
  5335. fi
  5336. if [ "$_syslog" ]; then
  5337. if _exists logger; then
  5338. if [ "$_syslog" = "0" ]; then
  5339. _clearaccountconf "SYS_LOG"
  5340. else
  5341. _saveaccountconf "SYS_LOG" "$_syslog"
  5342. fi
  5343. SYS_LOG="$_syslog"
  5344. else
  5345. _err "The 'logger' command is not found, can not enable syslog."
  5346. _clearaccountconf "SYS_LOG"
  5347. SYS_LOG=""
  5348. fi
  5349. fi
  5350. _processAccountConf
  5351. fi
  5352. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  5353. if [ "$DEBUG" ]; then
  5354. version
  5355. if [ "$_server" ]; then
  5356. _debug "Using server: $_server"
  5357. fi
  5358. fi
  5359. case "${_CMD}" in
  5360. install) install "$_nocron" "$_confighome" ;;
  5361. uninstall) uninstall "$_nocron" ;;
  5362. upgrade) upgrade ;;
  5363. issue)
  5364. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  5365. ;;
  5366. deploy)
  5367. deploy "$_domain" "$_deploy_hook" "$_ecc"
  5368. ;;
  5369. signcsr)
  5370. signcsr "$_csr" "$_webroot" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  5371. ;;
  5372. showcsr)
  5373. showcsr "$_csr" "$_domain"
  5374. ;;
  5375. installcert)
  5376. installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
  5377. ;;
  5378. renew)
  5379. renew "$_domain" "$_ecc"
  5380. ;;
  5381. renewAll)
  5382. renewAll "$_stopRenewOnError"
  5383. ;;
  5384. revoke)
  5385. revoke "$_domain" "$_ecc"
  5386. ;;
  5387. remove)
  5388. remove "$_domain" "$_ecc"
  5389. ;;
  5390. deactivate)
  5391. deactivate "$_domain,$_altdomains"
  5392. ;;
  5393. registeraccount)
  5394. registeraccount "$_accountkeylength"
  5395. ;;
  5396. updateaccount)
  5397. updateaccount
  5398. ;;
  5399. deactivateaccount)
  5400. deactivateaccount
  5401. ;;
  5402. list)
  5403. list "$_listraw"
  5404. ;;
  5405. installcronjob) installcronjob "$_confighome" ;;
  5406. uninstallcronjob) uninstallcronjob ;;
  5407. cron) cron ;;
  5408. toPkcs)
  5409. toPkcs "$_domain" "$_password" "$_ecc"
  5410. ;;
  5411. toPkcs8)
  5412. toPkcs8 "$_domain" "$_ecc"
  5413. ;;
  5414. createAccountKey)
  5415. createAccountKey "$_accountkeylength"
  5416. ;;
  5417. createDomainKey)
  5418. createDomainKey "$_domain" "$_keylength"
  5419. ;;
  5420. createCSR)
  5421. createCSR "$_domain" "$_altdomains" "$_ecc"
  5422. ;;
  5423. *)
  5424. if [ "$_CMD" ]; then
  5425. _err "Invalid command: $_CMD"
  5426. fi
  5427. showhelp
  5428. return 1
  5429. ;;
  5430. esac
  5431. _ret="$?"
  5432. if [ "$_ret" != "0" ]; then
  5433. return $_ret
  5434. fi
  5435. if [ "${_CMD}" = "install" ]; then
  5436. if [ "$_log" ]; then
  5437. if [ -z "$LOG_FILE" ]; then
  5438. LOG_FILE="$DEFAULT_LOG_FILE"
  5439. fi
  5440. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  5441. fi
  5442. if [ "$_log_level" ]; then
  5443. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5444. fi
  5445. if [ "$_syslog" ]; then
  5446. if _exists logger; then
  5447. if [ "$_syslog" = "0" ]; then
  5448. _clearaccountconf "SYS_LOG"
  5449. else
  5450. _saveaccountconf "SYS_LOG" "$_syslog"
  5451. fi
  5452. else
  5453. _err "The 'logger' command is not found, can not enable syslog."
  5454. _clearaccountconf "SYS_LOG"
  5455. SYS_LOG=""
  5456. fi
  5457. fi
  5458. _processAccountConf
  5459. fi
  5460. }
  5461. if [ "$INSTALLONLINE" ]; then
  5462. INSTALLONLINE=""
  5463. _installOnline
  5464. exit
  5465. fi
  5466. main() {
  5467. [ -z "$1" ] && showhelp && return
  5468. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  5469. }
  5470. main "$@"