tcp.go 2.4 KB

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