check_client_ip_job.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  208. cmd := "fail2ban-client"
  209. args := []string{"-h"}
  210. err := exec.Command(cmd, args...).Run()
  211. return err == nil
  212. }
  213. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  214. accessLogPath, err := xray.GetAccessLogPath()
  215. if err != nil {
  216. return false
  217. }
  218. if accessLogPath == "none" || accessLogPath == "" {
  219. if iplimitActive {
  220. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  221. }
  222. return false
  223. }
  224. return true
  225. }
  226. func (j *CheckClientIpJob) checkError(e error) {
  227. if e != nil {
  228. logger.Warning("client ip job err:", e)
  229. }
  230. }
  231. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  232. db := database.GetDB()
  233. InboundClientIps := &model.InboundClientIps{}
  234. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  235. if err != nil {
  236. return nil, err
  237. }
  238. return InboundClientIps, nil
  239. }
  240. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  241. inboundClientIps := &model.InboundClientIps{}
  242. jsonIps, err := json.Marshal(ipsWithTime)
  243. j.checkError(err)
  244. inboundClientIps.ClientEmail = clientEmail
  245. inboundClientIps.Ips = string(jsonIps)
  246. db := database.GetDB()
  247. tx := db.Begin()
  248. defer func() {
  249. if err == nil {
  250. tx.Commit()
  251. } else {
  252. tx.Rollback()
  253. }
  254. }()
  255. err = tx.Save(inboundClientIps).Error
  256. if err != nil {
  257. return err
  258. }
  259. return nil
  260. }
  261. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, newIpsWithTime []IPWithTimestamp) bool {
  262. // Get the inbound configuration
  263. inbound, err := j.getInboundByEmail(clientEmail)
  264. if err != nil {
  265. logger.Errorf("failed to fetch inbound settings for email %s: %s", clientEmail, err)
  266. return false
  267. }
  268. if inbound.Settings == "" {
  269. logger.Debug("wrong data:", inbound)
  270. return false
  271. }
  272. settings := map[string][]model.Client{}
  273. json.Unmarshal([]byte(inbound.Settings), &settings)
  274. clients := settings["clients"]
  275. // Find the client's IP limit
  276. var limitIp int
  277. var clientFound bool
  278. for _, client := range clients {
  279. if client.Email == clientEmail {
  280. limitIp = client.LimitIP
  281. clientFound = true
  282. break
  283. }
  284. }
  285. if !clientFound || limitIp <= 0 || !inbound.Enable {
  286. // No limit or inbound disabled, just update and return
  287. jsonIps, _ := json.Marshal(newIpsWithTime)
  288. inboundClientIps.Ips = string(jsonIps)
  289. db := database.GetDB()
  290. db.Save(inboundClientIps)
  291. return false
  292. }
  293. // Parse old IPs from database
  294. var oldIpsWithTime []IPWithTimestamp
  295. if inboundClientIps.Ips != "" {
  296. json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  297. }
  298. // Merge old and new IPs, evicting entries that haven't been
  299. // re-observed in a while. See mergeClientIps / #4077 for why.
  300. ipMap := mergeClientIps(oldIpsWithTime, newIpsWithTime, time.Now().Unix()-ipStaleAfterSeconds)
  301. // Convert back to slice and sort by timestamp (oldest first)
  302. // This ensures we always protect the original/current connections and ban new excess ones.
  303. allIps := make([]IPWithTimestamp, 0, len(ipMap))
  304. for ip, timestamp := range ipMap {
  305. allIps = append(allIps, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  306. }
  307. sort.Slice(allIps, func(i, j int) bool {
  308. return allIps[i].Timestamp < allIps[j].Timestamp // Ascending order (oldest first)
  309. })
  310. shouldCleanLog := false
  311. j.disAllowedIps = []string{}
  312. // Open log file
  313. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  314. if err != nil {
  315. logger.Errorf("failed to open IP limit log file: %s", err)
  316. return false
  317. }
  318. defer logIpFile.Close()
  319. log.SetOutput(logIpFile)
  320. log.SetFlags(log.LstdFlags)
  321. // Check if we exceed the limit
  322. if len(allIps) > limitIp {
  323. shouldCleanLog = true
  324. // Keep the oldest IPs (currently active connections) and ban the new excess ones.
  325. keptIps := allIps[:limitIp]
  326. bannedIps := allIps[limitIp:]
  327. // Log banned IPs in the format fail2ban filters expect: [LIMIT_IP] Email = X || Disconnecting OLD IP = Y || Timestamp = Z
  328. for _, ipTime := range bannedIps {
  329. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  330. log.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  331. }
  332. // Actually disconnect banned IPs by temporarily removing and re-adding user
  333. // This forces Xray to drop existing connections from banned IPs
  334. if len(bannedIps) > 0 {
  335. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  336. }
  337. // Update database with only the currently active (kept) IPs
  338. jsonIps, _ := json.Marshal(keptIps)
  339. inboundClientIps.Ips = string(jsonIps)
  340. } else {
  341. // Under limit, save all IPs
  342. jsonIps, _ := json.Marshal(allIps)
  343. inboundClientIps.Ips = string(jsonIps)
  344. }
  345. db := database.GetDB()
  346. err = db.Save(inboundClientIps).Error
  347. if err != nil {
  348. logger.Error("failed to save inboundClientIps:", err)
  349. return false
  350. }
  351. if len(j.disAllowedIps) > 0 {
  352. logger.Infof("[LIMIT_IP] Client %s: Kept %d current IPs, queued %d new IPs for fail2ban", clientEmail, limitIp, len(j.disAllowedIps))
  353. }
  354. return shouldCleanLog
  355. }
  356. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  357. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  358. var xrayAPI xray.XrayAPI
  359. apiPort := j.resolveXrayAPIPort()
  360. err := xrayAPI.Init(apiPort)
  361. if err != nil {
  362. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  363. return
  364. }
  365. defer xrayAPI.Close()
  366. // Find the client config
  367. var clientConfig map[string]any
  368. for _, client := range clients {
  369. if client.Email == clientEmail {
  370. // Convert client to map for API
  371. clientBytes, _ := json.Marshal(client)
  372. json.Unmarshal(clientBytes, &clientConfig)
  373. break
  374. }
  375. }
  376. if clientConfig == nil {
  377. return
  378. }
  379. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  380. protocol := string(inbound.Protocol)
  381. switch protocol {
  382. case "vmess", "vless", "trojan", "shadowsocks":
  383. // supported protocols, continue
  384. default:
  385. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  386. return
  387. }
  388. // For Shadowsocks, ensure the required "cipher" field is present by
  389. // reading it from the inbound settings (e.g., settings["method"]).
  390. if string(inbound.Protocol) == "shadowsocks" {
  391. var inboundSettings map[string]any
  392. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  393. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  394. } else {
  395. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  396. clientConfig["cipher"] = method
  397. }
  398. }
  399. }
  400. // Remove user to disconnect all connections
  401. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  402. if err != nil {
  403. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  404. return
  405. }
  406. // Wait a moment for disconnection to take effect
  407. time.Sleep(100 * time.Millisecond)
  408. // Re-add user to allow new connections
  409. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  410. if err != nil {
  411. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  412. }
  413. }
  414. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  415. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  416. var configErr error
  417. var templateErr error
  418. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  419. return port
  420. } else {
  421. configErr = err
  422. }
  423. db := database.GetDB()
  424. var template model.Setting
  425. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  426. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  427. return port
  428. } else {
  429. templateErr = parseErr
  430. }
  431. } else {
  432. templateErr = err
  433. }
  434. logger.Warningf(
  435. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  436. defaultXrayAPIPort,
  437. configErr,
  438. templateErr,
  439. )
  440. return defaultXrayAPIPort
  441. }
  442. func getAPIPortFromConfigPath(configPath string) (int, error) {
  443. configData, err := os.ReadFile(configPath)
  444. if err != nil {
  445. return 0, err
  446. }
  447. return getAPIPortFromConfigData(configData)
  448. }
  449. func getAPIPortFromConfigData(configData []byte) (int, error) {
  450. xrayConfig := &xray.Config{}
  451. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  452. return 0, err
  453. }
  454. for _, inboundConfig := range xrayConfig.InboundConfigs {
  455. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  456. return inboundConfig.Port, nil
  457. }
  458. }
  459. return 0, errors.New("api inbound port not found")
  460. }
  461. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  462. db := database.GetDB()
  463. inbound := &model.Inbound{}
  464. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  465. if err != nil {
  466. return nil, err
  467. }
  468. return inbound, nil
  469. }