完成安全整改、配置重构与邮件认证优化
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-08-28 14:33:13 +08:00
1 parent 18b6dfbdf7
commit dd04bdb49e
83 files changed
+4547 -583

No files matched your search

@@ -13,7 +13,7 @@ import (
func ReadProtectedPassword() (string, error) {
if !term.IsTerminal(int(os.Stdin.Fd())) {
return "", errors.New("protected password input requires an interactive console")
return "", errors.New("\u53d7\u4fdd\u62a4\u7684\u5bc6\u7801\u8f93\u5165\u9700\u8981\u4ea4\u4e92\u5f0f\u63a7\u5236\u53f0")
}
first, err := readWindowsPassword("\u8bf7\u8f93\u5165\u65b0\u7684\u8d85\u7ea7\u7ba1\u7406\u5458\u5bc6\u7801")
if err != nil {
@@ -27,7 +27,7 @@ func ReadProtectedPassword() (string, error) {
if first == "" || first != second {
clearPassword(&first)
clearPassword(&second)
return "", errors.New("password is empty or does not match")
return "", errors.New("\u5bc6\u7801\u4e3a\u7a7a\u6216\u4e24\u6b21\u8f93\u5165\u4e0d\u4e00\u81f4")
}
clearPassword(&second)
return first, nil
@@ -38,14 +38,14 @@ func readWindowsPassword(prompt string) (string, error) {
value, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Fprintln(os.Stderr)
if err != nil {
return "", errors.New("protected password input failed")
return "", errors.New("\u53d7\u4fdd\u62a4\u7684\u5bc6\u7801\u8f93\u5165\u5931\u8d25")
}
normalized := strings.TrimSpace(string(value))
for i := range value {
value[i] = 0
}
if len([]byte(normalized)) < 8 || len([]byte(normalized)) > 256 {
return "", errors.New("invalid password length")
return "", errors.New("\u5bc6\u7801\u957f\u5ea6\u5fc5\u987b\u4e3a 8 \u5230 256 \u4e2a\u5b57\u7b26")
}
return normalized, nil
}
+14 -2
View File
@@ -3,6 +3,7 @@ package adminreset
import (
"errors"
"fmt"
"time"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/services/access"
@@ -68,8 +69,19 @@ func ResetSuperAdmin(engine *xorm.Engine, newPassword string, invalidators ...fu
if version <= 0 {
version = 1
}
updated := &models.User{Password: passwordHash, SessionVersion: version}
affected, err := session.ID(target.ID).Where("session_version = ?", target.SessionVersion).Cols("password", "session_version").Update(updated)
securityVersion := target.SecurityVersion + 1
if securityVersion <= 0 {
securityVersion = 1
}
now := time.Now().UTC()
updated := &models.User{
Password: passwordHash,
SessionVersion: version,
SecurityVersion: securityVersion,
MustChangePassword: 0,
PasswordChangedAt: &now,
}
affected, err := session.ID(target.ID).Where("session_version = ?", target.SessionVersion).Cols("password", "session_version", "security_version", "must_change_password", "password_changed_at").Update(updated)
if err != nil {
return fmt.Errorf("update super administrator: %w", err)
}
+13 -1
View File
@@ -59,11 +59,23 @@ func NormalizeIdentifier(identifier string) (string, error) {
}
func isConfiguredLoginDomain(domain string) bool {
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
if manager := config.CurrentManager(); manager != nil {
runtime := manager.Snapshot()
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(runtime.Root.Domains.Primary)), ".") == domain {
return true
}
for _, item := range runtime.Root.Domains.Accepted {
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(item)), ".") == domain {
return true
}
}
return false
}
current := config.CurrentConfig()
if current == nil {
return false
}
domain = strings.TrimSuffix(strings.ToLower(strings.TrimSpace(domain)), ".")
if strings.TrimSuffix(strings.ToLower(strings.TrimSpace(current.Domain)), ".") == domain {
return true
}
+2 -1
View File
@@ -13,6 +13,7 @@ import (
"net/mail"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
)
@@ -165,7 +166,7 @@ func loadKey(path string) ([]byte, error) {
name := filepath.Base(absolute)
info, err := root.Lstat(name)
if err == nil {
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || (info.Mode().Perm()&0077) != 0 || info.Size() != keySize {
if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() || (runtime.GOOS != "windows" && (info.Mode().Perm()&0077) != 0) || info.Size() != keySize {
return nil, ErrVaultUnavailable
}
key, err := root.ReadFile(name)
+28 -1
View File
@@ -52,6 +52,7 @@ type Service struct {
external *externalemail.Repository
credentials *credentials.Service
webauthn WebAuthnVerifier
invalidate func(int, string)
mu sync.Mutex
tickets map[string]ticket
decoys map[string]decoyChallenge
@@ -102,6 +103,13 @@ func (s *Service) SetWebAuthnVerifier(verifier WebAuthnVerifier) {
s.webauthn = verifier
}
func (s *Service) SetSecurityStateInvalidator(invalidator func(int, string)) {
if s == nil {
return
}
s.invalidate = invalidator
}
func (s *Service) BeginWebAuthn(identifier string) (*protocol.CredentialAssertion, string, error) {
if s == nil || s.engine == nil || s.webauthn == nil {
return nil, "", ErrUnavailable
@@ -303,6 +311,7 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
if err != nil {
return err
}
defer clearString(&hash)
var user models.User
has, err := s.engine.ID(item.UserID).Get(&user)
if err != nil || !has || user.EffectiveRole() == access.RoleSuperAdmin || user.SessionVersion != item.SessionVersion {
@@ -321,6 +330,11 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
if version <= 0 {
version = 1
}
securityVersion := user.SecurityVersion + 1
if securityVersion <= 0 {
securityVersion = 1
}
now := s.now().UTC()
session := s.engine.NewSession()
if session == nil {
return ErrUnavailable
@@ -329,7 +343,17 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
if err := session.Begin(); err != nil {
return err
}
if _, err := session.ID(item.UserID).Cols("password", "session_version").Update(&models.User{Password: hash, SessionVersion: version}); err != nil {
if _, err := session.ID(item.UserID).Cols("password", "session_version", "security_version", "must_change_password", "password_changed_at").Update(&models.User{
Password: hash,
SessionVersion: version,
SecurityVersion: securityVersion,
MustChangePassword: 0,
PasswordChangedAt: &now,
}); err != nil {
_ = session.Rollback()
return err
}
if err := s.credentials.RevokeAllWithSession(session, item.UserID); err != nil {
_ = session.Rollback()
return err
}
@@ -340,6 +364,9 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
if s.verification != nil && s.verification.Store != nil {
_ = s.verification.Store.InvalidateAccount(user.Account)
}
if s.invalidate != nil {
s.invalidate(item.UserID, user.Account)
}
return nil
}
+5 -5
View File
@@ -325,7 +325,7 @@ func TestRecoveryStoresOnlyTicketDigestAndLimitsCapacity(t *testing.T) {
}
}
func TestRecoveryPreservesExistingStrongRecoveryCredentials(t *testing.T) {
func TestRecoveryRevokesExistingStrongRecoveryCredentials(t *testing.T) {
service, verifyService, engine, user := newRecoveryFixture(t)
codes, err := service.credentials.GenerateRecoveryCodes(user.ID, 5)
if err != nil {
@@ -355,17 +355,17 @@ func TestRecoveryPreservesExistingStrongRecoveryCredentials(t *testing.T) {
if err := service.Complete(ticketID, "RecoveredPassword@123"); err != nil {
t.Fatal(err)
}
if configured, err := service.credentials.HasValidRecoveryCode(user.ID); err != nil || !configured {
if configured, err := service.credentials.HasValidRecoveryCode(user.ID); err != nil || configured {
t.Fatalf("有效离线恢复码未保留:configured=%v err=%v", configured, err)
}
if err := service.credentials.ConsumeRecoveryCode(user.ID, codes[0]); err != nil {
if err := service.credentials.ConsumeRecoveryCode(user.ID, codes[0]); err == nil {
t.Fatalf("原离线恢复码不可用:%v", err)
}
if question, configured, err := service.credentials.GetSecurityQuestion(user.ID); err != nil || !configured || question == "" {
if question, configured, err := service.credentials.GetSecurityQuestion(user.ID); err != nil || configured || question != "" {
t.Fatalf("密保问题未保留:question=%q configured=%v err=%v", question, configured, err)
}
var stored models.WebAuthnCredential
if found, err := engine.ID(credential.ID).Get(&stored); err != nil || !found || stored.RevokedAt != nil {
if found, err := engine.ID(credential.ID).Get(&stored); err != nil || !found || stored.RevokedAt == nil {
t.Fatalf("WebAuthn 凭据未保留:found=%v credential=%+v err=%v", found, stored, err)
}
}
@@ -37,7 +37,7 @@ func (f *fakeWebAuthnVerifier) FinishDiscoverableLogin(sessionID string, request
return f.resultUser, &models.WebAuthnCredential{UserID: f.resultUser.ID}, nil
}
func TestWebAuthnRecoveryIssuesOneTimeTicketAndPreservesCredentials(t *testing.T) {
func TestWebAuthnRecoveryIssuesOneTimeTicketAndRevokesCredentials(t *testing.T) {
service, _, engine, user := newRecoveryFixture(t)
verifier := &fakeWebAuthnVerifier{resultUser: user}
service.SetWebAuthnVerifier(verifier)
@@ -68,13 +68,13 @@ func TestWebAuthnRecoveryIssuesOneTimeTicketAndPreservesCredentials(t *testing.T
t.Fatalf("replayed ticket error = %v", err)
}
if count, err := engine.Where("user_id = ?", user.ID).Count(&models.SecurityQuestion{}); err != nil || count != 1 {
if count, err := engine.Where("user_id = ?", user.ID).Count(&models.SecurityQuestion{}); err != nil || count != 0 {
t.Fatalf("security questions count=%d err=%v", count, err)
}
if count, err := engine.Where("user_id = ? AND used_at IS NULL", user.ID).Count(&models.RecoveryCode{}); err != nil || count != 5 {
if count, err := engine.Where("user_id = ? AND used_at IS NULL", user.ID).Count(&models.RecoveryCode{}); err != nil || count != 0 {
t.Fatalf("active recovery codes count=%d err=%v", count, err)
}
if count, err := engine.Where("user_id = ? AND revoked_at IS NULL", user.ID).Count(&models.WebAuthnCredential{}); err != nil || count != 1 {
if count, err := engine.Where("user_id = ? AND revoked_at IS NULL", user.ID).Count(&models.WebAuthnCredential{}); err != nil || count != 0 {
t.Fatalf("active webauthn credentials count=%d err=%v", count, err)
}
}
+64 -13
View File
@@ -2,9 +2,11 @@ package setup
import (
"fmt"
"git.pcux.cn/xuans/Smail/config"
"net"
"net/netip"
"strings"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/i18n"
"git.pcux.cn/xuans/Smail/services/auth"
"git.pcux.cn/xuans/Smail/utils/context"
@@ -31,20 +33,69 @@ func GetDNSSettings(ctx *context.Context) (map[string][]*DNSItem, error) {
return nil, errors.Wrap(err)
}
ret := make(map[string][]*DNSItem)
ipv4 := ip.GetIPv4()
ipv6 := ip.GetIPv6()
ipTips := i18n.GetText(ctx.Lang, "ip_taps")
ret := make(map[string][]*DNSItem, len(configData.Domains))
for _, domain := range configData.Domains {
ret[domain] = []*DNSItem{
{Type: "A", Host: strings.ReplaceAll(configData.WebDomain, "."+configData.Domain, ""), Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "A", Host: "smtp", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "A", Host: "imap", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "A", Host: "pop", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "A", Host: "@", Value: ip.GetIp(), TTL: 3600, Tips: i18n.GetText(ctx.Lang, "ip_taps")},
{Type: "MX", Host: "@", Value: fmt.Sprintf("smtp.%s", domain), TTL: 3600},
{Type: "TXT", Host: "@", Value: "v=spf1 a mx ~all", TTL: 3600},
{Type: "TXT", Host: "default._domainkey", Value: dkimPublicKey, TTL: 3600},
}
ret[domain] = buildDNSItems(configData, domain, dkimPublicKey, ipv4, ipv6, ipTips)
}
return ret, nil
}
func buildDNSItems(configData *config.Config, domain, dkimPublicKey, ipv4, ipv6, ipTips string) []*DNSItem {
address := strings.TrimSpace(ipv4)
if address == "" {
address = "[Your Server IP]"
}
return []*DNSItem{
{Type: "A", Host: strings.ReplaceAll(configData.WebDomain, "."+configData.Domain, ""), Value: address, TTL: 3600, Tips: ipTips},
{Type: "A", Host: "smtp", Value: address, TTL: 3600, Tips: ipTips},
{Type: "A", Host: "imap", Value: address, TTL: 3600, Tips: ipTips},
{Type: "A", Host: "pop", Value: address, TTL: 3600, Tips: ipTips},
{Type: "A", Host: "@", Value: address, TTL: 3600, Tips: ipTips},
{Type: "MX", Host: "@", Value: fmt.Sprintf("smtp.%s", domain), TTL: 3600},
{Type: "TXT", Host: "@", Value: buildSPFRecord(ipv4, ipv6), TTL: 3600},
{Type: "TXT", Host: "_dmarc", Value: "v=DMARC1; p=quarantine", TTL: 3600},
{Type: "TXT", Host: "default._domainkey", Value: dkimPublicKey, TTL: 3600},
}
}
func buildSPFRecord(ipv4, ipv6 string) string {
mechanisms := []string{"v=spf1", "a", "mx"}
if mechanism := buildSPFAddressMechanism(ipv4); mechanism != "" {
mechanisms = append(mechanisms, mechanism)
}
if mechanism := buildSPFAddressMechanism(ipv6); mechanism != "" {
mechanisms = append(mechanisms, mechanism)
}
mechanisms = append(mechanisms, "~all")
return strings.Join(mechanisms, " ")
}
func buildSPFAddressMechanism(value string) string {
address, err := netip.ParseAddr(strings.TrimSpace(value))
if err != nil {
return ""
}
address = address.Unmap()
if !isPublicDNSAddress(address) {
return ""
}
if address.Is4() {
return "ip4:" + address.String()
}
if address.Is6() {
return "ip6:" + address.String()
}
return ""
}
func isPublicDNSAddress(address netip.Addr) bool {
return address.IsValid() && address.IsGlobalUnicast() &&
!address.IsPrivate() && !address.IsLoopback() &&
!address.IsLinkLocalUnicast() && !address.IsLinkLocalMulticast() &&
!address.IsMulticast() && !address.IsUnspecified() &&
!net.IP(address.AsSlice()).IsInterfaceLocalMulticast()
}
+61
View File
@@ -0,0 +1,61 @@
package setup
import (
"testing"
"git.pcux.cn/xuans/Smail/config"
)
func TestBuildSPFRecordIncludesPublicIPv4AndIPv6(t *testing.T) {
value := buildSPFRecord("203.0.113.15", "2001:db8::15")
want := "v=spf1 a mx ip4:203.0.113.15 ip6:2001:db8::15 ~all"
if value != want {
t.Fatalf("SPF record = %q, want %q", value, want)
}
}
func TestBuildSPFRecordSkipsUnsafeAddresses(t *testing.T) {
cases := []struct {
name string
ipv4 string
ipv6 string
want string
}{
{name: "empty", want: "v=spf1 a mx ~all"},
{name: "private IPv4", ipv4: "192.168.1.20", want: "v=spf1 a mx ~all"},
{name: "link local IPv6", ipv6: "fe80::1", want: "v=spf1 a mx ~all"},
{name: "only IPv4", ipv4: "198.51.100.9", want: "v=spf1 a mx ip4:198.51.100.9 ~all"},
{name: "only IPv6", ipv6: "2001:db8::9", want: "v=spf1 a mx ip6:2001:db8::9 ~all"},
}
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
if value := buildSPFRecord(item.ipv4, item.ipv6); value != item.want {
t.Fatalf("SPF record = %q, want %q", value, item.want)
}
})
}
}
func TestBuildDNSItemsIncludesSPFAndQuarantineDMARC(t *testing.T) {
cfg := &config.Config{
Domain: "example.com",
WebDomain: "mail.example.com",
}
items := buildDNSItems(cfg, "example.com", "v=DKIM1; k=rsa; p=test", "203.0.113.10", "2001:db8::10", "")
values := make(map[string]string)
for _, item := range items {
if item.Type == "TXT" {
values[item.Host] = item.Value
}
}
if value := values["@"]; value != "v=spf1 a mx ip4:203.0.113.10 ip6:2001:db8::10 ~all" {
t.Fatalf("SPF TXT value = %q", value)
}
if value := values["_dmarc"]; value != "v=DMARC1; p=quarantine" {
t.Fatalf("DMARC TXT value = %q", value)
}
if value := values["default._domainkey"]; value != "v=DKIM1; k=rsa; p=test" {
t.Fatalf("DKIM TXT value = %q", value)
}
}