1
0

check_client_ip_job.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. var job *CheckClientIpJob
  18. var disAllowedIps []string
  19. var ipFiles = []string{
  20. xray.GetIPLimitLogPath(),
  21. xray.GetIPLimitPrevLogPath(),
  22. xray.GetIPLimitBannedLogPath(),
  23. xray.GetIPLimitBannedPrevLogPath(),
  24. xray.GetAccessPersistentLogPath(),
  25. xray.GetAccessPersistentPrevLogPath(),
  26. }
  27. func NewCheckClientIpJob() *CheckClientIpJob {
  28. job = new(CheckClientIpJob)
  29. return job
  30. }
  31. func (j *CheckClientIpJob) Run() {
  32. // create files required for iplimit if not exists
  33. for i := 0; i < len(ipFiles); i++ {
  34. file, err := os.OpenFile(ipFiles[i], os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  35. j.checkError(err)
  36. defer file.Close()
  37. }
  38. // check for limit ip
  39. if j.hasLimitIp() {
  40. j.checkFail2BanInstalled()
  41. j.processLogFile()
  42. }
  43. }
  44. func (j *CheckClientIpJob) hasLimitIp() bool {
  45. db := database.GetDB()
  46. var inbounds []*model.Inbound
  47. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  48. if err != nil {
  49. return false
  50. }
  51. for _, inbound := range inbounds {
  52. if inbound.Settings == "" {
  53. continue
  54. }
  55. settings := map[string][]model.Client{}
  56. json.Unmarshal([]byte(inbound.Settings), &settings)
  57. clients := settings["clients"]
  58. for _, client := range clients {
  59. limitIp := client.LimitIP
  60. if limitIp > 0 {
  61. return true
  62. }
  63. }
  64. }
  65. return false
  66. }
  67. func (j *CheckClientIpJob) checkFail2BanInstalled() {
  68. cmd := "fail2ban-client"
  69. args := []string{"-h"}
  70. err := exec.Command(cmd, args...).Run()
  71. if err != nil {
  72. logger.Warning("fail2ban is not installed. IP limiting may not work properly.")
  73. }
  74. }
  75. func (j *CheckClientIpJob) processLogFile() {
  76. accessLogPath := xray.GetAccessLogPath()
  77. if accessLogPath == "" {
  78. logger.Warning("access.log doesn't exist in your config.json")
  79. return
  80. }
  81. data, err := os.ReadFile(accessLogPath)
  82. InboundClientIps := make(map[string][]string)
  83. j.checkError(err)
  84. lines := strings.Split(string(data), "\n")
  85. for _, line := range lines {
  86. ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
  87. emailRegx, _ := regexp.Compile(`email:.+`)
  88. matchesIp := ipRegx.FindString(line)
  89. if len(matchesIp) > 0 {
  90. ip := string(matchesIp)
  91. if ip == "127.0.0.1" || ip == "1.1.1.1" {
  92. continue
  93. }
  94. matchesEmail := emailRegx.FindString(line)
  95. if matchesEmail == "" {
  96. continue
  97. }
  98. matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
  99. if InboundClientIps[matchesEmail] != nil {
  100. if j.contains(InboundClientIps[matchesEmail], ip) {
  101. continue
  102. }
  103. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  104. } else {
  105. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  106. }
  107. }
  108. }
  109. disAllowedIps = []string{}
  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. // create iplimit log file channel
  198. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_RDWR, 0644)
  199. if err != nil {
  200. logger.Errorf("failed to create or open ip limit log file: %s", err)
  201. }
  202. defer logIpFile.Close()
  203. log.SetOutput(logIpFile)
  204. log.SetFlags(log.LstdFlags)
  205. for _, client := range clients {
  206. if client.Email == clientEmail {
  207. limitIp := client.LimitIP
  208. if limitIp != 0 {
  209. shouldCleanLog = true
  210. if limitIp < len(ips) && inbound.Enable {
  211. disAllowedIps = append(disAllowedIps, ips[limitIp:]...)
  212. for i := limitIp; i < len(ips); i++ {
  213. log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
  214. }
  215. }
  216. }
  217. }
  218. }
  219. logger.Debug("disAllowedIps ", disAllowedIps)
  220. sort.Strings(disAllowedIps)
  221. db := database.GetDB()
  222. err = db.Save(inboundClientIps).Error
  223. if err != nil {
  224. return shouldCleanLog
  225. }
  226. return shouldCleanLog
  227. }
  228. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  229. db := database.GetDB()
  230. var inbounds *model.Inbound
  231. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  232. if err != nil {
  233. return nil, err
  234. }
  235. return inbounds, nil
  236. }