|
@@ -3,13 +3,12 @@ package tcp
|
|
|
import (
|
|
|
"errors"
|
|
|
"net"
|
|
|
- "server/dao/devices"
|
|
|
"server/utils/logger"
|
|
|
"strings"
|
|
|
+ "sync"
|
|
|
+ "time"
|
|
|
)
|
|
|
|
|
|
-var ScreenList []devices.Screens
|
|
|
-
|
|
|
func ListenTcp() {
|
|
|
|
|
|
listen, err := net.Listen("tcp", "0.0.0.0:9200")
|
|
@@ -17,30 +16,82 @@ func ListenTcp() {
|
|
|
logger.Logger.Errorf("listen failed, err:%v", err)
|
|
|
return
|
|
|
}
|
|
|
+
|
|
|
+ tracker := NewConnectionTracker()
|
|
|
+
|
|
|
for {
|
|
|
- conn, err := listen.Accept()
|
|
|
+ conn, err := listen.Accept()
|
|
|
if err != nil {
|
|
|
logger.Logger.Errorf("Accept failed, err:%v", err)
|
|
|
continue
|
|
|
}
|
|
|
- err = CheckConn(conn)
|
|
|
+ err = CheckConn(conn, tracker)
|
|
|
if err != nil {
|
|
|
+ conn.Close()
|
|
|
continue
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
-func CheckConn(conn net.Conn) error {
|
|
|
+func CheckConn(conn net.Conn, tracker *ConnectionTracker) error {
|
|
|
logger.Logger.Debugf("StartDevice addr:%s", conn.RemoteAddr().String())
|
|
|
arr := strings.Split(conn.RemoteAddr().String(), ":")
|
|
|
ip := arr[0]
|
|
|
- ScreenList = devices.QueryAllScreens()
|
|
|
- for _, v := range ScreenList {
|
|
|
- if v.IPAddress == ip {
|
|
|
- dev := Device{info: v}
|
|
|
- dev.Start(conn)
|
|
|
- return nil
|
|
|
+
|
|
|
+ tracker.recordConnection(ip)
|
|
|
+
|
|
|
+
|
|
|
+ if tracker.isMalicious(ip) {
|
|
|
+ logger.Logger.Debugf("恶意连接检测到 ip: %s\n", ip)
|
|
|
+ return errors.New("connection is Malicious")
|
|
|
+ }
|
|
|
+ device := Device{}
|
|
|
+ device.Start(conn)
|
|
|
+ return nil
|
|
|
+}
|
|
|
+
|
|
|
+type ConnectionTracker struct {
|
|
|
+ mu sync.Mutex
|
|
|
+ connections map[string][]time.Time
|
|
|
+}
|
|
|
+
|
|
|
+func NewConnectionTracker() *ConnectionTracker {
|
|
|
+ return &ConnectionTracker{
|
|
|
+ connections: make(map[string][]time.Time),
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+func (ct *ConnectionTracker) recordConnection(ip string) {
|
|
|
+ ct.mu.Lock()
|
|
|
+ defer ct.mu.Unlock()
|
|
|
+
|
|
|
+ now := time.Now()
|
|
|
+ ct.connections[ip] = append(ct.connections[ip], now)
|
|
|
+
|
|
|
+
|
|
|
+ ct.cleanUpExpired(ip, now)
|
|
|
+}
|
|
|
+
|
|
|
+func (ct *ConnectionTracker) cleanUpExpired(ip string, now time.Time) {
|
|
|
+ threshold := now.Add(-3 * time.Minute)
|
|
|
+ if timestamps, exists := ct.connections[ip]; exists {
|
|
|
+ var filtered []time.Time
|
|
|
+ for _, t := range timestamps {
|
|
|
+ if t.After(threshold) {
|
|
|
+ filtered = append(filtered, t)
|
|
|
+ }
|
|
|
}
|
|
|
+ ct.connections[ip] = filtered
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+func (ct *ConnectionTracker) isMalicious(ip string) bool {
|
|
|
+ ct.mu.Lock()
|
|
|
+ defer ct.mu.Unlock()
|
|
|
+
|
|
|
+ if timestamps, exists := ct.connections[ip]; exists {
|
|
|
+ return len(timestamps) >= 10
|
|
|
}
|
|
|
- return errors.New("not found")
|
|
|
+ return false
|
|
|
}
|