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.

7428 lines
199 KiB

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