Files
go_blog/middleware/security_headers.go
T
kevin 38cd09f723 fix: 安全加固,修复 P0/P1 安全漏洞
P0(高危):
- 新增全局 CSRF 中间件(同步器令牌),覆盖全部 30 个表单与 AJAX 请求
- 修复附件上传/列表/删除越权(IDOR),增加 admin/上传者/文章作者所有权校验
- 登录/注册成功后会话轮换,修复会话固定
- 会话密钥改用 crypto/rand 生成,配置缺失 secret 时拒绝启动

P1(中危):
- session 与 comment_uid cookie 增加 Secure/SameSite 标志
- 新增安全响应头:CSP、X-Content-Type-Options、X-Frame-Options、HSTS 等
- 新增 web.trusted_proxies 配置,修复 X-Forwarded-For 伪造
- 修复浏览量记录 goroutine 访问已回收 gin.Context 的数据竞争

补充 17 个安全回归测试(middleware/handlers),go test -race 全绿
2026-08-19 12:33:09 +08:00

43 lines
1.8 KiB
Go

package middleware
import "github.com/gin-gonic/gin"
// csp is the Content-Security-Policy for HTML responses.
//
// 'unsafe-inline' is required because templates embed inline <script> and
// <style> blocks (Go html/template is the XSS defense for those); the
// directive list restricts everything else (scripts can only load from the
// pinned CDN hosts, no third-party frames, no other origins for fetch).
// Tighten further once the third-party assets are vendored locally (see
// SECURITY_TODO P2-9).
const csp = "default-src 'self'; " +
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com https://cdn.tailwindcss.com; " +
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://cdnjs.cloudflare.com; " +
"img-src 'self' data: https: http:; " +
"font-src 'self' data: https:; " +
"connect-src 'self'; " +
"frame-ancestors 'none'; " +
"base-uri 'self'; " +
"form-action 'self'"
// SecurityHeaders sets hardening response headers on every response:
// CSP, nosniff, clickjacking (X-Frame-Options + frame-ancestors),
// referrer policy, and HSTS when the request arrived over HTTPS.
// Register it before all other middleware so the headers are present even
// on rejected (403/redirect) responses.
func SecurityHeaders() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Content-Security-Policy", csp)
c.Header("X-Content-Type-Options", "nosniff")
c.Header("X-Frame-Options", "DENY")
c.Header("Referrer-Policy", "strict-origin-when-cross-origin")
c.Header("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
if IsHTTPSRequest(c) {
// includeSubDomains is deliberately omitted: some subdomains of
// the site may still be served over plain HTTP.
c.Header("Strict-Transport-Security", "max-age=31536000")
}
c.Next()
}
}