check_client_ip_job.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  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/v2/database"
  15. "github.com/mhsanaei/3x-ui/v2/database/model"
  16. "github.com/mhsanaei/3x-ui/v2/logger"
  17. "github.com/mhsanaei/3x-ui/v2/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 ("oldest wins, newest loses") to
  38. // protect the original/current 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.Parse("2006/01/02 15:04:05", timestampMatches[1])
  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. // protected slot. the 30min cutoff alone isn't tight enough: an ip that
  217. // stopped connecting a few minutes ago still looks fresh to
  218. // mergeClientIps, and since the over-limit picker sorts ascending and
  219. // keeps the oldest, those idle entries used to win the slot while the
  220. // ip actually connecting got classified as excess and sent to fail2ban
  221. // every tick. see #4077 / #4091.
  222. //
  223. // live is sorted ascending so the "protect original, ban newcomer"
  224. // rule still holds when several ips are really connecting at once.
  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. cmd := "fail2ban-client"
  242. args := []string{"-h"}
  243. err := exec.Command(cmd, args...).Run()
  244. return err == nil
  245. }
  246. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  247. accessLogPath, err := xray.GetAccessLogPath()
  248. if err != nil {
  249. return false
  250. }
  251. if accessLogPath == "none" || accessLogPath == "" {
  252. if iplimitActive {
  253. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  254. }
  255. return false
  256. }
  257. return true
  258. }
  259. func (j *CheckClientIpJob) checkError(e error) {
  260. if e != nil {
  261. logger.Warning("client ip job err:", e)
  262. }
  263. }
  264. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  265. db := database.GetDB()
  266. InboundClientIps := &model.InboundClientIps{}
  267. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  268. if err != nil {
  269. return nil, err
  270. }
  271. return InboundClientIps, nil
  272. }
  273. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  274. inboundClientIps := &model.InboundClientIps{}
  275. jsonIps, err := json.Marshal(ipsWithTime)
  276. j.checkError(err)
  277. inboundClientIps.ClientEmail = clientEmail
  278. inboundClientIps.Ips = string(jsonIps)
  279. db := database.GetDB()
  280. tx := db.Begin()
  281. defer func() {
  282. if err == nil {
  283. tx.Commit()
  284. } else {
  285. tx.Rollback()
  286. }
  287. }()
  288. err = tx.Save(inboundClientIps).Error
  289. if err != nil {
  290. return err
  291. }
  292. return nil
  293. }
  294. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, newIpsWithTime []IPWithTimestamp) bool {
  295. // Get the inbound configuration
  296. inbound, err := j.getInboundByEmail(clientEmail)
  297. if err != nil {
  298. logger.Errorf("failed to fetch inbound settings for email %s: %s", clientEmail, err)
  299. return false
  300. }
  301. if inbound.Settings == "" {
  302. logger.Debug("wrong data:", inbound)
  303. return false
  304. }
  305. settings := map[string][]model.Client{}
  306. json.Unmarshal([]byte(inbound.Settings), &settings)
  307. clients := settings["clients"]
  308. // Find the client's IP limit
  309. var limitIp int
  310. var clientFound bool
  311. for _, client := range clients {
  312. if client.Email == clientEmail {
  313. limitIp = client.LimitIP
  314. clientFound = true
  315. break
  316. }
  317. }
  318. if !clientFound || limitIp <= 0 || !inbound.Enable {
  319. // No limit or inbound disabled, just update and return
  320. jsonIps, _ := json.Marshal(newIpsWithTime)
  321. inboundClientIps.Ips = string(jsonIps)
  322. db := database.GetDB()
  323. db.Save(inboundClientIps)
  324. return false
  325. }
  326. // Parse old IPs from database
  327. var oldIpsWithTime []IPWithTimestamp
  328. if inboundClientIps.Ips != "" {
  329. json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  330. }
  331. // Merge old and new IPs, evicting entries that haven't been
  332. // re-observed in a while. See mergeClientIps / #4077 for why.
  333. ipMap := mergeClientIps(oldIpsWithTime, newIpsWithTime, time.Now().Unix()-ipStaleAfterSeconds)
  334. // only ips seen in this scan count toward the limit. see
  335. // partitionLiveIps.
  336. observedThisScan := make(map[string]bool, len(newIpsWithTime))
  337. for _, ipTime := range newIpsWithTime {
  338. observedThisScan[ipTime.IP] = true
  339. }
  340. liveIps, historicalIps := partitionLiveIps(ipMap, observedThisScan)
  341. shouldCleanLog := false
  342. j.disAllowedIps = []string{}
  343. // Open log file
  344. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  345. if err != nil {
  346. logger.Errorf("failed to open IP limit log file: %s", err)
  347. return false
  348. }
  349. defer logIpFile.Close()
  350. log.SetOutput(logIpFile)
  351. log.SetFlags(log.LstdFlags)
  352. // historical db-only ips are excluded from this count on purpose.
  353. var keptLive []IPWithTimestamp
  354. if len(liveIps) > limitIp {
  355. shouldCleanLog = true
  356. // protect the oldest live ip, ban newcomers.
  357. keptLive = liveIps[:limitIp]
  358. bannedLive := liveIps[limitIp:]
  359. // log format is load-bearing: x-ui.sh create_iplimit_jails builds
  360. // filter.d/3x-ipl.conf with
  361. // 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+
  362. // don't change the wording.
  363. for _, ipTime := range bannedLive {
  364. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  365. log.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  366. }
  367. // force xray to drop existing connections from banned ips
  368. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  369. } else {
  370. keptLive = liveIps
  371. }
  372. // keep kept-live + historical in the blob so the panel keeps showing
  373. // recently seen ips. banned live ips are already in the fail2ban log
  374. // and will reappear in the next scan if they reconnect.
  375. dbIps := make([]IPWithTimestamp, 0, len(keptLive)+len(historicalIps))
  376. dbIps = append(dbIps, keptLive...)
  377. dbIps = append(dbIps, historicalIps...)
  378. jsonIps, _ := json.Marshal(dbIps)
  379. inboundClientIps.Ips = string(jsonIps)
  380. db := database.GetDB()
  381. err = db.Save(inboundClientIps).Error
  382. if err != nil {
  383. logger.Error("failed to save inboundClientIps:", err)
  384. return false
  385. }
  386. if len(j.disAllowedIps) > 0 {
  387. logger.Infof("[LIMIT_IP] Client %s: Kept %d live IPs, queued %d new IPs for fail2ban", clientEmail, len(keptLive), len(j.disAllowedIps))
  388. }
  389. return shouldCleanLog
  390. }
  391. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  392. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  393. var xrayAPI xray.XrayAPI
  394. apiPort := j.resolveXrayAPIPort()
  395. err := xrayAPI.Init(apiPort)
  396. if err != nil {
  397. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  398. return
  399. }
  400. defer xrayAPI.Close()
  401. // Find the client config
  402. var clientConfig map[string]any
  403. for _, client := range clients {
  404. if client.Email == clientEmail {
  405. // Convert client to map for API
  406. clientBytes, _ := json.Marshal(client)
  407. json.Unmarshal(clientBytes, &clientConfig)
  408. break
  409. }
  410. }
  411. if clientConfig == nil {
  412. return
  413. }
  414. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  415. protocol := string(inbound.Protocol)
  416. switch protocol {
  417. case "vmess", "vless", "trojan", "shadowsocks":
  418. // supported protocols, continue
  419. default:
  420. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  421. return
  422. }
  423. // For Shadowsocks, ensure the required "cipher" field is present by
  424. // reading it from the inbound settings (e.g., settings["method"]).
  425. if string(inbound.Protocol) == "shadowsocks" {
  426. var inboundSettings map[string]any
  427. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  428. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  429. } else {
  430. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  431. clientConfig["cipher"] = method
  432. }
  433. }
  434. }
  435. // Remove user to disconnect all connections
  436. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  437. if err != nil {
  438. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  439. return
  440. }
  441. // Wait a moment for disconnection to take effect
  442. time.Sleep(100 * time.Millisecond)
  443. // Re-add user to allow new connections
  444. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  445. if err != nil {
  446. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  447. }
  448. }
  449. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  450. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  451. var configErr error
  452. var templateErr error
  453. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  454. return port
  455. } else {
  456. configErr = err
  457. }
  458. db := database.GetDB()
  459. var template model.Setting
  460. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  461. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  462. return port
  463. } else {
  464. templateErr = parseErr
  465. }
  466. } else {
  467. templateErr = err
  468. }
  469. logger.Warningf(
  470. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  471. defaultXrayAPIPort,
  472. configErr,
  473. templateErr,
  474. )
  475. return defaultXrayAPIPort
  476. }
  477. func getAPIPortFromConfigPath(configPath string) (int, error) {
  478. configData, err := os.ReadFile(configPath)
  479. if err != nil {
  480. return 0, err
  481. }
  482. return getAPIPortFromConfigData(configData)
  483. }
  484. func getAPIPortFromConfigData(configData []byte) (int, error) {
  485. xrayConfig := &xray.Config{}
  486. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  487. return 0, err
  488. }
  489. for _, inboundConfig := range xrayConfig.InboundConfigs {
  490. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  491. return inboundConfig.Port, nil
  492. }
  493. }
  494. return 0, errors.New("api inbound port not found")
  495. }
  496. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  497. db := database.GetDB()
  498. inbound := &model.Inbound{}
  499. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  500. if err != nil {
  501. return nil, err
  502. }
  503. return inbound, nil
  504. }