check_client_ip_job.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. package job
  2. import (
  3. "encoding/json"
  4. "os"
  5. "regexp"
  6. "x-ui/database"
  7. "x-ui/database/model"
  8. "x-ui/logger"
  9. "x-ui/web/service"
  10. "x-ui/xray"
  11. "net"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/go-cmd/cmd"
  16. )
  17. type CheckClientIpJob struct {
  18. xrayService service.XrayService
  19. }
  20. var job *CheckClientIpJob
  21. var disAllowedIps []string
  22. func NewCheckClientIpJob() *CheckClientIpJob {
  23. job = new(CheckClientIpJob)
  24. return job
  25. }
  26. func (j *CheckClientIpJob) Run() {
  27. logger.Debug("Check Client IP Job...")
  28. processLogFile()
  29. // disAllowedIps = []string{"192.168.1.183","192.168.1.197"}
  30. blockedIps := []byte(strings.Join(disAllowedIps, ","))
  31. err := os.WriteFile(xray.GetBlockedIPsPath(), blockedIps, 0755)
  32. checkError(err)
  33. }
  34. func processLogFile() {
  35. accessLogPath := GetAccessLogPath()
  36. if accessLogPath == "" {
  37. logger.Warning("xray log not init in config.json")
  38. return
  39. }
  40. data, err := os.ReadFile(accessLogPath)
  41. InboundClientIps := make(map[string][]string)
  42. checkError(err)
  43. // clean log
  44. if err := os.Truncate(GetAccessLogPath(), 0); err != nil {
  45. checkError(err)
  46. }
  47. lines := strings.Split(string(data), "\n")
  48. for _, line := range lines {
  49. ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
  50. emailRegx, _ := regexp.Compile(`email:.+`)
  51. matchesIp := ipRegx.FindString(line)
  52. if len(matchesIp) > 0 {
  53. ip := string(matchesIp)
  54. if ip == "127.0.0.1" || ip == "1.1.1.1" {
  55. continue
  56. }
  57. matchesEmail := emailRegx.FindString(line)
  58. if matchesEmail == "" {
  59. continue
  60. }
  61. matchesEmail = strings.Split(matchesEmail, "email: ")[1]
  62. if InboundClientIps[matchesEmail] != nil {
  63. if contains(InboundClientIps[matchesEmail], ip) {
  64. continue
  65. }
  66. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  67. } else {
  68. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  69. }
  70. }
  71. }
  72. disAllowedIps = []string{}
  73. for clientEmail, ips := range InboundClientIps {
  74. inboundClientIps, err := GetInboundClientIps(clientEmail)
  75. sort.Strings(ips)
  76. if err != nil {
  77. addInboundClientIps(clientEmail, ips)
  78. } else {
  79. updateInboundClientIps(inboundClientIps, clientEmail, ips)
  80. }
  81. }
  82. // check if inbound connection is more than limited ip and drop connection
  83. LimitDevice := func() { LimitDevice() }
  84. stop := schedule(LimitDevice, 1000*time.Millisecond)
  85. time.Sleep(10 * time.Second)
  86. stop <- true
  87. }
  88. func GetAccessLogPath() string {
  89. config, err := os.ReadFile(xray.GetConfigPath())
  90. checkError(err)
  91. jsonConfig := map[string]interface{}{}
  92. err = json.Unmarshal([]byte(config), &jsonConfig)
  93. checkError(err)
  94. if jsonConfig["log"] != nil {
  95. jsonLog := jsonConfig["log"].(map[string]interface{})
  96. if jsonLog["access"] != nil {
  97. accessLogPath := jsonLog["access"].(string)
  98. return accessLogPath
  99. }
  100. }
  101. return ""
  102. }
  103. func checkError(e error) {
  104. if e != nil {
  105. logger.Warning("client ip job err:", e)
  106. }
  107. }
  108. func contains(s []string, str string) bool {
  109. for _, v := range s {
  110. if v == str {
  111. return true
  112. }
  113. }
  114. return false
  115. }
  116. func GetInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  117. db := database.GetDB()
  118. InboundClientIps := &model.InboundClientIps{}
  119. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  120. if err != nil {
  121. return nil, err
  122. }
  123. return InboundClientIps, nil
  124. }
  125. func addInboundClientIps(clientEmail string, ips []string) error {
  126. inboundClientIps := &model.InboundClientIps{}
  127. jsonIps, err := json.Marshal(ips)
  128. checkError(err)
  129. // Trim any leading/trailing whitespace from clientEmail
  130. clientEmail = strings.TrimSpace(clientEmail)
  131. inboundClientIps.ClientEmail = clientEmail
  132. inboundClientIps.Ips = string(jsonIps)
  133. db := database.GetDB()
  134. tx := db.Begin()
  135. defer func() {
  136. if err == nil {
  137. tx.Commit()
  138. } else {
  139. tx.Rollback()
  140. }
  141. }()
  142. err = tx.Save(inboundClientIps).Error
  143. if err != nil {
  144. return err
  145. }
  146. return nil
  147. }
  148. func updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) error {
  149. jsonIps, err := json.Marshal(ips)
  150. checkError(err)
  151. inboundClientIps.ClientEmail = clientEmail
  152. inboundClientIps.Ips = string(jsonIps)
  153. // check inbound limitation
  154. inbound, err := GetInboundByEmail(clientEmail)
  155. checkError(err)
  156. if inbound.Settings == "" {
  157. logger.Debug("wrong data ", inbound)
  158. return nil
  159. }
  160. settings := map[string][]model.Client{}
  161. json.Unmarshal([]byte(inbound.Settings), &settings)
  162. clients := settings["clients"]
  163. var disAllowedIps []string // initialize the slice
  164. for _, client := range clients {
  165. if client.Email == clientEmail {
  166. limitIp := client.LimitIP
  167. if limitIp < len(ips) && limitIp != 0 && inbound.Enable {
  168. disAllowedIps = append(disAllowedIps, ips[limitIp:]...)
  169. }
  170. }
  171. }
  172. logger.Debug("disAllowedIps ", disAllowedIps)
  173. sort.Strings(disAllowedIps)
  174. db := database.GetDB()
  175. err = db.Save(inboundClientIps).Error
  176. if err != nil {
  177. return err
  178. }
  179. return nil
  180. }
  181. func DisableInbound(id int) error {
  182. db := database.GetDB()
  183. result := db.Model(model.Inbound{}).
  184. Where("id = ? and enable = ?", id, true).
  185. Update("enable", false)
  186. err := result.Error
  187. logger.Warning("disable inbound with id:", id)
  188. if err == nil {
  189. job.xrayService.SetToNeedRestart()
  190. }
  191. return err
  192. }
  193. func GetInboundByEmail(clientEmail string) (*model.Inbound, error) {
  194. db := database.GetDB()
  195. var inbounds *model.Inbound
  196. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  197. if err != nil {
  198. return nil, err
  199. }
  200. return inbounds, nil
  201. }
  202. func LimitDevice() {
  203. var destIp, destPort, srcIp, srcPort string
  204. localIp, err := LocalIP()
  205. checkError(err)
  206. c := cmd.NewCmd("bash", "-c", "ss --tcp | grep -E '"+IPsToRegex(localIp)+"'| awk '{if($1==\"ESTAB\") print $4,$5;}'", "| sort | uniq -c | sort -nr | head")
  207. <-c.Start()
  208. if len(c.Status().Stdout) > 0 {
  209. ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
  210. portRegx, _ := regexp.Compile(`(?:(:))([0-9]..[^.][0-9]+)`)
  211. for _, row := range c.Status().Stdout {
  212. data := strings.Split(row, " ")
  213. if len(data) < 2 {
  214. continue // Skip this row if it doesn't have at least two elements
  215. }
  216. destIp = string(ipRegx.FindString(data[0]))
  217. destPort = portRegx.FindString(data[0])
  218. destPort = strings.Replace(destPort, ":", "", -1)
  219. srcIp = string(ipRegx.FindString(data[1]))
  220. srcPort = portRegx.FindString(data[1])
  221. srcPort = strings.Replace(srcPort, ":", "", -1)
  222. if contains(disAllowedIps, srcIp) {
  223. dropCmd := cmd.NewCmd("bash", "-c", "ss -K dport = "+srcPort)
  224. dropCmd.Start()
  225. logger.Debug("request droped : ", srcIp, srcPort, "to", destIp, destPort)
  226. }
  227. }
  228. }
  229. }
  230. func LocalIP() ([]string, error) {
  231. // get machine ips
  232. ifaces, err := net.Interfaces()
  233. ips := []string{}
  234. if err != nil {
  235. return ips, err
  236. }
  237. for _, i := range ifaces {
  238. addrs, err := i.Addrs()
  239. if err != nil {
  240. return ips, err
  241. }
  242. for _, addr := range addrs {
  243. var ip net.IP
  244. switch v := addr.(type) {
  245. case *net.IPNet:
  246. ip = v.IP
  247. case *net.IPAddr:
  248. ip = v.IP
  249. }
  250. ips = append(ips, ip.String())
  251. }
  252. }
  253. logger.Debug("System IPs : ", ips)
  254. return ips, nil
  255. }
  256. func IPsToRegex(ips []string) string {
  257. regx := ""
  258. for _, ip := range ips {
  259. regx += "(" + strings.Replace(ip, ".", "\\.", -1) + ")"
  260. }
  261. regx = "(" + strings.Replace(regx, ")(", ")|(.", -1) + ")"
  262. return regx
  263. }
  264. func schedule(LimitDevice func(), delay time.Duration) chan bool {
  265. stop := make(chan bool)
  266. go func() {
  267. for {
  268. LimitDevice()
  269. select {
  270. case <-time.After(delay):
  271. case <-stop:
  272. return
  273. }
  274. }
  275. }()
  276. return stop
  277. }