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.

7497 lines
201 KiB

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