check_client_ip_job.go 7.1 KB

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