install.sh 35 KB

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