x-ui.sh 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489
  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. #Add some basic function here
  8. function LOGD() {
  9. echo -e "${yellow}[DEG] $* ${plain}"
  10. }
  11. function LOGE() {
  12. echo -e "${red}[ERR] $* ${plain}"
  13. }
  14. function LOGI() {
  15. echo -e "${green}[INF] $* ${plain}"
  16. }
  17. # Port helpers: detect listener and owning process (best effort)
  18. is_port_in_use() {
  19. local port="$1"
  20. if command -v ss > /dev/null 2>&1; then
  21. ss -ltn 2> /dev/null | awk -v p=":${port}$" '$4 ~ p {exit 0} END {exit 1}'
  22. return
  23. fi
  24. if command -v netstat > /dev/null 2>&1; then
  25. netstat -lnt 2> /dev/null | awk -v p=":${port} " '$4 ~ p {exit 0} END {exit 1}'
  26. return
  27. fi
  28. if command -v lsof > /dev/null 2>&1; then
  29. lsof -nP -iTCP:${port} -sTCP:LISTEN > /dev/null 2>&1 && return 0
  30. fi
  31. return 1
  32. }
  33. # Simple helpers for domain/IP validation
  34. is_ipv4() {
  35. [[ "$1" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && return 0 || return 1
  36. }
  37. is_ipv6() {
  38. [[ "$1" =~ : ]] && return 0 || return 1
  39. }
  40. is_ip() {
  41. is_ipv4 "$1" || is_ipv6 "$1"
  42. }
  43. is_domain() {
  44. [[ "$1" =~ ^([A-Za-z0-9](-*[A-Za-z0-9])*\.)+(xn--[a-z0-9]{2,}|[A-Za-z]{2,})$ ]] && return 0 || return 1
  45. }
  46. # check root
  47. [[ $EUID -ne 0 ]] && LOGE "ERROR: You must be root to run this script! \n" && exit 1
  48. # Check OS and set release variable
  49. if [[ -f /etc/os-release ]]; then
  50. source /etc/os-release
  51. release=$ID
  52. elif [[ -f /usr/lib/os-release ]]; then
  53. source /usr/lib/os-release
  54. release=$ID
  55. else
  56. echo "Failed to check the system OS, please contact the author!" >&2
  57. exit 1
  58. fi
  59. echo "The OS release is: $release"
  60. os_version=""
  61. os_version=$(grep "^VERSION_ID" /etc/os-release | cut -d '=' -f2 | tr -d '"' | tr -d '.')
  62. # Declare Variables
  63. xui_folder="${XUI_MAIN_FOLDER:=/usr/local/x-ui}"
  64. xui_service="${XUI_SERVICE:=/etc/systemd/system}"
  65. log_folder="${XUI_LOG_FOLDER:=/var/log/x-ui}"
  66. mkdir -p "${log_folder}"
  67. iplimit_log_path="${log_folder}/3xipl.log"
  68. iplimit_banned_log_path="${log_folder}/3xipl-banned.log"
  69. confirm() {
  70. if [[ $# > 1 ]]; then
  71. echo && read -rp "$1 [Default $2]: " temp
  72. if [[ "${temp}" == "" ]]; then
  73. temp=$2
  74. fi
  75. else
  76. read -rp "$1 [y/n]: " temp
  77. fi
  78. if [[ "${temp}" == "y" || "${temp}" == "Y" ]]; then
  79. return 0
  80. else
  81. return 1
  82. fi
  83. }
  84. confirm_restart() {
  85. confirm "Restart the panel, Attention: Restarting the panel will also restart xray" "y"
  86. if [[ $? == 0 ]]; then
  87. restart
  88. else
  89. show_menu
  90. fi
  91. }
  92. before_show_menu() {
  93. echo && echo -n -e "${yellow}Press enter to return to the main menu: ${plain}" && read -r temp
  94. show_menu
  95. }
  96. install() {
  97. bash <(curl -Ls https://raw.githubusercontent.com/MHSanaei/3x-ui/main/install.sh)
  98. if [[ $? == 0 ]]; then
  99. if [[ $# == 0 ]]; then
  100. start
  101. else
  102. start 0
  103. fi
  104. fi
  105. }
  106. update() {
  107. confirm "This function will update all x-ui components to the latest version, and the data will not be lost. Do you want to continue?" "y"
  108. if [[ $? != 0 ]]; then
  109. LOGE "Cancelled"
  110. if [[ $# == 0 ]]; then
  111. before_show_menu
  112. fi
  113. return 0
  114. fi
  115. bash <(curl -Ls https://raw.githubusercontent.com/MHSanaei/3x-ui/main/update.sh)
  116. if [[ $? == 0 ]]; then
  117. LOGI "Update is complete, Panel has automatically restarted "
  118. before_show_menu
  119. fi
  120. }
  121. update_menu() {
  122. echo -e "${yellow}Updating Menu${plain}"
  123. confirm "This function will update the menu to the latest changes." "y"
  124. if [[ $? != 0 ]]; then
  125. LOGE "Cancelled"
  126. if [[ $# == 0 ]]; then
  127. before_show_menu
  128. fi
  129. return 0
  130. fi
  131. curl -fLRo /usr/bin/x-ui https://raw.githubusercontent.com/MHSanaei/3x-ui/main/x-ui.sh
  132. chmod +x ${xui_folder}/x-ui.sh
  133. chmod +x /usr/bin/x-ui
  134. if [[ $? == 0 ]]; then
  135. echo -e "${green}Update successful. The panel has automatically restarted.${plain}"
  136. exit 0
  137. else
  138. echo -e "${red}Failed to update the menu.${plain}"
  139. return 1
  140. fi
  141. }
  142. legacy_version() {
  143. echo -n "Enter the panel version (like 2.4.0):"
  144. read -r tag_version
  145. if [ -z "$tag_version" ]; then
  146. echo "Panel version cannot be empty. Exiting."
  147. exit 1
  148. fi
  149. # Use the entered panel version in the download link
  150. install_command="bash <(curl -Ls "https://raw.githubusercontent.com/mhsanaei/3x-ui/v$tag_version/install.sh") v$tag_version"
  151. echo "Downloading and installing panel version $tag_version..."
  152. eval $install_command
  153. }
  154. # Function to handle the deletion of the script file
  155. delete_script() {
  156. rm "$0" # Remove the script file itself
  157. exit 1
  158. }
  159. xui_env_file_path() {
  160. case "${release}" in
  161. ubuntu | debian | armbian)
  162. echo "/etc/default/x-ui"
  163. ;;
  164. arch | manjaro | parch | alpine)
  165. echo "/etc/conf.d/x-ui"
  166. ;;
  167. *)
  168. echo "/etc/sysconfig/x-ui"
  169. ;;
  170. esac
  171. }
  172. uninstall() {
  173. confirm "Are you sure you want to uninstall the panel? xray will also uninstalled!" "n"
  174. if [[ $? != 0 ]]; then
  175. if [[ $# == 0 ]]; then
  176. show_menu
  177. fi
  178. return 0
  179. fi
  180. if [[ $release == "alpine" ]]; then
  181. rc-service x-ui stop
  182. rc-update del x-ui
  183. rm /etc/init.d/x-ui -f
  184. else
  185. systemctl stop x-ui
  186. systemctl disable x-ui
  187. rm ${xui_service}/x-ui.service -f
  188. systemctl daemon-reload
  189. systemctl reset-failed
  190. fi
  191. rm /etc/x-ui/ -rf
  192. rm ${xui_folder}/ -rf
  193. rm -f "$(xui_env_file_path)"
  194. echo ""
  195. echo -e "Uninstalled Successfully.\n"
  196. echo "If you need to install this panel again, you can use below command:"
  197. echo -e "${green}bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh)${plain}"
  198. echo ""
  199. # Trap the SIGTERM signal
  200. trap delete_script SIGTERM
  201. delete_script
  202. }
  203. reset_user() {
  204. confirm "Are you sure to reset the username and password of the panel?" "n"
  205. if [[ $? != 0 ]]; then
  206. if [[ $# == 0 ]]; then
  207. show_menu
  208. fi
  209. return 0
  210. fi
  211. read -rp "Please set the login username [default is a random username]: " config_account
  212. [[ -z $config_account ]] && config_account=$(gen_random_string 10)
  213. read -rp "Please set the login password [default is a random password]: " config_password
  214. [[ -z $config_password ]] && config_password=$(gen_random_string 18)
  215. read -rp "Do you want to disable currently configured two-factor authentication? (y/n): " twoFactorConfirm
  216. if [[ $twoFactorConfirm != "y" && $twoFactorConfirm != "Y" ]]; then
  217. ${xui_folder}/x-ui setting -username "${config_account}" -password "${config_password}" -resetTwoFactor false > /dev/null 2>&1
  218. else
  219. ${xui_folder}/x-ui setting -username "${config_account}" -password "${config_password}" -resetTwoFactor true > /dev/null 2>&1
  220. echo -e "Two factor authentication has been disabled."
  221. fi
  222. echo -e "Panel login username has been reset to: ${green} ${config_account} ${plain}"
  223. echo -e "Panel login password has been reset to: ${green} ${config_password} ${plain}"
  224. echo -e "${green} Please use the new login username and password to access the X-UI panel. Also remember them! ${plain}"
  225. confirm_restart
  226. }
  227. gen_random_string() {
  228. local length="$1"
  229. openssl rand -base64 $((length * 2)) \
  230. | tr -dc 'a-zA-Z0-9' \
  231. | head -c "$length"
  232. }
  233. reset_webbasepath() {
  234. echo -e "${yellow}Resetting Web Base Path${plain}"
  235. read -rp "Are you sure you want to reset the web base path? (y/n): " confirm
  236. if [[ $confirm != "y" && $confirm != "Y" ]]; then
  237. echo -e "${yellow}Operation canceled.${plain}"
  238. return
  239. fi
  240. config_webBasePath=$(gen_random_string 18)
  241. # Apply the new web base path setting
  242. ${xui_folder}/x-ui setting -webBasePath "${config_webBasePath}" > /dev/null 2>&1
  243. echo -e "Web base path has been reset to: ${green}${config_webBasePath}${plain}"
  244. echo -e "${green}Please use the new web base path to access the panel.${plain}"
  245. restart
  246. }
  247. reset_config() {
  248. confirm "Are you sure you want to reset all panel settings, Account data will not be lost, Username and password will not change" "n"
  249. if [[ $? != 0 ]]; then
  250. if [[ $# == 0 ]]; then
  251. show_menu
  252. fi
  253. return 0
  254. fi
  255. ${xui_folder}/x-ui setting -reset
  256. echo -e "All panel settings have been reset to default."
  257. restart
  258. }
  259. check_config() {
  260. local info=$(${xui_folder}/x-ui setting -show true)
  261. if [[ $? != 0 ]]; then
  262. LOGE "get current settings error, please check logs"
  263. show_menu
  264. return
  265. fi
  266. LOGI "${info}"
  267. local db_env_file
  268. db_env_file="$(xui_env_file_path)"
  269. if [[ -r "$db_env_file" ]] && grep -q '^XUI_DB_TYPE=postgres' "$db_env_file"; then
  270. local dsn
  271. dsn="$(grep -E '^XUI_DB_DSN=' "$db_env_file" | head -1 | cut -d= -f2-)"
  272. local dsn_safe
  273. dsn_safe="$(echo "$dsn" | sed -E 's|(://[^:/@]+:)[^@]+@|\1****@|')"
  274. echo -e "${green}Database: PostgreSQL — ${dsn_safe}${plain}"
  275. else
  276. echo -e "${green}Database: SQLite (/etc/x-ui/x-ui.db)${plain}"
  277. fi
  278. local existing_webBasePath=$(echo "$info" | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  279. local existing_port=$(echo "$info" | grep -Eo 'port: .+' | awk '{print $2}')
  280. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep 'cert:' | awk -F': ' '{print $2}' | tr -d '[:space:]')
  281. local URL_lists=(
  282. "https://api4.ipify.org"
  283. "https://ipv4.icanhazip.com"
  284. "https://v4.api.ipinfo.io/ip"
  285. "https://ipv4.myexternalip.com/raw"
  286. "https://4.ident.me"
  287. "https://check-host.net/ip"
  288. )
  289. local server_ip=""
  290. for ip_address in "${URL_lists[@]}"; do
  291. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  292. local http_code=$(echo "$response" | tail -n1)
  293. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  294. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  295. server_ip="${ip_result}"
  296. break
  297. fi
  298. done
  299. if [[ -z "$server_ip" ]]; then
  300. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  301. while [[ -z "$server_ip" ]]; do
  302. read -rp "Please enter your server's public IPv4 address: " server_ip
  303. server_ip="${server_ip// /}"
  304. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  305. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  306. server_ip=""
  307. fi
  308. done
  309. fi
  310. if [[ -n "$existing_cert" ]]; then
  311. local domain=$(basename "$(dirname "$existing_cert")")
  312. if [[ "$domain" =~ ^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
  313. echo -e "${green}Access URL: https://${domain}:${existing_port}${existing_webBasePath}${plain}"
  314. else
  315. echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  316. fi
  317. else
  318. echo -e "${red}⚠ WARNING: No SSL certificate configured!${plain}"
  319. echo -e "${yellow}You can get a Let's Encrypt certificate for your IP address (valid ~6 days, auto-renews).${plain}"
  320. read -rp "Generate SSL certificate for IP now? [y/N]: " gen_ssl
  321. if [[ "$gen_ssl" == "y" || "$gen_ssl" == "Y" ]]; then
  322. stop 0 > /dev/null 2>&1
  323. ssl_cert_issue_for_ip
  324. if [[ $? -eq 0 ]]; then
  325. echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  326. # ssl_cert_issue_for_ip already restarts the panel, but ensure it's running
  327. start 0 > /dev/null 2>&1
  328. else
  329. LOGE "IP certificate setup failed."
  330. echo -e "${yellow}You can try again via option 19 (SSL Certificate Management).${plain}"
  331. start 0 > /dev/null 2>&1
  332. fi
  333. else
  334. echo -e "${yellow}Access URL: http://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  335. echo -e "${yellow}For security, please configure SSL certificate using option 19 (SSL Certificate Management)${plain}"
  336. fi
  337. fi
  338. }
  339. set_port() {
  340. echo -n "Enter port number[1-65535]: "
  341. read -r port
  342. if [[ -z "${port}" ]]; then
  343. LOGD "Cancelled"
  344. before_show_menu
  345. else
  346. ${xui_folder}/x-ui setting -port ${port}
  347. echo -e "The port is set, Please restart the panel now, and use the new port ${green}${port}${plain} to access web panel"
  348. confirm_restart
  349. fi
  350. }
  351. start() {
  352. check_status
  353. if [[ $? == 0 ]]; then
  354. echo ""
  355. LOGI "Panel is running, No need to start again, If you need to restart, please select restart"
  356. else
  357. if [[ $release == "alpine" ]]; then
  358. rc-service x-ui start
  359. else
  360. systemctl start x-ui
  361. fi
  362. sleep 2
  363. check_status
  364. if [[ $? == 0 ]]; then
  365. LOGI "x-ui Started Successfully"
  366. else
  367. LOGE "panel Failed to start, Probably because it takes longer than two seconds to start, Please check the log information later"
  368. fi
  369. fi
  370. if [[ $# == 0 ]]; then
  371. before_show_menu
  372. fi
  373. }
  374. stop() {
  375. check_status
  376. if [[ $? == 1 ]]; then
  377. echo ""
  378. LOGI "Panel stopped, No need to stop again!"
  379. else
  380. if [[ $release == "alpine" ]]; then
  381. rc-service x-ui stop
  382. else
  383. systemctl stop x-ui
  384. fi
  385. sleep 2
  386. check_status
  387. if [[ $? == 1 ]]; then
  388. LOGI "x-ui and xray stopped successfully"
  389. else
  390. LOGE "Panel stop failed, Probably because the stop time exceeds two seconds, Please check the log information later"
  391. fi
  392. fi
  393. if [[ $# == 0 ]]; then
  394. before_show_menu
  395. fi
  396. }
  397. restart() {
  398. if [[ $release == "alpine" ]]; then
  399. rc-service x-ui restart
  400. else
  401. systemctl restart x-ui
  402. fi
  403. sleep 2
  404. check_status
  405. if [[ $? == 0 ]]; then
  406. LOGI "x-ui and xray Restarted successfully"
  407. else
  408. LOGE "Panel restart failed, Probably because it takes longer than two seconds to start, Please check the log information later"
  409. fi
  410. if [[ $# == 0 ]]; then
  411. before_show_menu
  412. fi
  413. }
  414. restart_xray() {
  415. if [[ $release == "alpine" ]]; then
  416. rc-service x-ui reload
  417. else
  418. systemctl reload x-ui
  419. fi
  420. LOGI "xray-core Restart signal sent successfully, Please check the log information to confirm whether xray restarted successfully"
  421. sleep 2
  422. show_xray_status
  423. if [[ $# == 0 ]]; then
  424. before_show_menu
  425. fi
  426. }
  427. status() {
  428. if [[ $release == "alpine" ]]; then
  429. rc-service x-ui status
  430. else
  431. systemctl status x-ui -l
  432. fi
  433. if [[ $# == 0 ]]; then
  434. before_show_menu
  435. fi
  436. }
  437. enable() {
  438. if [[ $release == "alpine" ]]; then
  439. rc-update add x-ui default
  440. else
  441. systemctl enable x-ui
  442. fi
  443. if [[ $? == 0 ]]; then
  444. LOGI "x-ui Set to boot automatically on startup successfully"
  445. else
  446. LOGE "x-ui Failed to set Autostart"
  447. fi
  448. if [[ $# == 0 ]]; then
  449. before_show_menu
  450. fi
  451. }
  452. disable() {
  453. if [[ $release == "alpine" ]]; then
  454. rc-update del x-ui
  455. else
  456. systemctl disable x-ui
  457. fi
  458. if [[ $? == 0 ]]; then
  459. LOGI "x-ui Autostart Cancelled successfully"
  460. else
  461. LOGE "x-ui Failed to cancel autostart"
  462. fi
  463. if [[ $# == 0 ]]; then
  464. before_show_menu
  465. fi
  466. }
  467. show_log() {
  468. if [[ $release == "alpine" ]]; then
  469. echo -e "${green}\t1.${plain} Debug Log"
  470. echo -e "${green}\t0.${plain} Back to Main Menu"
  471. read -rp "Choose an option: " choice
  472. case "$choice" in
  473. 0)
  474. show_menu
  475. ;;
  476. 1)
  477. grep -F 'x-ui[' /var/log/messages
  478. if [[ $# == 0 ]]; then
  479. before_show_menu
  480. fi
  481. ;;
  482. *)
  483. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  484. show_log
  485. ;;
  486. esac
  487. else
  488. echo -e "${green}\t1.${plain} Debug Log"
  489. echo -e "${green}\t2.${plain} Clear All logs"
  490. echo -e "${green}\t0.${plain} Back to Main Menu"
  491. read -rp "Choose an option: " choice
  492. case "$choice" in
  493. 0)
  494. show_menu
  495. ;;
  496. 1)
  497. journalctl -u x-ui -e --no-pager -f -p debug
  498. if [[ $# == 0 ]]; then
  499. before_show_menu
  500. fi
  501. ;;
  502. 2)
  503. sudo journalctl --rotate
  504. sudo journalctl --vacuum-time=1s
  505. echo "All Logs cleared."
  506. restart
  507. ;;
  508. *)
  509. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  510. show_log
  511. ;;
  512. esac
  513. fi
  514. }
  515. bbr_menu() {
  516. echo -e "${green}\t1.${plain} Enable BBR"
  517. echo -e "${green}\t2.${plain} Disable BBR"
  518. echo -e "${green}\t0.${plain} Back to Main Menu"
  519. read -rp "Choose an option: " choice
  520. case "$choice" in
  521. 0)
  522. show_menu
  523. ;;
  524. 1)
  525. enable_bbr
  526. bbr_menu
  527. ;;
  528. 2)
  529. disable_bbr
  530. bbr_menu
  531. ;;
  532. *)
  533. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  534. bbr_menu
  535. ;;
  536. esac
  537. }
  538. disable_bbr() {
  539. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) != "bbr" ]] || [[ ! $(sysctl -n net.core.default_qdisc) =~ ^(fq|cake)$ ]]; then
  540. echo -e "${yellow}BBR is not currently enabled.${plain}"
  541. before_show_menu
  542. fi
  543. if [ -f "/etc/sysctl.d/99-bbr-x-ui.conf" ]; then
  544. old_settings=$(head -1 /etc/sysctl.d/99-bbr-x-ui.conf | tr -d '#')
  545. sysctl -w net.core.default_qdisc="${old_settings%:*}"
  546. sysctl -w net.ipv4.tcp_congestion_control="${old_settings#*:}"
  547. rm /etc/sysctl.d/99-bbr-x-ui.conf
  548. sysctl --system
  549. else
  550. # Replace BBR with CUBIC configurations
  551. if [ -f "/etc/sysctl.conf" ]; then
  552. sed -i 's/net.core.default_qdisc=fq/net.core.default_qdisc=pfifo_fast/' /etc/sysctl.conf
  553. sed -i 's/net.ipv4.tcp_congestion_control=bbr/net.ipv4.tcp_congestion_control=cubic/' /etc/sysctl.conf
  554. sysctl -p
  555. fi
  556. fi
  557. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) != "bbr" ]]; then
  558. echo -e "${green}BBR has been replaced with CUBIC successfully.${plain}"
  559. else
  560. echo -e "${red}Failed to replace BBR with CUBIC. Please check your system configuration.${plain}"
  561. fi
  562. }
  563. enable_bbr() {
  564. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) == "bbr" ]] && [[ $(sysctl -n net.core.default_qdisc) =~ ^(fq|cake)$ ]]; then
  565. echo -e "${green}BBR is already enabled!${plain}"
  566. before_show_menu
  567. fi
  568. # Enable BBR
  569. if [ -d "/etc/sysctl.d/" ]; then
  570. {
  571. echo "#$(sysctl -n net.core.default_qdisc):$(sysctl -n net.ipv4.tcp_congestion_control)"
  572. echo "net.core.default_qdisc = fq"
  573. echo "net.ipv4.tcp_congestion_control = bbr"
  574. } > "/etc/sysctl.d/99-bbr-x-ui.conf"
  575. if [ -f "/etc/sysctl.conf" ]; then
  576. # Backup old settings from sysctl.conf, if any
  577. sed -i 's/^net.core.default_qdisc/# &/' /etc/sysctl.conf
  578. sed -i 's/^net.ipv4.tcp_congestion_control/# &/' /etc/sysctl.conf
  579. fi
  580. sysctl --system
  581. else
  582. sed -i '/net.core.default_qdisc/d' /etc/sysctl.conf
  583. sed -i '/net.ipv4.tcp_congestion_control/d' /etc/sysctl.conf
  584. echo "net.core.default_qdisc=fq" | tee -a /etc/sysctl.conf
  585. echo "net.ipv4.tcp_congestion_control=bbr" | tee -a /etc/sysctl.conf
  586. sysctl -p
  587. fi
  588. # Verify that BBR is enabled
  589. if [[ $(sysctl -n net.ipv4.tcp_congestion_control) == "bbr" ]]; then
  590. echo -e "${green}BBR has been enabled successfully.${plain}"
  591. else
  592. echo -e "${red}Failed to enable BBR. Please check your system configuration.${plain}"
  593. fi
  594. }
  595. update_shell() {
  596. curl -fLRo /usr/bin/x-ui -z /usr/bin/x-ui https://github.com/MHSanaei/3x-ui/raw/main/x-ui.sh
  597. if [[ $? != 0 ]]; then
  598. echo ""
  599. LOGE "Failed to download script, Please check whether the machine can connect Github"
  600. before_show_menu
  601. else
  602. chmod +x /usr/bin/x-ui
  603. LOGI "Upgrade script succeeded, Please rerun the script"
  604. before_show_menu
  605. fi
  606. }
  607. # 0: running, 1: not running, 2: not installed
  608. check_status() {
  609. if [[ $release == "alpine" ]]; then
  610. if [[ ! -f /etc/init.d/x-ui ]]; then
  611. return 2
  612. fi
  613. if [[ $(rc-service x-ui status | grep -F 'status: started' -c) == 1 ]]; then
  614. return 0
  615. else
  616. return 1
  617. fi
  618. else
  619. if [[ ! -f ${xui_service}/x-ui.service ]]; then
  620. return 2
  621. fi
  622. temp=$(systemctl status x-ui | grep Active | awk '{print $3}' | cut -d "(" -f2 | cut -d ")" -f1)
  623. if [[ "${temp}" == "running" ]]; then
  624. return 0
  625. else
  626. return 1
  627. fi
  628. fi
  629. }
  630. check_enabled() {
  631. if [[ $release == "alpine" ]]; then
  632. if [[ $(rc-update show | grep -F 'x-ui' | grep default -c) == 1 ]]; then
  633. return 0
  634. else
  635. return 1
  636. fi
  637. else
  638. temp=$(systemctl is-enabled x-ui)
  639. if [[ "${temp}" == "enabled" ]]; then
  640. return 0
  641. else
  642. return 1
  643. fi
  644. fi
  645. }
  646. check_uninstall() {
  647. check_status
  648. if [[ $? != 2 ]]; then
  649. echo ""
  650. LOGE "Panel installed, Please do not reinstall"
  651. if [[ $# == 0 ]]; then
  652. before_show_menu
  653. fi
  654. return 1
  655. else
  656. return 0
  657. fi
  658. }
  659. check_install() {
  660. check_status
  661. if [[ $? == 2 ]]; then
  662. echo ""
  663. LOGE "Please install the panel first"
  664. if [[ $# == 0 ]]; then
  665. before_show_menu
  666. fi
  667. return 1
  668. else
  669. return 0
  670. fi
  671. }
  672. show_status() {
  673. check_status
  674. case $? in
  675. 0)
  676. echo -e "Panel state: ${green}Running${plain}"
  677. show_enable_status
  678. ;;
  679. 1)
  680. echo -e "Panel state: ${yellow}Not Running${plain}"
  681. show_enable_status
  682. ;;
  683. 2)
  684. echo -e "Panel state: ${red}Not Installed${plain}"
  685. ;;
  686. esac
  687. show_xray_status
  688. }
  689. show_enable_status() {
  690. check_enabled
  691. if [[ $? == 0 ]]; then
  692. echo -e "Start automatically: ${green}Yes${plain}"
  693. else
  694. echo -e "Start automatically: ${red}No${plain}"
  695. fi
  696. }
  697. check_xray_status() {
  698. count=$(ps -ef | grep "xray-linux" | grep -v "grep" | wc -l)
  699. if [[ count -ne 0 ]]; then
  700. return 0
  701. else
  702. return 1
  703. fi
  704. }
  705. show_xray_status() {
  706. check_xray_status
  707. if [[ $? == 0 ]]; then
  708. echo -e "xray state: ${green}Running${plain}"
  709. else
  710. echo -e "xray state: ${red}Not Running${plain}"
  711. fi
  712. }
  713. firewall_menu() {
  714. echo -e "${green}\t1.${plain} ${green}Install${plain} Firewall"
  715. echo -e "${green}\t2.${plain} Port List [numbered]"
  716. echo -e "${green}\t3.${plain} ${green}Open${plain} Ports"
  717. echo -e "${green}\t4.${plain} ${red}Delete${plain} Ports from List"
  718. echo -e "${green}\t5.${plain} ${green}Enable${plain} Firewall"
  719. echo -e "${green}\t6.${plain} ${red}Disable${plain} Firewall"
  720. echo -e "${green}\t7.${plain} Firewall Status"
  721. echo -e "${green}\t0.${plain} Back to Main Menu"
  722. read -rp "Choose an option: " choice
  723. case "$choice" in
  724. 0)
  725. show_menu
  726. ;;
  727. 1)
  728. install_firewall
  729. firewall_menu
  730. ;;
  731. 2)
  732. ufw status numbered
  733. firewall_menu
  734. ;;
  735. 3)
  736. open_ports
  737. firewall_menu
  738. ;;
  739. 4)
  740. delete_ports
  741. firewall_menu
  742. ;;
  743. 5)
  744. ufw enable
  745. firewall_menu
  746. ;;
  747. 6)
  748. ufw disable
  749. firewall_menu
  750. ;;
  751. 7)
  752. ufw status verbose
  753. firewall_menu
  754. ;;
  755. *)
  756. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  757. firewall_menu
  758. ;;
  759. esac
  760. }
  761. install_firewall() {
  762. if ! command -v ufw &> /dev/null; then
  763. echo "ufw firewall is not installed. Installing now..."
  764. apt-get update
  765. apt-get install -y ufw
  766. else
  767. echo "ufw firewall is already installed"
  768. fi
  769. # Check if the firewall is inactive
  770. if ufw status | grep -q "Status: active"; then
  771. echo "Firewall is already active"
  772. else
  773. echo "Activating firewall..."
  774. # Open the necessary ports
  775. ufw allow ssh
  776. ufw allow http
  777. ufw allow https
  778. ufw allow 2053/tcp #webPort
  779. ufw allow 2096/tcp #subport
  780. # Enable the firewall
  781. ufw --force enable
  782. fi
  783. }
  784. open_ports() {
  785. # Prompt the user to enter the ports they want to open
  786. read -rp "Enter the ports you want to open (e.g. 80,443,2053 or range 400-500): " ports
  787. # Check if the input is valid
  788. if ! [[ $ports =~ ^([0-9]+|[0-9]+-[0-9]+)(,([0-9]+|[0-9]+-[0-9]+))*$ ]]; then
  789. echo "Error: Invalid input. Please enter a comma-separated list of ports or a range of ports (e.g. 80,443,2053 or 400-500)." >&2
  790. exit 1
  791. fi
  792. # Open the specified ports using ufw
  793. IFS=',' read -ra PORT_LIST <<< "$ports"
  794. for port in "${PORT_LIST[@]}"; do
  795. if [[ $port == *-* ]]; then
  796. # Split the range into start and end ports
  797. start_port=$(echo $port | cut -d'-' -f1)
  798. end_port=$(echo $port | cut -d'-' -f2)
  799. # Open the port range
  800. ufw allow $start_port:$end_port/tcp
  801. ufw allow $start_port:$end_port/udp
  802. else
  803. # Open the single port
  804. ufw allow "$port"
  805. fi
  806. done
  807. # Confirm that the ports are opened
  808. echo "Opened the specified ports:"
  809. for port in "${PORT_LIST[@]}"; do
  810. if [[ $port == *-* ]]; then
  811. start_port=$(echo $port | cut -d'-' -f1)
  812. end_port=$(echo $port | cut -d'-' -f2)
  813. # Check if the port range has been successfully opened
  814. (ufw status | grep -q "$start_port:$end_port") && echo "$start_port-$end_port"
  815. else
  816. # Check if the individual port has been successfully opened
  817. (ufw status | grep -q "$port") && echo "$port"
  818. fi
  819. done
  820. }
  821. delete_ports() {
  822. # Display current rules with numbers
  823. echo "Current UFW rules:"
  824. ufw status numbered
  825. # Ask the user how they want to delete rules
  826. echo "Do you want to delete rules by:"
  827. echo "1) Rule numbers"
  828. echo "2) Ports"
  829. read -rp "Enter your choice (1 or 2): " choice
  830. if [[ $choice -eq 1 ]]; then
  831. # Deleting by rule numbers
  832. read -rp "Enter the rule numbers you want to delete (1, 2, etc.): " rule_numbers
  833. # Validate the input
  834. if ! [[ $rule_numbers =~ ^([0-9]+)(,[0-9]+)*$ ]]; then
  835. echo "Error: Invalid input. Please enter a comma-separated list of rule numbers." >&2
  836. exit 1
  837. fi
  838. # Split numbers into an array
  839. IFS=',' read -ra RULE_NUMBERS <<< "$rule_numbers"
  840. for rule_number in "${RULE_NUMBERS[@]}"; do
  841. # Delete the rule by number
  842. ufw delete "$rule_number" || echo "Failed to delete rule number $rule_number"
  843. done
  844. echo "Selected rules have been deleted."
  845. elif [[ $choice -eq 2 ]]; then
  846. # Deleting by ports
  847. read -rp "Enter the ports you want to delete (e.g. 80,443,2053 or range 400-500): " ports
  848. # Validate the input
  849. if ! [[ $ports =~ ^([0-9]+|[0-9]+-[0-9]+)(,([0-9]+|[0-9]+-[0-9]+))*$ ]]; then
  850. echo "Error: Invalid input. Please enter a comma-separated list of ports or a range of ports (e.g. 80,443,2053 or 400-500)." >&2
  851. exit 1
  852. fi
  853. # Split ports into an array
  854. IFS=',' read -ra PORT_LIST <<< "$ports"
  855. for port in "${PORT_LIST[@]}"; do
  856. if [[ $port == *-* ]]; then
  857. # Split the port range
  858. start_port=$(echo $port | cut -d'-' -f1)
  859. end_port=$(echo $port | cut -d'-' -f2)
  860. # Delete the port range
  861. ufw delete allow $start_port:$end_port/tcp
  862. ufw delete allow $start_port:$end_port/udp
  863. else
  864. # Delete a single port
  865. ufw delete allow "$port"
  866. fi
  867. done
  868. # Confirmation of deletion
  869. echo "Deleted the specified ports:"
  870. for port in "${PORT_LIST[@]}"; do
  871. if [[ $port == *-* ]]; then
  872. start_port=$(echo $port | cut -d'-' -f1)
  873. end_port=$(echo $port | cut -d'-' -f2)
  874. # Check if the port range has been deleted
  875. (ufw status | grep -q "$start_port:$end_port") || echo "$start_port-$end_port"
  876. else
  877. # Check if the individual port has been deleted
  878. (ufw status | grep -q "$port") || echo "$port"
  879. fi
  880. done
  881. else
  882. echo "${red}Error:${plain} Invalid choice. Please enter 1 or 2." >&2
  883. exit 1
  884. fi
  885. }
  886. update_all_geofiles() {
  887. update_geofiles "main"
  888. update_geofiles "IR"
  889. update_geofiles "RU"
  890. }
  891. update_geofiles() {
  892. case "${1}" in
  893. "main")
  894. dat_files=(geoip geosite)
  895. dat_source="Loyalsoldier/v2ray-rules-dat"
  896. ;;
  897. "IR")
  898. dat_files=(geoip_IR geosite_IR)
  899. dat_source="chocolate4u/Iran-v2ray-rules"
  900. ;;
  901. "RU")
  902. dat_files=(geoip_RU geosite_RU)
  903. dat_source="runetfreedom/russia-v2ray-rules-dat"
  904. ;;
  905. esac
  906. for dat in "${dat_files[@]}"; do
  907. # Remove suffix for remote filename (e.g., geoip_IR -> geoip)
  908. remote_file="${dat%%_*}"
  909. curl -fLRo ${xui_folder}/bin/${dat}.dat -z ${xui_folder}/bin/${dat}.dat \
  910. https://github.com/${dat_source}/releases/latest/download/${remote_file}.dat
  911. done
  912. }
  913. update_geo() {
  914. echo -e "${green}\t1.${plain} Loyalsoldier (geoip.dat, geosite.dat)"
  915. echo -e "${green}\t2.${plain} chocolate4u (geoip_IR.dat, geosite_IR.dat)"
  916. echo -e "${green}\t3.${plain} runetfreedom (geoip_RU.dat, geosite_RU.dat)"
  917. echo -e "${green}\t4.${plain} All"
  918. echo -e "${green}\t0.${plain} Back to Main Menu"
  919. read -rp "Choose an option: " choice
  920. case "$choice" in
  921. 0)
  922. show_menu
  923. ;;
  924. 1)
  925. update_geofiles "main"
  926. echo -e "${green}Loyalsoldier datasets have been updated successfully!${plain}"
  927. restart
  928. ;;
  929. 2)
  930. update_geofiles "IR"
  931. echo -e "${green}chocolate4u datasets have been updated successfully!${plain}"
  932. restart
  933. ;;
  934. 3)
  935. update_geofiles "RU"
  936. echo -e "${green}runetfreedom datasets have been updated successfully!${plain}"
  937. restart
  938. ;;
  939. 4)
  940. update_all_geofiles
  941. echo -e "${green}All geo files have been updated successfully!${plain}"
  942. restart
  943. ;;
  944. *)
  945. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  946. update_geo
  947. ;;
  948. esac
  949. before_show_menu
  950. }
  951. install_acme() {
  952. # Check if acme.sh is already installed
  953. if command -v ~/.acme.sh/acme.sh &> /dev/null; then
  954. LOGI "acme.sh is already installed."
  955. return 0
  956. fi
  957. LOGI "Installing acme.sh..."
  958. cd ~ || return 1 # Ensure you can change to the home directory
  959. curl -s https://get.acme.sh | sh
  960. if [ $? -ne 0 ]; then
  961. LOGE "Installation of acme.sh failed."
  962. return 1
  963. else
  964. LOGI "Installation of acme.sh succeeded."
  965. fi
  966. return 0
  967. }
  968. ssl_cert_issue_main() {
  969. echo -e "${green}\t1.${plain} Get SSL (Domain)"
  970. echo -e "${green}\t2.${plain} Revoke"
  971. echo -e "${green}\t3.${plain} Force Renew"
  972. echo -e "${green}\t4.${plain} Show Existing Domains"
  973. echo -e "${green}\t5.${plain} Set Cert paths for the panel"
  974. echo -e "${green}\t6.${plain} Get SSL for IP Address (6-day cert, auto-renews)"
  975. echo -e "${green}\t0.${plain} Back to Main Menu"
  976. read -rp "Choose an option: " choice
  977. case "$choice" in
  978. 0)
  979. show_menu
  980. ;;
  981. 1)
  982. ssl_cert_issue
  983. ssl_cert_issue_main
  984. ;;
  985. 2)
  986. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \;)
  987. if [ -z "$domains" ]; then
  988. echo "No certificates found to revoke."
  989. else
  990. echo "Existing domains:"
  991. echo "$domains"
  992. read -rp "Please enter a domain from the list to revoke the certificate: " domain
  993. if echo "$domains" | grep -qw "$domain"; then
  994. ~/.acme.sh/acme.sh --revoke -d ${domain}
  995. LOGI "Certificate revoked for domain: $domain"
  996. else
  997. echo "Invalid domain entered."
  998. fi
  999. fi
  1000. ssl_cert_issue_main
  1001. ;;
  1002. 3)
  1003. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \;)
  1004. if [ -z "$domains" ]; then
  1005. echo "No certificates found to renew."
  1006. else
  1007. echo "Existing domains:"
  1008. echo "$domains"
  1009. read -rp "Please enter a domain from the list to renew the SSL certificate: " domain
  1010. if echo "$domains" | grep -qw "$domain"; then
  1011. ~/.acme.sh/acme.sh --renew -d ${domain} --force
  1012. LOGI "Certificate forcefully renewed for domain: $domain"
  1013. else
  1014. echo "Invalid domain entered."
  1015. fi
  1016. fi
  1017. ssl_cert_issue_main
  1018. ;;
  1019. 4)
  1020. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \;)
  1021. if [ -z "$domains" ]; then
  1022. echo "No certificates found."
  1023. else
  1024. echo "Existing domains and their paths:"
  1025. for domain in $domains; do
  1026. local cert_path="/root/cert/${domain}/fullchain.pem"
  1027. local key_path="/root/cert/${domain}/privkey.pem"
  1028. if [[ -f "${cert_path}" && -f "${key_path}" ]]; then
  1029. echo -e "Domain: ${domain}"
  1030. echo -e "\tCertificate Path: ${cert_path}"
  1031. echo -e "\tPrivate Key Path: ${key_path}"
  1032. else
  1033. echo -e "Domain: ${domain} - Certificate or Key missing."
  1034. fi
  1035. done
  1036. fi
  1037. ssl_cert_issue_main
  1038. ;;
  1039. 5)
  1040. local domains=$(find /root/cert/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \;)
  1041. if [ -z "$domains" ]; then
  1042. echo "No certificates found."
  1043. else
  1044. echo "Available domains:"
  1045. echo "$domains"
  1046. read -rp "Please choose a domain to set the panel paths: " domain
  1047. if echo "$domains" | grep -qw "$domain"; then
  1048. local webCertFile="/root/cert/${domain}/fullchain.pem"
  1049. local webKeyFile="/root/cert/${domain}/privkey.pem"
  1050. if [[ -f "${webCertFile}" && -f "${webKeyFile}" ]]; then
  1051. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1052. echo "Panel paths set for domain: $domain"
  1053. echo " - Certificate File: $webCertFile"
  1054. echo " - Private Key File: $webKeyFile"
  1055. restart
  1056. else
  1057. echo "Certificate or private key not found for domain: $domain."
  1058. fi
  1059. else
  1060. echo "Invalid domain entered."
  1061. fi
  1062. fi
  1063. ssl_cert_issue_main
  1064. ;;
  1065. 6)
  1066. echo -e "${yellow}Let's Encrypt SSL Certificate for IP Address${plain}"
  1067. echo -e "This will obtain a certificate for your server's IP using the shortlived profile."
  1068. echo -e "${yellow}Certificate valid for ~6 days, auto-renews via acme.sh cron job.${plain}"
  1069. echo -e "${yellow}Port 80 must be open and accessible from the internet.${plain}"
  1070. confirm "Do you want to proceed?" "y"
  1071. if [[ $? == 0 ]]; then
  1072. ssl_cert_issue_for_ip
  1073. fi
  1074. ssl_cert_issue_main
  1075. ;;
  1076. *)
  1077. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1078. ssl_cert_issue_main
  1079. ;;
  1080. esac
  1081. }
  1082. ssl_cert_issue_for_ip() {
  1083. LOGI "Starting automatic SSL certificate generation for server IP..."
  1084. LOGI "Using Let's Encrypt shortlived profile (~6 days validity, auto-renews)"
  1085. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1086. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1087. # Get server IP
  1088. local URL_lists=(
  1089. "https://api4.ipify.org"
  1090. "https://ipv4.icanhazip.com"
  1091. "https://v4.api.ipinfo.io/ip"
  1092. "https://ipv4.myexternalip.com/raw"
  1093. "https://4.ident.me"
  1094. "https://check-host.net/ip"
  1095. )
  1096. local server_ip=""
  1097. for ip_address in "${URL_lists[@]}"; do
  1098. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  1099. local http_code=$(echo "$response" | tail -n1)
  1100. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  1101. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1102. server_ip="${ip_result}"
  1103. break
  1104. fi
  1105. done
  1106. if [[ -z "$server_ip" ]]; then
  1107. LOGI "Could not auto-detect server IP from any provider."
  1108. while [[ -z "$server_ip" ]]; do
  1109. read -rp "Please enter your server's public IPv4 address: " server_ip
  1110. server_ip="${server_ip// /}"
  1111. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1112. LOGE "Invalid IPv4 address. Please try again."
  1113. server_ip=""
  1114. fi
  1115. done
  1116. fi
  1117. LOGI "Server IP detected: ${server_ip}"
  1118. # Ask for optional IPv6
  1119. local ipv6_addr=""
  1120. read -rp "Do you have an IPv6 address to include? (leave empty to skip): " ipv6_addr
  1121. ipv6_addr="${ipv6_addr// /}" # Trim whitespace
  1122. # check for acme.sh first
  1123. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1124. LOGI "acme.sh not found, installing..."
  1125. install_acme
  1126. if [ $? -ne 0 ]; then
  1127. LOGE "Failed to install acme.sh"
  1128. return 1
  1129. fi
  1130. fi
  1131. # install socat
  1132. case "${release}" in
  1133. ubuntu | debian | armbian)
  1134. apt-get update > /dev/null 2>&1 && apt-get install socat -y > /dev/null 2>&1
  1135. ;;
  1136. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1137. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1138. ;;
  1139. centos)
  1140. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1141. yum -y update > /dev/null 2>&1 && yum -y install socat > /dev/null 2>&1
  1142. else
  1143. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1144. fi
  1145. ;;
  1146. arch | manjaro | parch)
  1147. pacman -Sy --noconfirm socat > /dev/null 2>&1
  1148. ;;
  1149. opensuse-tumbleweed | opensuse-leap)
  1150. zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1
  1151. ;;
  1152. alpine)
  1153. apk add socat curl openssl > /dev/null 2>&1
  1154. ;;
  1155. *)
  1156. LOGW "Unsupported OS for automatic socat installation"
  1157. ;;
  1158. esac
  1159. # Create certificate directory
  1160. certPath="/root/cert/ip"
  1161. mkdir -p "$certPath"
  1162. # Build domain arguments
  1163. local domain_args="-d ${server_ip}"
  1164. if [[ -n "$ipv6_addr" ]] && is_ipv6 "$ipv6_addr"; then
  1165. domain_args="${domain_args} -d ${ipv6_addr}"
  1166. LOGI "Including IPv6 address: ${ipv6_addr}"
  1167. fi
  1168. # Choose port for HTTP-01 listener (default 80, allow override)
  1169. local WebPort=""
  1170. read -rp "Port to use for ACME HTTP-01 listener (default 80): " WebPort
  1171. WebPort="${WebPort:-80}"
  1172. if ! [[ "${WebPort}" =~ ^[0-9]+$ ]] || ((WebPort < 1 || WebPort > 65535)); then
  1173. LOGE "Invalid port provided. Falling back to 80."
  1174. WebPort=80
  1175. fi
  1176. LOGI "Using port ${WebPort} to issue certificate for IP: ${server_ip}"
  1177. if [[ "${WebPort}" -ne 80 ]]; then
  1178. LOGI "Reminder: Let's Encrypt still reaches port 80; forward external port 80 to ${WebPort} for validation."
  1179. fi
  1180. while true; do
  1181. if is_port_in_use "${WebPort}"; then
  1182. LOGI "Port ${WebPort} is currently in use."
  1183. local alt_port=""
  1184. read -rp "Enter another port for acme.sh standalone listener (leave empty to abort): " alt_port
  1185. alt_port="${alt_port// /}"
  1186. if [[ -z "${alt_port}" ]]; then
  1187. LOGE "Port ${WebPort} is busy; cannot proceed with issuance."
  1188. return 1
  1189. fi
  1190. if ! [[ "${alt_port}" =~ ^[0-9]+$ ]] || ((alt_port < 1 || alt_port > 65535)); then
  1191. LOGE "Invalid port provided."
  1192. return 1
  1193. fi
  1194. WebPort="${alt_port}"
  1195. continue
  1196. else
  1197. LOGI "Port ${WebPort} is free and ready for standalone validation."
  1198. break
  1199. fi
  1200. done
  1201. # Reload command - restarts panel after renewal
  1202. local reloadCmd="systemctl restart x-ui 2>/dev/null || rc-service x-ui restart 2>/dev/null"
  1203. # issue the certificate for IP with shortlived profile
  1204. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1205. ~/.acme.sh/acme.sh --issue \
  1206. ${domain_args} \
  1207. --standalone \
  1208. --server letsencrypt \
  1209. --certificate-profile shortlived \
  1210. --days 6 \
  1211. --httpport ${WebPort} \
  1212. --force
  1213. if [ $? -ne 0 ]; then
  1214. LOGE "Failed to issue certificate for IP: ${server_ip}"
  1215. LOGE "Make sure port ${WebPort} is open and the server is accessible from the internet"
  1216. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  1217. rm -rf ~/.acme.sh/${server_ip} 2> /dev/null
  1218. [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} 2> /dev/null
  1219. rm -rf ${certPath} 2> /dev/null
  1220. return 1
  1221. else
  1222. LOGI "Certificate issued successfully for IP: ${server_ip}"
  1223. fi
  1224. # Install the certificate
  1225. # Note: acme.sh may report "Reload error" and exit non-zero if reloadcmd fails,
  1226. # but the cert files are still installed. We check for files instead of exit code.
  1227. ~/.acme.sh/acme.sh --installcert -d ${server_ip} \
  1228. --key-file "${certPath}/privkey.pem" \
  1229. --fullchain-file "${certPath}/fullchain.pem" \
  1230. --reloadcmd "${reloadCmd}" 2>&1 || true
  1231. # Verify certificate files exist (don't rely on exit code - reloadcmd failure causes non-zero)
  1232. if [[ ! -f "${certPath}/fullchain.pem" || ! -f "${certPath}/privkey.pem" ]]; then
  1233. LOGE "Certificate files not found after installation"
  1234. # Cleanup acme.sh data for both IPv4 and IPv6 if specified
  1235. rm -rf ~/.acme.sh/${server_ip} 2> /dev/null
  1236. [[ -n "$ipv6_addr" ]] && rm -rf ~/.acme.sh/${ipv6_addr} 2> /dev/null
  1237. rm -rf ${certPath} 2> /dev/null
  1238. return 1
  1239. fi
  1240. LOGI "Certificate files installed successfully"
  1241. # enable auto-renew
  1242. ~/.acme.sh/acme.sh --upgrade --auto-upgrade > /dev/null 2>&1
  1243. chmod 600 $certPath/privkey.pem 2> /dev/null
  1244. chmod 644 $certPath/fullchain.pem 2> /dev/null
  1245. # Prompt user to set panel paths after successful certificate installation
  1246. local webCertFile="${certPath}/fullchain.pem"
  1247. local webKeyFile="${certPath}/privkey.pem"
  1248. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1249. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1250. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1251. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1252. LOGI "Panel paths set for IP: $server_ip"
  1253. LOGI " - Certificate File: $webCertFile"
  1254. LOGI " - Private Key File: $webKeyFile"
  1255. LOGI " - Validity: ~6 days (auto-renews via acme.sh cron)"
  1256. echo -e "${green}Access URL: https://${server_ip}:${existing_port}${existing_webBasePath}${plain}"
  1257. LOGI "Panel will restart to apply SSL certificate..."
  1258. restart
  1259. else
  1260. LOGE "Error: Certificate or private key file not found for IP: $server_ip."
  1261. return 1
  1262. fi
  1263. else
  1264. LOGI "Skipping panel path setting."
  1265. fi
  1266. return 0
  1267. }
  1268. ssl_cert_issue() {
  1269. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1270. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1271. # check for acme.sh first
  1272. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1273. echo "acme.sh could not be found. we will install it"
  1274. install_acme
  1275. if [ $? -ne 0 ]; then
  1276. LOGE "install acme failed, please check logs"
  1277. exit 1
  1278. fi
  1279. fi
  1280. # install socat
  1281. case "${release}" in
  1282. ubuntu | debian | armbian)
  1283. apt-get update > /dev/null 2>&1 && apt-get install socat -y > /dev/null 2>&1
  1284. ;;
  1285. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1286. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1287. ;;
  1288. centos)
  1289. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1290. yum -y update > /dev/null 2>&1 && yum -y install socat > /dev/null 2>&1
  1291. else
  1292. dnf -y update > /dev/null 2>&1 && dnf -y install socat > /dev/null 2>&1
  1293. fi
  1294. ;;
  1295. arch | manjaro | parch)
  1296. pacman -Sy --noconfirm socat > /dev/null 2>&1
  1297. ;;
  1298. opensuse-tumbleweed | opensuse-leap)
  1299. zypper refresh > /dev/null 2>&1 && zypper -q install -y socat > /dev/null 2>&1
  1300. ;;
  1301. alpine)
  1302. apk add socat curl openssl > /dev/null 2>&1
  1303. ;;
  1304. *)
  1305. LOGW "Unsupported OS for automatic socat installation"
  1306. ;;
  1307. esac
  1308. if [ $? -ne 0 ]; then
  1309. LOGE "install socat failed, please check logs"
  1310. exit 1
  1311. else
  1312. LOGI "install socat succeed..."
  1313. fi
  1314. # get the domain here, and we need to verify it
  1315. local domain=""
  1316. while true; do
  1317. read -rp "Please enter your domain name: " domain
  1318. domain="${domain// /}" # Trim whitespace
  1319. if [[ -z "$domain" ]]; then
  1320. LOGE "Domain name cannot be empty. Please try again."
  1321. continue
  1322. fi
  1323. if ! is_domain "$domain"; then
  1324. LOGE "Invalid domain format: ${domain}. Please enter a valid domain name."
  1325. continue
  1326. fi
  1327. break
  1328. done
  1329. LOGD "Your domain is: ${domain}, checking it..."
  1330. SSL_ISSUED_DOMAIN="${domain}"
  1331. # detect existing certificate and reuse it if present
  1332. local cert_exists=0
  1333. if ~/.acme.sh/acme.sh --list 2> /dev/null | awk '{print $1}' | grep -Fxq "${domain}"; then
  1334. cert_exists=1
  1335. local certInfo=$(~/.acme.sh/acme.sh --list 2> /dev/null | grep -F "${domain}")
  1336. LOGI "Existing certificate found for ${domain}, will reuse it."
  1337. [[ -n "${certInfo}" ]] && LOGI "${certInfo}"
  1338. else
  1339. LOGI "Your domain is ready for issuing certificates now..."
  1340. fi
  1341. # create a directory for the certificate
  1342. certPath="/root/cert/${domain}"
  1343. if [ ! -d "$certPath" ]; then
  1344. mkdir -p "$certPath"
  1345. else
  1346. rm -rf "$certPath"
  1347. mkdir -p "$certPath"
  1348. fi
  1349. # get the port number for the standalone server
  1350. local WebPort=80
  1351. read -rp "Please choose which port to use (default is 80): " WebPort
  1352. if [[ ${WebPort} -gt 65535 || ${WebPort} -lt 1 ]]; then
  1353. LOGE "Your input ${WebPort} is invalid, will use default port 80."
  1354. WebPort=80
  1355. fi
  1356. LOGI "Will use port: ${WebPort} to issue certificates. Please make sure this port is open."
  1357. if [[ ${cert_exists} -eq 0 ]]; then
  1358. # issue the certificate
  1359. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1360. ~/.acme.sh/acme.sh --issue -d ${domain} --listen-v6 --standalone --httpport ${WebPort} --force
  1361. if [ $? -ne 0 ]; then
  1362. LOGE "Issuing certificate failed, please check logs."
  1363. rm -rf ~/.acme.sh/${domain}
  1364. exit 1
  1365. else
  1366. LOGE "Issuing certificate succeeded, installing certificates..."
  1367. fi
  1368. else
  1369. LOGI "Using existing certificate, installing certificates..."
  1370. fi
  1371. reloadCmd="x-ui restart"
  1372. LOGI "Default --reloadcmd for ACME is: ${yellow}x-ui restart"
  1373. LOGI "This command will run on every certificate issue and renew."
  1374. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  1375. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  1376. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; x-ui restart"
  1377. echo -e "${green}\t2.${plain} Input your own command"
  1378. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  1379. read -rp "Choose an option: " choice
  1380. case "$choice" in
  1381. 1)
  1382. LOGI "Reloadcmd is: systemctl reload nginx ; x-ui restart"
  1383. reloadCmd="systemctl reload nginx ; x-ui restart"
  1384. ;;
  1385. 2)
  1386. LOGD "It's recommended to put x-ui restart at the end, so it won't raise an error if other services fails"
  1387. read -rp "Please enter your reloadcmd (example: systemctl reload nginx ; x-ui restart): " reloadCmd
  1388. LOGI "Your reloadcmd is: ${reloadCmd}"
  1389. ;;
  1390. *)
  1391. LOGI "Keep default reloadcmd"
  1392. ;;
  1393. esac
  1394. fi
  1395. # install the certificate
  1396. local installOutput=""
  1397. installOutput=$(~/.acme.sh/acme.sh --installcert -d ${domain} \
  1398. --key-file /root/cert/${domain}/privkey.pem \
  1399. --fullchain-file /root/cert/${domain}/fullchain.pem --reloadcmd "${reloadCmd}" 2>&1)
  1400. local installRc=$?
  1401. echo "${installOutput}"
  1402. local installWroteFiles=0
  1403. if echo "${installOutput}" | grep -q "Installing key to:" && echo "${installOutput}" | grep -q "Installing full chain to:"; then
  1404. installWroteFiles=1
  1405. fi
  1406. if [[ -f "/root/cert/${domain}/privkey.pem" && -f "/root/cert/${domain}/fullchain.pem" && (${installRc} -eq 0 || ${installWroteFiles} -eq 1) ]]; then
  1407. LOGI "Installing certificate succeeded, enabling auto renew..."
  1408. else
  1409. LOGE "Installing certificate failed, exiting."
  1410. if [[ ${cert_exists} -eq 0 ]]; then
  1411. rm -rf ~/.acme.sh/${domain}
  1412. fi
  1413. exit 1
  1414. fi
  1415. # enable auto-renew
  1416. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  1417. if [ $? -ne 0 ]; then
  1418. LOGE "Auto renew failed, certificate details:"
  1419. ls -lah cert/*
  1420. chmod 600 $certPath/privkey.pem
  1421. chmod 644 $certPath/fullchain.pem
  1422. exit 1
  1423. else
  1424. LOGI "Auto renew succeeded, certificate details:"
  1425. ls -lah cert/*
  1426. chmod 600 $certPath/privkey.pem
  1427. chmod 644 $certPath/fullchain.pem
  1428. fi
  1429. # Prompt user to set panel paths after successful certificate installation
  1430. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1431. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1432. local webCertFile="/root/cert/${domain}/fullchain.pem"
  1433. local webKeyFile="/root/cert/${domain}/privkey.pem"
  1434. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1435. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1436. LOGI "Panel paths set for domain: $domain"
  1437. LOGI " - Certificate File: $webCertFile"
  1438. LOGI " - Private Key File: $webKeyFile"
  1439. echo -e "${green}Access URL: https://${domain}:${existing_port}${existing_webBasePath}${plain}"
  1440. restart
  1441. else
  1442. LOGE "Error: Certificate or private key file not found for domain: $domain."
  1443. fi
  1444. else
  1445. LOGI "Skipping panel path setting."
  1446. fi
  1447. }
  1448. ssl_cert_issue_CF() {
  1449. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  1450. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  1451. LOGI "****** Instructions for Use ******"
  1452. LOGI "Follow the steps below to complete the process:"
  1453. LOGI "1. Cloudflare Registered E-mail."
  1454. LOGI "2. Cloudflare Global API Key."
  1455. LOGI "3. The Domain Name."
  1456. LOGI "4. Once the certificate is issued, you will be prompted to set the certificate for the panel (optional)."
  1457. LOGI "5. The script also supports automatic renewal of the SSL certificate after installation."
  1458. confirm "Do you confirm the information and wish to proceed? [y/n]" "y"
  1459. if [ $? -eq 0 ]; then
  1460. # Check for acme.sh first
  1461. if ! command -v ~/.acme.sh/acme.sh &> /dev/null; then
  1462. echo "acme.sh could not be found. We will install it."
  1463. install_acme
  1464. if [ $? -ne 0 ]; then
  1465. LOGE "Install acme failed, please check logs."
  1466. exit 1
  1467. fi
  1468. fi
  1469. CF_Domain=""
  1470. LOGD "Please set a domain name:"
  1471. read -rp "Input your domain here: " CF_Domain
  1472. LOGD "Your domain name is set to: ${CF_Domain}"
  1473. # Set up Cloudflare API details
  1474. CF_GlobalKey=""
  1475. CF_AccountEmail=""
  1476. LOGD "Please set the API key:"
  1477. read -rp "Input your key here: " CF_GlobalKey
  1478. LOGD "Your API key is: ${CF_GlobalKey}"
  1479. LOGD "Please set up registered email:"
  1480. read -rp "Input your email here: " CF_AccountEmail
  1481. LOGD "Your registered email address is: ${CF_AccountEmail}"
  1482. # Set the default CA to Let's Encrypt
  1483. ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt --force
  1484. if [ $? -ne 0 ]; then
  1485. LOGE "Default CA, Let'sEncrypt fail, script exiting..."
  1486. exit 1
  1487. fi
  1488. export CF_Key="${CF_GlobalKey}"
  1489. export CF_Email="${CF_AccountEmail}"
  1490. # Issue the certificate using Cloudflare DNS
  1491. ~/.acme.sh/acme.sh --issue --dns dns_cf -d ${CF_Domain} -d *.${CF_Domain} --log --force
  1492. if [ $? -ne 0 ]; then
  1493. LOGE "Certificate issuance failed, script exiting..."
  1494. exit 1
  1495. else
  1496. LOGI "Certificate issued successfully, Installing..."
  1497. fi
  1498. # Install the certificate
  1499. certPath="/root/cert/${CF_Domain}"
  1500. if [ -d "$certPath" ]; then
  1501. rm -rf ${certPath}
  1502. fi
  1503. mkdir -p ${certPath}
  1504. if [ $? -ne 0 ]; then
  1505. LOGE "Failed to create directory: ${certPath}"
  1506. exit 1
  1507. fi
  1508. reloadCmd="x-ui restart"
  1509. LOGI "Default --reloadcmd for ACME is: ${yellow}x-ui restart"
  1510. LOGI "This command will run on every certificate issue and renew."
  1511. read -rp "Would you like to modify --reloadcmd for ACME? (y/n): " setReloadcmd
  1512. if [[ "$setReloadcmd" == "y" || "$setReloadcmd" == "Y" ]]; then
  1513. echo -e "\n${green}\t1.${plain} Preset: systemctl reload nginx ; x-ui restart"
  1514. echo -e "${green}\t2.${plain} Input your own command"
  1515. echo -e "${green}\t0.${plain} Keep default reloadcmd"
  1516. read -rp "Choose an option: " choice
  1517. case "$choice" in
  1518. 1)
  1519. LOGI "Reloadcmd is: systemctl reload nginx ; x-ui restart"
  1520. reloadCmd="systemctl reload nginx ; x-ui restart"
  1521. ;;
  1522. 2)
  1523. LOGD "It's recommended to put x-ui restart at the end, so it won't raise an error if other services fails"
  1524. read -rp "Please enter your reloadcmd (example: systemctl reload nginx ; x-ui restart): " reloadCmd
  1525. LOGI "Your reloadcmd is: ${reloadCmd}"
  1526. ;;
  1527. *)
  1528. LOGI "Keep default reloadcmd"
  1529. ;;
  1530. esac
  1531. fi
  1532. ~/.acme.sh/acme.sh --installcert -d ${CF_Domain} -d *.${CF_Domain} \
  1533. --key-file ${certPath}/privkey.pem \
  1534. --fullchain-file ${certPath}/fullchain.pem --reloadcmd "${reloadCmd}"
  1535. if [ $? -ne 0 ]; then
  1536. LOGE "Certificate installation failed, script exiting..."
  1537. exit 1
  1538. else
  1539. LOGI "Certificate installed successfully, Turning on automatic updates..."
  1540. fi
  1541. # Enable auto-update
  1542. ~/.acme.sh/acme.sh --upgrade --auto-upgrade
  1543. if [ $? -ne 0 ]; then
  1544. LOGE "Auto update setup failed, script exiting..."
  1545. exit 1
  1546. else
  1547. LOGI "The certificate is installed and auto-renewal is turned on. Specific information is as follows:"
  1548. ls -lah ${certPath}/*
  1549. chmod 600 ${certPath}/privkey.pem
  1550. chmod 644 ${certPath}/fullchain.pem
  1551. fi
  1552. # Prompt user to set panel paths after successful certificate installation
  1553. read -rp "Would you like to set this certificate for the panel? (y/n): " setPanel
  1554. if [[ "$setPanel" == "y" || "$setPanel" == "Y" ]]; then
  1555. local webCertFile="${certPath}/fullchain.pem"
  1556. local webKeyFile="${certPath}/privkey.pem"
  1557. if [[ -f "$webCertFile" && -f "$webKeyFile" ]]; then
  1558. ${xui_folder}/x-ui cert -webCert "$webCertFile" -webCertKey "$webKeyFile"
  1559. LOGI "Panel paths set for domain: $CF_Domain"
  1560. LOGI " - Certificate File: $webCertFile"
  1561. LOGI " - Private Key File: $webKeyFile"
  1562. echo -e "${green}Access URL: https://${CF_Domain}:${existing_port}${existing_webBasePath}${plain}"
  1563. restart
  1564. else
  1565. LOGE "Error: Certificate or private key file not found for domain: $CF_Domain."
  1566. fi
  1567. else
  1568. LOGI "Skipping panel path setting."
  1569. fi
  1570. else
  1571. show_menu
  1572. fi
  1573. }
  1574. run_speedtest() {
  1575. # Check if Speedtest is already installed
  1576. if ! command -v speedtest &> /dev/null; then
  1577. # If not installed, determine installation method
  1578. if command -v snap &> /dev/null; then
  1579. # Use snap to install Speedtest
  1580. echo "Installing Speedtest using snap..."
  1581. snap install speedtest
  1582. else
  1583. # Fallback to using package managers
  1584. local pkg_manager=""
  1585. local speedtest_install_script=""
  1586. if command -v dnf &> /dev/null; then
  1587. pkg_manager="dnf"
  1588. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.rpm.sh"
  1589. elif command -v yum &> /dev/null; then
  1590. pkg_manager="yum"
  1591. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.rpm.sh"
  1592. elif command -v apt-get &> /dev/null; then
  1593. pkg_manager="apt-get"
  1594. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh"
  1595. elif command -v apt &> /dev/null; then
  1596. pkg_manager="apt"
  1597. speedtest_install_script="https://packagecloud.io/install/repositories/ookla/speedtest-cli/script.deb.sh"
  1598. fi
  1599. if [[ -z $pkg_manager ]]; then
  1600. echo "Error: Package manager not found. You may need to install Speedtest manually."
  1601. return 1
  1602. else
  1603. echo "Installing Speedtest using $pkg_manager..."
  1604. curl -s $speedtest_install_script | bash
  1605. $pkg_manager install -y speedtest
  1606. fi
  1607. fi
  1608. fi
  1609. speedtest
  1610. }
  1611. ip_validation() {
  1612. ipv6_regex="^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$"
  1613. ipv4_regex="^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)$"
  1614. }
  1615. iplimit_main() {
  1616. echo -e "\n${green}\t1.${plain} Install Fail2ban and configure IP Limit"
  1617. echo -e "${green}\t2.${plain} Change Ban Duration"
  1618. echo -e "${green}\t3.${plain} Unban Everyone"
  1619. echo -e "${green}\t4.${plain} Ban Logs"
  1620. echo -e "${green}\t5.${plain} Ban an IP Address"
  1621. echo -e "${green}\t6.${plain} Unban an IP Address"
  1622. echo -e "${green}\t7.${plain} Real-Time Logs"
  1623. echo -e "${green}\t8.${plain} Service Status"
  1624. echo -e "${green}\t9.${plain} Service Restart"
  1625. echo -e "${green}\t10.${plain} Uninstall Fail2ban and IP Limit"
  1626. echo -e "${green}\t0.${plain} Back to Main Menu"
  1627. read -rp "Choose an option: " choice
  1628. case "$choice" in
  1629. 0)
  1630. show_menu
  1631. ;;
  1632. 1)
  1633. confirm "Proceed with installation of Fail2ban & IP Limit?" "y"
  1634. if [[ $? == 0 ]]; then
  1635. install_iplimit
  1636. else
  1637. iplimit_main
  1638. fi
  1639. ;;
  1640. 2)
  1641. read -rp "Please enter new Ban Duration in Minutes [default 30]: " NUM
  1642. if [[ $NUM =~ ^[0-9]+$ ]]; then
  1643. create_iplimit_jails ${NUM}
  1644. if [[ $release == "alpine" ]]; then
  1645. rc-service fail2ban restart
  1646. else
  1647. systemctl restart fail2ban
  1648. fi
  1649. else
  1650. echo -e "${red}${NUM} is not a number! Please, try again.${plain}"
  1651. fi
  1652. iplimit_main
  1653. ;;
  1654. 3)
  1655. confirm "Proceed with Unbanning everyone from IP Limit jail?" "y"
  1656. if [[ $? == 0 ]]; then
  1657. fail2ban-client reload --restart --unban 3x-ipl
  1658. truncate -s 0 "${iplimit_banned_log_path}"
  1659. echo -e "${green}All users Unbanned successfully.${plain}"
  1660. iplimit_main
  1661. else
  1662. echo -e "${yellow}Cancelled.${plain}"
  1663. fi
  1664. iplimit_main
  1665. ;;
  1666. 4)
  1667. show_banlog
  1668. iplimit_main
  1669. ;;
  1670. 5)
  1671. read -rp "Enter the IP address you want to ban: " ban_ip
  1672. ip_validation
  1673. if [[ $ban_ip =~ $ipv4_regex || $ban_ip =~ $ipv6_regex ]]; then
  1674. fail2ban-client set 3x-ipl banip "$ban_ip"
  1675. echo -e "${green}IP Address ${ban_ip} has been banned successfully.${plain}"
  1676. else
  1677. echo -e "${red}Invalid IP address format! Please try again.${plain}"
  1678. fi
  1679. iplimit_main
  1680. ;;
  1681. 6)
  1682. read -rp "Enter the IP address you want to unban: " unban_ip
  1683. ip_validation
  1684. if [[ $unban_ip =~ $ipv4_regex || $unban_ip =~ $ipv6_regex ]]; then
  1685. fail2ban-client set 3x-ipl unbanip "$unban_ip"
  1686. echo -e "${green}IP Address ${unban_ip} has been unbanned successfully.${plain}"
  1687. else
  1688. echo -e "${red}Invalid IP address format! Please try again.${plain}"
  1689. fi
  1690. iplimit_main
  1691. ;;
  1692. 7)
  1693. tail -f /var/log/fail2ban.log
  1694. iplimit_main
  1695. ;;
  1696. 8)
  1697. service fail2ban status
  1698. iplimit_main
  1699. ;;
  1700. 9)
  1701. if [[ $release == "alpine" ]]; then
  1702. rc-service fail2ban restart
  1703. else
  1704. systemctl restart fail2ban
  1705. fi
  1706. iplimit_main
  1707. ;;
  1708. 10)
  1709. remove_iplimit
  1710. iplimit_main
  1711. ;;
  1712. *)
  1713. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1714. iplimit_main
  1715. ;;
  1716. esac
  1717. }
  1718. install_iplimit() {
  1719. if ! command -v fail2ban-client &> /dev/null; then
  1720. echo -e "${green}Fail2ban is not installed. Installing now...!${plain}\n"
  1721. # Install fail2ban together with nftables. Recent fail2ban packages
  1722. # default to `banaction = nftables-multiport` in /etc/fail2ban/jail.conf,
  1723. # but the `nftables` package isn't pulled in as a dependency on most
  1724. # minimal server images (Debian 12+, Ubuntu 24+, fresh RHEL-family).
  1725. # Without `nft` in PATH the default sshd jail fails to ban with
  1726. # stderr: '/bin/sh: 1: nft: not found'
  1727. # even though our own 3x-ipl jail uses iptables. Bundling the binary
  1728. # at install time prevents that confusing log spam for new installs.
  1729. case "${release}" in
  1730. ubuntu)
  1731. apt-get update
  1732. if [[ "${os_version}" -ge 24 ]]; then
  1733. apt-get install python3-pip -y
  1734. python3 -m pip install pyasynchat --break-system-packages
  1735. fi
  1736. apt-get install fail2ban nftables -y
  1737. ;;
  1738. debian)
  1739. apt-get update
  1740. if [ "$os_version" -ge 12 ]; then
  1741. apt-get install -y python3-systemd
  1742. fi
  1743. apt-get install -y fail2ban nftables
  1744. ;;
  1745. armbian)
  1746. apt-get update && apt-get install fail2ban nftables -y
  1747. ;;
  1748. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1749. dnf -y update && dnf -y install fail2ban nftables
  1750. ;;
  1751. centos)
  1752. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1753. yum update -y && yum install epel-release -y
  1754. yum -y install fail2ban nftables
  1755. else
  1756. dnf -y update && dnf -y install fail2ban nftables
  1757. fi
  1758. ;;
  1759. arch | manjaro | parch)
  1760. pacman -Syu --noconfirm fail2ban nftables
  1761. ;;
  1762. alpine)
  1763. apk add fail2ban nftables
  1764. ;;
  1765. *)
  1766. echo -e "${red}Unsupported operating system. Please check the script and install the necessary packages manually.${plain}\n"
  1767. exit 1
  1768. ;;
  1769. esac
  1770. if ! command -v fail2ban-client &> /dev/null; then
  1771. echo -e "${red}Fail2ban installation failed.${plain}\n"
  1772. exit 1
  1773. fi
  1774. echo -e "${green}Fail2ban installed successfully!${plain}\n"
  1775. else
  1776. echo -e "${yellow}Fail2ban is already installed.${plain}\n"
  1777. fi
  1778. echo -e "${green}Configuring IP Limit...${plain}\n"
  1779. # make sure there's no conflict for jail files
  1780. iplimit_remove_conflicts
  1781. # Check if log file exists
  1782. if ! test -f "${iplimit_banned_log_path}"; then
  1783. touch ${iplimit_banned_log_path}
  1784. fi
  1785. # Check if service log file exists so fail2ban won't return error
  1786. if ! test -f "${iplimit_log_path}"; then
  1787. touch ${iplimit_log_path}
  1788. fi
  1789. # Create the iplimit jail files
  1790. # we didn't pass the bantime here to use the default value
  1791. create_iplimit_jails
  1792. # Launching fail2ban
  1793. if [[ $release == "alpine" ]]; then
  1794. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  1795. rc-service fail2ban start
  1796. else
  1797. rc-service fail2ban restart
  1798. fi
  1799. rc-update add fail2ban
  1800. else
  1801. if ! systemctl is-active --quiet fail2ban; then
  1802. systemctl start fail2ban
  1803. else
  1804. systemctl restart fail2ban
  1805. fi
  1806. systemctl enable fail2ban
  1807. fi
  1808. echo -e "${green}IP Limit installed and configured successfully!${plain}\n"
  1809. before_show_menu
  1810. }
  1811. remove_iplimit() {
  1812. echo -e "${green}\t1.${plain} Only remove IP Limit configurations"
  1813. echo -e "${green}\t2.${plain} Uninstall Fail2ban and IP Limit"
  1814. echo -e "${green}\t0.${plain} Back to Main Menu"
  1815. read -rp "Choose an option: " num
  1816. case "$num" in
  1817. 1)
  1818. rm -f /etc/fail2ban/filter.d/3x-ipl.conf
  1819. rm -f /etc/fail2ban/action.d/3x-ipl.conf
  1820. rm -f /etc/fail2ban/jail.d/3x-ipl.conf
  1821. if [[ $release == "alpine" ]]; then
  1822. rc-service fail2ban restart
  1823. else
  1824. systemctl restart fail2ban
  1825. fi
  1826. echo -e "${green}IP Limit removed successfully!${plain}\n"
  1827. before_show_menu
  1828. ;;
  1829. 2)
  1830. rm -rf /etc/fail2ban
  1831. if [[ $release == "alpine" ]]; then
  1832. rc-service fail2ban stop
  1833. else
  1834. systemctl stop fail2ban
  1835. fi
  1836. case "${release}" in
  1837. ubuntu | debian | armbian)
  1838. apt-get remove -y fail2ban
  1839. apt-get purge -y fail2ban -y
  1840. apt-get autoremove -y
  1841. ;;
  1842. fedora | amzn | virtuozzo | rhel | almalinux | rocky | ol)
  1843. dnf remove fail2ban -y
  1844. dnf autoremove -y
  1845. ;;
  1846. centos)
  1847. if [[ "${VERSION_ID}" =~ ^7 ]]; then
  1848. yum remove fail2ban -y
  1849. yum autoremove -y
  1850. else
  1851. dnf remove fail2ban -y
  1852. dnf autoremove -y
  1853. fi
  1854. ;;
  1855. arch | manjaro | parch)
  1856. pacman -Rns --noconfirm fail2ban
  1857. ;;
  1858. alpine)
  1859. apk del fail2ban
  1860. ;;
  1861. *)
  1862. echo -e "${red}Unsupported operating system. Please uninstall Fail2ban manually.${plain}\n"
  1863. exit 1
  1864. ;;
  1865. esac
  1866. echo -e "${green}Fail2ban and IP Limit removed successfully!${plain}\n"
  1867. before_show_menu
  1868. ;;
  1869. 0)
  1870. show_menu
  1871. ;;
  1872. *)
  1873. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  1874. remove_iplimit
  1875. ;;
  1876. esac
  1877. }
  1878. show_banlog() {
  1879. local system_log="/var/log/fail2ban.log"
  1880. echo -e "${green}Checking ban logs...${plain}\n"
  1881. if [[ $release == "alpine" ]]; then
  1882. if [[ $(rc-service fail2ban status | grep -F 'status: started' -c) == 0 ]]; then
  1883. echo -e "${red}Fail2ban service is not running!${plain}\n"
  1884. return 1
  1885. fi
  1886. else
  1887. if ! systemctl is-active --quiet fail2ban; then
  1888. echo -e "${red}Fail2ban service is not running!${plain}\n"
  1889. return 1
  1890. fi
  1891. fi
  1892. if [[ -f "$system_log" ]]; then
  1893. echo -e "${green}Recent system ban activities from fail2ban.log:${plain}"
  1894. grep "3x-ipl" "$system_log" | grep -E "Ban|Unban" | tail -n 10 || echo -e "${yellow}No recent system ban activities found${plain}"
  1895. echo ""
  1896. fi
  1897. if [[ -f "${iplimit_banned_log_path}" ]]; then
  1898. echo -e "${green}3X-IPL ban log entries:${plain}"
  1899. if [[ -s "${iplimit_banned_log_path}" ]]; then
  1900. grep -v "INIT" "${iplimit_banned_log_path}" | tail -n 10 || echo -e "${yellow}No ban entries found${plain}"
  1901. else
  1902. echo -e "${yellow}Ban log file is empty${plain}"
  1903. fi
  1904. else
  1905. echo -e "${red}Ban log file not found at: ${iplimit_banned_log_path}${plain}"
  1906. fi
  1907. echo -e "\n${green}Current jail status:${plain}"
  1908. fail2ban-client status 3x-ipl || echo -e "${yellow}Unable to get jail status${plain}"
  1909. }
  1910. create_iplimit_jails() {
  1911. # Use default bantime if not passed => 30 minutes
  1912. local bantime="${1:-30}"
  1913. # Uncomment 'allowipv6 = auto' in fail2ban.conf
  1914. sed -i 's/#allowipv6 = auto/allowipv6 = auto/g' /etc/fail2ban/fail2ban.conf
  1915. # On Debian 12+ fail2ban's default backend should be changed to systemd
  1916. if [[ "${release}" == "debian" && ${os_version} -ge 12 ]]; then
  1917. sed -i '0,/action =/s/backend = auto/backend = systemd/' /etc/fail2ban/jail.conf
  1918. fi
  1919. cat << EOF > /etc/fail2ban/jail.d/3x-ipl.conf
  1920. [3x-ipl]
  1921. enabled=true
  1922. backend=auto
  1923. filter=3x-ipl
  1924. action=3x-ipl
  1925. logpath=${iplimit_log_path}
  1926. maxretry=1
  1927. findtime=32
  1928. bantime=${bantime}m
  1929. EOF
  1930. cat << EOF > /etc/fail2ban/filter.d/3x-ipl.conf
  1931. [Definition]
  1932. datepattern = ^%%Y/%%m/%%d %%H:%%M:%%S
  1933. failregex = \[LIMIT_IP\]\s*Email\s*=\s*<F-USER>.+</F-USER>\s*\|\|\s*Disconnecting OLD IP\s*=\s*<ADDR>\s*\|\|\s*Timestamp\s*=\s*\d+
  1934. ignoreregex =
  1935. EOF
  1936. cat << EOF > /etc/fail2ban/action.d/3x-ipl.conf
  1937. [INCLUDES]
  1938. before = iptables-allports.conf
  1939. [Definition]
  1940. actionstart = <iptables> -N f2b-<name>
  1941. <iptables> -A f2b-<name> -j <returntype>
  1942. <iptables> -I <chain> -p <protocol> -j f2b-<name>
  1943. actionstop = <iptables> -D <chain> -p <protocol> -j f2b-<name>
  1944. <actionflush>
  1945. <iptables> -X f2b-<name>
  1946. actioncheck = <iptables> -n -L <chain> | grep -q 'f2b-<name>[ \t]'
  1947. actionban = <iptables> -I f2b-<name> 1 -s <ip> -j <blocktype>
  1948. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") BAN [Email] = <F-USER> [IP] = <ip> banned for <bantime> seconds." >> ${iplimit_banned_log_path}
  1949. actionunban = <iptables> -D f2b-<name> -s <ip> -j <blocktype>
  1950. echo "\$(date +"%%Y/%%m/%%d %%H:%%M:%%S") UNBAN [Email] = <F-USER> [IP] = <ip> unbanned." >> ${iplimit_banned_log_path}
  1951. [Init]
  1952. name = default
  1953. protocol = tcp
  1954. chain = INPUT
  1955. EOF
  1956. echo -e "${green}Ip Limit jail files created with a bantime of ${bantime} minutes.${plain}"
  1957. }
  1958. iplimit_remove_conflicts() {
  1959. local jail_files=(
  1960. /etc/fail2ban/jail.conf
  1961. /etc/fail2ban/jail.local
  1962. )
  1963. for file in "${jail_files[@]}"; do
  1964. # Check for [3x-ipl] config in jail file then remove it
  1965. if test -f "${file}" && grep -qw '3x-ipl' ${file}; then
  1966. sed -i "/\[3x-ipl\]/,/^$/d" ${file}
  1967. echo -e "${yellow}Removing conflicts of [3x-ipl] in jail (${file})!${plain}\n"
  1968. fi
  1969. done
  1970. }
  1971. SSH_port_forwarding() {
  1972. local URL_lists=(
  1973. "https://api4.ipify.org"
  1974. "https://ipv4.icanhazip.com"
  1975. "https://v4.api.ipinfo.io/ip"
  1976. "https://ipv4.myexternalip.com/raw"
  1977. "https://4.ident.me"
  1978. "https://check-host.net/ip"
  1979. )
  1980. local server_ip=""
  1981. for ip_address in "${URL_lists[@]}"; do
  1982. local response=$(curl -s -w "\n%{http_code}" --max-time 3 "${ip_address}" 2> /dev/null)
  1983. local http_code=$(echo "$response" | tail -n1)
  1984. local ip_result=$(echo "$response" | head -n-1 | tr -d '[:space:]"')
  1985. if [[ "${http_code}" == "200" && "${ip_result}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1986. server_ip="${ip_result}"
  1987. break
  1988. fi
  1989. done
  1990. if [[ -z "$server_ip" ]]; then
  1991. echo -e "${yellow}Could not auto-detect server IP from any provider.${plain}"
  1992. while [[ -z "$server_ip" ]]; do
  1993. read -rp "Please enter your server's public IPv4 address: " server_ip
  1994. server_ip="${server_ip// /}"
  1995. if [[ ! "$server_ip" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  1996. echo -e "${red}Invalid IPv4 address. Please try again.${plain}"
  1997. server_ip=""
  1998. fi
  1999. done
  2000. fi
  2001. local existing_webBasePath=$(${xui_folder}/x-ui setting -show true | grep -Eo 'webBasePath: .+' | awk '{print $2}')
  2002. local existing_port=$(${xui_folder}/x-ui setting -show true | grep -Eo 'port: .+' | awk '{print $2}')
  2003. local existing_listenIP=$(${xui_folder}/x-ui setting -getListen true | grep -Eo 'listenIP: .+' | awk '{print $2}')
  2004. local existing_cert=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'cert: .+' | awk '{print $2}')
  2005. local existing_key=$(${xui_folder}/x-ui setting -getCert true | grep -Eo 'key: .+' | awk '{print $2}')
  2006. local config_listenIP=""
  2007. local listen_choice=""
  2008. if [[ -n "$existing_cert" && -n "$existing_key" ]]; then
  2009. echo -e "${green}Panel is secure with SSL.${plain}"
  2010. before_show_menu
  2011. fi
  2012. if [[ -z "$existing_cert" && -z "$existing_key" && (-z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0") ]]; then
  2013. echo -e "\n${red}Warning: No Cert and Key found! The panel is not secure.${plain}"
  2014. echo "Please obtain a certificate or set up SSH port forwarding."
  2015. fi
  2016. if [[ -n "$existing_listenIP" && "$existing_listenIP" != "0.0.0.0" && (-z "$existing_cert" && -z "$existing_key") ]]; then
  2017. echo -e "\n${green}Current SSH Port Forwarding Configuration:${plain}"
  2018. echo -e "Standard SSH command:"
  2019. echo -e "${yellow}ssh -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2020. echo -e "\nIf using SSH key:"
  2021. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${existing_listenIP}:${existing_port} root@${server_ip}${plain}"
  2022. echo -e "\nAfter connecting, access the panel at:"
  2023. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2024. fi
  2025. echo -e "\nChoose an option:"
  2026. echo -e "${green}1.${plain} Set listen IP"
  2027. echo -e "${green}2.${plain} Clear listen IP"
  2028. echo -e "${green}0.${plain} Back to Main Menu"
  2029. read -rp "Choose an option: " num
  2030. case "$num" in
  2031. 1)
  2032. if [[ -z "$existing_listenIP" || "$existing_listenIP" == "0.0.0.0" ]]; then
  2033. echo -e "\nNo listenIP configured. Choose an option:"
  2034. echo -e "1. Use default IP (127.0.0.1)"
  2035. echo -e "2. Set a custom IP"
  2036. read -rp "Select an option (1 or 2): " listen_choice
  2037. config_listenIP="127.0.0.1"
  2038. [[ "$listen_choice" == "2" ]] && read -rp "Enter custom IP to listen on: " config_listenIP
  2039. ${xui_folder}/x-ui setting -listenIP "${config_listenIP}" > /dev/null 2>&1
  2040. echo -e "${green}listen IP has been set to ${config_listenIP}.${plain}"
  2041. echo -e "\n${green}SSH Port Forwarding Configuration:${plain}"
  2042. echo -e "Standard SSH command:"
  2043. echo -e "${yellow}ssh -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2044. echo -e "\nIf using SSH key:"
  2045. echo -e "${yellow}ssh -i <sshkeypath> -L 2222:${config_listenIP}:${existing_port} root@${server_ip}${plain}"
  2046. echo -e "\nAfter connecting, access the panel at:"
  2047. echo -e "${yellow}http://localhost:2222${existing_webBasePath}${plain}"
  2048. restart
  2049. else
  2050. config_listenIP="${existing_listenIP}"
  2051. echo -e "${green}Current listen IP is already set to ${config_listenIP}.${plain}"
  2052. fi
  2053. ;;
  2054. 2)
  2055. ${xui_folder}/x-ui setting -listenIP 0.0.0.0 > /dev/null 2>&1
  2056. echo -e "${green}Listen IP has been cleared.${plain}"
  2057. restart
  2058. ;;
  2059. 0)
  2060. show_menu
  2061. ;;
  2062. *)
  2063. echo -e "${red}Invalid option. Please select a valid number.${plain}\n"
  2064. SSH_port_forwarding
  2065. ;;
  2066. esac
  2067. }
  2068. show_usage() {
  2069. echo -e "┌────────────────────────────────────────────────────────────────┐
  2070. │ ${blue}x-ui control menu usages (subcommands):${plain} │
  2071. │ │
  2072. │ ${blue}x-ui${plain} - Admin Management Script │
  2073. │ ${blue}x-ui start${plain} - Start │
  2074. │ ${blue}x-ui stop${plain} - Stop │
  2075. │ ${blue}x-ui restart${plain} - Restart │
  2076. | ${blue}x-ui restart-xray${plain} - Restart Xray │
  2077. │ ${blue}x-ui status${plain} - Current Status │
  2078. │ ${blue}x-ui settings${plain} - Current Settings │
  2079. │ ${blue}x-ui enable${plain} - Enable Autostart on OS Startup │
  2080. │ ${blue}x-ui disable${plain} - Disable Autostart on OS Startup │
  2081. │ ${blue}x-ui log${plain} - Check logs │
  2082. │ ${blue}x-ui banlog${plain} - Check Fail2ban ban logs │
  2083. │ ${blue}x-ui update${plain} - Update │
  2084. │ ${blue}x-ui update-all-geofiles${plain} - Update all geo files │
  2085. │ ${blue}x-ui legacy${plain} - Legacy version │
  2086. │ ${blue}x-ui install${plain} - Install │
  2087. │ ${blue}x-ui uninstall${plain} - Uninstall │
  2088. └────────────────────────────────────────────────────────────────┘"
  2089. }
  2090. show_menu() {
  2091. echo -e "
  2092. ╔────────────────────────────────────────────────╗
  2093. │ ${green}3X-UI Panel Management Script${plain} │
  2094. │ ${green}0.${plain} Exit Script │
  2095. │────────────────────────────────────────────────│
  2096. │ ${green}1.${plain} Install │
  2097. │ ${green}2.${plain} Update │
  2098. │ ${green}3.${plain} Update Menu │
  2099. │ ${green}4.${plain} Legacy Version │
  2100. │ ${green}5.${plain} Uninstall │
  2101. │────────────────────────────────────────────────│
  2102. │ ${green}6.${plain} Reset Username & Password │
  2103. │ ${green}7.${plain} Reset Web Base Path │
  2104. │ ${green}8.${plain} Reset Settings │
  2105. │ ${green}9.${plain} Change Port │
  2106. │ ${green}10.${plain} View Current Settings │
  2107. │────────────────────────────────────────────────│
  2108. │ ${green}11.${plain} Start │
  2109. │ ${green}12.${plain} Stop │
  2110. │ ${green}13.${plain} Restart │
  2111. | ${green}14.${plain} Restart Xray │
  2112. │ ${green}15.${plain} Check Status │
  2113. │ ${green}16.${plain} Logs Management │
  2114. │────────────────────────────────────────────────│
  2115. │ ${green}17.${plain} Enable Autostart │
  2116. │ ${green}18.${plain} Disable Autostart │
  2117. │────────────────────────────────────────────────│
  2118. │ ${green}19.${plain} SSL Certificate Management │
  2119. │ ${green}20.${plain} Cloudflare SSL Certificate │
  2120. │ ${green}21.${plain} IP Limit Management │
  2121. │ ${green}22.${plain} Firewall Management │
  2122. │ ${green}23.${plain} SSH Port Forwarding Management │
  2123. │────────────────────────────────────────────────│
  2124. │ ${green}24.${plain} Enable BBR │
  2125. │ ${green}25.${plain} Update Geo Files │
  2126. │ ${green}26.${plain} Speedtest by Ookla │
  2127. ╚────────────────────────────────────────────────╝
  2128. "
  2129. show_status
  2130. echo && read -rp "Please enter your selection [0-26]: " num
  2131. case "${num}" in
  2132. 0)
  2133. exit 0
  2134. ;;
  2135. 1)
  2136. check_uninstall && install
  2137. ;;
  2138. 2)
  2139. check_install && update
  2140. ;;
  2141. 3)
  2142. check_install && update_menu
  2143. ;;
  2144. 4)
  2145. check_install && legacy_version
  2146. ;;
  2147. 5)
  2148. check_install && uninstall
  2149. ;;
  2150. 6)
  2151. check_install && reset_user
  2152. ;;
  2153. 7)
  2154. check_install && reset_webbasepath
  2155. ;;
  2156. 8)
  2157. check_install && reset_config
  2158. ;;
  2159. 9)
  2160. check_install && set_port
  2161. ;;
  2162. 10)
  2163. check_install && check_config
  2164. ;;
  2165. 11)
  2166. check_install && start
  2167. ;;
  2168. 12)
  2169. check_install && stop
  2170. ;;
  2171. 13)
  2172. check_install && restart
  2173. ;;
  2174. 14)
  2175. check_install && restart_xray
  2176. ;;
  2177. 15)
  2178. check_install && status
  2179. ;;
  2180. 16)
  2181. check_install && show_log
  2182. ;;
  2183. 17)
  2184. check_install && enable
  2185. ;;
  2186. 18)
  2187. check_install && disable
  2188. ;;
  2189. 19)
  2190. ssl_cert_issue_main
  2191. ;;
  2192. 20)
  2193. ssl_cert_issue_CF
  2194. ;;
  2195. 21)
  2196. iplimit_main
  2197. ;;
  2198. 22)
  2199. firewall_menu
  2200. ;;
  2201. 23)
  2202. SSH_port_forwarding
  2203. ;;
  2204. 24)
  2205. bbr_menu
  2206. ;;
  2207. 25)
  2208. update_geo
  2209. ;;
  2210. 26)
  2211. run_speedtest
  2212. ;;
  2213. *)
  2214. LOGE "Please enter the correct number [0-26]"
  2215. ;;
  2216. esac
  2217. }
  2218. if [[ $# > 0 ]]; then
  2219. case $1 in
  2220. "start")
  2221. check_install 0 && start 0
  2222. ;;
  2223. "stop")
  2224. check_install 0 && stop 0
  2225. ;;
  2226. "restart")
  2227. check_install 0 && restart 0
  2228. ;;
  2229. "restart-xray")
  2230. check_install 0 && restart_xray 0
  2231. ;;
  2232. "status")
  2233. check_install 0 && status 0
  2234. ;;
  2235. "settings")
  2236. check_install 0 && check_config 0
  2237. ;;
  2238. "enable")
  2239. check_install 0 && enable 0
  2240. ;;
  2241. "disable")
  2242. check_install 0 && disable 0
  2243. ;;
  2244. "log")
  2245. check_install 0 && show_log 0
  2246. ;;
  2247. "banlog")
  2248. check_install 0 && show_banlog 0
  2249. ;;
  2250. "update")
  2251. check_install 0 && update 0
  2252. ;;
  2253. "legacy")
  2254. check_install 0 && legacy_version 0
  2255. ;;
  2256. "install")
  2257. check_uninstall 0 && install 0
  2258. ;;
  2259. "uninstall")
  2260. check_install 0 && uninstall 0
  2261. ;;
  2262. "update-all-geofiles")
  2263. check_install 0 && update_all_geofiles 0 && restart 0
  2264. ;;
  2265. *) show_usage ;;
  2266. esac
  2267. else
  2268. show_menu
  2269. fi