check_clinet_ip_job.go 7.6 KB

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