fix(security): 修复 P2 中危项(cookie/协议限速/路径遍历/默认口令/中继TLS/安全头/信息泄露)

- 会话 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。
This commit is contained in:
2026-08-19 16:45:21 +08:00
parent c725d0b91e
commit 3f28ec20f4
26 changed files with 799 additions and 101 deletions
+5 -2
View File
@@ -15,8 +15,11 @@ type User struct {
UsedBytes int64 `gorm:"default:0" json:"used_bytes"`
IsActive bool `gorm:"default:true" json:"is_active"`
IsAdmin bool `gorm:"default:false" json:"is_admin"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// MustChangePassword 为 true 时该用户(通常是初始管理员或被重置密码的
// 用户)在首次登录后必须修改密码。
MustChangePassword bool `gorm:"default:false" json:"-"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName specifies the table name for User.
+11
View File
@@ -10,6 +10,7 @@ import (
"strings"
"time"
"mail_go/config"
"mail_go/internal/db"
"mail_go/internal/mailutil"
"mail_go/internal/store"
@@ -26,12 +27,22 @@ import (
// imapBackend implements backend.Backend.
type imapBackend struct {
stores *store.Stores
banCfg config.BanConfig
}
// Login authenticates a user by email and password.
func (b *imapBackend) Login(connInfo *imap.ConnInfo, username, password string) (backend.User, error) {
clientIP := store.ClientIPFromAddr(connInfo.RemoteAddr)
// 已封禁 IP 一律拒绝认证(防协议层暴力破解)
if banned, _ := b.stores.Bans.IsBanned(clientIP); banned {
return nil, backend.ErrInvalidCredentials
}
user, err := b.stores.Users.Authenticate(username, password)
if err != nil {
// 认证失败计数,达到阈值封禁(与 Web 登录共用 ban_entries
b.stores.RecordAuthFailure(clientIP, b.banCfg.MaxFailAttempts, b.banCfg.BanDurationMin)
return nil, fmt.Errorf("invalid credentials: %w", err)
}
+4 -2
View File
@@ -17,15 +17,17 @@ import (
type IMAPServer struct {
stores *store.Stores
cfg config.IMAPConfig
banCfg config.BanConfig
tlsLoader *tlsutil.Loader
}
// NewIMAPServer creates a new IMAP server instance. tlsLoader may be nil
// when TLS is not configured.
func NewIMAPServer(cfg config.IMAPConfig, stores *store.Stores, tlsLoader *tlsutil.Loader) *IMAPServer {
func NewIMAPServer(cfg config.IMAPConfig, stores *store.Stores, tlsLoader *tlsutil.Loader, banCfg config.BanConfig) *IMAPServer {
return &IMAPServer{
stores: stores,
cfg: cfg,
banCfg: banCfg,
tlsLoader: tlsLoader,
}
}
@@ -40,7 +42,7 @@ func (s *IMAPServer) tlsConfig() (*tls.Config, error) {
// newServer creates a configured imapserver.Server with the given address.
func (s *IMAPServer) newServer(addr string, tlsConfig *tls.Config) *imapserver.Server {
be := &imapBackend{stores: s.stores}
be := &imapBackend{stores: s.stores, banCfg: s.banCfg}
srv := imapserver.New(be)
srv.Addr = addr
srv.TLSConfig = tlsConfig
+25 -13
View File
@@ -49,11 +49,12 @@ func newPermError(format string, args ...interface{}) *DeliveryError {
// RelayConfig describes a smarthost through which all external mail is sent.
type RelayConfig struct {
Host string
Port int // 465 = implicit TLS; other ports may use STARTTLS
Username string // AUTH PLAIN credentials (empty = no authentication)
Password string
StartTLS bool // use STARTTLS on non-465 ports
Host string
Port int // 465 = implicit TLS; other ports may use STARTTLS
Username string // AUTH PLAIN credentials (empty = no authentication)
Password string
StartTLS bool // use STARTTLS on non-465 ports
TLSInsecure bool // skip certificate verification (test-only, credentials leak risk)
}
// Mailer performs direct MX delivery (or smarthost relay) of a single message.
@@ -131,6 +132,8 @@ func (m *Mailer) Deliver(from, to string, data []byte) (string, error) {
}
// deliverViaRelay sends the message through the configured smarthost.
// The relay carries AUTH credentials, so its TLS certificate is verified
// unless RelayTLSInsecure is explicitly enabled.
func (m *Mailer) deliverViaRelay(from, to string, data []byte) (string, error) {
port := m.Relay.Port
if port == 0 {
@@ -139,7 +142,8 @@ func (m *Mailer) deliverViaRelay(from, to string, data []byte) (string, error) {
implicitTLS := port == 465
return m.smtpTransaction(m.Relay.Host, port, implicitTLS,
m.Relay.StartTLS && !implicitTLS,
m.Relay.Username, m.Relay.Password, from, to, data)
m.Relay.Username, m.Relay.Password, from, to, data,
m.Relay.TLSInsecure)
}
// smtpClient wraps a textproto connection to a remote SMTP server.
@@ -240,13 +244,17 @@ func (c *smtpClient) authPlain(username, password string) error {
}
// deliverToHost performs a full SMTP transaction with a single MX host.
// Direct MX delivery is opportunistic TLS: certificates are not verified
// because most MX certificates cannot be validated over a cold connection.
func (m *Mailer) deliverToHost(host, from, to string, data []byte) (string, error) {
return m.smtpTransaction(host, m.port(), false, false, "", "", from, to, data)
return m.smtpTransaction(host, m.port(), false, false, "", "", from, to, data, true)
}
// smtpTransaction performs one complete SMTP session: connect, greeting,
// optional implicit TLS / STARTTLS, optional AUTH PLAIN, MAIL/RCPT/DATA/QUIT.
func (m *Mailer) smtpTransaction(host string, port int, implicitTLS, startTLS bool, username, password, from, to string, data []byte) (string, error) {
// tlsInsecure 控制 TLS 握手时是否跳过证书验证:直投 MX 用 true(机会式
// TLS),relay 用配置值(默认 false,保护中继凭据)。
func (m *Mailer) smtpTransaction(host string, port int, implicitTLS, startTLS bool, username, password, from, to string, data []byte, tlsInsecure bool) (string, error) {
addr := net.JoinHostPort(host, strconv.Itoa(port))
ctx, cancel := context.WithTimeout(context.Background(), m.ConnectTimeout)
@@ -267,11 +275,12 @@ func (m *Mailer) smtpTransaction(host string, port int, implicitTLS, startTLS bo
tlsServerName := host
if ip := net.ParseIP(host); ip != nil {
tlsServerName = "" // no SNI for IP literals
// IP literal 同样作为 ServerName:证书验证模式下校验其 IP SAN
tlsServerName = ip.String()
}
if implicitTLS {
tlsConn, err := tlsClientHandshake(ctx, conn, tlsServerName, host)
tlsConn, err := tlsClientHandshake(ctx, conn, tlsServerName, host, tlsInsecure)
if err != nil {
return "", err
}
@@ -294,7 +303,7 @@ func (m *Mailer) smtpTransaction(host string, port int, implicitTLS, startTLS bo
if _, _, err := c.cmd(220, "STARTTLS"); err != nil {
return "", err
}
tlsConn, err := tlsClientHandshake(ctx, conn, tlsServerName, host)
tlsConn, err := tlsClientHandshake(ctx, conn, tlsServerName, host, tlsInsecure)
if err != nil {
return "", err
}
@@ -354,10 +363,13 @@ func (m *Mailer) smtpTransaction(host string, port int, implicitTLS, startTLS bo
}
// tlsClientHandshake upgrades a plain connection to TLS.
func tlsClientHandshake(ctx context.Context, conn net.Conn, serverName, host string) (net.Conn, error) {
// Direct MX delivery passes insecure=true (opportunistic TLS: remote MX
// certificates often cannot be verified). Relays with AUTH credentials must
// pass insecure=false so the connection cannot be MITM'd.
func tlsClientHandshake(ctx context.Context, conn net.Conn, serverName, host string, insecure bool) (net.Conn, error) {
tlsConn := tls.Client(conn, &tls.Config{
ServerName: serverName,
InsecureSkipVerify: true, // remote MX certificates often cannot be verified
InsecureSkipVerify: insecure,
})
if err := tlsConn.HandshakeContext(ctx); err != nil {
return nil, newTempError("TLS handshake with %s failed: %v", host, err)
+177
View File
@@ -2,8 +2,16 @@ package outbound
import (
"bufio"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/pem"
"math/big"
"net"
"strconv"
"strings"
"testing"
"time"
@@ -340,3 +348,172 @@ func TestMailerSmarthostRelay(t *testing.T) {
t.Fatalf("relay data mismatch.\ngot: %q\nwant: %q", res.gotData, input)
}
}
// startTLSSMTPServer 起一个支持 STARTTLS 的 SMTP 服务器(自签证书),
// 供 relay TLS 验证测试使用:未升级 TLS 时广告 STARTTLS 能力,
// 收到 STARTTLS 后升级为 TLS 并重新 EHLO。
func startTLSSMTPServer(t *testing.T) (addr string, cleanup func()) {
t.Helper()
cert, err := tls.X509KeyPair(makeSelfSignedCertPEM(t))
if err != nil {
t.Fatalf("load self-signed cert: %v", err)
}
tlsCfg := &tls.Config{Certificates: []tls.Certificate{cert}}
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func() {
defer conn.Close()
r := bufio.NewReader(conn)
w := bufio.NewWriter(conn)
_, _ = w.WriteString("220 relay.test ESMTP ready\r\n")
_ = w.Flush()
for {
line, err := r.ReadString('\n')
if err != nil {
return
}
up := strings.ToUpper(strings.TrimRight(line, "\r\n"))
switch {
case strings.HasPrefix(up, "STARTTLS"):
_, _ = w.WriteString("220 2.0.0 ready to start TLS\r\n")
_ = w.Flush()
tlsConn := tls.Server(conn, tlsCfg)
if err := tlsConn.Handshake(); err != nil {
return
}
conn = tlsConn
r = bufio.NewReader(conn)
w = bufio.NewWriter(conn)
case strings.HasPrefix(up, "EHLO"), strings.HasPrefix(up, "HELO"):
_, _ = w.WriteString("250-relay.test\r\n250-STARTTLS\r\n250 8BITMIME\r\n")
_ = w.Flush()
case strings.HasPrefix(up, "AUTH PLAIN"):
_, _ = w.WriteString("235 2.0.0 ok\r\n")
_ = w.Flush()
case strings.HasPrefix(up, "DATA"):
_, _ = w.WriteString("354 go ahead\r\n")
_ = w.Flush()
for {
dl, err := r.ReadString('\n')
if err != nil {
return
}
if strings.TrimRight(dl, "\r\n") == "." {
break
}
}
_, _ = w.WriteString("250 2.0.0 queued\r\n")
_ = w.Flush()
case strings.HasPrefix(up, "QUIT"):
_, _ = w.WriteString("221 bye\r\n")
_ = w.Flush()
return
default:
_, _ = w.WriteString("250 ok\r\n")
_ = w.Flush()
}
}
}()
}
}()
addr = ln.Addr().String()
return addr, func() { ln.Close() }
}
// makeSelfSignedCertPEM 生成一对自签证书(CN=relay.test)。
func makeSelfSignedCertPEM(t *testing.T) (certPEM, keyPEM []byte) {
t.Helper()
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatalf("generate key: %v", err)
}
tmpl := &x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "relay.test"},
NotBefore: time.Now().Add(-time.Hour),
NotAfter: time.Now().Add(24 * time.Hour),
DNSNames: []string{"relay.test"},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatalf("create certificate: %v", err)
}
certPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
keyPEM = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
return certPEM, keyPEM
}
// TestMailerRelayRejectsUntrustedCert 中继使用自签证书时默认必须拒绝
// (证书验证开启,防止凭据被中间人截获)。
func TestMailerRelayRejectsUntrustedCert(t *testing.T) {
addr, cleanup := startTLSSMTPServer(t)
defer cleanup()
m := NewMailer("mail.lmve.net", 5*time.Second)
m.Relay = &RelayConfig{
Host: "127.0.0.1",
Port: mustPort(t, addr),
Username: "relay-user",
Password: "relay-pass",
TLSInsecure: false,
}
input := []byte("From: a@lmve.net\r\nTo: b@bogus-domain.invalid\r\nSubject: relay\r\n\r\nbody\r\n")
_, err := m.Deliver("a@lmve.net", "b@bogus-domain.invalid", input)
if err == nil {
t.Fatal("relay with untrusted self-signed cert should be rejected")
}
if !strings.Contains(err.Error(), "certificate") {
t.Fatalf("expected certificate verification error, got: %v", err)
}
}
// TestMailerRelayInsecureSkipsVerification 显式开启 relay_tls_insecure
// 后,自签证书的中继可以完成 TLS 握手并进入 SMTP 会话。
func TestMailerRelayInsecureSkipsVerification(t *testing.T) {
addr, cleanup := startTLSSMTPServer(t)
defer cleanup()
m := NewMailer("mail.lmve.net", 5*time.Second)
m.Relay = &RelayConfig{
Host: "127.0.0.1",
Port: mustPort(t, addr),
Username: "relay-user",
Password: "relay-pass",
TLSInsecure: true,
}
input := []byte("From: a@lmve.net\r\nTo: b@bogus-domain.invalid\r\nSubject: relay\r\n\r\nbody\r\n")
resp, err := m.Deliver("a@lmve.net", "b@bogus-domain.invalid", input)
if err != nil {
t.Fatalf("relay with TLSInsecure should proceed: %v", err)
}
if !strings.HasPrefix(resp, "250") {
t.Fatalf("unexpected response: %q", resp)
}
}
func mustPort(t *testing.T, addr string) int {
t.Helper()
_, portStr, err := net.SplitHostPort(addr)
if err != nil {
t.Fatalf("split %q: %v", addr, err)
}
port, err := strconv.Atoi(portStr)
if err != nil {
t.Fatalf("port %q: %v", portStr, err)
}
return port
}
+6 -5
View File
@@ -64,11 +64,12 @@ func NewManager(cfg config.OutboundConfig, hostname string, stores *store.Stores
if cfg.RelayHost != "" {
m.mailer.Relay = &RelayConfig{
Host: cfg.RelayHost,
Port: cfg.RelayPort,
Username: cfg.RelayUser,
Password: cfg.RelayPassword,
StartTLS: cfg.RelayStartTLS,
Host: cfg.RelayHost,
Port: cfg.RelayPort,
Username: cfg.RelayUser,
Password: cfg.RelayPassword,
StartTLS: cfg.RelayStartTLS,
TLSInsecure: cfg.RelayTLSInsecure,
}
log.Printf("outbound: using smarthost relay %s:%d", cfg.RelayHost, cfg.RelayPort)
}
+15 -2
View File
@@ -22,14 +22,15 @@ type POP3Server struct {
listener net.Listener
stores *store.Stores
cfg config.POP3Config
banCfg config.BanConfig
tlsLoader *tlsutil.Loader
wg sync.WaitGroup
}
// NewPOP3Server creates a new POP3 server instance. tlsLoader may be nil
// when TLS is not configured.
func NewPOP3Server(cfg config.POP3Config, stores *store.Stores, tlsLoader *tlsutil.Loader) *POP3Server {
return &POP3Server{stores: stores, cfg: cfg, tlsLoader: tlsLoader}
func NewPOP3Server(cfg config.POP3Config, stores *store.Stores, tlsLoader *tlsutil.Loader, banCfg config.BanConfig) *POP3Server {
return &POP3Server{stores: stores, cfg: cfg, banCfg: banCfg, tlsLoader: tlsLoader}
}
func (s *POP3Server) tlsConfig() (*tls.Config, error) {
@@ -107,6 +108,14 @@ func (s *POP3Server) handleConn(conn net.Conn) {
defer conn.Close()
conn.SetDeadline(time.Now().Add(10 * time.Minute))
clientIP := store.ClientIPFromAddr(conn.RemoteAddr())
// 已封禁 IP 直接拒绝(防协议层暴力破解)
if banned, _ := s.stores.Bans.IsBanned(clientIP); banned {
sendResponse(conn, "-ERR access denied")
return
}
reader := bufio.NewReader(conn)
var user *db.User
var messages []pop3Message
@@ -272,8 +281,12 @@ func (s *POP3Server) handlePASS(conn net.Conn, password string, user *db.User) (
return nil, nil, nil
}
clientIP := store.ClientIPFromAddr(conn.RemoteAddr())
authUser, err := s.stores.Users.Authenticate(user.Username, password)
if err != nil {
// 认证失败计数,达到阈值封禁(与 Web 登录共用 ban_entries
s.stores.RecordAuthFailure(clientIP, s.banCfg.MaxFailAttempts, s.banCfg.BanDurationMin)
sendResponse(conn, "-ERR authentication failed")
return nil, nil, nil
}
+19 -5
View File
@@ -36,13 +36,14 @@ type SMTPServer struct {
storage *storage.AttachmentStorage
outbound *outbound.Manager
cfg config.SMTPConfig
banCfg config.BanConfig
tlsLoader *tlsutil.Loader
}
// NewSMTPServer creates a new SMTP server instance. tlsLoader may be nil
// when TLS is not configured.
func NewSMTPServer(cfg config.SMTPConfig, stores *store.Stores, attStorage *storage.AttachmentStorage, ob *outbound.Manager, tlsLoader *tlsutil.Loader) *SMTPServer {
return &SMTPServer{stores: stores, storage: attStorage, outbound: ob, cfg: cfg, tlsLoader: tlsLoader}
func NewSMTPServer(cfg config.SMTPConfig, stores *store.Stores, attStorage *storage.AttachmentStorage, ob *outbound.Manager, tlsLoader *tlsutil.Loader, banCfg config.BanConfig) *SMTPServer {
return &SMTPServer{stores: stores, storage: attStorage, outbound: ob, cfg: cfg, banCfg: banCfg, tlsLoader: tlsLoader}
}
func (s *SMTPServer) tlsConfig() (*tls.Config, error) {
@@ -108,9 +109,10 @@ type smtpBackend struct {
// NewSession creates a new SMTP session for the incoming connection.
func (be *smtpBackend) NewSession(c *smtp.Conn) (smtp.Session, error) {
return &smtpSession{
backend: be,
mode: be.mode,
rcpts: make([]string, 0),
backend: be,
mode: be.mode,
rcpts: make([]string, 0),
clientIP: store.ClientIPFromAddr(c.Conn().RemoteAddr()),
}, nil
}
@@ -126,6 +128,7 @@ type smtpSession struct {
userID uint
email string
user *db.User
clientIP string
}
// AuthMechanisms returns supported SMTP AUTH mechanisms.
@@ -139,8 +142,19 @@ func (s *smtpSession) Auth(mech string) (sasl.Server, error) {
return nil, smtp.ErrAuthUnknownMechanism
}
return sasl.NewPlainServer(func(identity, username, password string) error {
// 已封禁 IP 一律拒绝认证(防协议层暴力破解)
if banned, _ := s.backend.server.stores.Bans.IsBanned(s.clientIP); banned {
return smtp.ErrAuthFailed
}
user, err := s.backend.server.stores.Users.Authenticate(username, password)
if err != nil {
// 认证失败计数,达到阈值封禁(与 Web 登录共用 ban_entries
s.backend.server.stores.RecordAuthFailure(
s.clientIP,
s.backend.server.banCfg.MaxFailAttempts,
s.backend.server.banCfg.BanDurationMin,
)
return smtp.ErrAuthFailed
}
+47 -11
View File
@@ -4,11 +4,16 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/google/uuid"
)
// savedFileRe 匹配 Save 生成的文件名:UUID(小写十六进制)+ 可选白名单扩展名。
// 只允许这种格式的路径进入文件系统,杜绝路径遍历(../)、绝对路径等。
var savedFileRe = regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}(\.[A-Za-z0-9._-]{1,32})?$`)
// AttachmentStorage handles file operations for email attachments on disk.
type AttachmentStorage struct {
baseDir string // cfg.Storage.AttachDir
@@ -19,6 +24,24 @@ func NewAttachmentStorage(baseDir string) *AttachmentStorage {
return &AttachmentStorage{baseDir: baseDir}
}
// safeExt 提取并白名单化文件扩展名:只保留字母数字与 ._-,最长 32 字符。
// 非法字符(含 CR/LF、路径分隔符)直接丢弃扩展名。
func safeExt(filename string) string {
ext := filepath.Ext(filename)
if len(ext) > 33 {
return ""
}
for _, r := range ext {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9':
case r == '.', r == '_', r == '-':
default:
return ""
}
}
return ext
}
// Save writes attachment data to disk and returns the relative file path.
// The filename is generated as {uuid}{ext} to avoid collisions.
func (s *AttachmentStorage) Save(filename string, data []byte) (string, error) {
@@ -27,8 +50,8 @@ func (s *AttachmentStorage) Save(filename string, data []byte) (string, error) {
return "", fmt.Errorf("创建附件目录失败: %w", err)
}
// Generate a unique filename with the original extension
ext := filepath.Ext(filename)
// Generate a unique filename with a sanitized extension
ext := safeExt(filename)
uniqueName := uuid.New().String() + ext
fullPath := filepath.Join(s.baseDir, uniqueName)
@@ -41,7 +64,10 @@ func (s *AttachmentStorage) Save(filename string, data []byte) (string, error) {
// Read reads attachment data from disk given a relative path.
func (s *AttachmentStorage) Read(relPath string) ([]byte, error) {
fullPath := s.FullPath(relPath)
fullPath, err := s.FullPath(relPath)
if err != nil {
return nil, err
}
data, err := os.ReadFile(fullPath)
if err != nil {
return nil, fmt.Errorf("读取附件文件失败: %w", err)
@@ -51,19 +77,29 @@ func (s *AttachmentStorage) Read(relPath string) ([]byte, error) {
// Delete removes an attachment file from disk given a relative path.
func (s *AttachmentStorage) Delete(relPath string) error {
fullPath := s.FullPath(relPath)
fullPath, err := s.FullPath(relPath)
if err != nil {
return err
}
if err := os.Remove(fullPath); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("删除附件文件失败: %w", err)
}
return nil
}
// FullPath returns the absolute path for a given relative path.
func (s *AttachmentStorage) FullPath(relPath string) string {
// Prevent directory traversal attacks
cleanRel := filepath.Clean(relPath)
if strings.HasPrefix(cleanRel, "..") {
cleanRel = strings.TrimPrefix(cleanRel, "../")
// FullPath returns the absolute path for a relative path produced by Save.
// Paths that do not match the saved-file format (traversal attempts,
// absolute paths, unrelated names) are rejected with an error so they can
// never escape baseDir.
func (s *AttachmentStorage) FullPath(relPath string) (string, error) {
if !savedFileRe.MatchString(relPath) {
return "", fmt.Errorf("非法的附件路径: %q", relPath)
}
return filepath.Join(s.baseDir, cleanRel)
// 兜底校验:解析后的路径必须仍在 baseDir 内
fullPath := filepath.Join(s.baseDir, relPath)
if !strings.HasPrefix(fullPath, filepath.Clean(s.baseDir)+string(os.PathSeparator)) {
return "", fmt.Errorf("附件路径越界: %q", relPath)
}
return fullPath, nil
}
+97
View File
@@ -0,0 +1,97 @@
package storage
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/google/uuid"
)
// TestFullPathRejectsTraversal 验证路径遍历/绝对路径等恶意输入被拒绝。
func TestFullPathRejectsTraversal(t *testing.T) {
s := NewAttachmentStorage(filepath.Join(t.TempDir(), "attachments"))
valid := uuid.New().String() + ".pdf"
bad := []string{
"../secret.txt",
"../../etc/passwd",
"..",
"....//x",
"/etc/passwd",
"a/../b.txt",
"sub/file.png",
"",
".", "..\\..\\x", // windows style
"00000000-0000-0000-0000-000000000000.exe\r\nBcc: x@y.com",
"garbage",
"00000000-0000-0000-0000-000000000000.%2e%2e",
}
for _, p := range bad {
if _, err := s.FullPath(p); err == nil {
t.Errorf("FullPath(%q) should be rejected", p)
}
}
// 合法文件名必须通过
full, err := s.FullPath(valid)
if err != nil {
t.Fatalf("FullPath(%q) rejected: %v", valid, err)
}
if !strings.HasPrefix(full, s.baseDir+string(os.PathSeparator)) {
t.Fatalf("FullPath(%q) = %q escapes baseDir", valid, full)
}
}
// TestSaveSanitizesExtension 验证恶意扩展名不会进入文件名。
func TestSaveSanitizesExtension(t *testing.T) {
s := NewAttachmentStorage(filepath.Join(t.TempDir(), "attachments"))
// 换行/路径分隔符等非法字符的扩展名应被丢弃
rel, err := s.Save("evil.pdf\r\nBcc: x@y.com", []byte("data"))
if err != nil {
t.Fatalf("Save: %v", err)
}
if strings.ContainsAny(rel, "\r\n/\\") {
t.Fatalf("saved name contains dangerous chars: %q", rel)
}
if !savedFileRe.MatchString(rel) {
t.Fatalf("saved name %q does not match allowed pattern", rel)
}
// 后续 Read 应能按返回的路径读取
if _, err := s.Read(rel); err != nil {
t.Fatalf("Read after Save: %v", err)
}
// 正常扩展名保留
rel2, err := s.Save("report.pdf", []byte("data"))
if err != nil {
t.Fatalf("Save: %v", err)
}
if !strings.HasSuffix(rel2, ".pdf") {
t.Fatalf("extension lost: %q", rel2)
}
}
// TestReadDeleteRoundTrip 正常读写删流程。
func TestReadDeleteRoundTrip(t *testing.T) {
dir := t.TempDir()
s := NewAttachmentStorage(filepath.Join(dir, "attachments"))
rel, err := s.Save("a.txt", []byte("hello"))
if err != nil {
t.Fatalf("Save: %v", err)
}
data, err := s.Read(rel)
if err != nil || string(data) != "hello" {
t.Fatalf("Read = %q, %v", data, err)
}
if err := s.Delete(rel); err != nil {
t.Fatalf("Delete: %v", err)
}
// 删除后路径仍然合法(删除不存在文件不算错误)
if err := s.Delete(rel); err != nil {
t.Fatalf("Delete again: %v", err)
}
}
+43
View File
@@ -0,0 +1,43 @@
package store
import (
"fmt"
"net"
"time"
"mail_go/internal/db"
)
// ClientIPFromAddr 从 net.Addr 提取客户端 IP 字符串(去掉端口)。
// 解析失败返回空字符串,调用方应据此跳过封禁逻辑(不误封)。
func ClientIPFromAddr(addr net.Addr) string {
if addr == nil {
return ""
}
host, _, err := net.SplitHostPort(addr.String())
if err != nil {
return addr.String()
}
return host
}
// RecordAuthFailure 记录一次协议层(SMTP/IMAP/POP3)认证失败:
// 失败计数累加,达到 maxFail 阈值时封禁该 IP(封禁时长 minutes 分钟)。
// 返回 (是否触发封禁, 当前失败计数)。Web 登录的封禁逻辑在
// handlers.AuthHandler 中,与这里独立。
func (s *Stores) RecordAuthFailure(ip string, maxFail int, minutes int) (banned bool, failCount int) {
if ip == "" || maxFail <= 0 {
return false, 0
}
failCount, _ = s.Bans.IncrementFail(ip)
if failCount >= maxFail {
_ = s.Bans.Create(&db.BanEntry{
IPAddress: ip,
Reason: fmt.Sprintf("邮件协议认证失败次数过多 (%d次)", failCount),
FailCount: failCount,
ExpiresAt: time.Now().Add(time.Duration(minutes) * time.Minute),
})
return true, failCount
}
return false, failCount
}
+113
View File
@@ -0,0 +1,113 @@
package store
import (
"net"
"path/filepath"
"testing"
"time"
"mail_go/internal/db"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func newTestStores(t *testing.T) *Stores {
t.Helper()
gdb, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "test.db")), &gorm.Config{})
if err != nil {
t.Fatalf("open sqlite: %v", err)
}
if err := gdb.AutoMigrate(&db.User{}, &db.Domain{}, &db.Message{}, &db.Attachment{}, &db.BanEntry{}, &db.OutboundMessage{}); err != nil {
t.Fatalf("migrate: %v", err)
}
return NewStores(gdb)
}
// TestRecordAuthFailureBansAfterThreshold 验证连续认证失败达到阈值后封禁。
func TestRecordAuthFailureBansAfterThreshold(t *testing.T) {
s := newTestStores(t)
const ip = "203.0.113.10"
const maxFail = 3
// 前两次失败不封禁
for i := 1; i < maxFail; i++ {
banned, count := s.RecordAuthFailure(ip, maxFail, 30)
if banned {
t.Fatalf("attempt %d should not be banned yet", i)
}
if count != i {
t.Fatalf("attempt %d: fail count = %d, want %d", i, count, i)
}
}
// 第三次失败触发封禁
banned, count := s.RecordAuthFailure(ip, maxFail, 30)
if !banned {
t.Fatal("attempt reaching threshold should ban the IP")
}
if count != maxFail {
t.Fatalf("fail count = %d, want %d", count, maxFail)
}
// IP 现在处于封禁状态
banned, entry := s.Bans.IsBanned(ip)
if !banned {
t.Fatal("IP should be banned")
}
if entry.ExpiresAt.Before(time.Now().Add(29 * time.Minute)) {
t.Fatalf("ban expiry too short: %v", entry.ExpiresAt)
}
}
// TestRecordAuthFailureEmptyIPSafe 空 IP 不应产生副作用。
func TestRecordAuthFailureEmptyIPSafe(t *testing.T) {
s := newTestStores(t)
banned, count := s.RecordAuthFailure("", 3, 30)
if banned || count != 0 {
t.Fatalf("empty IP must be a no-op: banned=%v count=%d", banned, count)
}
if _, err := s.Bans.GetByIP(""); err == nil {
t.Fatal("empty IP should not be recorded")
}
}
// TestRecordAuthFailureWebAndProtocolShared 协议层与 Web 层共用封禁记录。
func TestRecordAuthFailureWebAndProtocolShared(t *testing.T) {
s := newTestStores(t)
const ip = "198.51.100.20"
// Web 层已封禁(直接建记录模拟),协议层认证必须被拒绝
s.Bans.Create(&db.BanEntry{
IPAddress: ip,
Reason: "web login failures",
FailCount: 5,
ExpiresAt: time.Now().Add(30 * time.Minute),
})
if banned, _ := s.Bans.IsBanned(ip); !banned {
t.Fatal("IP should be banned for both web and protocol auth")
}
}
func TestClientIPFromAddr(t *testing.T) {
cases := []struct {
addr net.Addr
want string
}{
{nil, ""},
{addrMock("203.0.113.5:12345"), "203.0.113.5"},
{addrMock("[2001:db8::1]:993"), "2001:db8::1"},
{addrMock("bad-format"), "bad-format"},
}
for _, tc := range cases {
if got := ClientIPFromAddr(tc.addr); got != tc.want {
t.Errorf("ClientIPFromAddr(%v) = %q, want %q", tc.addr, got, tc.want)
}
}
}
// addrMock 实现 net.Addr 的最小桩。
type addrMock string
func (a addrMock) Network() string { return "tcp" }
func (a addrMock) String() string { return string(a) }
+7 -2
View File
@@ -124,9 +124,14 @@ func (s *userStoreGorm) UpdateUsedBytes(id uint, delta int64) error {
Update("used_bytes", gorm.Expr("used_bytes + ?", delta)).Error
}
// UpdatePassword updates the password hash for a user.
// UpdatePassword updates the password hash for a user and clears the
// must-change-password flag (the user has now set their own password).
func (s *userStoreGorm) UpdatePassword(userID uint, hashedPassword string) error {
return s.db.Model(&db.User{}).Where("id = ?", userID).Update("password_hash", hashedPassword).Error
return s.db.Model(&db.User{}).Where("id = ?", userID).
Updates(map[string]interface{}{
"password_hash": hashedPassword,
"must_change_password": false,
}).Error
}
// ListAll retrieves a paginated list of all users across all domains.
+2
View File
@@ -696,6 +696,8 @@ func (h *AdminHandler) UpdateUser(c *gin.Context) {
return
}
user.PasswordHash = string(hashedPassword)
// 管理员重置的密码必须由用户本人修改后才能正常使用
user.MustChangePassword = true
}
if err := h.stores.Users.Update(user); err != nil {
+4 -4
View File
@@ -170,7 +170,7 @@ func (h *AuthHandler) LDAPLogin(c *gin.Context) {
remaining := h.banCfg.MaxFailAttempts - failCount
c.HTML(200, "login", gin.H{
"error": fmt.Sprintf("LDAP 认证失败,还剩 %d 次尝试机会: %v", remaining, err),
"error": fmt.Sprintf("LDAP 认证失败,还剩 %d 次尝试机会", remaining),
"oauth2Enabled": h.authCfg.OAuth2Enabled,
"ldapEnabled": h.authCfg.LDAPEnabled,
"oauth2Provider": h.authCfg.OAuth2Provider,
@@ -182,7 +182,7 @@ func (h *AuthHandler) LDAPLogin(c *gin.Context) {
user, err := h.stores.Users.GetByEmail(email)
if err != nil {
c.HTML(200, "login", gin.H{
"error": fmt.Sprintf("LDAP 用户 %s 在系统中不存在", email),
"error": "LDAP 账号未接入本系统,请联系管理员",
"oauth2Enabled": h.authCfg.OAuth2Enabled,
"ldapEnabled": h.authCfg.LDAPEnabled,
"oauth2Provider": h.authCfg.OAuth2Provider,
@@ -308,7 +308,7 @@ func (h *AuthHandler) OAuth2Callback(c *gin.Context) {
if err != nil {
log.Printf("OAuth2 回调失败: %v", err)
c.HTML(200, "login", gin.H{
"error": fmt.Sprintf("OAuth2 认证失败: %v", err),
"error": "OAuth2 认证失败,请重试或联系管理员",
"oauth2Enabled": h.authCfg.OAuth2Enabled,
"ldapEnabled": h.authCfg.LDAPEnabled,
"oauth2Provider": h.authCfg.OAuth2Provider,
@@ -320,7 +320,7 @@ func (h *AuthHandler) OAuth2Callback(c *gin.Context) {
user, err := h.stores.Users.GetByEmail(email)
if err != nil {
c.HTML(200, "login", gin.H{
"error": fmt.Sprintf("OAuth2 用户 %s 在系统中不存在", email),
"error": "OAuth2 账号未接入本系统,请联系管理员",
"oauth2Enabled": h.authCfg.OAuth2Enabled,
"ldapEnabled": h.authCfg.LDAPEnabled,
"oauth2Provider": h.authCfg.OAuth2Provider,
+1
View File
@@ -723,6 +723,7 @@ func (h *MailHandler) Settings(c *gin.Context) {
"activeFolder": "settings",
"error": "",
"success": "",
"mustChange": c.Query("force") == "1",
"inboxUnread": inboxUnread,
"draftsTotal": draftsTotal,
"sentTotal": sentTotal,
+7
View File
@@ -48,6 +48,13 @@ func AuthMiddleware(stores *store.Stores) gin.HandlerFunc {
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()
+36
View File
@@ -0,0 +1,36 @@
package middleware
import (
"github.com/gin-gonic/gin"
)
// securityCSP 是本应用的基础 CSP。
//
// 说明:
// - 模板大量使用内联脚本/样式(Quill 初始化、行内事件处理、
// avatarStyle 内联 CSS),故 script-src / style-src 需要
// 'unsafe-inline'
// - 邮件正文在 srcdoc iframe 中渲染,可能引用远程图片(https:),
// 因此 img-src 放行 https,同时仍阻止 data: 以外的自定义协议;
// - frame-ancestors 'none' 与 X-Frame-Options 共同防护点击劫持;
// - connect-src 'self' / form-action 'self' 阻止页面数据外泄到
// 外部域名。
const securityCSP = "default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https:; " +
"connect-src 'self'; object-src 'none'; base-uri 'self'; " +
"form-action 'self'; frame-ancestors 'none'"
// SecurityHeaders 为所有响应设置基础安全头:HSTS、点击劫持防护、
// MIME 嗅探防护、Referrer 策略与基础 CSP。
func SecurityHeaders() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
c.Header("X-Frame-Options", "DENY")
c.Header("X-Content-Type-Options", "nosniff")
c.Header("Referrer-Policy", "strict-origin-when-cross-origin")
c.Header("Content-Security-Policy", securityCSP)
c.Next()
}
}
+45
View File
@@ -0,0 +1,45 @@
package middleware
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
)
// TestSecurityHeaders 验证所有基础安全响应头都存在。
func TestSecurityHeaders(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(SecurityHeaders())
r.GET("/", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
r.ServeHTTP(w, req)
for _, h := range []string{
"Strict-Transport-Security",
"X-Frame-Options",
"X-Content-Type-Options",
"Referrer-Policy",
"Content-Security-Policy",
} {
if v := w.Header().Get(h); v == "" {
t.Errorf("missing security header %q", h)
}
}
// 关键头内容抽查
if got := w.Header().Get("X-Frame-Options"); got != "DENY" {
t.Errorf("X-Frame-Options = %q, want DENY", got)
}
if got := w.Header().Get("Content-Security-Policy"); !strings.Contains(got, "frame-ancestors 'none'") {
t.Errorf("CSP should include frame-ancestors 'none', got %q", got)
}
if got := w.Header().Get("Content-Security-Policy"); !strings.Contains(got, "connect-src 'self'") {
t.Errorf("CSP should include connect-src 'self', got %q", got)
}
}
+3
View File
@@ -191,6 +191,7 @@ func NewWebServer(cfg config.WebConfig, stores *store.Stores, attStorage *storag
cookieStore.Options(sessions.Options{
HttpOnly: true,
SameSite: 3, // SameSiteStrictMode(比 Lax 更严格)
Secure: cfg.CookieSecure,
MaxAge: 86400,
Path: "/",
})
@@ -226,6 +227,8 @@ func (ws *WebServer) registerRoutes() {
// Apply BanMiddleware globally before public routes
ws.engine.Use(middleware.BanMiddleware(ws.stores))
// Security headers on every response
ws.engine.Use(middleware.SecurityHeaders())
// Public routes (no auth required)
ws.engine.GET("/login", authHandler.ShowLogin)
+10 -1
View File
@@ -70,7 +70,7 @@ func newTestWebServer(t *testing.T, secretKey string) (*WebServer, *store.Stores
baseDir := t.TempDir()
attStorage := storage.NewAttachmentStorage(filepath.Join(baseDir, "attachments"))
cfg := config.WebConfig{Addr: "127.0.0.1:0", SecretKey: secretKey}
cfg := config.WebConfig{Addr: "127.0.0.1:0", SecretKey: secretKey, CookieSecure: true}
ws, err := NewWebServer(cfg, stores, attStorage, config.StorageConfig{BaseDir: baseDir},
config.AuthConfig{}, config.BanConfig{MaxFailAttempts: 100}, config.CaddyConfig{}, nil)
@@ -104,6 +104,15 @@ func TestSessionSignedWithConfiguredSecretKey(t *testing.T) {
for _, c := range resp.Cookies() {
if c.Name == "mail_go_session" {
sessionCookie = c.Value
if !c.HttpOnly {
t.Error("session cookie must be HttpOnly")
}
if !c.Secure {
t.Error("session cookie must be Secure")
}
if c.SameSite != http.SameSiteStrictMode {
t.Errorf("session cookie SameSite = %v, want Strict", c.SameSite)
}
}
}
if sessionCookie == "" {
+3
View File
@@ -14,6 +14,9 @@
<main class="mail-main settings-main">
{{if .error}}<div class="alert alert-error">{{.error}}</div>{{end}}
{{if .success}}<div class="alert alert-success">{{.success}}</div>{{end}}
{{if .mustChange}}<div class="alert" style="border:1px solid #ffa940;background:#fff7e6;color:#d46b08;border-radius:8px;padding:12px 16px;margin-bottom:16px;font-size:13.5px;">
⚠️ 首次登录/密码已被重置,请立即修改密码后再继续使用邮箱功能。
</div>{{end}}
<div class="card" style="max-width:720px;">
<h2 style="font-size:17px;margin-bottom:18px;display:flex;align-items:center;gap:10px;">