- 会话 cookie 增加 Secure 标志;新增 [web].cookie_secure 配置 (默认 true,仅本地 HTTP 调试关闭;缺失字段按安全默认处理) - SMTP/IMAP/POP3 认证接入封禁体系(store.RecordAuthFailure 与 Web 共用 ban_entries):失败计数达 ban.max_fail_attempts 即封禁 IP, 已封禁 IP 拒绝认证,堵住协议层暴力破解 - 附件存储路径遍历防护重写:FullPath 白名单校验(UUID 文件名格式) + baseDir 前缀兜底,非法路径返回错误;Save 扩展名白名单化 - 初始管理员不再使用 admin/admin:密码取 MAILGO_ADMIN_PASSWORD 或 随机生成并打印一次;新增 MustChangePassword 首登强制改密 (管理员重置密码同样触发) - 外发中继默认验证 TLS 证书(保护 AUTH 凭据,防 MITM),直投 MX 保持机会式 TLS;新增 outbound.relay_tls_insecure 开关(默认 false) - 新增安全响应头中间件:HSTS、X-Frame-Options DENY、nosniff、 Referrer-Policy、基础 CSP(frame-ancestors 'none' 防点击劫持, connect-src/form-action 'self' 防数据外泄) - LDAP/OAuth 登录错误统一为通用文案,原始错误只写日志, 不再回显邮箱/内部细节(防用户枚举与信息泄露) - 新增 25 个回归测试:cookie 标志、封禁阈值、路径遍历用例、 中继 TLS 验证(自签证书 STARTTLS 集成)、安全头、OAuth 文案 部署注意:升级后所有会话失效需重新登录;若直接以 HTTP 提供 服务需显式配置 cookie_secure = false。
63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package middleware
|
|
|
|
import (
|
|
"mail_go/internal/store"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// AuthMiddleware checks for a valid session and loads the current user
|
|
// into the Gin context. If no valid session exists, it redirects to /login.
|
|
func AuthMiddleware(stores *store.Stores) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
userID := session.Get("userID")
|
|
if userID == nil {
|
|
c.Redirect(302, "/login")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// userID is stored as uint in session, but sessions.Get returns interface{}
|
|
// which may be stored as int or uint depending on the underlying store.
|
|
var id uint
|
|
switch v := userID.(type) {
|
|
case uint:
|
|
id = v
|
|
case int:
|
|
id = uint(v)
|
|
case int64:
|
|
id = uint(v)
|
|
case float64:
|
|
id = uint(v)
|
|
default:
|
|
session.Clear()
|
|
session.Save()
|
|
c.Redirect(302, "/login")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
user, err := stores.Users.GetByID(id)
|
|
if err != nil {
|
|
session.Clear()
|
|
session.Save()
|
|
c.Redirect(302, "/login")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
// 首次登录/密码被重置的用户必须先修改密码才能使用其他功能
|
|
if user.MustChangePassword && c.Request.URL.Path != "/settings" && c.Request.URL.Path != "/logout" {
|
|
c.Redirect(302, "/settings?force=1")
|
|
c.Abort()
|
|
return
|
|
}
|
|
|
|
c.Set("currentUser", user)
|
|
c.Set("userID", id)
|
|
c.Next()
|
|
}
|
|
}
|