check_client_ip_job.go 7.8 KB

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