check_client_ip_job.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package job
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "io"
  6. "log"
  7. "os"
  8. "os/exec"
  9. "regexp"
  10. "sort"
  11. "strings"
  12. "time"
  13. "x-ui/database"
  14. "x-ui/database/model"
  15. "x-ui/logger"
  16. "x-ui/xray"
  17. )
  18. type CheckClientIpJob struct {
  19. lastClear int64
  20. disAllowedIps []string
  21. }
  22. var job *CheckClientIpJob
  23. func NewCheckClientIpJob() *CheckClientIpJob {
  24. job = new(CheckClientIpJob)
  25. return job
  26. }
  27. func (j *CheckClientIpJob) Run() {
  28. if j.lastClear == 0 {
  29. j.lastClear = time.Now().Unix()
  30. }
  31. f2bInstalled := j.checkFail2BanInstalled()
  32. accessLogPath := xray.GetAccessLogPath()
  33. clearAccessLog := false
  34. if j.hasLimitIp() {
  35. if f2bInstalled && accessLogPath == "./access.log" {
  36. clearAccessLog = j.processLogFile()
  37. } else {
  38. if !f2bInstalled {
  39. logger.Warning("fail2ban is not installed. IP limiting may not work properly.")
  40. }
  41. switch accessLogPath {
  42. case "none":
  43. logger.Warning("Access log is set to 'none', check your Xray Configs")
  44. case "":
  45. logger.Warning("Access log doesn't exist in your Xray Configs")
  46. default:
  47. logger.Warning("Current access.log path is not compatible with IP Limit")
  48. }
  49. }
  50. }
  51. if clearAccessLog || accessLogPath == "./access.log" && time.Now().Unix() - j.lastClear > 3600 {
  52. j.clearAccessLog()
  53. }
  54. }
  55. func (j *CheckClientIpJob) clearAccessLog() {
  56. logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  57. j.checkError(err)
  58. // reopen the access log file for reading
  59. accessLogPath := xray.GetAccessLogPath()
  60. file, err := os.Open(accessLogPath)
  61. j.checkError(err)
  62. // copy access log content to persistent file
  63. _, err = io.Copy(logAccessP, file)
  64. j.checkError(err)
  65. // close the file after copying content
  66. logAccessP.Close()
  67. file.Close()
  68. // clean access log
  69. err = os.Truncate(accessLogPath, 0)
  70. j.checkError(err)
  71. j.lastClear = time.Now().Unix()
  72. }
  73. func (j *CheckClientIpJob) hasLimitIp() bool {
  74. db := database.GetDB()
  75. var inbounds []*model.Inbound
  76. err := db.Model(model.Inbound{}).Find(&inbounds).Error
  77. if err != nil {
  78. return false
  79. }
  80. for _, inbound := range inbounds {
  81. if inbound.Settings == "" {
  82. continue
  83. }
  84. settings := map[string][]model.Client{}
  85. json.Unmarshal([]byte(inbound.Settings), &settings)
  86. clients := settings["clients"]
  87. for _, client := range clients {
  88. limitIp := client.LimitIP
  89. if limitIp > 0 {
  90. return true
  91. }
  92. }
  93. }
  94. return false
  95. }
  96. func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
  97. cmd := "fail2ban-client"
  98. args := []string{"-h"}
  99. err := exec.Command(cmd, args...).Run()
  100. return err == nil
  101. }
  102. func (j *CheckClientIpJob) processLogFile() bool {
  103. accessLogPath := xray.GetAccessLogPath()
  104. file, err := os.Open(accessLogPath)
  105. j.checkError(err)
  106. InboundClientIps := make(map[string][]string)
  107. scanner := bufio.NewScanner(file)
  108. for scanner.Scan() {
  109. line := scanner.Text()
  110. ipRegx, _ := regexp.Compile(`(\d+\.\d+\.\d+\.\d+).* accepted`)
  111. emailRegx, _ := regexp.Compile(`email:.+`)
  112. matches := ipRegx.FindStringSubmatch(line)
  113. if len(matches) > 1 {
  114. ip := matches[1]
  115. if ip == "127.0.0.1" {
  116. continue
  117. }
  118. matchesEmail := emailRegx.FindString(line)
  119. if matchesEmail == "" {
  120. continue
  121. }
  122. matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
  123. if InboundClientIps[matchesEmail] != nil {
  124. if j.contains(InboundClientIps[matchesEmail], ip) {
  125. continue
  126. }
  127. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  128. } else {
  129. InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
  130. }
  131. }
  132. }
  133. j.checkError(scanner.Err())
  134. file.Close()
  135. shouldCleanLog := false
  136. for clientEmail, ips := range InboundClientIps {
  137. inboundClientIps, err := j.getInboundClientIps(clientEmail)
  138. sort.Strings(ips)
  139. if err != nil {
  140. j.addInboundClientIps(clientEmail, ips)
  141. } else {
  142. shouldCleanLog = j.updateInboundClientIps(inboundClientIps, clientEmail, ips)
  143. }
  144. }
  145. return shouldCleanLog
  146. }
  147. func (j *CheckClientIpJob) checkError(e error) {
  148. if e != nil {
  149. logger.Warning("client ip job err:", e)
  150. }
  151. }
  152. func (j *CheckClientIpJob) contains(s []string, str string) bool {
  153. for _, v := range s {
  154. if v == str {
  155. return true
  156. }
  157. }
  158. return false
  159. }
  160. func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
  161. db := database.GetDB()
  162. InboundClientIps := &model.InboundClientIps{}
  163. err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
  164. if err != nil {
  165. return nil, err
  166. }
  167. return InboundClientIps, nil
  168. }
  169. func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ips []string) error {
  170. inboundClientIps := &model.InboundClientIps{}
  171. jsonIps, err := json.Marshal(ips)
  172. j.checkError(err)
  173. inboundClientIps.ClientEmail = clientEmail
  174. inboundClientIps.Ips = string(jsonIps)
  175. db := database.GetDB()
  176. tx := db.Begin()
  177. defer func() {
  178. if err == nil {
  179. tx.Commit()
  180. } else {
  181. tx.Rollback()
  182. }
  183. }()
  184. err = tx.Save(inboundClientIps).Error
  185. if err != nil {
  186. return err
  187. }
  188. return nil
  189. }
  190. func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
  191. jsonIps, err := json.Marshal(ips)
  192. j.checkError(err)
  193. inboundClientIps.ClientEmail = clientEmail
  194. inboundClientIps.Ips = string(jsonIps)
  195. // check inbound limitation
  196. inbound, err := j.getInboundByEmail(clientEmail)
  197. j.checkError(err)
  198. if inbound.Settings == "" {
  199. logger.Debug("wrong data ", inbound)
  200. return false
  201. }
  202. settings := map[string][]model.Client{}
  203. json.Unmarshal([]byte(inbound.Settings), &settings)
  204. clients := settings["clients"]
  205. shouldCleanLog := false
  206. j.disAllowedIps = []string{}
  207. // create iplimit log file channel
  208. logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
  209. if err != nil {
  210. logger.Errorf("failed to create or open ip limit log file: %s", err)
  211. }
  212. defer logIpFile.Close()
  213. log.SetOutput(logIpFile)
  214. log.SetFlags(log.LstdFlags)
  215. for _, client := range clients {
  216. if client.Email == clientEmail {
  217. limitIp := client.LimitIP
  218. if limitIp != 0 {
  219. shouldCleanLog = true
  220. if limitIp < len(ips) && inbound.Enable {
  221. j.disAllowedIps = append(j.disAllowedIps, ips[limitIp:]...)
  222. for i := limitIp; i < len(ips); i++ {
  223. log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
  224. }
  225. }
  226. }
  227. }
  228. }
  229. sort.Strings(j.disAllowedIps)
  230. if len(j.disAllowedIps) > 0 {
  231. logger.Debug("disAllowedIps ", j.disAllowedIps)
  232. }
  233. db := database.GetDB()
  234. err = db.Save(inboundClientIps).Error
  235. j.checkError(err)
  236. return shouldCleanLog
  237. }
  238. func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
  239. db := database.GetDB()
  240. var inbounds *model.Inbound
  241. err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
  242. if err != nil {
  243. return nil, err
  244. }
  245. return inbounds, nil
  246. }