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.

6244 lines
164 KiB

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