check_client_ip_job.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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. for ip, ts := range ipMap {
  202. entry := IPWithTimestamp{IP: ip, Timestamp: ts}
  203. if observedThisScan[ip] {
  204. live = append(live, entry)
  205. } else {
  206. historical = append(historical, entry)
  207. }
  208. }
  209. sort.Slice(live, func(i, j int) bool { return live[i].Timestamp < live[j].Timestamp })
  210. sort.Slice(historical, func(i, j int) bool { return historical[i].Timestamp < historical[j].Timestamp })
  211. return live, historical
  212. }
  213. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  214. if !isFail2BanEnabled() {
  215. return false
  216. }
  217. cmd := "fail2ban-client"
  218. args := []string{"-h"}
  219. err := exec.Command(cmd, args...).Run()
  220. return err == nil
  221. }
  222. func isFail2BanEnabled() bool {
  223. value, ok := os.LookupEnv("XUI_ENABLE_FAIL2BAN")
  224. return !ok || value == "true"
  225. }
  226. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  227. accessLogPath, err := xray.GetAccessLogPath()
  228. if err != nil {
  229. return false
  230. }
  231. if accessLogPath == "none" || accessLogPath == "" {
  232. if iplimitActive {
  233. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  234. }
  235. return false
  236. }
  237. return true
  238. }
  239. func (j *CheckClientIpJob) checkError(e error) {
  240. if e != nil {
  241. logger.Warning("client ip job err:", e)
  242. }
  243. }
  244. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  245. db := database.GetDB()
  246. InboundClientIps := &model.InboundClientIps{}
  247. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  248. if err != nil {
  249. return nil, err
  250. }
  251. return InboundClientIps, nil
  252. }
  253. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  254. inboundClientIps := &model.InboundClientIps{}
  255. jsonIps, err := json.Marshal(ipsWithTime)
  256. j.checkError(err)
  257. inboundClientIps.ClientEmail = clientEmail
  258. inboundClientIps.Ips = string(jsonIps)
  259. db := database.GetDB()
  260. tx := db.Begin()
  261. defer func() {
  262. if err == nil {
  263. tx.Commit()
  264. } else {
  265. tx.Rollback()
  266. }
  267. }()
  268. err = tx.Save(inboundClientIps).Error
  269. if err != nil {
  270. return err
  271. }
  272. return nil
  273. }
  274. // delInboundClientIps drops the inbound_client_ips tracking row for an email
  275. // that no longer maps to any inbound (a renamed or deleted client), so stale
  276. // access-log entries don't keep a ghost row alive (#4963).
  277. func (j *CheckClientIpJob) delInboundClientIps(clientEmail string) {
  278. db := database.GetDB()
  279. if err := db.Where("client_email = ?", clientEmail).Delete(&model.InboundClientIps{}).Error; err != nil {
  280. j.checkError(err)
  281. }
  282. }
  283. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, inbound *model.Inbound, clientEmail string, newIpsWithTime []IPWithTimestamp, enforce bool) bool {
  284. if inbound.Settings == "" {
  285. logger.Debug("wrong data:", inbound)
  286. return false
  287. }
  288. settings := map[string][]model.Client{}
  289. json.Unmarshal([]byte(inbound.Settings), &settings)
  290. clients := settings["clients"]
  291. // Find the client's IP limit
  292. var limitIp int
  293. var clientFound bool
  294. for _, client := range clients {
  295. if client.Email == clientEmail {
  296. limitIp = client.LimitIP
  297. clientFound = true
  298. break
  299. }
  300. }
  301. if !enforce || !clientFound || limitIp <= 0 || !inbound.Enable {
  302. // Nothing to enforce (collection-only run, no limit, client missing, or
  303. // inbound disabled): record the observed IPs for the panel and return.
  304. jsonIps, _ := json.Marshal(newIpsWithTime)
  305. inboundClientIps.Ips = string(jsonIps)
  306. db := database.GetDB()
  307. db.Save(inboundClientIps)
  308. return false
  309. }
  310. // Parse old IPs from database
  311. var oldIpsWithTime []IPWithTimestamp
  312. if inboundClientIps.Ips != "" {
  313. json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  314. }
  315. ipMap := mergeClientIps(oldIpsWithTime, newIpsWithTime, time.Now().Unix()-ipStaleAfterSeconds)
  316. // only ips seen in this scan count toward the limit. see
  317. // partitionLiveIps.
  318. observedThisScan := make(map[string]bool, len(newIpsWithTime))
  319. for _, ipTime := range newIpsWithTime {
  320. observedThisScan[ipTime.IP] = true
  321. }
  322. liveIps, historicalIps := partitionLiveIps(ipMap, observedThisScan)
  323. shouldCleanLog := false
  324. j.disAllowedIps = []string{}
  325. // historical db-only ips are excluded from this count on purpose.
  326. var keptLive []IPWithTimestamp
  327. if len(liveIps) > limitIp {
  328. shouldCleanLog = true
  329. // keep the newest live ips, ban older ones.
  330. cutoff := len(liveIps) - limitIp
  331. keptLive = liveIps[cutoff:]
  332. bannedLive := liveIps[:cutoff]
  333. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  334. if err != nil {
  335. logger.Errorf("failed to open IP limit log file: %s", err)
  336. return false
  337. }
  338. defer logIpFile.Close()
  339. ipLogger := log.New(logIpFile, "", log.LstdFlags)
  340. // log format is load-bearing: x-ui.sh create_iplimit_jails builds
  341. // filter.d/3x-ipl.conf with
  342. // 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+
  343. // don't change the wording.
  344. for _, ipTime := range bannedLive {
  345. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  346. ipLogger.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  347. }
  348. // force xray to drop existing connections from banned ips
  349. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  350. } else {
  351. keptLive = liveIps
  352. }
  353. // keep kept-live + historical in the blob so the panel keeps showing
  354. // recently seen ips. banned live ips are already in the fail2ban log
  355. // and will reappear in the next scan if they reconnect.
  356. dbIps := make([]IPWithTimestamp, 0, len(keptLive)+len(historicalIps))
  357. dbIps = append(dbIps, keptLive...)
  358. dbIps = append(dbIps, historicalIps...)
  359. jsonIps, _ := json.Marshal(dbIps)
  360. inboundClientIps.Ips = string(jsonIps)
  361. db := database.GetDB()
  362. err := db.Save(inboundClientIps).Error
  363. if err != nil {
  364. logger.Error("failed to save inboundClientIps:", err)
  365. return false
  366. }
  367. if len(j.disAllowedIps) > 0 {
  368. logger.Infof("[LIMIT_IP] Client %s: Kept %d live IPs, queued %d old IPs for fail2ban", clientEmail, len(keptLive), len(j.disAllowedIps))
  369. }
  370. return shouldCleanLog
  371. }
  372. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  373. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  374. var xrayAPI xray.XrayAPI
  375. apiPort := j.resolveXrayAPIPort()
  376. err := xrayAPI.Init(apiPort)
  377. if err != nil {
  378. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  379. return
  380. }
  381. defer xrayAPI.Close()
  382. // Find the client config
  383. var clientConfig map[string]any
  384. for _, client := range clients {
  385. if client.Email == clientEmail {
  386. // Convert client to map for API
  387. clientBytes, _ := json.Marshal(client)
  388. json.Unmarshal(clientBytes, &clientConfig)
  389. break
  390. }
  391. }
  392. if clientConfig == nil {
  393. return
  394. }
  395. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  396. protocol := string(inbound.Protocol)
  397. switch protocol {
  398. case "vmess", "vless", "trojan", "shadowsocks":
  399. // supported protocols, continue
  400. default:
  401. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  402. return
  403. }
  404. // For Shadowsocks, ensure the required "cipher" field is present by
  405. // reading it from the inbound settings (e.g., settings["method"]).
  406. if string(inbound.Protocol) == "shadowsocks" {
  407. var inboundSettings map[string]any
  408. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  409. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  410. } else {
  411. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  412. clientConfig["cipher"] = method
  413. }
  414. }
  415. }
  416. // Remove user to disconnect all connections
  417. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  418. if err != nil {
  419. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  420. return
  421. }
  422. // Wait a moment for disconnection to take effect
  423. time.Sleep(100 * time.Millisecond)
  424. // Re-add user to allow new connections
  425. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  426. if err != nil {
  427. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  428. }
  429. }
  430. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  431. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  432. var configErr error
  433. var templateErr error
  434. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  435. return port
  436. } else {
  437. configErr = err
  438. }
  439. db := database.GetDB()
  440. var template model.Setting
  441. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  442. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  443. return port
  444. } else {
  445. templateErr = parseErr
  446. }
  447. } else {
  448. templateErr = err
  449. }
  450. logger.Warningf(
  451. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  452. defaultXrayAPIPort,
  453. configErr,
  454. templateErr,
  455. )
  456. return defaultXrayAPIPort
  457. }
  458. func getAPIPortFromConfigPath(configPath string) (int, error) {
  459. configData, err := os.ReadFile(configPath)
  460. if err != nil {
  461. return 0, err
  462. }
  463. return getAPIPortFromConfigData(configData)
  464. }
  465. func getAPIPortFromConfigData(configData []byte) (int, error) {
  466. xrayConfig := &xray.Config{}
  467. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  468. return 0, err
  469. }
  470. for _, inboundConfig := range xrayConfig.InboundConfigs {
  471. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  472. return inboundConfig.Port, nil
  473. }
  474. }
  475. return 0, errors.New("api inbound port not found")
  476. }
  477. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  478. db := database.GetDB()
  479. inbound := &model.Inbound{}
  480. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  481. if err != nil {
  482. return nil, err
  483. }
  484. return inbound, nil
  485. }