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.

6091 lines
158 KiB

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