1
0

check_client_ip_job.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. package job
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "regexp"
  11. "runtime"
  12. "sort"
  13. "time"
  14. "github.com/mhsanaei/3x-ui/v3/database"
  15. "github.com/mhsanaei/3x-ui/v3/database/model"
  16. "github.com/mhsanaei/3x-ui/v3/logger"
  17. "github.com/mhsanaei/3x-ui/v3/xray"
  18. )
  19. // IPWithTimestamp tracks an IP address with its last seen timestamp
  20. type IPWithTimestamp struct {
  21. IP string `json:"ip"`
  22. Timestamp int64 `json:"timestamp"`
  23. }
  24. // CheckClientIpJob monitors client IP addresses from access logs and manages IP blocking based on configured limits.
  25. type CheckClientIpJob struct {
  26. lastClear int64
  27. disAllowedIps []string
  28. }
  29. var job *CheckClientIpJob
  30. const defaultXrayAPIPort = 62789
  31. // ipStaleAfterSeconds controls how long a client IP kept in the
  32. // per-client tracking table (model.InboundClientIps.Ips) is considered
  33. // still "active" before it's evicted during the next scan.
  34. //
  35. // Without this eviction, an IP that connected once and then went away
  36. // keeps sitting in the table with its old timestamp. Because the
  37. // excess-IP selector sorts ascending ("newest wins, oldest loses") to
  38. // protect the most recent connections, that stale entry keeps
  39. // occupying a slot and the IP that is *actually* currently using the
  40. // config gets classified as "new excess" and banned by fail2ban on
  41. // every single run — producing the continuous ban loop from #4077.
  42. //
  43. // 30 minutes is chosen so an actively-streaming client (where xray
  44. // emits a fresh `accepted` log line whenever it opens a new TCP) will
  45. // always refresh its timestamp well within the window, but a client
  46. // that has really stopped using the config will drop out of the table
  47. // in a bounded time and free its slot.
  48. const ipStaleAfterSeconds = int64(30 * 60)
  49. // NewCheckClientIpJob creates a new client IP monitoring job instance.
  50. func NewCheckClientIpJob() *CheckClientIpJob {
  51. job = new(CheckClientIpJob)
  52. return job
  53. }
  54. func (j *CheckClientIpJob) Run() {
  55. if j.lastClear == 0 {
  56. j.lastClear = time.Now().Unix()
  57. }
  58. shouldClearAccessLog := false
  59. fail2BanEnabled := isFail2BanEnabled()
  60. iplimitActive := fail2BanEnabled && j.hasLimitIp()
  61. f2bInstalled := false
  62. if iplimitActive {
  63. f2bInstalled = j.checkFail2BanInstalled()
  64. }
  65. isAccessLogAvailable := j.checkAccessLogAvailable(iplimitActive)
  66. if isAccessLogAvailable {
  67. if runtime.GOOS == "windows" {
  68. if iplimitActive {
  69. shouldClearAccessLog = j.processLogFile()
  70. }
  71. } else {
  72. if iplimitActive {
  73. if f2bInstalled {
  74. shouldClearAccessLog = j.processLogFile()
  75. } else {
  76. logger.Warning("[LimitIP] Fail2Ban is not installed, Please install Fail2Ban from the x-ui bash menu.")
  77. }
  78. }
  79. }
  80. }
  81. if shouldClearAccessLog || (isAccessLogAvailable && time.Now().Unix()-j.lastClear > 3600) {
  82. j.clearAccessLog()
  83. }
  84. }
  85. func (j *CheckClientIpJob) clearAccessLog() {
  86. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  87. j.checkError(err)
  88. defer logAccessP.Close()
  89. accessLogPath, err := xray.GetAccessLogPath()
  90. j.checkError(err)
  91. file, err := os.Open(accessLogPath)
  92. j.checkError(err)
  93. defer file.Close()
  94. _, err = io.Copy(logAccessP, file)
  95. j.checkError(err)
  96. err = os.Truncate(accessLogPath, 0)
  97. j.checkError(err)
  98. j.lastClear = time.Now().Unix()
  99. }
  100. func (j *CheckClientIpJob) hasLimitIp() bool {
  101. db := database.GetDB()
  102. var inbounds []*model.Inbound
  103. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  104. if err != nil {
  105. return false
  106. }
  107. for _, inbound := range inbounds {
  108. if inbound.Settings == "" {
  109. continue
  110. }
  111. settings := map[string][]model.Client{}
  112. json.Unmarshal([]byte(inbound.Settings), &settings)
  113. clients := settings["clients"]
  114. for _, client := range clients {
  115. limitIp := client.LimitIP
  116. if limitIp > 0 {
  117. return true
  118. }
  119. }
  120. }
  121. return false
  122. }
  123. func (j *CheckClientIpJob) processLogFile() bool {
  124. ipRegex := regexp.MustCompile(`from (?:tcp:|udp:)?\[?([0-9a-fA-F\.:]+)\]?:\d+ accepted`)
  125. emailRegex := regexp.MustCompile(`email: (.+)$`)
  126. timestampRegex := regexp.MustCompile(`^(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})`)
  127. accessLogPath, _ := xray.GetAccessLogPath()
  128. file, _ := os.Open(accessLogPath)
  129. defer file.Close()
  130. // Track IPs with their last seen timestamp
  131. inboundClientIps := make(map[string]map[string]int64, 100)
  132. scanner := bufio.NewScanner(file)
  133. for scanner.Scan() {
  134. line := scanner.Text()
  135. ipMatches := ipRegex.FindStringSubmatch(line)
  136. if len(ipMatches) < 2 {
  137. continue
  138. }
  139. ip := ipMatches[1]
  140. if ip == "127.0.0.1" || ip == "::1" {
  141. continue
  142. }
  143. emailMatches := emailRegex.FindStringSubmatch(line)
  144. if len(emailMatches) < 2 {
  145. continue
  146. }
  147. email := emailMatches[1]
  148. // Extract timestamp from log line
  149. var timestamp int64
  150. timestampMatches := timestampRegex.FindStringSubmatch(line)
  151. if len(timestampMatches) >= 2 {
  152. t, err := time.ParseInLocation("2006/01/02 15:04:05", timestampMatches[1], time.Local)
  153. if err == nil {
  154. timestamp = t.Unix()
  155. } else {
  156. timestamp = time.Now().Unix()
  157. }
  158. } else {
  159. timestamp = time.Now().Unix()
  160. }
  161. if _, exists := inboundClientIps[email]; !exists {
  162. inboundClientIps[email] = make(map[string]int64)
  163. }
  164. // Update timestamp - keep the latest
  165. if existingTime, ok := inboundClientIps[email][ip]; !ok || timestamp > existingTime {
  166. inboundClientIps[email][ip] = timestamp
  167. }
  168. }
  169. if err := scanner.Err(); err != nil {
  170. j.checkError(err)
  171. }
  172. shouldCleanLog := false
  173. for email, ipTimestamps := range inboundClientIps {
  174. // Convert to IPWithTimestamp slice
  175. ipsWithTime := make([]IPWithTimestamp, 0, len(ipTimestamps))
  176. for ip, timestamp := range ipTimestamps {
  177. ipsWithTime = append(ipsWithTime, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  178. }
  179. clientIpsRecord, err := j.getInboundClientIps(email)
  180. if err != nil {
  181. j.addInboundClientIps(email, ipsWithTime)
  182. continue
  183. }
  184. shouldCleanLog = j.updateInboundClientIps(clientIpsRecord, email, ipsWithTime) || shouldCleanLog
  185. }
  186. return shouldCleanLog
  187. }
  188. // mergeClientIps combines the persisted (old) and freshly observed (new)
  189. // IP-with-timestamp lists for a single client into a map. An entry is
  190. // dropped if its last-seen timestamp is older than staleCutoff.
  191. //
  192. // Extracted as a helper so updateInboundClientIps can stay DB-oriented
  193. // and the merge policy can be exercised by a unit test.
  194. func mergeClientIps(old, new []IPWithTimestamp, staleCutoff int64) map[string]int64 {
  195. ipMap := make(map[string]int64, len(old)+len(new))
  196. for _, ipTime := range old {
  197. if ipTime.Timestamp < staleCutoff {
  198. continue
  199. }
  200. ipMap[ipTime.IP] = ipTime.Timestamp
  201. }
  202. for _, ipTime := range new {
  203. if ipTime.Timestamp < staleCutoff {
  204. continue
  205. }
  206. if existingTime, ok := ipMap[ipTime.IP]; !ok || ipTime.Timestamp > existingTime {
  207. ipMap[ipTime.IP] = ipTime.Timestamp
  208. }
  209. }
  210. return ipMap
  211. }
  212. // partitionLiveIps splits the merged ip map into live (seen in the
  213. // current scan) and historical (only in the db blob, still inside the
  214. // staleness window).
  215. //
  216. // only live ips count toward the per-client limit. historical ones stay
  217. // in the db so the panel keeps showing them, but they must not take a
  218. // live slot or get re-banned. the 30min cutoff alone isn't tight enough:
  219. // an ip that stopped connecting a few minutes ago still looks fresh to
  220. // mergeClientIps, and without this split it would keep triggering
  221. // fail2ban even though it isn't currently connected. see #4077 / #4091.
  222. //
  223. // live is sorted ascending by timestamp (oldest → newest), so we keep
  224. // the most recent entries at the end of the slice (last IP wins).
  225. func partitionLiveIps(ipMap map[string]int64, observedThisScan map[string]bool) (live, historical []IPWithTimestamp) {
  226. live = make([]IPWithTimestamp, 0, len(observedThisScan))
  227. historical = make([]IPWithTimestamp, 0, len(ipMap))
  228. for ip, ts := range ipMap {
  229. entry := IPWithTimestamp{IP: ip, Timestamp: ts}
  230. if observedThisScan[ip] {
  231. live = append(live, entry)
  232. } else {
  233. historical = append(historical, entry)
  234. }
  235. }
  236. sort.Slice(live, func(i, j int) bool { return live[i].Timestamp < live[j].Timestamp })
  237. sort.Slice(historical, func(i, j int) bool { return historical[i].Timestamp < historical[j].Timestamp })
  238. return live, historical
  239. }
  240. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  241. if !isFail2BanEnabled() {
  242. return false
  243. }
  244. cmd := "fail2ban-client"
  245. args := []string{"-h"}
  246. err := exec.Command(cmd, args...).Run()
  247. return err == nil
  248. }
  249. func isFail2BanEnabled() bool {
  250. value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
  251. return !ok || value == "true"
  252. }
  253. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  254. accessLogPath, err := xray.GetAccessLogPath()
  255. if err != nil {
  256. return false
  257. }
  258. if accessLogPath == "none" || accessLogPath == "" {
  259. if iplimitActive {
  260. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  261. }
  262. return false
  263. }
  264. return true
  265. }
  266. func (j *CheckClientIpJob) checkError(e error) {
  267. if e != nil {
  268. logger.Warning("client ip job err:", e)
  269. }
  270. }
  271. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  272. db := database.GetDB()
  273. InboundClientIps := &model.InboundClientIps{}
  274. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  275. if err != nil {
  276. return nil, err
  277. }
  278. return InboundClientIps, nil
  279. }
  280. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  281. inboundClientIps := &model.InboundClientIps{}
  282. jsonIps, err := json.Marshal(ipsWithTime)
  283. j.checkError(err)
  284. inboundClientIps.ClientEmail = clientEmail
  285. inboundClientIps.Ips = string(jsonIps)
  286. db := database.GetDB()
  287. tx := db.Begin()
  288. defer func() {
  289. if err == nil {
  290. tx.Commit()
  291. } else {
  292. tx.Rollback()
  293. }
  294. }()
  295. err = tx.Save(inboundClientIps).Error
  296. if err != nil {
  297. return err
  298. }
  299. return nil
  300. }
  301. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, newIpsWithTime []IPWithTimestamp) bool {
  302. // Get the inbound configuration
  303. inbound, err := j.getInboundByEmail(clientEmail)
  304. if err != nil {
  305. logger.Errorf("failed to fetch inbound settings for email %s: %s", clientEmail, err)
  306. return false
  307. }
  308. if inbound.Settings == "" {
  309. logger.Debug("wrong data:", inbound)
  310. return false
  311. }
  312. settings := map[string][]model.Client{}
  313. json.Unmarshal([]byte(inbound.Settings), &settings)
  314. clients := settings["clients"]
  315. // Find the client's IP limit
  316. var limitIp int
  317. var clientFound bool
  318. for _, client := range clients {
  319. if client.Email == clientEmail {
  320. limitIp = client.LimitIP
  321. clientFound = true
  322. break
  323. }
  324. }
  325. if !clientFound || limitIp <= 0 || !inbound.Enable {
  326. // No limit or inbound disabled, just update and return
  327. jsonIps, _ := json.Marshal(newIpsWithTime)
  328. inboundClientIps.Ips = string(jsonIps)
  329. db := database.GetDB()
  330. db.Save(inboundClientIps)
  331. return false
  332. }
  333. // Parse old IPs from database
  334. var oldIpsWithTime []IPWithTimestamp
  335. if inboundClientIps.Ips != "" {
  336. json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  337. }
  338. // Merge old and new IPs, evicting entries that haven't been
  339. // re-observed in a while. See mergeClientIps / #4077 for why.
  340. ipMap := mergeClientIps(oldIpsWithTime, newIpsWithTime, time.Now().Unix()-ipStaleAfterSeconds)
  341. // only ips seen in this scan count toward the limit. see
  342. // partitionLiveIps.
  343. observedThisScan := make(map[string]bool, len(newIpsWithTime))
  344. for _, ipTime := range newIpsWithTime {
  345. observedThisScan[ipTime.IP] = true
  346. }
  347. liveIps, historicalIps := partitionLiveIps(ipMap, observedThisScan)
  348. shouldCleanLog := false
  349. j.disAllowedIps = []string{}
  350. // historical db-only ips are excluded from this count on purpose.
  351. var keptLive []IPWithTimestamp
  352. if len(liveIps) > limitIp {
  353. shouldCleanLog = true
  354. // keep the newest live ips, ban older ones.
  355. cutoff := len(liveIps) - limitIp
  356. keptLive = liveIps[cutoff:]
  357. bannedLive := liveIps[:cutoff]
  358. // Open log file only when a ban entry needs to be written.
  359. // Use a local logger to avoid mutating the global log.* state,
  360. // which would redirect all standard-library logging to this file
  361. // and leave a dangling closed-file handle after the defer fires.
  362. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  363. if err != nil {
  364. logger.Errorf("failed to open IP limit log file: %s", err)
  365. return false
  366. }
  367. defer logIpFile.Close()
  368. ipLogger := log.New(logIpFile, "", log.LstdFlags)
  369. // log format is load-bearing: x-ui.sh create_iplimit_jails builds
  370. // filter.d/3x-ipl.conf with
  371. // 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+
  372. // don't change the wording.
  373. for _, ipTime := range bannedLive {
  374. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  375. ipLogger.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  376. }
  377. // force xray to drop existing connections from banned ips
  378. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  379. } else {
  380. keptLive = liveIps
  381. }
  382. // keep kept-live + historical in the blob so the panel keeps showing
  383. // recently seen ips. banned live ips are already in the fail2ban log
  384. // and will reappear in the next scan if they reconnect.
  385. dbIps := make([]IPWithTimestamp, 0, len(keptLive)+len(historicalIps))
  386. dbIps = append(dbIps, keptLive...)
  387. dbIps = append(dbIps, historicalIps...)
  388. jsonIps, _ := json.Marshal(dbIps)
  389. inboundClientIps.Ips = string(jsonIps)
  390. db := database.GetDB()
  391. err = db.Save(inboundClientIps).Error
  392. if err != nil {
  393. logger.Error("failed to save inboundClientIps:", err)
  394. return false
  395. }
  396. if len(j.disAllowedIps) > 0 {
  397. logger.Infof("[LIMIT_IP] Client %s: Kept %d live IPs, queued %d old IPs for fail2ban", clientEmail, len(keptLive), len(j.disAllowedIps))
  398. }
  399. return shouldCleanLog
  400. }
  401. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  402. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  403. var xrayAPI xray.XrayAPI
  404. apiPort := j.resolveXrayAPIPort()
  405. err := xrayAPI.Init(apiPort)
  406. if err != nil {
  407. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  408. return
  409. }
  410. defer xrayAPI.Close()
  411. // Find the client config
  412. var clientConfig map[string]any
  413. for _, client := range clients {
  414. if client.Email == clientEmail {
  415. // Convert client to map for API
  416. clientBytes, _ := json.Marshal(client)
  417. json.Unmarshal(clientBytes, &clientConfig)
  418. break
  419. }
  420. }
  421. if clientConfig == nil {
  422. return
  423. }
  424. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  425. protocol := string(inbound.Protocol)
  426. switch protocol {
  427. case "vmess", "vless", "trojan", "shadowsocks":
  428. // supported protocols, continue
  429. default:
  430. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  431. return
  432. }
  433. // For Shadowsocks, ensure the required "cipher" field is present by
  434. // reading it from the inbound settings (e.g., settings["method"]).
  435. if string(inbound.Protocol) == "shadowsocks" {
  436. var inboundSettings map[string]any
  437. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  438. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  439. } else {
  440. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  441. clientConfig["cipher"] = method
  442. }
  443. }
  444. }
  445. // Remove user to disconnect all connections
  446. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  447. if err != nil {
  448. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  449. return
  450. }
  451. // Wait a moment for disconnection to take effect
  452. time.Sleep(100 * time.Millisecond)
  453. // Re-add user to allow new connections
  454. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  455. if err != nil {
  456. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  457. }
  458. }
  459. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  460. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  461. var configErr error
  462. var templateErr error
  463. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  464. return port
  465. } else {
  466. configErr = err
  467. }
  468. db := database.GetDB()
  469. var template model.Setting
  470. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  471. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  472. return port
  473. } else {
  474. templateErr = parseErr
  475. }
  476. } else {
  477. templateErr = err
  478. }
  479. logger.Warningf(
  480. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  481. defaultXrayAPIPort,
  482. configErr,
  483. templateErr,
  484. )
  485. return defaultXrayAPIPort
  486. }
  487. func getAPIPortFromConfigPath(configPath string) (int, error) {
  488. configData, err := os.ReadFile(configPath)
  489. if err != nil {
  490. return 0, err
  491. }
  492. return getAPIPortFromConfigData(configData)
  493. }
  494. func getAPIPortFromConfigData(configData []byte) (int, error) {
  495. xrayConfig := &xray.Config{}
  496. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  497. return 0, err
  498. }
  499. for _, inboundConfig := range xrayConfig.InboundConfigs {
  500. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  501. return inboundConfig.Port, nil
  502. }
  503. }
  504. return 0, errors.New("api inbound port not found")
  505. }
  506. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  507. db := database.GetDB()
  508. inbound := &model.Inbound{}
  509. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  510. if err != nil {
  511. return nil, err
  512. }
  513. return inbound, nil
  514. }