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.

7092 lines
191 KiB

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