1
0

check_client_ip_job.go 17 KB

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