1
0

check_client_ip_job.go 6.5 KB

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