check_client_ip_job.go 7.0 KB

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