- #9 CDN 本地化:marked/DOMPurify/highlight.js/cropperjs/easymde 入 static/vendor(go:embed),Tailwind 改静态构建(scripts/build_tailwind.sh),CSP 收紧为 default-src 'self' - #10 登录限速:IP+用户名维度 5 次失败锁 15 分钟,内存实现有界(handlers/login_ratelimit.go) - #25 计时侧信道:用户不存在时执行 dummy bcrypt 抹平时间差(随 #10 实施) - #11 配置文件权限 0640 - #12 首启随机一次性密码(弃用 admin/admin) - #13 unix socket 660 + 代理用户加组提示 - #22 storage_dir 路径穿越校验(单安全路径段) - #23 密码最小长度统一(改密/建号/重置),#24 邮箱格式统一校验 - 新增 13 个单元测试;go test ./... 含 -race 全绿
41 lines
1.5 KiB
Go
41 lines
1.5 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). All
|
|
// third-party assets are vendored locally (SECURITY_TODO #9), so the policy
|
|
// allows no other origins for scripts or styles.
|
|
const csp = "default-src 'self'; " +
|
|
"script-src 'self' 'unsafe-inline'; " +
|
|
"style-src 'self' 'unsafe-inline'; " +
|
|
"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()
|
|
}
|
|
}
|