check_client_ip_job.go 7.1 KB

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