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.

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