check_client_ip_job.go 7.2 KB

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