install.sh 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. #!/bin/bash
  2. red='\033[0;31m'
  3. green='\033[0;32m'
  4. blue='\033[0;34m'
  5. yellow='\033[0;33m'
  6. plain='\033[0m'
  7. cur_dir=$(pwd)
  8. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  9. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  10. # check root
  11. [[ $EUID -ne 0 ]] && echo -e "${red}Fatal error: ${plain} Please run this script with root privilege \n " && exit 1
  12. # Check OS and set release variable
  13. if [[ -f /etc/os-release ]]; then
  14. source /etc/os-release
  15. release=$ID
  16. elif [[ -f /usr/lib/os-release ]]; then
  17. source /usr/lib/os-release
  18. release=$ID
  19. else
  20. echo "Failed to check the system OS, please contact the author!" >&2
  21. exit 1
  22. fi
  23. echo "The OS release is: $release"
  24. arch() {
  25. case "$(uname -m)" in
  26. x86_64 | x64 | amd64) echo 'amd64' ;;
  27. i*86 | x86) echo '386' ;;
  28. armv8* | armv8 | arm64 | aarch64) echo 'arm64' ;;
  29. armv7* | armv7 | arm) echo 'armv7' ;;
  30. armv6* | armv6) echo 'armv6' ;;
  31. armv5* | armv5) echo 'armv5' ;;
  32. s390x) echo 's390x' ;;
  33. *) echo -e "${green}Unsupported CPU architecture! ${plain}" && rm -f install.sh && exit 1 ;;
  34. esac
  35. }
  36. echo "Arch: $(arch)"
  37. # Simple helpers
  38. is_ipv4() {
  39. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  40. }
  41. is_ipv6() {
  42. [[ "$1" =~ : ]] && return 0 || return 1
  43. }
  44. is_ip() {
  45. is_ipv4 "$1" || is_ipv6 "$1"
  46. }
  47. is_domain() {
  48. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+(xn--[a-z0-9]{2,}|[A-Za-z]{2,})$ ]] && return 0 || return 1
  49. }
  50. # Port helpers
  51. is_port_in_use() {
  52. local port="$1"
  53. if command -v ss >/dev/null 2>&1; then
  54. ss -ltn 2>/dev/null | awk -v p=":${port}$" '$4 ~ p {exit 0} END {exit 1}'
  55. return
  56. fi
  57. if command -v netstat >/dev/null 2>&1; then
  58. netstat -lnt 2>/dev/null | awk -v p=":${port} " '$4 ~ p {exit 0} END {exit 1}'
  59. return
  60. fi
  61. if command -v lsof >/dev/null 2>&1; then
  62. lsof -nP -iTCP:${port} -sTCP:LISTEN >/dev/null 2>&1 && return 0
  63. fi
  64. return 1
  65. }
  66. install_base() {
  67. case "${release}" in
  68. ubuntu | debian | armbian)
  69. apt-get update && apt-get install -y -q curl tar tzdata socat ca-certificates
  70. ;;
  71. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  72. dnf -y update && dnf install -y -q curl tar tzdata socat ca-certificates
  73. ;;
  74. centos)
  75. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  76. yum -y update && yum install -y curl tar tzdata socat ca-certificates
  77. else
  78. dnf -y update && dnf install -y -q curl tar tzdata socat ca-certificates
  79. fi
  80. ;;
  81. arch | manjaro | parch)
  82. pacman -Syu && pacman -Syu --noconfirm curl tar tzdata socat ca-certificates
  83. ;;
  84. opensuse-tumbleweed | opensuse-leap)
  85. zypper refresh && zypper -q install -y curl tar timezone socat ca-certificates
  86. ;;
  87. alpine)
  88. apk update && apk add curl tar tzdata socat ca-certificates
  89. ;;
  90. *)
  91. apt-get update && apt-get install -y -q curl tar tzdata socat ca-certificates
  92. ;;
  93. esac
  94. }
  95. gen_random_string() {
  96. local length="$1"
  97. local random_string=$(LC_ALL=C tr -dc 'a-zA-Z0-9' </dev/urandom | fold -w "$length" | head -n 1)
  98. echo "$random_string"
  99. }
  100. install_acme() {
  101. echo -e "${green}Installing acme.sh for SSL certificate management...${plain}"
  102. cd ~ || return 1
  103. curl -s https://get.acme.sh | sh >/dev/null 2>&1
  104. if [ $? -ne 0 ]; then
  105. echo -e "${red}Failed to install acme.sh${plain}"
  106. return 1
  107. else
  108. echo -e "${green}acme.sh installed successfully${plain}"
  109. fi
  110. return 0
  111. }
  112. setup_ssl_certificate() {
  113. local domain="$1"
  114. local server_ip="$2"
  115. local existing_port="$3"
  116. local existing_webBasePath="$4"
  117. echo -e "${green}Setting up SSL certificate...${plain}"
  118. # Check if acme.sh is installed
  119. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  120. install_acme
  121. if [ $? -ne 0 ]; then
  122. echo -e "${yellow}Failed to install acme.sh, skipping SSL setup${plain}"
  123. return 1
  124. fi
  125. fi
  126. # Create certificate directory
  127. local certPath="/root/cert/${domain}"
  128. mkdir -p "$certPath"
  129. # Issue certificate
  130. echo -e "${green}Issuing SSL certificate for ${domain}...${plain}"
  131. echo -e "${yellow}Note: Port 80 must be open and accessible from the internet${plain}"
  132. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt >/dev/null 2>&1
  133. ~/.acme.sh/acme.sh --issue -d ${domain} --listen-v6 --standalone --httpport 80 --force
  134. if [ $? -ne 0 ]; then
  135. echo -e "${yellow}Failed to issue certificate for ${domain}${plain}"
  136. echo -e "${yellow}Please ensure port 80 is open and try again later with: x-ui${plain}"
  137. rm -rf ~/.acme.sh/${domain} 2>/dev/null
  138. rm -rf "$certPath" 2>/dev/null
  139. return 1
  140. fi
  141. # Install certificate
  142. ~/.acme.sh/acme.sh --installcert -d ${domain} \
  143. --key-file /root/cert/${domain}/privkey.pem \
  144. --fullchain-file /root/cert/${domain}/fullchain.pem \
  145. --reloadcmd "systemctl restart x-ui" >/dev/null 2>&1
  146. if [ $? -ne 0 ]; then
  147. echo -e "${yellow}Failed to install certificate${plain}"
  148. return 1
  149. fi
  150. # Enable auto-renew
  151. ~/.acme.sh/acme.sh --upgrade --auto-upgrade >/dev/null 2>&1
  152. # Secure permissions: private key readable only by owner
  153. chmod 600 $certPath/privkey.pem 2>/dev/null
  154. chmod 644 $certPath/fullchain.pem 2>/dev/null
  155. # Set certificate for panel
  156. local webCertFile="/root/cert/${domain}/fullchain.pem"
  157. local webKeyFile="/root/cert/${domain}/privkey.pem"
  158. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  159. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile" >/dev/null 2>&1
  160. echo -e "${green}SSL certificate installed and configured successfully!${plain}"
  161. return 0
  162. else
  163. echo -e "${yellow}Certificate files not found${plain}"
  164. return 1
  165. fi
  166. }
  167. # Issue Let's Encrypt IP certificate with shortlived profile (~6 days validity)
  168. # Requires acme.sh and port 80 open for HTTP-01 challenge
  169. setup_ip_certificate() {
  170. local ipv4="$1"
  171. local ipv6="$2" # optional
  172. echo -e "${green}Setting up Let's Encrypt IP certificate (shortlived profile)...${plain}"
  173. echo -e "${yellow}Note: IP certificates are valid for ~6 days and will auto-renew.${plain}"
  174. echo -e "${yellow}Default listener is port 80. If you choose another port, ensure external port 80 forwards to it.${plain}"
  175. # Check for acme.sh
  176. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  177. install_acme
  178. if [ $? -ne 0 ]; then
  179. echo -e "${red}Failed to install acme.sh${plain}"
  180. return 1
  181. fi
  182. fi
  183. # Validate IP address
  184. if [[ -z "$ipv4" ]]; then
  185. echo -e "${red}IPv4 address is required${plain}"
  186. return 1
  187. fi
  188. if ! is_ipv4 "$ipv4"; then
  189. echo -e "${red}Invalid IPv4 address: $ipv4${plain}"
  190. return 1
  191. fi
  192. # Create certificate directory
  193. local certDir="/root/cert/ip"
  194. mkdir -p "$certDir"
  195. # Build domain arguments
  196. local domain_args="-d ${ipv4}"
  197. if [[ -n "$ipv6" ]] && is_ipv6 "$ipv6"; then
  198. domain_args="${domain_args} -d ${ipv6}"
  199. echo -e "${green}Including IPv6 address: ${ipv6}${plain}"
  200. fi
  201. # Set reload command for auto-renewal (add || true so it doesn't fail during first install)
  202. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null || true"
  203. # Choose port for HTTP-01 listener (default 80, prompt override)
  204. local WebPort=""
  205. read -rp "Port to use for ACME HTTP-01 listener (default 80): " WebPort
  206. WebPort="${WebPort:-80}"
  207. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  208. echo -e "${red}Invalid port provided. Falling back to 80.${plain}"
  209. WebPort=80
  210. fi
  211. echo -e "${green}Using port ${WebPort} for standalone validation.${plain}"
  212. if [[ "${WebPort}" -ne 80 ]]; then
  213. echo -e "${yellow}Reminder: Let's Encrypt still connects on port 80; forward external port 80 to ${WebPort}.${plain}"
  214. fi
  215. # Ensure chosen port is available
  216. while true; do
  217. if is_port_in_use "${WebPort}"; then
  218. echo -e "${yellow}Port ${WebPort} is in use.${plain}"
  219. local alt_port=""
  220. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  221. alt_port="${alt_port// /}"
  222. if [[ -z "${alt_port}" ]]; then
  223. echo -e "${red}Port ${WebPort} is busy; cannot proceed.${plain}"
  224. return 1
  225. fi
  226. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  227. echo -e "${red}Invalid port provided.${plain}"
  228. return 1
  229. fi
  230. WebPort="${alt_port}"
  231. continue
  232. else
  233. echo -e "${green}Port ${WebPort} is free and ready for standalone validation.${plain}"
  234. break
  235. fi
  236. done
  237. # Issue certificate with shortlived profile
  238. echo -e "${green}Issuing IP certificate for ${ipv4}...${plain}"
  239. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt >/dev/null 2>&1
  240. ~/.acme.sh/acme.sh --issue \
  241. ${domain_args} \
  242. --standalone \
  243. --server letsencrypt \
  244. --certificate-profile shortlived \
  245. --days 6 \
  246. --httpport ${WebPort} \
  247. --force
  248. if [ $? -ne 0 ]; then
  249. echo -e "${red}Failed to issue IP certificate${plain}"
  250. echo -e "${yellow}Please ensure port ${WebPort} is reachable (or forwarded from external port 80)${plain}"
  251. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  252. rm -rf ~/.acme.sh/${ipv4} 2>/dev/null
  253. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} 2>/dev/null
  254. rm -rf ${certDir} 2>/dev/null
  255. return 1
  256. fi
  257. echo -e "${green}Certificate issued successfully, installing...${plain}"
  258. # Install certificate
  259. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  260. # but the cert files are still installed. We check for files instead of exit code.
  261. ~/.acme.sh/acme.sh --installcert -d ${ipv4} \
  262. --key-file "${certDir}/privkey.pem" \
  263. --fullchain-file "${certDir}/fullchain.pem" \
  264. --reloadcmd "${reloadCmd}" 2>&1 || true
  265. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  266. if [[ ! -f "${certDir}/fullchain.pem" || ! -f "${certDir}/privkey.pem" ]]; then
  267. echo -e "${red}Certificate files not found after installation${plain}"
  268. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  269. rm -rf ~/.acme.sh/${ipv4} 2>/dev/null
  270. [[ -n "$ipv6" ]] && rm -rf ~/.acme.sh/${ipv6} 2>/dev/null
  271. rm -rf ${certDir} 2>/dev/null
  272. return 1
  273. fi
  274. echo -e "${green}Certificate files installed successfully${plain}"
  275. # Enable auto-upgrade for acme.sh (ensures cron job runs)
  276. ~/.acme.sh/acme.sh --upgrade --auto-upgrade >/dev/null 2>&1
  277. # Secure permissions: private key readable only by owner
  278. chmod 600 ${certDir}/privkey.pem 2>/dev/null
  279. chmod 644 ${certDir}/fullchain.pem 2>/dev/null
  280. # Configure panel to use the certificate
  281. echo -e "${green}Setting certificate paths for the panel...${plain}"
  282. ${xui_folder}/x-ui cert -webCert "${certDir}/fullchain.pem" -webCertKey "${certDir}/privkey.pem"
  283. if [ $? -ne 0 ]; then
  284. echo -e "${yellow}Warning: Could not set certificate paths automatically${plain}"
  285. echo -e "${yellow}Certificate files are at:${plain}"
  286. echo -e " Cert: ${certDir}/fullchain.pem"
  287. echo -e " Key: ${certDir}/privkey.pem"
  288. else
  289. echo -e "${green}Certificate paths configured successfully${plain}"
  290. fi
  291. echo -e "${green}IP certificate installed and configured successfully!${plain}"
  292. echo -e "${green}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  293. echo -e "${yellow}acme.sh will automatically renew and reload x-ui before expiry.${plain}"
  294. return 0
  295. }
  296. # Comprehensive manual SSL certificate issuance via acme.sh
  297. ssl_cert_issue() {
  298. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep 'webBasePath:' | awk -F': ' '{print $2}' | tr -d '[:space:]' | sed 's#^/##')
  299. local existing_port=$(${xui_folder}/x-ui setting -show true | grep 'port:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  300. # check for acme.sh first
  301. if ! command -v ~/.acme.sh/acme.sh &>/dev/null; then
  302. echo "acme.sh could not be found. Installing now..."
  303. cd ~ || return 1
  304. curl -s https://get.acme.sh | sh
  305. if [ $? -ne 0 ]; then
  306. echo -e "${red}Failed to install acme.sh${plain}"
  307. return 1
  308. else
  309. echo -e "${green}acme.sh installed successfully${plain}"
  310. fi
  311. fi
  312. # get the domain here, and we need to verify it
  313. local domain=""
  314. while true; do
  315. read -rp "Please enter your domain name: " domain
  316. domain="${domain// /}" # Trim whitespace
  317. if [[ -z "$domain" ]]; then
  318. echo -e "${red}Domain name cannot be empty. Please try again.${plain}"
  319. continue
  320. fi
  321. if ! is_domain "$domain"; then
  322. echo -e "${red}Invalid domain format: ${domain}. Please enter a valid domain name.${plain}"
  323. continue
  324. fi
  325. break
  326. done
  327. echo -e "${green}Your domain is: ${domain}, checking it...${plain}"
  328. # check if there already exists a certificate
  329. local currentCert=$(~/.acme.sh/acme.sh --list | tail -1 | awk '{print $1}')
  330. if [ "${currentCert}" == "${domain}" ]; then
  331. local certInfo=$(~/.acme.sh/acme.sh --list)
  332. echo -e "${red}System already has certificates for this domain. Cannot issue again.${plain}"
  333. echo -e "${yellow}Current certificate details:${plain}"
  334. echo "$certInfo"
  335. return 1
  336. else
  337. echo -e "${green}Your domain is ready for issuing certificates now...${plain}"
  338. fi
  339. # create a directory for the certificate
  340. certPath="/root/cert/${domain}"
  341. if [ ! -d "$certPath" ]; then
  342. mkdir -p "$certPath"
  343. else
  344. rm -rf "$certPath"
  345. mkdir -p "$certPath"
  346. fi
  347. # get the port number for the standalone server
  348. local WebPort=80
  349. read -rp "Please choose which port to use (default is 80): " WebPort
  350. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  351. echo -e "${yellow}Your input ${WebPort} is invalid, will use default port 80.${plain}"
  352. WebPort=80
  353. fi
  354. echo -e "${green}Will use port: ${WebPort} to issue certificates. Please make sure this port is open.${plain}"
  355. # Stop panel temporarily
  356. echo -e "${yellow}Stopping panel temporarily...${plain}"
  357. systemctl stop x-ui 2>/dev/null || rc-service x-ui stop 2>/dev/null
  358. # issue the certificate
  359. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt
  360. ~/.acme.sh/acme.sh --issue -d ${domain} --listen-v6 --standalone --httpport ${WebPort} --force
  361. if [ $? -ne 0 ]; then
  362. echo -e "${red}Issuing certificate failed, please check logs.${plain}"
  363. rm -rf ~/.acme.sh/${domain}
  364. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  365. return 1
  366. else
  367. echo -e "${green}Issuing certificate succeeded, installing certificates...${plain}"
  368. fi
  369. # Setup reload command
  370. reloadCmd="systemctl restart x-ui || rc-service x-ui restart"
  371. echo -e "${green}Default --reloadcmd for ACME is: ${yellow}systemctl restart x-ui || rc-service x-ui restart${plain}"
  372. echo -e "${green}This command will run on every certificate issue and renew.${plain}"
  373. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  374. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  375. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; systemctl restart x-ui"
  376. echo -e "${green}\t2.${plain} Input your own command"
  377. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  378. read -rp "Choose an option: " choice
  379. case "$choice" in
  380. 1)
  381. echo -e "${green}Reloadcmd is: systemctl reload nginx ; systemctl restart x-ui${plain}"
  382. reloadCmd="systemctl reload nginx ; systemctl restart x-ui"
  383. ;;
  384. 2)
  385. echo -e "${yellow}It's recommended to put x-ui restart at the end${plain}"
  386. read -rp "Please enter your custom reloadcmd: " reloadCmd
  387. echo -e "${green}Reloadcmd is: ${reloadCmd}${plain}"
  388. ;;
  389. *)
  390. echo -e "${green}Keeping default reloadcmd${plain}"
  391. ;;
  392. esac
  393. fi
  394. # install the certificate
  395. ~/.acme.sh/acme.sh --installcert -d ${domain} \
  396. --key-file /root/cert/${domain}/privkey.pem \
  397. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}"
  398. if [ $? -ne 0 ]; then
  399. echo -e "${red}Installing certificate failed, exiting.${plain}"
  400. rm -rf ~/.acme.sh/${domain}
  401. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  402. return 1
  403. else
  404. echo -e "${green}Installing certificate succeeded, enabling auto renew...${plain}"
  405. fi
  406. # enable auto-renew
  407. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  408. if [ $? -ne 0 ]; then
  409. echo -e "${yellow}Auto renew setup had issues, certificate details:${plain}"
  410. ls -lah /root/cert/${domain}/
  411. # Secure permissions: private key readable only by owner
  412. chmod 600 $certPath/privkey.pem 2>/dev/null
  413. chmod 644 $certPath/fullchain.pem 2>/dev/null
  414. else
  415. echo -e "${green}Auto renew succeeded, certificate details:${plain}"
  416. ls -lah /root/cert/${domain}/
  417. # Secure permissions: private key readable only by owner
  418. chmod 600 $certPath/privkey.pem 2>/dev/null
  419. chmod 644 $certPath/fullchain.pem 2>/dev/null
  420. fi
  421. # start panel
  422. systemctl start x-ui 2>/dev/null || rc-service x-ui start 2>/dev/null
  423. # Prompt user to set panel paths after successful certificate installation
  424. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  425. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  426. local webCertFile="/root/cert/${domain}/fullchain.pem"
  427. local webKeyFile="/root/cert/${domain}/privkey.pem"
  428. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  429. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  430. echo -e "${green}Certificate paths set for the panel${plain}"
  431. echo -e "${green}Certificate File: $webCertFile${plain}"
  432. echo -e "${green}Private Key File: $webKeyFile${plain}"
  433. echo ""
  434. echo -e "${green}Access URL: https://${domain}:${existing_port}/${existing_webBasePath}${plain}"
  435. echo -e "${yellow}Panel will restart to apply SSL certificate...${plain}"
  436. systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null
  437. else
  438. echo -e "${red}Error: Certificate or private key file not found for domain: $domain.${plain}"
  439. fi
  440. else
  441. echo -e "${yellow}Skipping panel path setting.${plain}"
  442. fi
  443. return 0
  444. }
  445. # Reusable interactive SSL setup (domain or IP)
  446. # Sets global `SSL_HOST` to the chosen domain/IP for Access URL usage
  447. prompt_and_setup_ssl() {
  448. local panel_port="$1"
  449. local web_base_path="$2" # expected without leading slash
  450. local server_ip="$3"
  451. local ssl_choice=""
  452. echo -e "${yellow}Choose SSL certificate setup method:${plain}"
  453. echo -e "${green}1.${plain} Let's Encrypt for Domain (90-day validity, auto-renews)"
  454. echo -e "${green}2.${plain} Let's Encrypt for IP Address (6-day validity, auto-renews)"
  455. echo -e "${green}3.${plain} Custom SSL Certificate (Path to existing files)"
  456. echo -e "${blue}Note:${plain} Options 1 & 2 require port 80 open. Option 3 requires manual paths."
  457. read -rp "Choose an option (default 2 for IP): " ssl_choice
  458. ssl_choice="${ssl_choice// /}" # Trim whitespace
  459. # Default to 2 (IP cert) if input is empty or invalid (not 1 or 3)
  460. if [[ "$ssl_choice" != "1" && "$ssl_choice" != "3" ]]; then
  461. ssl_choice="2"
  462. fi
  463. case "$ssl_choice" in
  464. 1)
  465. # User chose Let's Encrypt domain option
  466. echo -e "${green}Using Let's Encrypt for domain certificate...${plain}"
  467. ssl_cert_issue
  468. # Extract the domain that was used from the certificate
  469. local cert_domain=$(~/.acme.sh/acme.sh --list 2>/dev/null | tail -1 | awk '{print $1}')
  470. if [[ -n "${cert_domain}" ]]; then
  471. SSL_HOST="${cert_domain}"
  472. echo -e "${green}✓ SSL certificate configured successfully with domain: ${cert_domain}${plain}"
  473. else
  474. echo -e "${yellow}SSL setup may have completed, but domain extraction failed${plain}"
  475. SSL_HOST="${server_ip}"
  476. fi
  477. ;;
  478. 2)
  479. # User chose Let's Encrypt IP certificate option
  480. echo -e "${green}Using Let's Encrypt for IP certificate (shortlived profile)...${plain}"
  481. # Ask for optional IPv6
  482. local ipv6_addr=""
  483. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  484. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  485. # Stop panel if running (port 80 needed)
  486. if [[ $release == "alpine" ]]; then
  487. rc-service x-ui stop >/dev/null 2>&1
  488. else
  489. systemctl stop x-ui >/dev/null 2>&1
  490. fi
  491. setup_ip_certificate "${server_ip}" "${ipv6_addr}"
  492. if [ $? -eq 0 ]; then
  493. SSL_HOST="${server_ip}"
  494. echo -e "${green}✓ Let's Encrypt IP certificate configured successfully${plain}"
  495. else
  496. echo -e "${red}✗ IP certificate setup failed. Please check port 80 is open.${plain}"
  497. SSL_HOST="${server_ip}"
  498. fi
  499. ;;
  500. 3)
  501. # User chose Custom Paths (User Provided) option
  502. echo -e "${green}Using custom existing certificate...${plain}"
  503. local custom_cert=""
  504. local custom_key=""
  505. local custom_domain=""
  506. # 3.1 Request Domain to compose Panel URL later
  507. read -rp "Please enter domain name certificate issued for: " custom_domain
  508. custom_domain="${custom_domain// /}" # Убираем пробелы
  509. # 3.2 Loop for Certificate Path
  510. while true; do
  511. read -rp "Input certificate path (keywords: .crt / fullchain): " custom_cert
  512. # Strip quotes if present
  513. custom_cert=$(echo "$custom_cert" | tr -d '"' | tr -d "'")
  514. if [[ -f "$custom_cert" && -r "$custom_cert" && -s "$custom_cert" ]]; then
  515. break
  516. elif [[ ! -f "$custom_cert" ]]; then
  517. echo -e "${red}Error: File does not exist! Try again.${plain}"
  518. elif [[ ! -r "$custom_cert" ]]; then
  519. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  520. else
  521. echo -e "${red}Error: File is empty!${plain}"
  522. fi
  523. done
  524. # 3.3 Loop for Private Key Path
  525. while true; do
  526. read -rp "Input private key path (keywords: .key / privatekey): " custom_key
  527. # Strip quotes if present
  528. custom_key=$(echo "$custom_key" | tr -d '"' | tr -d "'")
  529. if [[ -f "$custom_key" && -r "$custom_key" && -s "$custom_key" ]]; then
  530. break
  531. elif [[ ! -f "$custom_key" ]]; then
  532. echo -e "${red}Error: File does not exist! Try again.${plain}"
  533. elif [[ ! -r "$custom_key" ]]; then
  534. echo -e "${red}Error: File exists but is not readable (check permissions)!${plain}"
  535. else
  536. echo -e "${red}Error: File is empty!${plain}"
  537. fi
  538. done
  539. # 3.4 Apply Settings via x-ui binary
  540. ${xui_folder}/x-ui cert -webCert "$custom_cert" -webCertKey "$custom_key" >/dev/null 2>&1
  541. # Set SSL_HOST for composing Panel URL
  542. if [[ -n "$custom_domain" ]]; then
  543. SSL_HOST="$custom_domain"
  544. else
  545. SSL_HOST="${server_ip}"
  546. fi
  547. echo -e "${green}✓ Custom certificate paths applied.${plain}"
  548. echo -e "${yellow}Note: You are responsible for renewing these files externally.${plain}"
  549. systemctl restart x-ui >/dev/null 2>&1 || rc-service x-ui restart >/dev/null 2>&1
  550. ;;
  551. *)
  552. echo -e "${red}Invalid option. Skipping SSL setup.${plain}"
  553. SSL_HOST="${server_ip}"
  554. ;;
  555. esac
  556. }
  557. config_after_install() {
  558. local existing_hasDefaultCredential=$(${xui_folder}/x-ui setting -show true | grep -Eo 'hasDefaultCredential: .+' | awk '{print $2}')
  559. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}' | sed 's#^/##')
  560. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  561. # Properly detect empty cert by checking if cert: line exists and has content after it
  562. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  563. local URL_lists=(
  564. "https://api4.ipify.org"
  565. "https://ipv4.icanhazip.com"
  566. "https://v4.api.ipinfo.io/ip"
  567. "https://ipv4.myexternalip.com/raw"
  568. "https://4.ident.me"
  569. "https://check-host.net/ip"
  570. )
  571. local server_ip=""
  572. for ip_address in "${URL_lists[@]}"; do
  573. server_ip=$(curl -s --max-time 3 "${ip_address}" 2>/dev/null | tr -d '[:space:]')
  574. if [[ -n "${server_ip}" ]]; then
  575. break
  576. fi
  577. done
  578. if [[ ${#existing_webBasePath} -lt 4 ]]; then
  579. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  580. local config_webBasePath=$(gen_random_string 18)
  581. local config_username=$(gen_random_string 10)
  582. local config_password=$(gen_random_string 10)
  583. read -rp "Would you like to customize the Panel Port settings? (If not, a random port will be applied) [y/n]: " config_confirm
  584. if [[ "${config_confirm}" == "y" || "${config_confirm}" == "Y" ]]; then
  585. read -rp "Please set up the panel port: " config_port
  586. echo -e "${yellow}Your Panel Port is: ${config_port}${plain}"
  587. else
  588. local config_port=$(shuf -i 1024-62000 -n 1)
  589. echo -e "${yellow}Generated random port: ${config_port}${plain}"
  590. fi
  591. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}" -port "${config_port}" -webBasePath "${config_webBasePath}"
  592. echo ""
  593. echo -e "${green}═══════════════════════════════════════════${plain}"
  594. echo -e "${green} SSL Certificate Setup (MANDATORY) ${plain}"
  595. echo -e "${green}═══════════════════════════════════════════${plain}"
  596. echo -e "${yellow}For security, SSL certificate is required for all panels.${plain}"
  597. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  598. echo ""
  599. prompt_and_setup_ssl "${config_port}" "${config_webBasePath}" "${server_ip}"
  600. # Display final credentials and access information
  601. echo ""
  602. echo -e "${green}═══════════════════════════════════════════${plain}"
  603. echo -e "${green} Panel Installation Complete! ${plain}"
  604. echo -e "${green}═══════════════════════════════════════════${plain}"
  605. echo -e "${green}Username: ${config_username}${plain}"
  606. echo -e "${green}Password: ${config_password}${plain}"
  607. echo -e "${green}Port: ${config_port}${plain}"
  608. echo -e "${green}WebBasePath: ${config_webBasePath}${plain}"
  609. echo -e "${green}Access URL: https://${SSL_HOST}:${config_port}/${config_webBasePath}${plain}"
  610. echo -e "${green}═══════════════════════════════════════════${plain}"
  611. echo -e "${yellow}⚠ IMPORTANT: Save these credentials securely!${plain}"
  612. echo -e "${yellow}⚠ SSL Certificate: Enabled and configured${plain}"
  613. else
  614. local config_webBasePath=$(gen_random_string 18)
  615. echo -e "${yellow}WebBasePath is missing or too short. Generating a new one...${plain}"
  616. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}"
  617. echo -e "${green}New WebBasePath: ${config_webBasePath}${plain}"
  618. # If the panel is already installed but no certificate is configured, prompt for SSL now
  619. if [[ -z "${existing_cert}" ]]; then
  620. echo ""
  621. echo -e "${green}═══════════════════════════════════════════${plain}"
  622. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  623. echo -e "${green}═══════════════════════════════════════════${plain}"
  624. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  625. echo ""
  626. prompt_and_setup_ssl "${existing_port}" "${config_webBasePath}" "${server_ip}"
  627. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${config_webBasePath}${plain}"
  628. else
  629. # If a cert already exists, just show the access URL
  630. echo -e "${green}Access URL: https://${server_ip}:${existing_port}/${config_webBasePath}${plain}"
  631. fi
  632. fi
  633. else
  634. if [[ "$existing_hasDefaultCredential" == "true" ]]; then
  635. local config_username=$(gen_random_string 10)
  636. local config_password=$(gen_random_string 10)
  637. echo -e "${yellow}Default credentials detected. Security update required...${plain}"
  638. ${xui_folder}/x-ui setting -username "${config_username}" -password "${config_password}"
  639. echo -e "Generated new random login credentials:"
  640. echo -e "###############################################"
  641. echo -e "${green}Username: ${config_username}${plain}"
  642. echo -e "${green}Password: ${config_password}${plain}"
  643. echo -e "###############################################"
  644. else
  645. echo -e "${green}Username, Password, and WebBasePath are properly set.${plain}"
  646. fi
  647. # Existing install: if no cert configured, prompt user for SSL setup
  648. # Properly detect empty cert by checking if cert: line exists and has content after it
  649. existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  650. if [[ -z "$existing_cert" ]]; then
  651. echo ""
  652. echo -e "${green}═══════════════════════════════════════════${plain}"
  653. echo -e "${green} SSL Certificate Setup (RECOMMENDED) ${plain}"
  654. echo -e "${green}═══════════════════════════════════════════${plain}"
  655. echo -e "${yellow}Let's Encrypt now supports both domains and IP addresses!${plain}"
  656. echo ""
  657. prompt_and_setup_ssl "${existing_port}" "${existing_webBasePath}" "${server_ip}"
  658. echo -e "${green}Access URL: https://${SSL_HOST}:${existing_port}/${existing_webBasePath}${plain}"
  659. else
  660. echo -e "${green}SSL certificate already configured. No action needed.${plain}"
  661. fi
  662. fi
  663. ${xui_folder}/x-ui migrate
  664. }
  665. install_x-ui() {
  666. cd ${xui_folder%/x-ui}/
  667. # Download resources
  668. if [ $# == 0 ]; then
  669. tag_version=$(curl -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  670. if [[ ! -n "$tag_version" ]]; then
  671. echo -e "${yellow}Trying to fetch version with IPv4...${plain}"
  672. tag_version=$(curl -4 -Ls "https://api.github.com/repos/MHSanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
  673. if [[ ! -n "$tag_version" ]]; then
  674. echo -e "${red}Failed to fetch x-ui version, it may be due to GitHub API restrictions, please try it later${plain}"
  675. exit 1
  676. fi
  677. fi
  678. echo -e "Got x-ui latest version: ${tag_version}, beginning the installation..."
  679. curl -4fLRo ${xui_folder}-linux-$(arch).tar.gz https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz
  680. if [[ $? -ne 0 ]]; then
  681. echo -e "${red}Downloading x-ui failed, please be sure that your server can access GitHub ${plain}"
  682. exit 1
  683. fi
  684. else
  685. tag_version=$1
  686. tag_version_numeric=${tag_version#v}
  687. min_version="2.3.5"
  688. if [[ "$(printf '%s\n' "$min_version" "$tag_version_numeric" | sort -V | head -n1)" != "$min_version" ]]; then
  689. echo -e "${red}Please use a newer version (at least v2.3.5). Exiting installation.${plain}"
  690. exit 1
  691. fi
  692. url="https://github.com/MHSanaei/3x-ui/releases/download/${tag_version}/x-ui-linux-$(arch).tar.gz"
  693. echo -e "Beginning to install x-ui $1"
  694. curl -4fLRo ${xui_folder}-linux-$(arch).tar.gz ${url}
  695. if [[ $? -ne 0 ]]; then
  696. echo -e "${red}Download x-ui $1 failed, please check if the version exists ${plain}"
  697. exit 1
  698. fi
  699. fi
  700. curl -4fLRo /usr/bin/x-ui-temp https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
  701. if [[ $? -ne 0 ]]; then
  702. echo -e "${red}Failed to download x-ui.sh${plain}"
  703. exit 1
  704. fi
  705. # Stop x-ui service and remove old resources
  706. if [[ -e ${xui_folder}/ ]]; then
  707. if [[ $release == "alpine" ]]; then
  708. rc-service x-ui stop
  709. else
  710. systemctl stop x-ui
  711. fi
  712. rm ${xui_folder}/ -rf
  713. fi
  714. # Extract resources and set permissions
  715. tar zxvf x-ui-linux-$(arch).tar.gz
  716. rm x-ui-linux-$(arch).tar.gz -f
  717. cd x-ui
  718. chmod +x x-ui
  719. chmod +x x-ui.sh
  720. # Check the system's architecture and rename the file accordingly
  721. if [[ $(arch) == "armv5" || $(arch) == "armv6" || $(arch) == "armv7" ]]; then
  722. mv bin/xray-linux-$(arch) bin/xray-linux-arm
  723. chmod +x bin/xray-linux-arm
  724. fi
  725. chmod +x x-ui bin/xray-linux-$(arch)
  726. # Update x-ui cli and se set permission
  727. mv -f /usr/bin/x-ui-temp /usr/bin/x-ui
  728. chmod +x /usr/bin/x-ui
  729. mkdir -p /var/log/x-ui
  730. config_after_install
  731. # Etckeeper compatibility
  732. if [ -d "/etc/.git" ]; then
  733. if [ -f "/etc/.gitignore" ]; then
  734. if ! grep -q "x-ui/x-ui.db" "/etc/.gitignore"; then
  735. echo "" >> "/etc/.gitignore"
  736. echo "x-ui/x-ui.db" >> "/etc/.gitignore"
  737. echo -e "${green}Added x-ui.db to /etc/.gitignore for etckeeper${plain}"
  738. fi
  739. else
  740. echo "x-ui/x-ui.db" > "/etc/.gitignore"
  741. echo -e "${green}Created /etc/.gitignore and added x-ui.db for etckeeper${plain}"
  742. fi
  743. fi
  744. if [[ $release == "alpine" ]]; then
  745. curl -4fLRo /etc/init.d/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.rc
  746. if [[ $? -ne 0 ]]; then
  747. echo -e "${red}Failed to download x-ui.rc${plain}"
  748. exit 1
  749. fi
  750. chmod +x /etc/init.d/x-ui
  751. rc-update add x-ui
  752. rc-service x-ui start
  753. else
  754. # Install systemd service file
  755. service_installed=false
  756. if [ -f "x-ui.service" ]; then
  757. echo -e "${green}Found x-ui.service in extracted files, installing...${plain}"
  758. cp -f x-ui.service ${xui_service}/ >/dev/null 2>&1
  759. if [[ $? -eq 0 ]]; then
  760. service_installed=true
  761. fi
  762. fi
  763. if [ "$service_installed" = false ]; then
  764. case "${release}" in
  765. ubuntu | debian | armbian)
  766. if [ -f "x-ui.service.debian" ]; then
  767. echo -e "${green}Found x-ui.service.debian in extracted files, installing...${plain}"
  768. cp -f x-ui.service.debian ${xui_service}/x-ui.service >/dev/null 2>&1
  769. if [[ $? -eq 0 ]]; then
  770. service_installed=true
  771. fi
  772. fi
  773. ;;
  774. arch | manjaro | parch)
  775. if [ -f "x-ui.service.arch" ]; then
  776. echo -e "${green}Found x-ui.service.arch in extracted files, installing...${plain}"
  777. cp -f x-ui.service.arch ${xui_service}/x-ui.service >/dev/null 2>&1
  778. if [[ $? -eq 0 ]]; then
  779. service_installed=true
  780. fi
  781. fi
  782. ;;
  783. *)
  784. if [ -f "x-ui.service.rhel" ]; then
  785. echo -e "${green}Found x-ui.service.rhel in extracted files, installing...${plain}"
  786. cp -f x-ui.service.rhel ${xui_service}/x-ui.service >/dev/null 2>&1
  787. if [[ $? -eq 0 ]]; then
  788. service_installed=true
  789. fi
  790. fi
  791. ;;
  792. esac
  793. fi
  794. # If service file not found in tar.gz, download from GitHub
  795. if [ "$service_installed" = false ]; then
  796. echo -e "${yellow}Service files not found in tar.gz, downloading from GitHub...${plain}"
  797. case "${release}" in
  798. ubuntu | debian | armbian)
  799. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.debian >/dev/null 2>&1
  800. ;;
  801. arch | manjaro | parch)
  802. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.arch >/dev/null 2>&1
  803. ;;
  804. *)
  805. curl -4fLRo ${xui_service}/x-ui.service https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.service.rhel >/dev/null 2>&1
  806. ;;
  807. esac
  808. if [[ $? -ne 0 ]]; then
  809. echo -e "${red}Failed to install x-ui.service from GitHub${plain}"
  810. exit 1
  811. fi
  812. service_installed=true
  813. fi
  814. if [ "$service_installed" = true ]; then
  815. echo -e "${green}Setting up systemd unit...${plain}"
  816. chown root:root ${xui_service}/x-ui.service >/dev/null 2>&1
  817. chmod 644 ${xui_service}/x-ui.service >/dev/null 2>&1
  818. systemctl daemon-reload
  819. systemctl enable x-ui
  820. systemctl start x-ui
  821. else
  822. echo -e "${red}Failed to install x-ui.service file${plain}"
  823. exit 1
  824. fi
  825. fi
  826. echo -e "${green}x-ui ${tag_version}${plain} installation finished, it is running now..."
  827. echo -e ""
  828. echo -e "┌───────────────────────────────────────────────────────┐
  829. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  830. │ │
  831. │ ${blue}x-ui${plain} - Admin Management Script │
  832. │ ${blue}x-ui start${plain} - Start │
  833. │ ${blue}x-ui stop${plain} - Stop │
  834. │ ${blue}x-ui restart${plain} - Restart │
  835. │ ${blue}x-ui status${plain} - Current Status │
  836. │ ${blue}x-ui settings${plain} - Current Settings │
  837. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  838. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  839. │ ${blue}x-ui log${plain} - Check logs │
  840. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  841. │ ${blue}x-ui update${plain} - Update │
  842. │ ${blue}x-ui legacy${plain} - Legacy version │
  843. │ ${blue}x-ui install${plain} - Install │
  844. │ ${blue}x-ui uninstall${plain} - Uninstall │
  845. └───────────────────────────────────────────────────────┘"
  846. }
  847. echo -e "${green}Running...${plain}"
  848. install_base
  849. install_x-ui $1