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

351 lines
7.4 KiB
Go
Raw Normal View History

2023-02-28 22:54:29 +03:00
package job
import (
2023-04-13 22:37:13 +03:00
"encoding/json"
"os"
"regexp"
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/web/service"
"x-ui/xray"
2023-04-28 00:00:49 +03:00
2023-02-28 22:54:29 +03:00
"net"
"sort"
2023-04-13 22:37:13 +03:00
"strings"
"time"
2023-04-28 00:00:49 +03:00
"github.com/go-cmd/cmd"
2023-02-28 22:54:29 +03:00
)
type CheckClientIpJob struct {
2023-04-28 00:00:49 +03:00
xrayService service.XrayService
2023-02-28 22:54:29 +03:00
}
2023-04-13 22:37:13 +03:00
2023-02-28 22:54:29 +03:00
var job *CheckClientIpJob
var disAllowedIps []string
2023-02-28 22:54:29 +03:00
func NewCheckClientIpJob() *CheckClientIpJob {
job = new(CheckClientIpJob)
2023-02-28 22:54:29 +03:00
return job
}
func (j *CheckClientIpJob) Run() {
logger.Debug("Check Client IP Job...")
processLogFile()
2023-02-28 22:54:29 +03:00
blockedIps := []byte(strings.Join(disAllowedIps, ","))
2023-02-28 22:54:29 +03:00
2023-05-23 17:24:15 +03:00
// check if file exists, if not create one
_, err := os.Stat(xray.GetBlockedIPsPath())
2023-05-23 17:24:15 +03:00
if os.IsNotExist(err) {
_, err = os.OpenFile(xray.GetBlockedIPsPath(), os.O_RDWR|os.O_CREATE, 0755)
2023-05-23 17:24:15 +03:00
checkError(err)
}
err = os.WriteFile(xray.GetBlockedIPsPath(), blockedIps, 0755)
2023-05-23 17:24:15 +03:00
checkError(err)
2023-02-28 22:54:29 +03:00
}
func processLogFile() {
2023-02-28 22:54:29 +03:00
accessLogPath := GetAccessLogPath()
2023-04-13 22:37:13 +03:00
if accessLogPath == "" {
2023-05-23 17:24:15 +03:00
logger.Warning("access.log doesn't exist in your config.json")
2023-02-28 22:54:29 +03:00
return
}
2023-04-13 22:37:13 +03:00
data, err := os.ReadFile(accessLogPath)
2023-02-28 22:54:29 +03:00
InboundClientIps := make(map[string][]string)
2023-04-13 22:37:13 +03:00
checkError(err)
2023-02-28 22:54:29 +03:00
// clean log
if err := os.Truncate(GetAccessLogPath(), 0); err != nil {
checkError(err)
}
2023-04-13 22:37:13 +03:00
2023-04-28 00:00:49 +03:00
lines := strings.Split(string(data), "\n")
2023-02-28 22:54:29 +03:00
for _, line := range lines {
ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
emailRegx, _ := regexp.Compile(`email:.+`)
2023-02-28 22:54:29 +03:00
matchesIp := ipRegx.FindString(line)
2023-04-13 22:37:13 +03:00
if len(matchesIp) > 0 {
2023-02-28 22:54:29 +03:00
ip := string(matchesIp)
2023-04-13 22:37:13 +03:00
if ip == "127.0.0.1" || ip == "1.1.1.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 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
}
}
disAllowedIps = []string{}
2023-02-28 22:54:29 +03:00
for clientEmail, ips := range InboundClientIps {
2023-04-13 22:37:13 +03:00
inboundClientIps, err := GetInboundClientIps(clientEmail)
2023-04-28 00:00:49 +03:00
sort.Strings(ips)
2023-04-13 22:37:13 +03:00
if err != nil {
addInboundClientIps(clientEmail, ips)
2023-05-23 17:24:15 +03:00
2023-04-13 22:37:13 +03:00
} else {
updateInboundClientIps(inboundClientIps, clientEmail, ips)
2023-02-28 22:54:29 +03:00
}
2023-05-23 17:24:15 +03:00
2023-04-13 22:37:13 +03:00
}
2023-02-28 22:54:29 +03:00
// check if inbound connection is more than limited ip and drop connection
LimitDevice := func() { LimitDevice() }
2023-04-13 22:37:13 +03:00
stop := schedule(LimitDevice, 1000*time.Millisecond)
2023-02-28 22:54:29 +03:00
time.Sleep(10 * time.Second)
stop <- true
2023-04-13 22:37:13 +03:00
2023-02-28 22:54:29 +03:00
}
func GetAccessLogPath() string {
2023-04-13 22:37:13 +03:00
config, err := os.ReadFile(xray.GetConfigPath())
checkError(err)
2023-02-28 22:54:29 +03:00
jsonConfig := map[string]interface{}{}
2023-04-13 22:37:13 +03:00
err = json.Unmarshal([]byte(config), &jsonConfig)
2023-02-28 22:54:29 +03:00
checkError(err)
2023-04-13 22:37:13 +03:00
if jsonConfig["log"] != nil {
2023-02-28 22:54:29 +03:00
jsonLog := jsonConfig["log"].(map[string]interface{})
2023-04-13 22:37:13 +03:00
if jsonLog["access"] != nil {
2023-02-28 22:54:29 +03:00
accessLogPath := jsonLog["access"].(string)
return accessLogPath
}
}
return ""
}
func 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 contains(s []string, str string) bool {
for _, v := range s {
if v == str {
return true
}
}
2023-02-28 22:54:29 +03:00
return false
}
func GetInboundClientIps(clientEmail string) (*model.InboundClientIps, error) {
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 addInboundClientIps(clientEmail string, ips []string) error {
2023-02-28 22:54:29 +03:00
inboundClientIps := &model.InboundClientIps{}
jsonIps, err := json.Marshal(ips)
2023-02-28 22:54:29 +03:00
checkError(err)
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 updateInboundClientIps(inboundClientIps *model.InboundClientIps, clientEmail string, ips []string) error {
jsonIps, err := json.Marshal(ips)
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 := GetInboundByEmail(clientEmail)
checkError(err)
if inbound.Settings == "" {
2023-04-13 22:37:13 +03:00
logger.Debug("wrong data ", inbound)
2023-02-28 22:54:29 +03:00
return nil
}
settings := map[string][]model.Client{}
json.Unmarshal([]byte(inbound.Settings), &settings)
clients := settings["clients"]
for _, client := range clients {
if client.Email == clientEmail {
2023-02-28 22:54:29 +03:00
limitIp := client.LimitIP
2023-04-13 22:37:13 +03:00
if limitIp < len(ips) && limitIp != 0 && inbound.Enable {
disAllowedIps = append(disAllowedIps, ips[limitIp:]...)
2023-02-28 22:54:29 +03:00
}
}
}
logger.Debug("disAllowedIps ", disAllowedIps)
sort.Strings(disAllowedIps)
2023-02-28 22:54:29 +03:00
db := database.GetDB()
err = db.Save(inboundClientIps).Error
if err != nil {
return err
}
return nil
}
2023-04-13 22:37:13 +03:00
func DisableInbound(id int) error {
2023-02-28 22:54:29 +03:00
db := database.GetDB()
result := db.Model(model.Inbound{}).
Where("id = ? and enable = ?", id, true).
Update("enable", false)
err := result.Error
2023-04-13 22:37:13 +03:00
logger.Warning("disable inbound with id:", id)
2023-02-28 22:54:29 +03:00
if err == nil {
job.xrayService.SetToNeedRestart()
}
return err
}
func GetInboundByEmail(clientEmail string) (*model.Inbound, error) {
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
}
return inbounds, nil
}
2023-03-25 19:16:03 +03:00
func LimitDevice() {
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
localIp, err := LocalIP()
checkError(err)
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
c := cmd.NewCmd("bash", "-c", "ss --tcp | grep -E '"+IPsToRegex(localIp)+"'| awk '{if($1==\"ESTAB\") print $4,$5;}'", "| sort | uniq -c | sort -nr | head")
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
<-c.Start()
if len(c.Status().Stdout) > 0 {
ipRegx, _ := regexp.Compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`)
portRegx, _ := regexp.Compile(`(?:(:))([0-9]..[^.][0-9]+)`)
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
for _, row := range c.Status().Stdout {
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
data := strings.Split(row, " ")
2023-02-28 22:54:29 +03:00
2023-05-23 17:24:15 +03:00
destIp, destPort, srcIp, srcPort := "", "", "", ""
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
destIp = string(ipRegx.FindString(data[0]))
2023-05-23 17:24:15 +03:00
2023-04-13 22:37:13 +03:00
destPort = portRegx.FindString(data[0])
destPort = strings.Replace(destPort, ":", "", -1)
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
srcIp = string(ipRegx.FindString(data[1]))
2023-05-23 17:24:15 +03:00
2023-04-13 22:37:13 +03:00
srcPort = portRegx.FindString(data[1])
srcPort = strings.Replace(srcPort, ":", "", -1)
2023-02-28 22:54:29 +03:00
if contains(disAllowedIps, srcIp) {
2023-04-13 22:37:13 +03:00
dropCmd := cmd.NewCmd("bash", "-c", "ss -K dport = "+srcPort)
dropCmd.Start()
2023-02-28 22:54:29 +03:00
2023-04-13 22:37:13 +03:00
logger.Debug("request droped : ", srcIp, srcPort, "to", destIp, destPort)
}
}
}
2023-05-23 17:24:15 +03:00
2023-04-13 22:37:13 +03:00
}
2023-03-25 19:16:03 +03:00
2023-02-28 22:54:29 +03:00
func LocalIP() ([]string, error) {
// get machine ips
ifaces, err := net.Interfaces()
ips := []string{}
if err != nil {
return ips, err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return ips, err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
2023-04-13 22:37:13 +03:00
ips = append(ips, ip.String())
2023-02-28 22:54:29 +03:00
}
}
2023-04-13 22:37:13 +03:00
logger.Debug("System IPs : ", ips)
2023-02-28 22:54:29 +03:00
return ips, nil
}
2023-04-13 22:37:13 +03:00
func IPsToRegex(ips []string) string {
2023-02-28 22:54:29 +03:00
regx := ""
for _, ip := range ips {
regx += "(" + strings.Replace(ip, ".", "\\.", -1) + ")"
}
2023-04-13 22:37:13 +03:00
regx = "(" + strings.Replace(regx, ")(", ")|(.", -1) + ")"
2023-02-28 22:54:29 +03:00
return regx
}
func schedule(LimitDevice func(), delay time.Duration) chan bool {
stop := make(chan bool)
go func() {
for {
LimitDevice()
select {
case <-time.After(delay):
case <-stop:
return
}
}
}()
return stop
}