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.

7661 lines
205 KiB

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