check_client_ip_job.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. // NewCheckClientIpJob creates a new client IP monitoring job instance.
  32. func NewCheckClientIpJob() *CheckClientIpJob {
  33. job = new(CheckClientIpJob)
  34. return job
  35. }
  36. func (j *CheckClientIpJob) Run() {
  37. if j.lastClear == 0 {
  38. j.lastClear = time.Now().Unix()
  39. }
  40. shouldClearAccessLog := false
  41. iplimitActive := j.hasLimitIp()
  42. f2bInstalled := j.checkFail2BanInstalled()
  43. isAccessLogAvailable := j.checkAccessLogAvailable(iplimitActive)
  44. if isAccessLogAvailable {
  45. if runtime.GOOS == "windows" {
  46. if iplimitActive {
  47. shouldClearAccessLog = j.processLogFile()
  48. }
  49. } else {
  50. if iplimitActive {
  51. if f2bInstalled {
  52. shouldClearAccessLog = j.processLogFile()
  53. } else {
  54. if !f2bInstalled {
  55. logger.Warning("[LimitIP] Fail2Ban is not installed, Please install Fail2Ban from the x-ui bash menu.")
  56. }
  57. }
  58. }
  59. }
  60. }
  61. if shouldClearAccessLog || (isAccessLogAvailable && time.Now().Unix()-j.lastClear > 3600) {
  62. j.clearAccessLog()
  63. }
  64. }
  65. func (j *CheckClientIpJob) clearAccessLog() {
  66. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  67. j.checkError(err)
  68. defer logAccessP.Close()
  69. accessLogPath, err := xray.GetAccessLogPath()
  70. j.checkError(err)
  71. file, err := os.Open(accessLogPath)
  72. j.checkError(err)
  73. defer file.Close()
  74. _, err = io.Copy(logAccessP, file)
  75. j.checkError(err)
  76. err = os.Truncate(accessLogPath, 0)
  77. j.checkError(err)
  78. j.lastClear = time.Now().Unix()
  79. }
  80. func (j *CheckClientIpJob) hasLimitIp() bool {
  81. db := database.GetDB()
  82. var inbounds []*model.Inbound
  83. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  84. if err != nil {
  85. return false
  86. }
  87. for _, inbound := range inbounds {
  88. if inbound.Settings == "" {
  89. continue
  90. }
  91. settings := map[string][]model.Client{}
  92. json.Unmarshal([]byte(inbound.Settings), &settings)
  93. clients := settings["clients"]
  94. for _, client := range clients {
  95. limitIp := client.LimitIP
  96. if limitIp > 0 {
  97. return true
  98. }
  99. }
  100. }
  101. return false
  102. }
  103. func (j *CheckClientIpJob) processLogFile() bool {
  104. ipRegex := regexp.MustCompile(`from (?:tcp:|udp:)?\[?([0-9a-fA-F\.:]+)\]?:\d+ accepted`)
  105. emailRegex := regexp.MustCompile(`email: (.+)$`)
  106. timestampRegex := regexp.MustCompile(`^(\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2})`)
  107. accessLogPath, _ := xray.GetAccessLogPath()
  108. file, _ := os.Open(accessLogPath)
  109. defer file.Close()
  110. // Track IPs with their last seen timestamp
  111. inboundClientIps := make(map[string]map[string]int64, 100)
  112. scanner := bufio.NewScanner(file)
  113. for scanner.Scan() {
  114. line := scanner.Text()
  115. ipMatches := ipRegex.FindStringSubmatch(line)
  116. if len(ipMatches) < 2 {
  117. continue
  118. }
  119. ip := ipMatches[1]
  120. if ip == "127.0.0.1" || ip == "::1" {
  121. continue
  122. }
  123. emailMatches := emailRegex.FindStringSubmatch(line)
  124. if len(emailMatches) < 2 {
  125. continue
  126. }
  127. email := emailMatches[1]
  128. // Extract timestamp from log line
  129. var timestamp int64
  130. timestampMatches := timestampRegex.FindStringSubmatch(line)
  131. if len(timestampMatches) >= 2 {
  132. t, err := time.Parse("2006/01/02 15:04:05", timestampMatches[1])
  133. if err == nil {
  134. timestamp = t.Unix()
  135. } else {
  136. timestamp = time.Now().Unix()
  137. }
  138. } else {
  139. timestamp = time.Now().Unix()
  140. }
  141. if _, exists := inboundClientIps[email]; !exists {
  142. inboundClientIps[email] = make(map[string]int64)
  143. }
  144. // Update timestamp - keep the latest
  145. if existingTime, ok := inboundClientIps[email][ip]; !ok || timestamp > existingTime {
  146. inboundClientIps[email][ip] = timestamp
  147. }
  148. }
  149. shouldCleanLog := false
  150. for email, ipTimestamps := range inboundClientIps {
  151. // Convert to IPWithTimestamp slice
  152. ipsWithTime := make([]IPWithTimestamp, 0, len(ipTimestamps))
  153. for ip, timestamp := range ipTimestamps {
  154. ipsWithTime = append(ipsWithTime, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  155. }
  156. clientIpsRecord, err := j.getInboundClientIps(email)
  157. if err != nil {
  158. j.addInboundClientIps(email, ipsWithTime)
  159. continue
  160. }
  161. shouldCleanLog = j.updateInboundClientIps(clientIpsRecord, email, ipsWithTime) || shouldCleanLog
  162. }
  163. return shouldCleanLog
  164. }
  165. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  166. cmd := "fail2ban-client"
  167. args := []string{"-h"}
  168. err := exec.Command(cmd, args...).Run()
  169. return err == nil
  170. }
  171. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  172. accessLogPath, err := xray.GetAccessLogPath()
  173. if err != nil {
  174. return false
  175. }
  176. if accessLogPath == "none" || accessLogPath == "" {
  177. if iplimitActive {
  178. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  179. }
  180. return false
  181. }
  182. return true
  183. }
  184. func (j *CheckClientIpJob) checkError(e error) {
  185. if e != nil {
  186. logger.Warning("client ip job err:", e)
  187. }
  188. }
  189. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  190. db := database.GetDB()
  191. InboundClientIps := &model.InboundClientIps{}
  192. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  193. if err != nil {
  194. return nil, err
  195. }
  196. return InboundClientIps, nil
  197. }
  198. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ipsWithTime []IPWithTimestamp) error {
  199. inboundClientIps := &model.InboundClientIps{}
  200. jsonIps, err := json.Marshal(ipsWithTime)
  201. j.checkError(err)
  202. inboundClientIps.ClientEmail = clientEmail
  203. inboundClientIps.Ips = string(jsonIps)
  204. db := database.GetDB()
  205. tx := db.Begin()
  206. defer func() {
  207. if err == nil {
  208. tx.Commit()
  209. } else {
  210. tx.Rollback()
  211. }
  212. }()
  213. err = tx.Save(inboundClientIps).Error
  214. if err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, newIpsWithTime []IPWithTimestamp) bool {
  220. // Get the inbound configuration
  221. inbound, err := j.getInboundByEmail(clientEmail)
  222. if err != nil {
  223. logger.Errorf("failed to fetch inbound settings for email %s: %s", clientEmail, err)
  224. return false
  225. }
  226. if inbound.Settings == "" {
  227. logger.Debug("wrong data:", inbound)
  228. return false
  229. }
  230. settings := map[string][]model.Client{}
  231. json.Unmarshal([]byte(inbound.Settings), &settings)
  232. clients := settings["clients"]
  233. // Find the client's IP limit
  234. var limitIp int
  235. var clientFound bool
  236. for _, client := range clients {
  237. if client.Email == clientEmail {
  238. limitIp = client.LimitIP
  239. clientFound = true
  240. break
  241. }
  242. }
  243. if !clientFound || limitIp <= 0 || !inbound.Enable {
  244. // No limit or inbound disabled, just update and return
  245. jsonIps, _ := json.Marshal(newIpsWithTime)
  246. inboundClientIps.Ips = string(jsonIps)
  247. db := database.GetDB()
  248. db.Save(inboundClientIps)
  249. return false
  250. }
  251. // Parse old IPs from database
  252. var oldIpsWithTime []IPWithTimestamp
  253. if inboundClientIps.Ips != "" {
  254. json.Unmarshal([]byte(inboundClientIps.Ips), &oldIpsWithTime)
  255. }
  256. // Merge old and new IPs, keeping the latest timestamp for each IP
  257. ipMap := make(map[string]int64)
  258. for _, ipTime := range oldIpsWithTime {
  259. ipMap[ipTime.IP] = ipTime.Timestamp
  260. }
  261. for _, ipTime := range newIpsWithTime {
  262. if existingTime, ok := ipMap[ipTime.IP]; !ok || ipTime.Timestamp > existingTime {
  263. ipMap[ipTime.IP] = ipTime.Timestamp
  264. }
  265. }
  266. // Convert back to slice and sort by timestamp (oldest first)
  267. // This ensures we always protect the original/current connections and ban new excess ones.
  268. allIps := make([]IPWithTimestamp, 0, len(ipMap))
  269. for ip, timestamp := range ipMap {
  270. allIps = append(allIps, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  271. }
  272. sort.Slice(allIps, func(i, j int) bool {
  273. return allIps[i].Timestamp < allIps[j].Timestamp // Ascending order (oldest first)
  274. })
  275. shouldCleanLog := false
  276. j.disAllowedIps = []string{}
  277. // Open log file
  278. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  279. if err != nil {
  280. logger.Errorf("failed to open IP limit log file: %s", err)
  281. return false
  282. }
  283. defer logIpFile.Close()
  284. log.SetOutput(logIpFile)
  285. log.SetFlags(log.LstdFlags)
  286. // Check if we exceed the limit
  287. if len(allIps) > limitIp {
  288. shouldCleanLog = true
  289. // Keep the oldest IPs (currently active connections) and ban the new excess ones.
  290. keptIps := allIps[:limitIp]
  291. bannedIps := allIps[limitIp:]
  292. // Log banned IPs in the format fail2ban filters expect: [LIMIT_IP] Email = X || Disconnecting OLD IP = Y || Timestamp = Z
  293. for _, ipTime := range bannedIps {
  294. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  295. log.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  296. }
  297. // Actually disconnect banned IPs by temporarily removing and re-adding user
  298. // This forces Xray to drop existing connections from banned IPs
  299. if len(bannedIps) > 0 {
  300. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  301. }
  302. // Update database with only the currently active (kept) IPs
  303. jsonIps, _ := json.Marshal(keptIps)
  304. inboundClientIps.Ips = string(jsonIps)
  305. } else {
  306. // Under limit, save all IPs
  307. jsonIps, _ := json.Marshal(allIps)
  308. inboundClientIps.Ips = string(jsonIps)
  309. }
  310. db := database.GetDB()
  311. err = db.Save(inboundClientIps).Error
  312. if err != nil {
  313. logger.Error("failed to save inboundClientIps:", err)
  314. return false
  315. }
  316. if len(j.disAllowedIps) > 0 {
  317. logger.Infof("[LIMIT_IP] Client %s: Kept %d current IPs, queued %d new IPs for fail2ban", clientEmail, limitIp, len(j.disAllowedIps))
  318. }
  319. return shouldCleanLog
  320. }
  321. // disconnectClientTemporarily removes and re-adds a client to force disconnect banned connections
  322. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  323. var xrayAPI xray.XrayAPI
  324. apiPort := j.resolveXrayAPIPort()
  325. err := xrayAPI.Init(apiPort)
  326. if err != nil {
  327. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  328. return
  329. }
  330. defer xrayAPI.Close()
  331. // Find the client config
  332. var clientConfig map[string]any
  333. for _, client := range clients {
  334. if client.Email == clientEmail {
  335. // Convert client to map for API
  336. clientBytes, _ := json.Marshal(client)
  337. json.Unmarshal(clientBytes, &clientConfig)
  338. break
  339. }
  340. }
  341. if clientConfig == nil {
  342. return
  343. }
  344. // Only perform remove/re-add for protocols supported by XrayAPI.AddUser
  345. protocol := string(inbound.Protocol)
  346. switch protocol {
  347. case "vmess", "vless", "trojan", "shadowsocks":
  348. // supported protocols, continue
  349. default:
  350. logger.Warningf("[LIMIT_IP] Temporary disconnect is not supported for protocol %s on inbound %s", protocol, inbound.Tag)
  351. return
  352. }
  353. // For Shadowsocks, ensure the required "cipher" field is present by
  354. // reading it from the inbound settings (e.g., settings["method"]).
  355. if string(inbound.Protocol) == "shadowsocks" {
  356. var inboundSettings map[string]any
  357. if err := json.Unmarshal([]byte(inbound.Settings), &inboundSettings); err != nil {
  358. logger.Warningf("[LIMIT_IP] Failed to parse inbound settings for shadowsocks cipher: %v", err)
  359. } else {
  360. if method, ok := inboundSettings["method"].(string); ok && method != "" {
  361. clientConfig["cipher"] = method
  362. }
  363. }
  364. }
  365. // Remove user to disconnect all connections
  366. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  367. if err != nil {
  368. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  369. return
  370. }
  371. // Wait a moment for disconnection to take effect
  372. time.Sleep(100 * time.Millisecond)
  373. // Re-add user to allow new connections
  374. err = xrayAPI.AddUser(protocol, inbound.Tag, clientConfig)
  375. if err != nil {
  376. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  377. }
  378. }
  379. // resolveXrayAPIPort returns the API inbound port from running config, then template config, then default.
  380. func (j *CheckClientIpJob) resolveXrayAPIPort() int {
  381. var configErr error
  382. var templateErr error
  383. if port, err := getAPIPortFromConfigPath(xray.GetConfigPath()); err == nil {
  384. return port
  385. } else {
  386. configErr = err
  387. }
  388. db := database.GetDB()
  389. var template model.Setting
  390. if err := db.Where("key = ?", "xrayTemplateConfig").First(&template).Error; err == nil {
  391. if port, parseErr := getAPIPortFromConfigData([]byte(template.Value)); parseErr == nil {
  392. return port
  393. } else {
  394. templateErr = parseErr
  395. }
  396. } else {
  397. templateErr = err
  398. }
  399. logger.Warningf(
  400. "[LIMIT_IP] Could not determine Xray API port from config or template; falling back to default port %d (config error: %v, template error: %v)",
  401. defaultXrayAPIPort,
  402. configErr,
  403. templateErr,
  404. )
  405. return defaultXrayAPIPort
  406. }
  407. func getAPIPortFromConfigPath(configPath string) (int, error) {
  408. configData, err := os.ReadFile(configPath)
  409. if err != nil {
  410. return 0, err
  411. }
  412. return getAPIPortFromConfigData(configData)
  413. }
  414. func getAPIPortFromConfigData(configData []byte) (int, error) {
  415. xrayConfig := &xray.Config{}
  416. if err := json.Unmarshal(configData, xrayConfig); err != nil {
  417. return 0, err
  418. }
  419. for _, inboundConfig := range xrayConfig.InboundConfigs {
  420. if inboundConfig.Tag == "api" && inboundConfig.Port > 0 {
  421. return inboundConfig.Port, nil
  422. }
  423. }
  424. return 0, errors.New("api inbound port not found")
  425. }
  426. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  427. db := database.GetDB()
  428. inbound := &model.Inbound{}
  429. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  430. if err != nil {
  431. return nil, err
  432. }
  433. return inbound, nil
  434. }