This commit is contained in:
1 parent
b5a3e601c7
commit
8899e74a66
23 files changed
+918
-21
No files matched your search
@@ -45,6 +45,11 @@ var (
|
||||
)
|
||||
|
||||
func AuthenticateProtocol(protocol string, remoteAddress string, account string, plain string) (*models.User, error) {
|
||||
var grant *credentials.ProtocolGrant
|
||||
return authenticateProtocol(protocol, remoteAddress, account, plain, &grant)
|
||||
}
|
||||
|
||||
func authenticateProtocol(protocol string, remoteAddress string, account string, plain string, grant **credentials.ProtocolGrant) (*models.User, error) {
|
||||
normalizedProtocol, protocolErr := credentials.NormalizeProtocol(protocol)
|
||||
normalizedAccount := strings.ToLower(strings.TrimSpace(account))
|
||||
if normalizedIdentifier, err := NormalizeProtocolIdentifier(account); err == nil {
|
||||
@@ -85,11 +90,11 @@ func AuthenticateProtocol(protocol string, remoteAddress string, account string,
|
||||
if err != nil {
|
||||
return fail()
|
||||
}
|
||||
matched, err := service.CheckClientOrProtocolCode(userID, normalizedProtocol, plain)
|
||||
matched, err := service.CheckClientOrProtocolGrant(userID, normalizedProtocol, plain)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil || !matched {
|
||||
if err != nil || matched == nil {
|
||||
return fail()
|
||||
}
|
||||
var user models.User
|
||||
@@ -99,6 +104,7 @@ func AuthenticateProtocol(protocol string, remoteAddress string, account string,
|
||||
}
|
||||
protocolPairAttempts.clear(pairKey)
|
||||
protocolAccountAttempts.clear(accountKey)
|
||||
*grant = matched
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/credentials"
|
||||
)
|
||||
|
||||
// ProtocolSession 保存不可变身份与凭据快照,拒绝后的连接不能通过重新启用恢复权限。
|
||||
type ProtocolSession struct {
|
||||
user models.User
|
||||
grant *credentials.ProtocolGrant
|
||||
invalid atomic.Bool
|
||||
}
|
||||
|
||||
func AuthenticateProtocolSession(protocol, remoteAddress, account, plain string) (*models.User, *ProtocolSession, error) {
|
||||
var grant *credentials.ProtocolGrant
|
||||
user, err := authenticateProtocol(protocol, remoteAddress, account, plain, &grant)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
session := &ProtocolSession{user: *user, grant: grant}
|
||||
if err := session.Check(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return user, session, nil
|
||||
}
|
||||
|
||||
// Check 在每条数据命令前复核授权;数据库故障或切换时也不沿用旧权限。
|
||||
func (s *ProtocolSession) Check() error {
|
||||
denied := errors.New("protocol authorization revoked")
|
||||
if s == nil || s.invalid.Load() {
|
||||
return denied
|
||||
}
|
||||
engine := db.Instance
|
||||
if engine != nil && s.grant.Valid(engine) {
|
||||
var user models.User
|
||||
has, err := engine.ID(s.user.ID).Where("disabled = 0").Get(&user)
|
||||
if err == nil && has && user.Account == s.user.Account && user.Password == s.user.Password &&
|
||||
user.SessionVersion == s.user.SessionVersion && user.SecurityVersion == s.user.SecurityVersion &&
|
||||
user.EffectiveRole() == s.user.EffectiveRole() && user.MustChangePassword == s.user.MustChangePassword && !s.invalid.Load() {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
s.invalid.Store(true)
|
||||
return denied
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/config"
|
||||
"git.pcux.cn/xuans/Smail/db"
|
||||
"git.pcux.cn/xuans/Smail/internal/passwordtest"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/credentials"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func TestProtocolSessionRechecksUserAndCredential(t *testing.T) {
|
||||
for _, kind := range []string{"protocol", "client"} {
|
||||
for _, change := range []string{"revoke", "disabled", "password", "session_version", "security_version", "role", "deleted", "database_failure"} {
|
||||
t.Run(kind+"/"+change, func(t *testing.T) {
|
||||
oldDB, oldConfig := db.Instance, config.Instance
|
||||
engine, err := xorm.NewEngine("sqlite", filepath.Join(t.TempDir(), "session.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = engine.Close(); db.Instance, config.Instance = oldDB, oldConfig })
|
||||
db.Instance = engine
|
||||
config.Instance = &config.Config{Domain: "example.com"}
|
||||
if err := engine.Sync2(&models.User{}, &models.UserEmail{}, &models.ClientCredential{}, &models.ProtocolCredential{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
user := models.User{Account: "session-user", Password: "test-hash", Role: "user", SessionVersion: 1, SecurityVersion: 1}
|
||||
if _, err := engine.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
address, now := "session-user@example.com", time.Now().UTC()
|
||||
if _, err := engine.Insert(&models.UserEmail{UserID: user.ID, Address: address, AddressCanonical: &address, VerifiedAt: &now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service, err := credentials.NewService(engine)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var code string
|
||||
var clientID int
|
||||
if kind == "protocol" {
|
||||
if err := service.SetProtocolEnabled(user.ID, "smtp", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err = service.GenerateProtocolCode(user.ID, "smtp")
|
||||
} else {
|
||||
var item *credentials.ClientCredentialItem
|
||||
code, item, err = service.CreateClientCredential(user.ID, "会话验收")
|
||||
if item != nil {
|
||||
clientID = item.ID
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, session, err := AuthenticateProtocolSession("smtp", "192.0.2.91:1234", address, code)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// 命令复核不占用密码哈希容量,也不累加登录失败计数。
|
||||
release := passwordtest.Hold(t)
|
||||
if err := session.Check(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
switch change {
|
||||
case "revoke":
|
||||
if kind == "protocol" {
|
||||
err = service.RevokeProtocolCode(user.ID, "smtp")
|
||||
} else {
|
||||
err = service.RevokeClientCredential(user.ID, clientID)
|
||||
}
|
||||
case "disabled":
|
||||
_, err = engine.ID(user.ID).Cols("disabled").Update(&models.User{Disabled: 1})
|
||||
case "password":
|
||||
_, err = engine.ID(user.ID).Cols("password").Update(&models.User{Password: "new-hash"})
|
||||
case "session_version":
|
||||
_, err = engine.ID(user.ID).Incr("session_version", 1).Update(&models.User{})
|
||||
case "security_version":
|
||||
_, err = engine.ID(user.ID).Incr("security_version", 1).Update(&models.User{})
|
||||
case "role":
|
||||
_, err = engine.ID(user.ID).Cols("role").Update(&models.User{Role: "admin"})
|
||||
case "deleted":
|
||||
_, err = engine.ID(user.ID).Delete(&models.User{})
|
||||
case "database_failure":
|
||||
err = engine.Close()
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wait sync.WaitGroup
|
||||
for range 4 {
|
||||
wait.Add(1)
|
||||
go func() {
|
||||
defer wait.Done()
|
||||
if session.Check() == nil {
|
||||
t.Error("旧会话仍可访问数据")
|
||||
}
|
||||
}()
|
||||
}
|
||||
wait.Wait()
|
||||
if change == "disabled" {
|
||||
if _, err := engine.ID(user.ID).Cols("disabled").Update(&models.User{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session.Check() == nil {
|
||||
t.Fatal("被拒绝的连接不应恢复授权")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -292,36 +292,53 @@ func (s *Service) VerifyClientOrProtocolCode(userID int, protocol string, rawPla
|
||||
|
||||
// CheckClientOrProtocolCode 将计算过载向上返回,避免被当成密码错误累计封禁。
|
||||
func (s *Service) CheckClientOrProtocolCode(userID int, protocol string, rawPlain string) (bool, error) {
|
||||
grant, err := s.CheckClientOrProtocolGrant(userID, protocol, rawPlain)
|
||||
return grant != nil, err
|
||||
}
|
||||
|
||||
// CheckClientOrProtocolGrant 返回本次实际匹配的凭据快照,不保存明文授权码。
|
||||
func (s *Service) CheckClientOrProtocolGrant(userID int, protocol string, rawPlain string) (*ProtocolGrant, error) {
|
||||
if s == nil || s.engine == nil || userID <= 0 || rawPlain == "" || len([]byte(rawPlain)) > 256 {
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
return nil, password.CheckDummy(rawPlain)
|
||||
}
|
||||
cleanedPlain := CleanAuthCode(rawPlain)
|
||||
if cleanedPlain == "" {
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
return nil, password.CheckDummy(rawPlain)
|
||||
}
|
||||
protocol, err := NormalizeProtocol(protocol)
|
||||
if err != nil {
|
||||
return nil, password.CheckDummy(rawPlain)
|
||||
}
|
||||
|
||||
// 1. 优先校验客户端专属授权码
|
||||
var clients []models.ClientCredential
|
||||
err := s.engine.Where("user_id = ? AND revoked_at IS NULL AND code_hash != ''", userID).Find(&clients)
|
||||
err = s.engine.Where("user_id = ? AND revoked_at IS NULL AND code_hash != ''", userID).Find(&clients)
|
||||
if err == nil && len(clients) > 0 {
|
||||
for _, client := range clients {
|
||||
// 比对清洗后的统一大写无横线授权码
|
||||
matched, err := password.Check(client.CodeHash, cleanedPlain)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
if matched {
|
||||
grant := &ProtocolGrant{engine: s.engine, userID: userID, protocol: protocol, client: true, id: client.ID, version: client.CodeVersion, hash: client.CodeHash}
|
||||
now := s.now()
|
||||
affected, err := s.engine.ID(client.ID).
|
||||
Where("revoked_at IS NULL AND code_version = ? AND code_hash = ?", client.CodeVersion, client.CodeHash).
|
||||
Cols("last_used_at", "updated_at").Update(&models.ClientCredential{LastUsedAt: &now})
|
||||
if err != nil || affected == 1 {
|
||||
return err == nil, err
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
valid, err := s.engine.ID(client.ID).
|
||||
Where("revoked_at IS NULL AND code_version = ? AND code_hash = ?", client.CodeVersion, client.CodeHash).
|
||||
Exist(&models.ClientCredential{})
|
||||
return valid, err
|
||||
if err != nil || !valid {
|
||||
return nil, err
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -329,40 +346,44 @@ func (s *Service) CheckClientOrProtocolCode(userID int, protocol string, rawPlai
|
||||
// 2. 回退校验旧版按协议划分的授权码(支持 cleanedPlain 或原樣 rawPlain)
|
||||
protocol, err = NormalizeProtocol(protocol)
|
||||
if err != nil {
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
return nil, password.CheckDummy(rawPlain)
|
||||
}
|
||||
var item models.ProtocolCredential
|
||||
has, err := s.engine.Where("user_id = ? AND protocol = ? AND enabled = ? AND revoked_at IS NULL", userID, protocol, true).Get(&item)
|
||||
if err != nil || !has || item.CodeHash == "" {
|
||||
return false, password.CheckDummy(rawPlain)
|
||||
return nil, password.CheckDummy(rawPlain)
|
||||
}
|
||||
|
||||
// 兼容旧哈希直接比对原始输入,或者比对清洗后的输入
|
||||
trimmedPlain := strings.TrimSpace(rawPlain)
|
||||
matched, err := password.Check(item.CodeHash, trimmedPlain)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
if !matched && trimmedPlain != cleanedPlain {
|
||||
matched, err = password.Check(item.CodeHash, cleanedPlain)
|
||||
}
|
||||
if err != nil || !matched {
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
grant := &ProtocolGrant{engine: s.engine, userID: userID, protocol: protocol, id: item.ID, version: item.CodeVersion, hash: item.CodeHash}
|
||||
|
||||
now := s.now()
|
||||
affected, err := s.engine.ID(item.ID).
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Cols("last_used_at", "updated_at").Update(&models.ProtocolCredential{LastUsedAt: &now})
|
||||
if err == nil && affected == 1 {
|
||||
return true, nil
|
||||
return grant, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
valid, err := s.engine.ID(item.ID).
|
||||
Where("enabled = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", true, item.CodeVersion, item.CodeHash).
|
||||
Exist(&models.ProtocolCredential{})
|
||||
return valid, err
|
||||
if err != nil || !valid {
|
||||
return nil, err
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
@@ -113,7 +113,12 @@ func (s *Service) SetProtocolEnabled(userID int, protocol string, enabled bool)
|
||||
return nil
|
||||
}
|
||||
item.Enabled = enabled
|
||||
if _, err := s.engine.ID(item.ID).Cols("enabled", "updated_at").Update(&item); err != nil {
|
||||
update := s.engine.ID(item.ID).Cols("enabled", "updated_at")
|
||||
if !enabled {
|
||||
// 即使关闭后立即开启且旧连接尚未发命令,也不能恢复旧会话的授权。
|
||||
update = update.Incr("code_version", 1)
|
||||
}
|
||||
if _, err := update.Update(&item); err != nil {
|
||||
return fmt.Errorf("update protocol credential: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package credentials
|
||||
|
||||
import (
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
// ProtocolGrant 绑定认证时匹配的单个凭据;命令复核不重复执行密码哈希。
|
||||
// 字段不导出,避免授权码哈希进入日志、接口响应或持久化会话。
|
||||
type ProtocolGrant struct {
|
||||
engine *xorm.Engine
|
||||
userID int
|
||||
protocol string
|
||||
client bool
|
||||
id int
|
||||
version int
|
||||
hash string
|
||||
}
|
||||
|
||||
func (g *ProtocolGrant) Valid(engine *xorm.Engine) bool {
|
||||
if g == nil || engine == nil || engine != g.engine || g.id <= 0 {
|
||||
return false
|
||||
}
|
||||
query := engine.ID(g.id).Where("user_id = ? AND revoked_at IS NULL AND code_version = ? AND code_hash = ?", g.userID, g.version, g.hash)
|
||||
var valid bool
|
||||
var err error
|
||||
if g.client {
|
||||
valid, err = query.Exist(&models.ClientCredential{})
|
||||
} else {
|
||||
valid, err = query.Where("protocol = ? AND enabled = ?", g.protocol, true).Exist(&models.ProtocolCredential{})
|
||||
}
|
||||
return err == nil && valid
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package credentials
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
)
|
||||
|
||||
func TestProtocolGrantTracksCredentialChanges(t *testing.T) {
|
||||
for _, change := range []string{"revoke", "rotate", "disable_enable", "delete", "hash", "version", "database"} {
|
||||
t.Run(change, func(t *testing.T) {
|
||||
s := newFixture(t)
|
||||
if err := s.SetProtocolEnabled(1, ProtocolSMTP, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
code, err := s.GenerateProtocolCode(1, ProtocolSMTP)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
grant, err := s.CheckClientOrProtocolGrant(1, ProtocolSMTP, code)
|
||||
if err != nil || !grant.Valid(s.engine) {
|
||||
t.Fatalf("授权快照无效:%v", err)
|
||||
}
|
||||
data, err := json.Marshal(grant)
|
||||
if err != nil || string(data) != "{}" {
|
||||
t.Fatal("授权快照泄漏内部字段")
|
||||
}
|
||||
switch change {
|
||||
case "revoke":
|
||||
err = s.RevokeProtocolCode(1, ProtocolSMTP)
|
||||
case "rotate":
|
||||
_, err = s.GenerateProtocolCode(1, ProtocolSMTP)
|
||||
case "disable_enable":
|
||||
err = s.SetProtocolEnabled(1, ProtocolSMTP, false)
|
||||
if err == nil {
|
||||
err = s.SetProtocolEnabled(1, ProtocolSMTP, true)
|
||||
}
|
||||
case "delete":
|
||||
_, err = s.engine.Where("user_id = ?", 1).Delete(&models.ProtocolCredential{})
|
||||
case "hash":
|
||||
_, err = s.engine.Where("user_id = ?", 1).Cols("code_hash").Update(&models.ProtocolCredential{CodeHash: "replacement"})
|
||||
case "version":
|
||||
_, err = s.engine.Where("user_id = ?", 1).Incr("code_version", 1).Update(&models.ProtocolCredential{})
|
||||
case "database":
|
||||
if grant.Valid(newFixture(t).engine) {
|
||||
t.Fatal("数据库切换后沿用旧授权")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if grant.Valid(s.engine) {
|
||||
t.Fatal("失效的凭据快照仍然有效")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientGrantRevocationPreservesOtherClients(t *testing.T) {
|
||||
s := newFixture(t)
|
||||
first, item, err := s.CreateClientCredential(1, "被撤销客户端")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, _, err := s.CreateClientCredential(1, "保留客户端")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, protocol := range SupportedProtocols() {
|
||||
grant, err := s.CheckClientOrProtocolGrant(1, protocol, first)
|
||||
if err != nil || !grant.Valid(s.engine) {
|
||||
t.Fatalf("客户端授权失败:%v", err)
|
||||
}
|
||||
}
|
||||
firstGrant, err := s.CheckClientOrProtocolGrant(1, ProtocolIMAP, first)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secondGrant, err := s.CheckClientOrProtocolGrant(1, ProtocolIMAP, second)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.RevokeClientCredential(1, item.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if firstGrant.Valid(s.engine) || !secondGrant.Valid(s.engine) {
|
||||
t.Fatal("客户端撤销范围不正确")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user