1 parent
1e2f9befae
commit
19d1338d8a
6 files changed
+383
-47
No files matched your search
@@ -197,6 +197,7 @@ type verificationCheckRequest struct {
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
RecoveryCode string `json:"recovery_code"`
|
||||
Continuation string `json:"continuation"`
|
||||
BindingID int `json:"binding_id"`
|
||||
}
|
||||
|
||||
@@ -587,8 +588,19 @@ func VerifyPasswordRecovery(ctx *context.Context, w http.ResponseWriter, req *ht
|
||||
}
|
||||
if methodOffline {
|
||||
ticket, err = runtime.recovery.VerifyOfflineWithContext(input.Account, input.Question, input.Answer, input.RecoveryCode, remoteIP(req), browserContext)
|
||||
} else if strings.EqualFold(strings.TrimSpace(input.Method), "email_recovery_code") {
|
||||
ticket, err = runtime.recovery.ContinueEmailWithContext(input.Continuation, input.Account, input.Email, input.RecoveryCode, browserContext)
|
||||
} else {
|
||||
ticket, err = runtime.recovery.VerifyWithContext(input.ID, input.Account, input.Email, input.Code, input.RecoveryCode, remoteIP(req), browserContext)
|
||||
var result recovery.EmailVerificationResult
|
||||
result, err = runtime.recovery.VerifyEmailStepWithContext(input.ID, input.Account, input.Email, input.Code, remoteIP(req), browserContext)
|
||||
if err == nil {
|
||||
// 附加验证尚未完成,操作日志不能提前标记为身份验证成功。
|
||||
if observer, ok := w.(interface{ ObservePending(bool) }); ok {
|
||||
observer.ObservePending(result.RequiresRecoveryCode)
|
||||
}
|
||||
response.NewSuccessResponse(result).FPrint(w)
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
emailRecoveryFailureIPAttempts.recordFailure(failureKey)
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
package recovery
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/auth"
|
||||
)
|
||||
|
||||
const maxEmailContinuationAttempts = 5
|
||||
|
||||
// EmailVerificationResult 仅在邮箱核验通过后告知是否需要管理员附加验证。
|
||||
type EmailVerificationResult struct {
|
||||
Ticket string `json:"ticket,omitempty"`
|
||||
RequiresRecoveryCode bool `json:"requires_recovery_code,omitempty"`
|
||||
Continuation string `json:"continuation,omitempty"`
|
||||
ExpiresIn int `json:"expires_in,omitempty"`
|
||||
}
|
||||
|
||||
// 中间凭证与重置票据分开存储,不能用于直接修改密码。
|
||||
type emailContinuation struct {
|
||||
ticket
|
||||
Account string
|
||||
SecurityVersion int
|
||||
Attempts int
|
||||
Busy bool
|
||||
}
|
||||
|
||||
func (s *Service) VerifyEmailStepWithContext(challengeID, account, email, code, remoteIP, browserContext string) (EmailVerificationResult, error) {
|
||||
if strings.TrimSpace(browserContext) == "" {
|
||||
return EmailVerificationResult{}, ErrRecoveryDenied
|
||||
}
|
||||
user, binding, err := s.verifyEmailIdentity(challengeID, account, email, code, remoteIP, browserContext)
|
||||
if err != nil {
|
||||
return EmailVerificationResult{}, err
|
||||
}
|
||||
if user.EffectiveRole() != access.RoleAdmin {
|
||||
id, err := s.issueTicketFor(user.ID, user.SessionVersion, "email", binding.ID, binding.CredentialVersion, browserContext)
|
||||
return EmailVerificationResult{Ticket: id}, err
|
||||
}
|
||||
id, err := newTicketID()
|
||||
if err != nil {
|
||||
return EmailVerificationResult{}, err
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
now := s.now()
|
||||
s.cleanupLocked(now)
|
||||
if len(s.emailPending) >= maxRecoveryTickets {
|
||||
return EmailVerificationResult{}, ErrUnavailable
|
||||
}
|
||||
s.emailPending[ticketKey(id)] = &emailContinuation{
|
||||
ticket: ticket{
|
||||
UserID: user.ID, SessionVersion: user.SessionVersion,
|
||||
CredentialID: binding.ID, CredentialVersion: binding.CredentialVersion,
|
||||
BrowserContextDigest: sha256.Sum256([]byte(strings.TrimSpace(browserContext))),
|
||||
HasBrowserContextDigest: true, ExpiresAt: now.Add(authorizationTTL),
|
||||
},
|
||||
Account: user.Account, SecurityVersion: user.SecurityVersion,
|
||||
}
|
||||
return EmailVerificationResult{
|
||||
RequiresRecoveryCode: true, Continuation: id, ExpiresIn: int(authorizationTTL.Seconds()),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) ContinueEmailWithContext(continuation, identifier, email, recoveryCode, browserContext string) (string, error) {
|
||||
defer clearString(&recoveryCode)
|
||||
if s == nil || s.engine == nil || s.credentials == nil || s.external == nil {
|
||||
return "", ErrUnavailable
|
||||
}
|
||||
account, err := auth.NormalizeIdentifier(identifier)
|
||||
if err != nil || strings.TrimSpace(continuation) == "" || strings.TrimSpace(browserContext) == "" {
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
key := ticketKey(continuation)
|
||||
contextDigest := sha256.Sum256([]byte(strings.TrimSpace(browserContext)))
|
||||
s.mu.Lock()
|
||||
s.cleanupLocked(s.now())
|
||||
pending, ok := s.emailPending[key]
|
||||
if !ok {
|
||||
s.mu.Unlock()
|
||||
return "", ErrRecoveryExpired
|
||||
}
|
||||
if pending.Busy || !strings.EqualFold(account, pending.Account) || subtle.ConstantTimeCompare(contextDigest[:], pending.BrowserContextDigest[:]) != 1 {
|
||||
s.mu.Unlock()
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
pending.Attempts++
|
||||
pending.Busy = true
|
||||
s.mu.Unlock()
|
||||
|
||||
// 数据库和恢复码哈希验证不占用全局锁;同一凭证同时只能有一个请求验证。
|
||||
invalidate := false
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if s.emailPending[key] == pending {
|
||||
if invalidate || pending.Attempts >= maxEmailContinuationAttempts {
|
||||
delete(s.emailPending, key)
|
||||
} else {
|
||||
pending.Busy = false
|
||||
}
|
||||
}
|
||||
}()
|
||||
user, err := s.loadRecoverableUser(account)
|
||||
if err != nil || user.ID != pending.UserID || user.EffectiveRole() != access.RoleAdmin || user.SessionVersion != pending.SessionVersion || user.SecurityVersion != pending.SecurityVersion {
|
||||
invalidate = true
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
binding, err := s.external.FindVerifiedByEmail(email)
|
||||
if err != nil || binding.UserID != pending.UserID || binding.ID != pending.CredentialID || binding.CredentialVersion != pending.CredentialVersion {
|
||||
invalidate = true
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
if err := s.credentials.ConsumeRecoveryCode(user.ID, recoveryCode); err != nil {
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
invalidate = true
|
||||
ticketID, err := s.issueTicketFor(user.ID, user.SessionVersion, "email_admin", binding.ID, binding.CredentialVersion, browserContext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
s.mu.Lock()
|
||||
active := s.emailPending[key] == pending && s.now().Before(pending.ExpiresAt)
|
||||
delete(s.emailPending, key)
|
||||
if !active {
|
||||
delete(s.tickets, ticketKey(ticketID))
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if !active {
|
||||
return "", ErrRecoveryExpired
|
||||
}
|
||||
return ticketID, nil
|
||||
}
|
||||
@@ -55,6 +55,7 @@ type Service struct {
|
||||
invalidate func(int, string)
|
||||
mu sync.Mutex
|
||||
tickets map[string]ticket
|
||||
emailPending map[string]*emailContinuation
|
||||
decoys map[string]decoyChallenge
|
||||
now func() time.Time
|
||||
}
|
||||
@@ -92,7 +93,8 @@ func NewService(engine *xorm.Engine, verify *verification.Service, external *ext
|
||||
}
|
||||
return &Service{
|
||||
engine: engine, verification: verify, external: external, credentials: credential,
|
||||
tickets: make(map[string]ticket), decoys: make(map[string]decoyChallenge), now: time.Now,
|
||||
tickets: make(map[string]ticket), emailPending: make(map[string]*emailContinuation),
|
||||
decoys: make(map[string]decoyChallenge), now: time.Now,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -224,43 +226,47 @@ func (s *Service) Verify(challengeID, account, email, code, recoveryCode, remote
|
||||
}
|
||||
|
||||
func (s *Service) VerifyWithContext(challengeID, account, email, code, recoveryCode, remoteIP, browserContext string) (string, error) {
|
||||
user, item, err := s.verifyEmailIdentity(challengeID, account, email, code, remoteIP, browserContext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
method := "email"
|
||||
if user.EffectiveRole() == access.RoleAdmin {
|
||||
if strings.TrimSpace(recoveryCode) == "" {
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
if err := s.credentials.ConsumeRecoveryCode(user.ID, recoveryCode); err != nil {
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
method = "email_admin"
|
||||
}
|
||||
return s.issueTicketFor(user.ID, user.SessionVersion, method, item.ID, item.CredentialVersion, browserContext)
|
||||
}
|
||||
|
||||
func (s *Service) verifyEmailIdentity(challengeID, account, email, code, remoteIP, browserContext string) (*models.User, *models.ExternalEmail, error) {
|
||||
if s == nil || s.verification == nil {
|
||||
return "", ErrUnavailable
|
||||
return nil, nil, ErrUnavailable
|
||||
}
|
||||
if s.consumeDecoyChallengeWithContext(challengeID, account, email, code, browserContext) {
|
||||
return "", ErrRecoveryDenied
|
||||
return nil, nil, ErrRecoveryDenied
|
||||
}
|
||||
normalizedAccount, normalizeErr := auth.NormalizeIdentifier(account)
|
||||
if normalizeErr != nil {
|
||||
return "", ErrRecoveryDenied
|
||||
return nil, nil, ErrRecoveryDenied
|
||||
}
|
||||
var user models.User
|
||||
has, err := s.engine.Where("account = ? AND disabled = 0", normalizedAccount).Get(&user)
|
||||
if err != nil || !has || user.EffectiveRole() == access.RoleSuperAdmin || s.external == nil {
|
||||
return "", ErrRecoveryDenied
|
||||
return nil, nil, ErrRecoveryDenied
|
||||
}
|
||||
item, err := s.external.FindVerifiedByEmail(email)
|
||||
if err != nil || item.UserID != user.ID {
|
||||
return "", ErrRecoveryDenied
|
||||
return nil, nil, ErrRecoveryDenied
|
||||
}
|
||||
if err := s.verification.VerifyBoundWithContext(challengeID, normalizedAccount, email, code, verification.PurposePasswordRecover, item.ID, remoteIP, browserContext); err != nil {
|
||||
return "", err
|
||||
return nil, nil, err
|
||||
}
|
||||
ticketID, err := s.issueTicketFor(user.ID, user.SessionVersion, "email", item.ID, item.CredentialVersion, browserContext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if user.EffectiveRole() == access.RoleAdmin {
|
||||
if strings.TrimSpace(recoveryCode) == "" {
|
||||
s.invalidateTicket(ticketID)
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
if err := s.credentials.ConsumeRecoveryCode(user.ID, recoveryCode); err != nil {
|
||||
s.invalidateTicket(ticketID)
|
||||
return "", ErrRecoveryDenied
|
||||
}
|
||||
}
|
||||
return ticketID, nil
|
||||
return &user, item, nil
|
||||
}
|
||||
|
||||
func (s *Service) VerifyOffline(identifier, question, answer, recoveryCode, remoteIP string) (string, error) {
|
||||
@@ -343,7 +349,10 @@ func (s *Service) CompleteWithContext(ticketID, newPassword, browserContext stri
|
||||
if err != nil || !has || user.Disabled != 0 || user.EffectiveRole() == access.RoleSuperAdmin || user.SessionVersion != item.SessionVersion {
|
||||
return ErrRecoveryDenied
|
||||
}
|
||||
if item.Method == "email" {
|
||||
if item.Method == "email" || item.Method == "email_admin" {
|
||||
if user.EffectiveRole() == access.RoleAdmin && item.Method != "email_admin" {
|
||||
return ErrRecoveryDenied
|
||||
}
|
||||
if s.external == nil || item.CredentialID <= 0 {
|
||||
return ErrRecoveryDenied
|
||||
}
|
||||
@@ -457,6 +466,11 @@ func (s *Service) cleanupLocked(now time.Time) {
|
||||
delete(s.tickets, id)
|
||||
}
|
||||
}
|
||||
for id, item := range s.emailPending {
|
||||
if !now.Before(item.ExpiresAt) {
|
||||
delete(s.emailPending, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) issueDecoyChallenge(account, email string) (string, error) {
|
||||
@@ -550,6 +564,11 @@ func (s *Service) InvalidateUser(userID int) {
|
||||
delete(s.tickets, id)
|
||||
}
|
||||
}
|
||||
for id, item := range s.emailPending {
|
||||
if item.UserID == userID {
|
||||
delete(s.emailPending, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) invalidateTicket(ticketID string) {
|
||||
|
||||
Reference in new issue
Block a user