check_client_ip_job.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package job
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "io"
  6. "log"
  7. "os"
  8. "os/exec"
  9. "regexp"
  10. "sort"
  11. "strings"
  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. disAllowedIps []string
  20. }
  21. var job *CheckClientIpJob
  22. var ipFiles = []string{
  23. xray.GetIPLimitLogPath(),
  24. xray.GetIPLimitPrevLogPath(),
  25. xray.GetIPLimitBannedLogPath(),
  26. xray.GetIPLimitBannedPrevLogPath(),
  27. xray.GetAccessPersistentLogPath(),
  28. xray.GetAccessPersistentPrevLogPath(),
  29. }
  30. func NewCheckClientIpJob() *CheckClientIpJob {
  31. job = new(CheckClientIpJob)
  32. return job
  33. }
  34. func (j *CheckClientIpJob) Run() {
  35. // create files required for iplimit if not exists
  36. for i := 0; i < len(ipFiles); i++ {
  37. file, err := os.OpenFile(ipFiles[i], os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  38. j.checkError(err)
  39. defer file.Close()
  40. }
  41. // check for limit ip
  42. if j.hasLimitIp() {
  43. j.checkFail2BanInstalled()
  44. j.processLogFile()
  45. }
  46. }
  47. func (j *CheckClientIpJob) hasLimitIp() bool {
  48. db := database.GetDB()
  49. var inbounds []*model.Inbound
  50. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  51. if err != nil {
  52. return false
  53. }
  54. for _, inbound := range inbounds {
  55. if inbound.Settings == "" {
  56. continue
  57. }
  58. settings := map[string][]model.Client{}
  59. json.Unmarshal([]byte(inbound.Settings), &settings)
  60. clients := settings["clients"]
  61. for _, client := range clients {
  62. limitIp := client.LimitIP
  63. if limitIp > 0 {
  64. return true
  65. }
  66. }
  67. }
  68. return false
  69. }
  70. func (j *CheckClientIpJob) checkFail2BanInstalled() {
  71. cmd := "fail2ban-client"
  72. args := []string{"-h"}
  73. err := exec.Command(cmd, args...).Run()
  74. if err != nil {
  75. logger.Error("fail2ban is not installed. IP limiting may not work properly.")
  76. }
  77. }
  78. func (j *CheckClientIpJob) processLogFile() {
  79. accessLogPath := xray.GetAccessLogPath()
  80. if accessLogPath == "none" {
  81. logger.Error("Access log is set to 'none' check your Xray Configs")
  82. return
  83. }
  84. if accessLogPath == "" {
  85. logger.Error("Access log doesn't exist in your Xray Configs")
  86. return
  87. }
  88. file, err := os.Open(accessLogPath)
  89. j.checkError(err)
  90. defer file.Close()
  91. InboundClientIps := make(map[string][]string)
  92. scanner := bufio.NewScanner(file)
  93. for scanner.Scan() {
  94. line := scanner.Text()
  95. ipRegx, _ := regexp.Compile(`(\d+\.\d+\.\d+\.\d+).* accepted`)
  96. emailRegx, _ := regexp.Compile(`email:.+`)
  97. matches := ipRegx.FindStringSubmatch(line)
  98. if len(matches) > 1 {
  99. ip := matches[1]
  100. if ip == "127.0.0.1" || ip == "[::1]" {
  101. continue
  102. }
  103. matchesEmail := emailRegx.FindString(line)
  104. if matchesEmail == "" {
  105. continue
  106. }
  107. matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
  108. if InboundClientIps[matchesEmail] != nil {
  109. if j.contains(InboundClientIps[matchesEmail], ip) {
  110. continue
  111. }
  112. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  113. } else {
  114. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  115. }
  116. }
  117. }
  118. j.checkError(scanner.Err())
  119. shouldCleanLog := false
  120. for clientEmail, ips := range InboundClientIps {
  121. inboundClientIps, err := j.getInboundClientIps(clientEmail)
  122. sort.Strings(ips)
  123. if err != nil {
  124. j.addInboundClientIps(clientEmail, ips)
  125. } else {
  126. shouldCleanLog = j.updateInboundClientIps(inboundClientIps, clientEmail, ips)
  127. }
  128. }
  129. // added delay before cleaning logs to reduce chance of logging IP that already has been banned
  130. time.Sleep(time.Second * 2)
  131. if shouldCleanLog {
  132. // copy access log to persistent file
  133. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  134. j.checkError(err)
  135. defer logAccessP.Close()
  136. // reopen the access log file for reading
  137. file, err := os.Open(accessLogPath)
  138. j.checkError(err)
  139. defer file.Close()
  140. // copy access log content to persistent file
  141. _, err = io.Copy(logAccessP, file)
  142. j.checkError(err)
  143. // clean access log
  144. if err := os.Truncate(xray.GetAccessLogPath(), 0); err != nil {
  145. j.checkError(err)
  146. }
  147. }
  148. }
  149. func (j *CheckClientIpJob) checkError(e error) {
  150. if e != nil {
  151. logger.Warning("client ip job err:", e)
  152. }
  153. }
  154. func (j *CheckClientIpJob) contains(s []string, str string) bool {
  155. for _, v := range s {
  156. if v == str {
  157. return true
  158. }
  159. }
  160. return false
  161. }
  162. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  163. db := database.GetDB()
  164. InboundClientIps := &model.InboundClientIps{}
  165. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  166. if err != nil {
  167. return nil, err
  168. }
  169. return InboundClientIps, nil
  170. }
  171. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ips []string) error {
  172. inboundClientIps := &model.InboundClientIps{}
  173. jsonIps, err := json.Marshal(ips)
  174. j.checkError(err)
  175. inboundClientIps.ClientEmail = clientEmail
  176. inboundClientIps.Ips = string(jsonIps)
  177. db := database.GetDB()
  178. tx := db.Begin()
  179. defer func() {
  180. if err == nil {
  181. tx.Commit()
  182. } else {
  183. tx.Rollback()
  184. }
  185. }()
  186. err = tx.Save(inboundClientIps).Error
  187. if err != nil {
  188. return err
  189. }
  190. return nil
  191. }
  192. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
  193. jsonIps, err := json.Marshal(ips)
  194. j.checkError(err)
  195. inboundClientIps.ClientEmail = clientEmail
  196. inboundClientIps.Ips = string(jsonIps)
  197. // check inbound limitation
  198. inbound, err := j.getInboundByEmail(clientEmail)
  199. j.checkError(err)
  200. if inbound.Settings == "" {
  201. logger.Debug("wrong data ", inbound)
  202. return false
  203. }
  204. settings := map[string][]model.Client{}
  205. json.Unmarshal([]byte(inbound.Settings), &settings)
  206. clients := settings["clients"]
  207. shouldCleanLog := false
  208. j.disAllowedIps = []string{}
  209. // create iplimit log file channel
  210. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  211. if err != nil {
  212. logger.Errorf("failed to create or open ip limit log file: %s", err)
  213. }
  214. defer logIpFile.Close()
  215. log.SetOutput(logIpFile)
  216. log.SetFlags(log.LstdFlags)
  217. for _, client := range clients {
  218. if client.Email == clientEmail {
  219. limitIp := client.LimitIP
  220. if limitIp != 0 {
  221. shouldCleanLog = true
  222. if limitIp < len(ips) && inbound.Enable {
  223. j.disAllowedIps = append(j.disAllowedIps, ips[limitIp:]...)
  224. for i := limitIp; i < len(ips); i++ {
  225. log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
  226. }
  227. }
  228. }
  229. }
  230. }
  231. sort.Strings(j.disAllowedIps)
  232. if len(j.disAllowedIps) > 0 {
  233. logger.Debug("disAllowedIps ", j.disAllowedIps)
  234. }
  235. db := database.GetDB()
  236. err = db.Save(inboundClientIps).Error
  237. if err != nil {
  238. return shouldCleanLog
  239. }
  240. return shouldCleanLog
  241. }
  242. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  243. db := database.GetDB()
  244. var inbounds *model.Inbound
  245. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  246. if err != nil {
  247. return nil, err
  248. }
  249. return inbounds, nil
  250. }