tcp.go 2.7 KB

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