check_client_ip_job.go 7.5 KB

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