check_client_ip_job.go 6.8 KB

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