check_client_ip_job.go 6.6 KB

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