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.

8023 lines
218 KiB

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