check_client_ip_job.go 7.0 KB

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