check_client_ip_job.go 16 KB

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