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.

7847 lines
211 KiB

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