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.

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