1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| var ( ipRequestCount = make(map[string][]time.Time) ipMutex = sync.RWMutex{} maxRequests = 100 timeWindow = time.Minute )
func SecurityMiddleware() gin.HandlerFunc { return func(c *gin.Context) { path := c.Request.URL.Path if isSuspiciousPath(path) { log.Printf("可疑路径访问 - IP: %s, Path: %s, UA: %s", c.ClientIP(), path, c.GetHeader("User-Agent")) c.JSON(http.StatusNotFound, gin.H{"error": "路径不存在"}) c.Abort() return }
if containsXSS(c.Request.URL.RawQuery) { log.Printf("XSS攻击尝试 - IP: %s, Query: %s", c.ClientIP(), c.Request.URL.RawQuery) c.JSON(http.StatusBadRequest, gin.H{"error": "请求被拒绝"}) c.Abort() return }
c.Header("X-Content-Type-Options", "nosniff") c.Header("X-Frame-Options", "DENY") c.Header("X-XSS-Protection", "1; mode=block") c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
c.Next() } }
func RateLimitMiddleware() gin.HandlerFunc { return func(c *gin.Context) { ip := c.ClientIP() ipMutex.Lock() now := time.Now() if requests, exists := ipRequestCount[ip]; exists { var validRequests []time.Time for _, reqTime := range requests { if now.Sub(reqTime) < timeWindow { validRequests = append(validRequests, reqTime) } } ipRequestCount[ip] = validRequests } if len(ipRequestCount[ip]) >= maxRequests { ipMutex.Unlock() log.Printf("频率限制触发 - IP: %s, 请求数: %d", ip, len(ipRequestCount[ip])) c.JSON(http.StatusTooManyRequests, gin.H{"error": "请求过于频繁"}) c.Abort() return } ipRequestCount[ip] = append(ipRequestCount[ip], now) ipMutex.Unlock() c.Next() } }
func isSuspiciousPath(path string) bool { suspiciousPaths := []string{ "/v1/", "/v2/", "/v3/", "/api/v", "/admin", "/wp-admin", "/phpmyadmin", "/jobs/", "/chart/", "/templates/", "/site/content_store", "/observables", "/.env", "/config", "/.git", } for _, suspicious := range suspiciousPaths { if strings.Contains(path, suspicious) { return true } } return false }
func containsXSS(query string) bool { xssPatterns := []string{ "<script", "</script>", "javascript:", "alert(", "document.domain", "eval(", "onload=", "onerror=", "onclick=", } queryLower := strings.ToLower(query) for _, pattern := range xssPatterns { if strings.Contains(queryLower, pattern) { return true } } return false }
|