check_client_ip_job.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. package job
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "log"
  8. "os"
  9. "os/exec"
  10. "regexp"
  11. "runtime"
  12. "sort"
  13. "strconv"
  14. "time"
  15. "github.com/mhsanaei/3x-ui/v2/database"
  16. "github.com/mhsanaei/3x-ui/v2/database/model"
  17. "github.com/mhsanaei/3x-ui/v2/logger"
  18. "github.com/mhsanaei/3x-ui/v2/xray"
  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. // 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 (newest first)
  267. allIps := make([]IPWithTimestamp, 0, len(ipMap))
  268. for ip, timestamp := range ipMap {
  269. allIps = append(allIps, IPWithTimestamp{IP: ip, Timestamp: timestamp})
  270. }
  271. sort.Slice(allIps, func(i, j int) bool {
  272. return allIps[i].Timestamp > allIps[j].Timestamp // Descending order (newest first)
  273. })
  274. shouldCleanLog := false
  275. j.disAllowedIps = []string{}
  276. // Open log file
  277. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  278. if err != nil {
  279. logger.Errorf("failed to open IP limit log file: %s", err)
  280. return false
  281. }
  282. defer logIpFile.Close()
  283. log.SetOutput(logIpFile)
  284. log.SetFlags(log.LstdFlags)
  285. // Check if we exceed the limit
  286. if len(allIps) > limitIp {
  287. shouldCleanLog = true
  288. // Keep only the newest IPs (up to limitIp)
  289. keptIps := allIps[:limitIp]
  290. disconnectedIps := allIps[limitIp:]
  291. // Log the disconnected IPs (old ones)
  292. for _, ipTime := range disconnectedIps {
  293. j.disAllowedIps = append(j.disAllowedIps, ipTime.IP)
  294. log.Printf("[LIMIT_IP] Email = %s || Disconnecting OLD IP = %s || Timestamp = %d", clientEmail, ipTime.IP, ipTime.Timestamp)
  295. }
  296. // Actually disconnect old IPs by temporarily removing and re-adding user
  297. // This forces Xray to drop existing connections from old IPs
  298. if len(disconnectedIps) > 0 {
  299. j.disconnectClientTemporarily(inbound, clientEmail, clients)
  300. }
  301. // Update database with only the newest IPs
  302. jsonIps, _ := json.Marshal(keptIps)
  303. inboundClientIps.Ips = string(jsonIps)
  304. } else {
  305. // Under limit, save all IPs
  306. jsonIps, _ := json.Marshal(allIps)
  307. inboundClientIps.Ips = string(jsonIps)
  308. }
  309. db := database.GetDB()
  310. err = db.Save(inboundClientIps).Error
  311. if err != nil {
  312. logger.Error("failed to save inboundClientIps:", err)
  313. return false
  314. }
  315. if len(j.disAllowedIps) > 0 {
  316. logger.Infof("[LIMIT_IP] Client %s: Kept %d newest IPs, disconnected %d old IPs", clientEmail, limitIp, len(j.disAllowedIps))
  317. }
  318. return shouldCleanLog
  319. }
  320. // disconnectClientTemporarily removes and re-adds a client to force disconnect old connections
  321. func (j *CheckClientIpJob) disconnectClientTemporarily(inbound *model.Inbound, clientEmail string, clients []model.Client) {
  322. var xrayAPI xray.XrayAPI
  323. // Get panel settings for API port
  324. db := database.GetDB()
  325. var apiPort int
  326. var apiPortSetting model.Setting
  327. if err := db.Where("key = ?", "xrayApiPort").First(&apiPortSetting).Error; err == nil {
  328. apiPort, _ = strconv.Atoi(apiPortSetting.Value)
  329. }
  330. if apiPort == 0 {
  331. apiPort = 10085 // Default API port
  332. }
  333. err := xrayAPI.Init(apiPort)
  334. if err != nil {
  335. logger.Warningf("[LIMIT_IP] Failed to init Xray API for disconnection: %v", err)
  336. return
  337. }
  338. defer xrayAPI.Close()
  339. // Find the client config
  340. var clientConfig map[string]any
  341. for _, client := range clients {
  342. if client.Email == clientEmail {
  343. // Convert client to map for API
  344. clientBytes, _ := json.Marshal(client)
  345. json.Unmarshal(clientBytes, &clientConfig)
  346. break
  347. }
  348. }
  349. if clientConfig == nil {
  350. return
  351. }
  352. // Remove user to disconnect all connections
  353. err = xrayAPI.RemoveUser(inbound.Tag, clientEmail)
  354. if err != nil {
  355. logger.Warningf("[LIMIT_IP] Failed to remove user %s: %v", clientEmail, err)
  356. return
  357. }
  358. // Wait a moment for disconnection to take effect
  359. time.Sleep(100 * time.Millisecond)
  360. // Re-add user to allow new connections
  361. err = xrayAPI.AddUser(string(inbound.Protocol), inbound.Tag, clientConfig)
  362. if err != nil {
  363. logger.Warningf("[LIMIT_IP] Failed to re-add user %s: %v", clientEmail, err)
  364. }
  365. }
  366. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  367. db := database.GetDB()
  368. inbound := &model.Inbound{}
  369. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  370. if err != nil {
  371. return nil, err
  372. }
  373. return inbound, nil
  374. }