check_client_ip_job.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. // check if file exists, if not create one
  32. _, err := os.Stat(xray.GetBlockedIPsPath())
  33. if os.IsNotExist(err) {
  34. _, err = os.OpenFile(xray.GetBlockedIPsPath(), os.O_RDWR|os.O_CREATE, 0755)
  35. checkError(err)
  36. }
  37. err = os.WriteFile(xray.GetBlockedIPsPath(), blockedIps, 0755)
  38. checkError(err)
  39. }
  40. func processLogFile() {
  41. accessLogPath := GetAccessLogPath()
  42. if accessLogPath == "" {
  43. logger.Warning("access.log doesn't exist in your config.json")
  44. return
  45. }
  46. data, err := os.ReadFile(accessLogPath)
  47. InboundClientIps := make(map[string][]string)
  48. checkError(err)
  49. // clean log
  50. if err := os.Truncate(GetAccessLogPath(), 0); err != nil {
  51. checkError(err)
  52. }
  53. lines := strings.Split(string(data), "\n")
  54. for _, line := range lines {
  55. ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
  56. emailRegx, _ := regexp.Compile(`email:.+`)
  57. matchesIp := ipRegx.FindString(line)
  58. if len(matchesIp) > 0 {
  59. ip := string(matchesIp)
  60. if ip == "127.0.0.1" || ip == "1.1.1.1" {
  61. continue
  62. }
  63. matchesEmail := emailRegx.FindString(line)
  64. if matchesEmail == "" {
  65. continue
  66. }
  67. matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
  68. if InboundClientIps[matchesEmail] != nil {
  69. if contains(InboundClientIps[matchesEmail], ip) {
  70. continue
  71. }
  72. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  73. } else {
  74. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  75. }
  76. }
  77. }
  78. disAllowedIps = []string{}
  79. for clientEmail, ips := range InboundClientIps {
  80. inboundClientIps, err := GetInboundClientIps(clientEmail)
  81. sort.Strings(ips)
  82. if err != nil {
  83. addInboundClientIps(clientEmail, ips)
  84. } else {
  85. updateInboundClientIps(inboundClientIps, clientEmail, ips)
  86. }
  87. }
  88. // check if inbound connection is more than limited ip and drop connection
  89. LimitDevice := func() { LimitDevice() }
  90. stop := schedule(LimitDevice, 1000*time.Millisecond)
  91. time.Sleep(10 * time.Second)
  92. stop <- true
  93. }
  94. func GetAccessLogPath() string {
  95. config, err := os.ReadFile(xray.GetConfigPath())
  96. checkError(err)
  97. jsonConfig := map[string]interface{}{}
  98. err = json.Unmarshal([]byte(config), &jsonConfig)
  99. checkError(err)
  100. if jsonConfig["log"] != nil {
  101. jsonLog := jsonConfig["log"].(map[string]interface{})
  102. if jsonLog["access"] != nil {
  103. accessLogPath := jsonLog["access"].(string)
  104. return accessLogPath
  105. }
  106. }
  107. return ""
  108. }
  109. func checkError(e error) {
  110. if e != nil {
  111. logger.Warning("client ip job err:", e)
  112. }
  113. }
  114. func contains(s []string, str string) bool {
  115. for _, v := range s {
  116. if v == str {
  117. return true
  118. }
  119. }
  120. return false
  121. }
  122. func GetInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  123. db := database.GetDB()
  124. InboundClientIps := &model.InboundClientIps{}
  125. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  126. if err != nil {
  127. return nil, err
  128. }
  129. return InboundClientIps, nil
  130. }
  131. func addInboundClientIps(clientEmail string, ips []string) error {
  132. inboundClientIps := &model.InboundClientIps{}
  133. jsonIps, err := json.Marshal(ips)
  134. checkError(err)
  135. inboundClientIps.ClientEmail = clientEmail
  136. inboundClientIps.Ips = string(jsonIps)
  137. db := database.GetDB()
  138. tx := db.Begin()
  139. defer func() {
  140. if err == nil {
  141. tx.Commit()
  142. } else {
  143. tx.Rollback()
  144. }
  145. }()
  146. err = tx.Save(inboundClientIps).Error
  147. if err != nil {
  148. return err
  149. }
  150. return nil
  151. }
  152. func updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) error {
  153. jsonIps, err := json.Marshal(ips)
  154. checkError(err)
  155. inboundClientIps.ClientEmail = clientEmail
  156. inboundClientIps.Ips = string(jsonIps)
  157. // check inbound limitation
  158. inbound, err := GetInboundByEmail(clientEmail)
  159. checkError(err)
  160. if inbound.Settings == "" {
  161. logger.Debug("wrong data ", inbound)
  162. return nil
  163. }
  164. settings := map[string][]model.Client{}
  165. json.Unmarshal([]byte(inbound.Settings), &settings)
  166. clients := settings["clients"]
  167. for _, client := range clients {
  168. if client.Email == clientEmail {
  169. limitIp := client.LimitIP
  170. if limitIp < len(ips) && limitIp != 0 && inbound.Enable {
  171. disAllowedIps = append(disAllowedIps, ips[limitIp:]...)
  172. }
  173. }
  174. }
  175. logger.Debug("disAllowedIps ", disAllowedIps)
  176. sort.Strings(disAllowedIps)
  177. db := database.GetDB()
  178. err = db.Save(inboundClientIps).Error
  179. if err != nil {
  180. return err
  181. }
  182. return nil
  183. }
  184. func DisableInbound(id int) error {
  185. db := database.GetDB()
  186. result := db.Model(model.Inbound{}).
  187. Where("id = ? and enable = ?", id, true).
  188. Update("enable", false)
  189. err := result.Error
  190. logger.Warning("disable inbound with id:", id)
  191. if err == nil {
  192. job.xrayService.SetToNeedRestart()
  193. }
  194. return err
  195. }
  196. func GetInboundByEmail(clientEmail string) (*model.Inbound, error) {
  197. db := database.GetDB()
  198. var inbounds *model.Inbound
  199. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  200. if err != nil {
  201. return nil, err
  202. }
  203. return inbounds, nil
  204. }
  205. func LimitDevice() {
  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. destIp, destPort, srcIp, srcPort := "", "", "", ""
  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. }