check_clinet_ip_job.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. // Trim any leading/trailing whitespace from clientEmail
  132. clientEmail = strings.TrimSpace(clientEmail)
  133. inboundClientIps.ClientEmail = clientEmail
  134. inboundClientIps.Ips = string(jsonIps)
  135. db := database.GetDB()
  136. tx := db.Begin()
  137. defer func() {
  138. if err == nil {
  139. tx.Commit()
  140. } else {
  141. tx.Rollback()
  142. }
  143. }()
  144. err = tx.Save(inboundClientIps).Error
  145. if err != nil {
  146. return err
  147. }
  148. return nil
  149. }
  150. func updateInboundClientIps(inboundClientIps *model.InboundClientIps,clientEmail string,ips []string) error {
  151. jsonIps, err := json.Marshal(ips)
  152. checkError(err)
  153. inboundClientIps.ClientEmail = clientEmail
  154. inboundClientIps.Ips = string(jsonIps)
  155. // check inbound limitation
  156. inbound, err := GetInboundByEmail(clientEmail)
  157. checkError(err)
  158. if inbound.Settings == "" {
  159. logger.Debug("wrong data ",inbound)
  160. return nil
  161. }
  162. settings := map[string][]model.Client{}
  163. json.Unmarshal([]byte(inbound.Settings), &settings)
  164. clients := settings["clients"]
  165. for _, client := range clients {
  166. if client.Email == clientEmail {
  167. limitIp := client.LimitIP
  168. if(limitIp < len(ips) && limitIp != 0 && inbound.Enable) {
  169. disAllowedIps = append(disAllowedIps,ips[limitIp:]...)
  170. }
  171. }
  172. }
  173. logger.Debug("disAllowedIps ",disAllowedIps)
  174. sort.Sort(sort.StringSlice(disAllowedIps))
  175. db := database.GetDB()
  176. err = db.Save(inboundClientIps).Error
  177. if err != nil {
  178. return err
  179. }
  180. return nil
  181. }
  182. func DisableInbound(id int) error{
  183. db := database.GetDB()
  184. result := db.Model(model.Inbound{}).
  185. Where("id = ? and enable = ?", id, true).
  186. Update("enable", false)
  187. err := result.Error
  188. logger.Warning("disable inbound with id:",id)
  189. if err == nil {
  190. job.xrayService.SetToNeedRestart()
  191. }
  192. return err
  193. }
  194. func GetInboundByEmail(clientEmail string) (*model.Inbound, error) {
  195. db := database.GetDB()
  196. var inbounds *model.Inbound
  197. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%" + clientEmail + "%").Find(&inbounds).Error
  198. if err != nil {
  199. return nil, err
  200. }
  201. return inbounds, nil
  202. }
  203. func LimitDevice() {
  204. var destIp, destPort, srcIp, srcPort string
  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. if len(data) < 2 {
  215. continue // Skip this row if it doesn't have at least two elements
  216. }
  217. destIp = string(ipRegx.FindString(data[0]))
  218. destPort = portRegx.FindString(data[0])
  219. destPort = strings.Replace(destPort,":","",-1)
  220. srcIp = string(ipRegx.FindString(data[1]))
  221. srcPort = portRegx.FindString(data[1])
  222. srcPort = strings.Replace(srcPort,":","",-1)
  223. if contains(disAllowedIps,srcIp){
  224. dropCmd := cmd.NewCmd("bash","-c","ss -K dport = " + srcPort)
  225. dropCmd.Start()
  226. logger.Debug("request droped : ",srcIp,srcPort,"to",destIp,destPort)
  227. }
  228. }
  229. }
  230. }
  231. func LocalIP() ([]string, error) {
  232. // get machine ips
  233. ifaces, err := net.Interfaces()
  234. ips := []string{}
  235. if err != nil {
  236. return ips, err
  237. }
  238. for _, i := range ifaces {
  239. addrs, err := i.Addrs()
  240. if err != nil {
  241. return ips, err
  242. }
  243. for _, addr := range addrs {
  244. var ip net.IP
  245. switch v := addr.(type) {
  246. case *net.IPNet:
  247. ip = v.IP
  248. case *net.IPAddr:
  249. ip = v.IP
  250. }
  251. ips = append(ips,ip.String())
  252. }
  253. }
  254. logger.Debug("System IPs : ",ips)
  255. return ips, nil
  256. }
  257. func IPsToRegex(ips []string) (string){
  258. regx := ""
  259. for _, ip := range ips {
  260. regx += "(" + strings.Replace(ip, ".", "\\.", -1) + ")"
  261. }
  262. regx = "(" + strings.Replace(regx, ")(", ")|(.", -1) + ")"
  263. return regx
  264. }
  265. func schedule(LimitDevice func(), delay time.Duration) chan bool {
  266. stop := make(chan bool)
  267. go func() {
  268. for {
  269. LimitDevice()
  270. select {
  271. case <-time.After(delay):
  272. case <-stop:
  273. return
  274. }
  275. }
  276. }()
  277. return stop
  278. }