1
0

check_client_ip_job.go 7.5 KB

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