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.

7850 lines
211 KiB

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