1
0

check_client_ip_job.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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. blockedIps := []byte(strings.Join(disAllowedIps, ","))
  30. // check if file exists, if not create one
  31. _, err := os.Stat(xray.GetBlockedIPsPath())
  32. if os.IsNotExist(err) {
  33. _, err = os.OpenFile(xray.GetBlockedIPsPath(), os.O_RDWR|os.O_CREATE, 0755)
  34. checkError(err)
  35. }
  36. err = os.WriteFile(xray.GetBlockedIPsPath(), blockedIps, 0755)
  37. checkError(err)
  38. }
  39. func processLogFile() {
  40. accessLogPath := GetAccessLogPath()
  41. if accessLogPath == "" {
  42. logger.Warning("access.log doesn't exist in your config.json")
  43. return
  44. }
  45. data, err := os.ReadFile(accessLogPath)
  46. InboundClientIps := make(map[string][]string)
  47. checkError(err)
  48. // clean log
  49. if err := os.Truncate(GetAccessLogPath(), 0); err != nil {
  50. checkError(err)
  51. }
  52. lines := strings.Split(string(data), "\n")
  53. for _, line := range lines {
  54. ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
  55. emailRegx, _ := regexp.Compile(`email:.+`)
  56. matchesIp := ipRegx.FindString(line)
  57. if len(matchesIp) > 0 {
  58. ip := string(matchesIp)
  59. if ip == "127.0.0.1" || ip == "1.1.1.1" {
  60. continue
  61. }
  62. matchesEmail := emailRegx.FindString(line)
  63. if matchesEmail == "" {
  64. continue
  65. }
  66. matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
  67. if InboundClientIps[matchesEmail] != nil {
  68. if contains(InboundClientIps[matchesEmail], ip) {
  69. continue
  70. }
  71. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  72. } else {
  73. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  74. }
  75. }
  76. }
  77. disAllowedIps = []string{}
  78. for clientEmail, ips := range InboundClientIps {
  79. inboundClientIps, err := GetInboundClientIps(clientEmail)
  80. sort.Strings(ips)
  81. if err != nil {
  82. addInboundClientIps(clientEmail, ips)
  83. } else {
  84. updateInboundClientIps(inboundClientIps, clientEmail, ips)
  85. }
  86. }
  87. // check if inbound connection is more than limited ip and drop connection
  88. LimitDevice := func() { LimitDevice() }
  89. stop := schedule(LimitDevice, 1000*time.Millisecond)
  90. time.Sleep(10 * time.Second)
  91. stop <- true
  92. }
  93. func GetAccessLogPath() string {
  94. config, err := os.ReadFile(xray.GetConfigPath())
  95. checkError(err)
  96. jsonConfig := map[string]interface{}{}
  97. err = json.Unmarshal([]byte(config), &jsonConfig)
  98. checkError(err)
  99. if jsonConfig["log"] != nil {
  100. jsonLog := jsonConfig["log"].(map[string]interface{})
  101. if jsonLog["access"] != nil {
  102. accessLogPath := jsonLog["access"].(string)
  103. return accessLogPath
  104. }
  105. }
  106. return ""
  107. }
  108. func checkError(e error) {
  109. if e != nil {
  110. logger.Warning("client ip job err:", e)
  111. }
  112. }
  113. func contains(s []string, str string) bool {
  114. for _, v := range s {
  115. if v == str {
  116. return true
  117. }
  118. }
  119. return false
  120. }
  121. func GetInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  122. db := database.GetDB()
  123. InboundClientIps := &model.InboundClientIps{}
  124. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  125. if err != nil {
  126. return nil, err
  127. }
  128. return InboundClientIps, nil
  129. }
  130. func addInboundClientIps(clientEmail string, ips []string) error {
  131. inboundClientIps := &model.InboundClientIps{}
  132. jsonIps, err := json.Marshal(ips)
  133. checkError(err)
  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.Strings(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. localIp, err := LocalIP()
  206. checkError(err)
  207. c := cmd.NewCmd("bash", "-c", "ss --tcp | grep -E '"+IPsToRegex(localIp)+"'| awk '{if($1==\"ESTAB\") print $4,$5;}'", "| sort | uniq -c | sort -nr | head")
  208. <-c.Start()
  209. if len(c.Status().Stdout) > 0 {
  210. ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
  211. portRegx, _ := regexp.Compile(`(?:(:))([0-9]..[^.][0-9]+)`)
  212. for _, row := range c.Status().Stdout {
  213. data := strings.Split(row, " ")
  214. destIp, destPort, srcIp, srcPort := "", "", "", ""
  215. destIp = string(ipRegx.FindString(data[0]))
  216. destPort = portRegx.FindString(data[0])
  217. destPort = strings.Replace(destPort, ":", "", -1)
  218. srcIp = string(ipRegx.FindString(data[1]))
  219. srcPort = portRegx.FindString(data[1])
  220. srcPort = strings.Replace(srcPort, ":", "", -1)
  221. if contains(disAllowedIps, srcIp) {
  222. dropCmd := cmd.NewCmd("bash", "-c", "ss -K dport = "+srcPort)
  223. dropCmd.Start()
  224. logger.Debug("request droped : ", srcIp, srcPort, "to", destIp, destPort)
  225. }
  226. }
  227. }
  228. }
  229. func LocalIP() ([]string, error) {
  230. // get machine ips
  231. ifaces, err := net.Interfaces()
  232. ips := []string{}
  233. if err != nil {
  234. return ips, err
  235. }
  236. for _, i := range ifaces {
  237. addrs, err := i.Addrs()
  238. if err != nil {
  239. return ips, err
  240. }
  241. for _, addr := range addrs {
  242. var ip net.IP
  243. switch v := addr.(type) {
  244. case *net.IPNet:
  245. ip = v.IP
  246. case *net.IPAddr:
  247. ip = v.IP
  248. }
  249. ips = append(ips, ip.String())
  250. }
  251. }
  252. logger.Debug("System IPs : ", ips)
  253. return ips, nil
  254. }
  255. func IPsToRegex(ips []string) string {
  256. regx := ""
  257. for _, ip := range ips {
  258. regx += "(" + strings.Replace(ip, ".", "\\.", -1) + ")"
  259. }
  260. regx = "(" + strings.Replace(regx, ")(", ")|(.", -1) + ")"
  261. return regx
  262. }
  263. func schedule(LimitDevice func(), delay time.Duration) chan bool {
  264. stop := make(chan bool)
  265. go func() {
  266. for {
  267. LimitDevice()
  268. select {
  269. case <-time.After(delay):
  270. case <-stop:
  271. return
  272. }
  273. }
  274. }()
  275. return stop
  276. }