3x-ui/web/job/check_client_ip_job.go

305 lines
6.8 KiB
Go
Raw Normal View History

2023-02-28 22:54:29 +03:00
package job
import (
"bufio"
2023-04-13 22:37:13 +03:00
"encoding/json"
"io"
"log"
2023-04-13 22:37:13 +03:00
"os"
2023-09-01 12:53:50 +03:00
"os/exec"
2023-04-13 22:37:13 +03:00
"regexp"
"sort"
"strings"
"time"
2023-02-28 22:54:29 +03:00
"x-ui/database"
"x-ui/database/model"
2023-04-13 22:37:13 +03:00
"x-ui/logger"
"x-ui/xray"
2023-02-28 22:54:29 +03:00
)
type CheckClientIpJob struct {
lastClear int64
disAllowedIps []string
}
2023-04-13 22:37:13 +03:00
2023-02-28 22:54:29 +03:00
var job *CheckClientIpJob
func NewCheckClientIpJob() *CheckClientIpJob {
job = new(CheckClientIpJob)
2023-02-28 22:54:29 +03:00
return job
}
func (j *CheckClientIpJob) Run() {
if j.lastClear == 0 {
j.lastClear = time.Now().Unix()
}
f2bInstalled := j.checkFail2BanInstalled()
accessLogPath := xray.GetAccessLogPath()
clearAccessLog := false
if j.hasLimitIp() {
if f2bInstalled && accessLogPath == "./access.log" {
clearAccessLog = j.processLogFile()
2024-03-02 20:40:12 +03:00
} else {
if !f2bInstalled {
2024-03-02 20:40:12 +03:00
logger.Warning("fail2ban is not installed. IP limiting may not work properly.")
}
switch accessLogPath {
2024-03-02 20:40:12 +03:00
case "none":
logger.Warning("Access log is set to 'none', check your Xray Configs")
case "":
logger.Warning("Access log doesn't exist in your Xray Configs")
default:
logger.Warning("Current access.log path is not compatible with IP Limit")
2024-03-02 20:40:12 +03:00
}
}
}
if clearAccessLog || accessLogPath == "./access.log" && time.Now().Unix() - j.lastClear > 3600 {
j.clearAccessLog()
}
}
func (j *CheckClientIpJob) clearAccessLog() {
logAccessP, err := os.OpenFile(xray.GetAccessPersistentLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
j.checkError(err)
// reopen the access log file for reading
accessLogPath := xray.GetAccessLogPath()
file, err := os.Open(accessLogPath)
j.checkError(err)
// copy access log content to persistent file
_, err = io.Copy(logAccessP, file)
j.checkError(err)
2024-03-02 20:40:12 +03:00
// close the file after copying content
logAccessP.Close()
2024-03-02 20:40:12 +03:00
file.Close()
// clean access log
err = os.Truncate(accessLogPath, 0)
j.checkError(err)
j.lastClear = time.Now().Unix()
2023-02-28 22:54:29 +03:00
}
func (j *CheckClientIpJob) hasLimitIp() bool {
db := database.GetDB()
var inbounds []*model.Inbound
err := db.Model(model.Inbound{}).Find(&inbounds).Error
if err != nil {
return false
}
for _, inbound := range inbounds {
if inbound.Settings == "" {
continue
}
settings := map[string][]model.Client{}
json.Unmarshal([]byte(inbound.Settings), &settings)
clients := settings["clients"]
for _, client := range clients {
limitIp := client.LimitIP
if limitIp > 0 {
return true
}
}
}
return false
}
2024-03-02 20:40:12 +03:00
func (j *CheckClientIpJob) checkFail2BanInstalled() bool {
2023-09-01 12:53:50 +03:00
cmd := "fail2ban-client"
args := []string{"-h"}
err := exec.Command(cmd, args...).Run()
2024-03-02 20:40:12 +03:00
return err == nil
}
func (j *CheckClientIpJob) processLogFile() bool {
accessLogPath := xray.GetAccessLogPath()
file, err := os.Open(accessLogPath)
j.checkError(err)
InboundClientIps := make(map[string][]string)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
2023-02-28 22:54:29 +03:00
ipRegx, _ := regexp.Compile(`(\d+\.\d+\.\d+\.\d+).* accepted`)
emailRegx, _ := regexp.Compile(`email:.+`)
2023-02-28 22:54:29 +03:00
matches := ipRegx.FindStringSubmatch(line)
if len(matches) > 1 {
ip := matches[1]
if ip == "127.0.0.1" {
2023-02-28 22:54:29 +03:00
continue
}
matchesEmail := emailRegx.FindString(line)
2023-04-13 22:37:13 +03:00
if matchesEmail == "" {
2023-02-28 22:54:29 +03:00
continue
}
2023-05-23 17:24:15 +03:00
matchesEmail = strings.TrimSpace(strings.Split(matchesEmail, "email: ")[1])
2023-04-13 22:37:13 +03:00
if InboundClientIps[matchesEmail] != nil {
if j.contains(InboundClientIps[matchesEmail], ip) {
continue
}
InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
} else {
2023-04-13 22:37:13 +03:00
InboundClientIps[matchesEmail] = append(InboundClientIps[matchesEmail], ip)
}
2023-02-28 22:54:29 +03:00
}
}
j.checkError(scanner.Err())
file.Close()
shouldCleanLog := false
2023-02-28 22:54:29 +03:00
for clientEmail, ips := range InboundClientIps {
inboundClientIps, err := j.getInboundClientIps(clientEmail)
2023-04-28 00:00:49 +03:00
sort.Strings(ips)
2023-04-13 22:37:13 +03:00
if err != nil {
j.addInboundClientIps(clientEmail, ips)
2023-04-13 22:37:13 +03:00
} else {
shouldCleanLog = j.updateInboundClientIps(inboundClientIps, clientEmail, ips)
2023-02-28 22:54:29 +03:00
}
2023-04-13 22:37:13 +03:00
}
return shouldCleanLog
2023-02-28 22:54:29 +03:00
}
func (j *CheckClientIpJob) checkError(e error) {
2023-04-13 22:37:13 +03:00
if e != nil {
2023-02-28 22:54:29 +03:00
logger.Warning("client ip job err:", e)
}
}
func (j *CheckClientIpJob) contains(s []string, str string) bool {
2023-02-28 22:54:29 +03:00
for _, v := range s {
if v == str {
return true
}
}
2023-02-28 22:54:29 +03:00
return false
}
func (j *CheckClientIpJob) getInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
2023-02-28 22:54:29 +03:00
db := database.GetDB()
InboundClientIps := &model.InboundClientIps{}
err := db.Model(model.InboundClientIps{}).Where("client_email = ?", clientEmail).First(InboundClientIps).Error
if err != nil {
return nil, err
}
return InboundClientIps, nil
}
func (j *CheckClientIpJob) addInboundClientIps(clientEmail string, ips []string) error {
2023-02-28 22:54:29 +03:00
inboundClientIps := &model.InboundClientIps{}
jsonIps, err := json.Marshal(ips)
j.checkError(err)
2023-02-28 22:54:29 +03:00
inboundClientIps.ClientEmail = clientEmail
inboundClientIps.Ips = string(jsonIps)
db := database.GetDB()
tx := db.Begin()
defer func() {
if err == nil {
tx.Commit()
} else {
tx.Rollback()
2023-02-28 22:54:29 +03:00
}
}()
err = tx.Save(inboundClientIps).Error
if err != nil {
return err
}
return nil
}
func (j *CheckClientIpJob) updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) bool {
jsonIps, err := json.Marshal(ips)
j.checkError(err)
inboundClientIps.ClientEmail = clientEmail
inboundClientIps.Ips = string(jsonIps)
2023-04-13 22:37:13 +03:00
2023-02-28 22:54:29 +03:00
// check inbound limitation
inbound, err := j.getInboundByEmail(clientEmail)
j.checkError(err)
2023-02-28 22:54:29 +03:00
if inbound.Settings == "" {
2023-04-13 22:37:13 +03:00
logger.Debug("wrong data ", inbound)
return false
2023-02-28 22:54:29 +03:00
}
settings := map[string][]model.Client{}
json.Unmarshal([]byte(inbound.Settings), &settings)
clients := settings["clients"]
shouldCleanLog := false
j.disAllowedIps = []string{}
2023-02-28 22:54:29 +03:00
// create iplimit log file channel
logIpFile, err := os.OpenFile(xray.GetIPLimitLogPath(), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
logger.Errorf("failed to create or open ip limit log file: %s", err)
}
defer logIpFile.Close()
log.SetOutput(logIpFile)
log.SetFlags(log.LstdFlags)
2023-02-28 22:54:29 +03:00
for _, client := range clients {
if client.Email == clientEmail {
limitIp := client.LimitIP
if limitIp != 0 {
shouldCleanLog = true
if limitIp < len(ips) && inbound.Enable {
j.disAllowedIps = append(j.disAllowedIps, ips[limitIp:]...)
for i := limitIp; i < len(ips); i++ {
log.Printf("[LIMIT_IP] Email = %s || SRC = %s", clientEmail, ips[i])
}
}
}
2023-02-28 22:54:29 +03:00
}
}
sort.Strings(j.disAllowedIps)
if len(j.disAllowedIps) > 0 {
logger.Debug("disAllowedIps ", j.disAllowedIps)
}
2023-02-28 22:54:29 +03:00
db := database.GetDB()
err = db.Save(inboundClientIps).Error
j.checkError(err)
return shouldCleanLog
2023-02-28 22:54:29 +03:00
}
func (j *CheckClientIpJob) getInboundByEmail(clientEmail string) (*model.Inbound, error) {
2023-02-28 22:54:29 +03:00
db := database.GetDB()
var inbounds *model.Inbound
2023-04-13 22:37:13 +03:00
err := db.Model(model.Inbound{}).Where("settings LIKE ?", "%"+clientEmail+"%").Find(&inbounds).Error
2023-02-28 22:54:29 +03:00
if err != nil {
return nil, err
}
2023-02-28 22:54:29 +03:00
return inbounds, nil
}