tcp.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package tcp
  2. import (
  3. "errors"
  4. "go.uber.org/zap"
  5. "net"
  6. "server/global"
  7. "strings"
  8. "sync"
  9. "time"
  10. )
  11. func ListenTcp() {
  12. var listen net.Listener
  13. var err error
  14. // 监听当前的tcp连接
  15. for {
  16. listen, err = net.Listen("tcp", "0.0.0.0:9200")
  17. if err != nil {
  18. global.GVA_LOG.Error("Listen failed, Retrying in 5 seconds...", zap.Error(err))
  19. time.Sleep(5 * time.Second) // 休眠一段时间后重试
  20. continue
  21. }
  22. break // 成功监听后退出循环
  23. }
  24. tracker := NewConnectionTracker() //创建连接检测器
  25. for {
  26. conn, err := listen.Accept()
  27. if err != nil {
  28. global.GVA_LOG.Error("Accept failed,", zap.Error(err))
  29. continue
  30. }
  31. err = CheckConn(conn, tracker)
  32. if err != nil {
  33. conn.Close() // 如果是恶意连接,则关闭连接
  34. continue
  35. }
  36. }
  37. }
  38. func CheckConn(conn net.Conn, tracker *ConnectionTracker) error {
  39. global.GVA_LOG.Debug("StartDevice", zap.String("addr", conn.RemoteAddr().String()))
  40. arr := strings.Split(conn.RemoteAddr().String(), ":")
  41. ip := arr[0]
  42. // 记录连接
  43. tracker.recordConnection(ip)
  44. // 检查是否为恶意连接
  45. if tracker.isMalicious(ip) {
  46. global.GVA_LOG.Debug("恶意连接检测到", zap.String("ip", ip))
  47. return errors.New("connection is Malicious")
  48. }
  49. device := Device{}
  50. device.Start(conn)
  51. return nil
  52. }
  53. type ConnectionTracker struct {
  54. mu sync.Mutex
  55. connections map[string][]time.Time // 存储每个 IP 的连接时间戳
  56. }
  57. func NewConnectionTracker() *ConnectionTracker {
  58. return &ConnectionTracker{
  59. connections: make(map[string][]time.Time),
  60. }
  61. }
  62. func (ct *ConnectionTracker) recordConnection(ip string) {
  63. ct.mu.Lock()
  64. defer ct.mu.Unlock()
  65. now := time.Now()
  66. ct.connections[ip] = append(ct.connections[ip], now)
  67. // 清理过期的连接记录
  68. ct.cleanUpExpired(ip, now)
  69. }
  70. func (ct *ConnectionTracker) cleanUpExpired(ip string, now time.Time) {
  71. threshold := now.Add(-3 * time.Minute)
  72. if timestamps, exists := ct.connections[ip]; exists {
  73. var filtered []time.Time
  74. for _, t := range timestamps {
  75. if t.After(threshold) { // 检查时间戳是否在三分钟内
  76. filtered = append(filtered, t) // 如果在范围内,保存到 filtered 列表
  77. }
  78. }
  79. ct.connections[ip] = filtered
  80. }
  81. }
  82. // 判断是否是恶意连接
  83. func (ct *ConnectionTracker) isMalicious(ip string) bool {
  84. ct.mu.Lock()
  85. defer ct.mu.Unlock()
  86. if timestamps, exists := ct.connections[ip]; exists {
  87. return len(timestamps) >= 10 // 定义恶意连接的阈值
  88. }
  89. return false
  90. }