check_client_ip_job.go 11 KB

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