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.

7952 lines
216 KiB

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