check_client_ip_job.go 17 KB

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