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.

8053 lines
221 KiB

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