check_client_ip_job.go 7.1 KB

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