check_client_ip_job.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. "time"
  13. "github.com/mhsanaei/3x-ui/v2/database"
  14. "github.com/mhsanaei/3x-ui/v2/database/model"
  15. "github.com/mhsanaei/3x-ui/v2/logger"
  16. "github.com/mhsanaei/3x-ui/v2/xray"
  17. )
  18. // CheckClientIpJob monitors client IP addresses from access logs and manages IP blocking based on configured limits.
  19. type CheckClientIpJob struct {
  20. lastClear int64
  21. disAllowedIps []string
  22. }
  23. var job *CheckClientIpJob
  24. // NewCheckClientIpJob creates a new client IP monitoring job instance.
  25. func NewCheckClientIpJob() *CheckClientIpJob {
  26. job = new(CheckClientIpJob)
  27. return job
  28. }
  29. func (j *CheckClientIpJob) Run() {
  30. if j.lastClear == 0 {
  31. j.lastClear = time.Now().Unix()
  32. }
  33. shouldClearAccessLog := false
  34. iplimitActive := j.hasLimitIp()
  35. f2bInstalled := j.checkFail2BanInstalled()
  36. isAccessLogAvailable := j.checkAccessLogAvailable(iplimitActive)
  37. if isAccessLogAvailable {
  38. if runtime.GOOS == "windows" {
  39. if iplimitActive {
  40. shouldClearAccessLog = j.processLogFile()
  41. }
  42. } else {
  43. if iplimitActive {
  44. if f2bInstalled {
  45. shouldClearAccessLog = j.processLogFile()
  46. } else {
  47. if !f2bInstalled {
  48. logger.Warning("[LimitIP] Fail2Ban is not installed, Please install Fail2Ban from the x-ui bash menu.")
  49. }
  50. }
  51. }
  52. }
  53. }
  54. if shouldClearAccessLog || (isAccessLogAvailable && time.Now().Unix()-j.lastClear > 3600) {
  55. j.clearAccessLog()
  56. }
  57. }
  58. func (j *CheckClientIpJob) clearAccessLog() {
  59. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644)
  60. j.checkError(err)
  61. defer logAccessP.Close()
  62. accessLogPath, err := xray.GetAccessLogPath()
  63. j.checkError(err)
  64. file, err := os.Open(accessLogPath)
  65. j.checkError(err)
  66. defer file.Close()
  67. _, err = io.Copy(logAccessP, file)
  68. j.checkError(err)
  69. err = os.Truncate(accessLogPath, 0)
  70. j.checkError(err)
  71. j.lastClear = time.Now().Unix()
  72. }
  73. func (j *CheckClientIpJob) hasLimitIp() bool {
  74. db := database.GetDB()
  75. var inbounds []*model.Inbound
  76. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  77. if err != nil {
  78. return false
  79. }
  80. for _, inbound := range inbounds {
  81. if inbound.Settings == "" {
  82. continue
  83. }
  84. settings := map[string][]model.Client{}
  85. json.Unmarshal([]byte(inbound.Settings), &settings)
  86. clients := settings["clients"]
  87. for _, client := range clients {
  88. limitIp := client.LimitIP
  89. if limitIp > 0 {
  90. return true
  91. }
  92. }
  93. }
  94. return false
  95. }
  96. func (j *CheckClientIpJob) processLogFile() bool {
  97. ipRegex := regexp.MustCompile(`from (?:tcp:|udp:)?\[?([0-9a-fA-F\.:]+)\]?:\d+ accepted`)
  98. emailRegex := regexp.MustCompile(`email: (.+)$`)
  99. accessLogPath, _ := xray.GetAccessLogPath()
  100. file, _ := os.Open(accessLogPath)
  101. defer file.Close()
  102. inboundClientIps := make(map[string]map[string]struct{}, 100)
  103. scanner := bufio.NewScanner(file)
  104. for scanner.Scan() {
  105. line := scanner.Text()
  106. ipMatches := ipRegex.FindStringSubmatch(line)
  107. if len(ipMatches) < 2 {
  108. continue
  109. }
  110. ip := ipMatches[1]
  111. if ip == "127.0.0.1" || ip == "::1" {
  112. continue
  113. }
  114. emailMatches := emailRegex.FindStringSubmatch(line)
  115. if len(emailMatches) < 2 {
  116. continue
  117. }
  118. email := emailMatches[1]
  119. if _, exists := inboundClientIps[email]; !exists {
  120. inboundClientIps[email] = make(map[string]struct{})
  121. }
  122. inboundClientIps[email][ip] = struct{}{}
  123. }
  124. shouldCleanLog := false
  125. for email, uniqueIps := range inboundClientIps {
  126. ips := make([]string, 0, len(uniqueIps))
  127. for ip := range uniqueIps {
  128. ips = append(ips, ip)
  129. }
  130. sort.Strings(ips)
  131. clientIpsRecord, err := j.getInboundClientIps(email)
  132. if err != nil {
  133. j.addInboundClientIps(email, ips)
  134. continue
  135. }
  136. shouldCleanLog = j.updateInboundClientIps(clientIpsRecord, email, ips) || shouldCleanLog
  137. }
  138. return shouldCleanLog
  139. }
  140. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  141. cmd := "fail2ban-client"
  142. args := []string{"-h"}
  143. err := exec.Command(cmd, args...).Run()
  144. return err == nil
  145. }
  146. func (j *CheckClientIpJob) checkAccessLogAvailable(iplimitActive bool) bool {
  147. accessLogPath, err := xray.GetAccessLogPath()
  148. if err != nil {
  149. return false
  150. }
  151. if accessLogPath == "none" || accessLogPath == "" {
  152. if iplimitActive {
  153. logger.Warning("[LimitIP] Access log path is not set, Please configure the access log path in Xray configs.")
  154. }
  155. return false
  156. }
  157. return true
  158. }
  159. func (j *CheckClientIpJob) checkError(e error) {
  160. if e != nil {
  161. logger.Warning("client ip job err:", e)
  162. }
  163. }
  164. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  165. db := database.GetDB()
  166. InboundClientIps := &model.InboundClientIps{}
  167. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  168. if err != nil {
  169. return nil, err
  170. }
  171. return InboundClientIps, nil
  172. }
  173. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ips []string) error {
  174. inboundClientIps := &model.InboundClientIps{}
  175. jsonIps, err := json.Marshal(ips)
  176. j.checkError(err)
  177. inboundClientIps.ClientEmail = clientEmail
  178. inboundClientIps.Ips = string(jsonIps)
  179. db := database.GetDB()
  180. tx := db.Begin()
  181. defer func() {
  182. if err == nil {
  183. tx.Commit()
  184. } else {
  185. tx.Rollback()
  186. }
  187. }()
  188. err = tx.Save(inboundClientIps).Error
  189. if err != nil {
  190. return err
  191. }
  192. return nil
  193. }
  194. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
  195. jsonIps, err := json.Marshal(ips)
  196. if err != nil {
  197. logger.Error("failed to marshal IPs to JSON:", err)
  198. return false
  199. }
  200. inboundClientIps.ClientEmail = clientEmail
  201. inboundClientIps.Ips = string(jsonIps)
  202. inbound, err := j.getInboundByEmail(clientEmail)
  203. if err != nil {
  204. logger.Errorf("failed to fetch inbound settings for email %s: %s", clientEmail, err)
  205. return false
  206. }
  207. if inbound.Settings == "" {
  208. logger.Debug("wrong data:", inbound)
  209. return false
  210. }
  211. settings := map[string][]model.Client{}
  212. json.Unmarshal([]byte(inbound.Settings), &settings)
  213. clients := settings["clients"]
  214. shouldCleanLog := false
  215. j.disAllowedIps = []string{}
  216. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  217. if err != nil {
  218. logger.Errorf("failed to open IP limit log file: %s", err)
  219. return false
  220. }
  221. defer logIpFile.Close()
  222. log.SetOutput(logIpFile)
  223. log.SetFlags(log.LstdFlags)
  224. for _, client := range clients {
  225. if client.Email == clientEmail {
  226. limitIp := client.LimitIP
  227. if limitIp > 0 && inbound.Enable {
  228. shouldCleanLog = true
  229. if limitIp < len(ips) {
  230. j.disAllowedIps = append(j.disAllowedIps, ips[limitIp:]...)
  231. for i := limitIp; i < len(ips); i++ {
  232. log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
  233. }
  234. }
  235. }
  236. }
  237. }
  238. sort.Strings(j.disAllowedIps)
  239. if len(j.disAllowedIps) > 0 {
  240. logger.Debug("disAllowedIps:", j.disAllowedIps)
  241. }
  242. db := database.GetDB()
  243. err = db.Save(inboundClientIps).Error
  244. if err != nil {
  245. logger.Error("failed to save inboundClientIps:", err)
  246. return false
  247. }
  248. return shouldCleanLog
  249. }
  250. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  251. db := database.GetDB()
  252. inbound := &model.Inbound{}
  253. err := db.Model(&model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").First(inbound).Error
  254. if err != nil {
  255. return nil, err
  256. }
  257. return inbound, nil
  258. }