Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[server] Minor enhancements in handling srp failures

Neeraj Gupta0b5f89c7055a
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index ea3805e7ce..a4c627d19b 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -966,6 +966,16 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRep
_ = userAuthRepo.RemoveExpiredOTTs()
})
+ schedule(c, "@every 10m", func() {
+ // Clean up fake SRP sessions older than 1 hour (3600 seconds = 3600000000 microseconds)
+ deleted, err := userAuthRepo.CleanupOldFakeSessions(context.Background(), 3600000000)
+ if err != nil {
+ log.WithError(err).Error("Failed to cleanup old fake SRP sessions")
+ } else if deleted > 0 {
+ log.WithField("count", deleted).Info("Cleaned up old fake SRP sessions")
+ }
+ })
+
schedule(c, "@every 24h", func() {
_ = userAuthRepo.RemoveDeletedTokens(timeUtil.MicrosecondsBeforeDays(30))
_ = castDb.DeleteOldSessions(context.Background(), timeUtil.MicrosecondsBeforeDays(7))
diff --git a/server/ente/srp.go b/server/ente/srp.go
index 6a55dd1e86..e3d0153287 100644
--- a/server/ente/srp.go
+++ b/server/ente/srp.go
@@ -91,6 +91,7 @@ type SRPSessionEntity struct {
SRP_A string
IsVerified bool
AttemptCount int32
+ IsFake bool
}
type SRPAuthEntity struct {
diff --git a/server/migrations/107_add_srp_fake_session_tracking.down.sql b/server/migrations/107_add_srp_fake_session_tracking.down.sql
new file mode 100644
index 0000000000..9de72d47e5
--- /dev/null
+++ b/server/migrations/107_add_srp_fake_session_tracking.down.sql
@@ -0,0 +1,3 @@
+-- Remove the fake session tracking
+DROP INDEX IF EXISTS idx_srp_sessions_fake_created;
+ALTER TABLE srp_sessions DROP COLUMN IF EXISTS is_fake;
\ No newline at end of file
diff --git a/server/migrations/107_add_srp_fake_session_tracking.up.sql b/server/migrations/107_add_srp_fake_session_tracking.up.sql
new file mode 100644
index 0000000000..77aa5e4ef8
--- /dev/null
+++ b/server/migrations/107_add_srp_fake_session_tracking.up.sql
@@ -0,0 +1,8 @@
+-- Add is_fake column to track fake sessions for user enumeration protection
+ALTER TABLE srp_sessions
+ADD COLUMN IF NOT EXISTS is_fake BOOLEAN NOT NULL DEFAULT false;
+
+-- Create an index to help with cleanup of fake sessions
+CREATE INDEX IF NOT EXISTS idx_srp_sessions_fake_created
+ON srp_sessions(is_fake, created_at)
+WHERE is_fake = true;
\ No newline at end of file
diff --git a/server/pkg/controller/user/srp.go b/server/pkg/controller/user/srp.go
index 788d779ac1..1e59de34de 100644
--- a/server/pkg/controller/user/srp.go
+++ b/server/pkg/controller/user/srp.go
@@ -14,6 +14,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
+ mathRand "math/rand"
"net/http"
"strings"
"time"
@@ -121,7 +122,7 @@ func (c *UserController) CreateSrpSession(context *gin.Context, req ente.CreateS
srpAuthEntity, err := c.UserAuthRepo.GetSRPAuthEntityBySRPUserID(context, req.SRPUserID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
- return fCreateSession(req.SRPUserID.String(), req.SRPA)
+ return c.fCreateSession(req.SRPUserID.String(), req.SRPA)
}
return nil, stacktrace.Propagate(err, "failed to get srp auth entity")
}
@@ -152,7 +153,10 @@ func (c *UserController) VerifySRPSession(context *gin.Context, req ente.VerifyS
srpAuthEntity, err := c.UserAuthRepo.GetSRPAuthEntityBySRPUserID(context, req.SRPUserID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
- return nil, stacktrace.Propagate(ente.ErrInvalidPassword, "missing session, return invalid password")
+ // For non-existent users, try to verify against the fake session
+ // This will always fail but maintains consistent timing and error responses
+ _, verifyErr := c.verifySRPSession(context, "fake-verifier", req.SessionID, req.SRPM1)
+ return nil, verifyErr
}
return nil, stacktrace.Propagate(err, "")
}
@@ -235,8 +239,24 @@ func (c *UserController) verifySRPSession(ctx context.Context,
}
srpSession, err := c.UserAuthRepo.GetSrpSessionEntity(ctx, sessionID)
if err != nil {
+ // Session not found - return invalid password to avoid revealing non-existence
+ if errors.Is(err, sql.ErrNoRows) {
+ // Add small delay to simulate processing
+ time.Sleep(time.Duration(10+mathRand.Intn(20)) * time.Millisecond)
+ return nil, stacktrace.Propagate(ente.ErrInvalidPassword, "session not found")
+ }
return nil, stacktrace.Propagate(err, "")
}
+
+ // Handle fake sessions - always fail with invalid password
+ if srpSession.IsFake {
+ // Simulate realistic timing for fake session verification
+ time.Sleep(time.Duration(20+mathRand.Intn(30)) * time.Millisecond)
+ // Increment attempt count for fake sessions too
+ _ = c.UserAuthRepo.IncrementSrpSessionAttemptCount(ctx, sessionID)
+ return nil, stacktrace.Propagate(ente.ErrInvalidPassword, "fake session verification")
+ }
+
if srpSession.IsVerified {
return nil, stacktrace.Propagate(&ente.ApiError{
Code: "SESSION_ALREADY_VERIFIED",
@@ -324,21 +344,50 @@ func fSrpAttributes(email string, hashKey []byte) (*ente.GetSRPAttributesRespons
}, nil
}
-func fCreateSession(srpUserID string, srpA string) (*ente.CreateSRPSessionResponse, error) {
+func (c *UserController) fCreateSession(srpUserID string, srpA string) (*ente.CreateSRPSessionResponse, error) {
srpABytes := convertStringToBytes(srpA)
if len(srpABytes) != 512 {
return nil, ente.NewBadRequestWithMessage("Invalid length for srpA")
}
- time.Sleep(20 * time.Millisecond)
- // generate 512 bytes of random data
+
+ // Simulate realistic timing with variable delay (30-80ms)
+ // This matches the timing variance of real SRP operations
+ baseDelay := 30
+ variableDelay := mathRand.Intn(50)
+ time.Sleep(time.Duration(baseDelay+variableDelay) * time.Millisecond)
+
+ // Generate realistic fake SRP data
+ serverSecret := make([]byte, 64) // Same size as real srp.GenKey()
+ _, err := rand.Read(serverSecret)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to generate server secret")
+ }
+
+ // Generate fake SRP B value (512 bytes like real)
srpBBytes := make([]byte, 512)
- _, err := rand.Read(srpBBytes)
+ _, err = rand.Read(srpBBytes)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to generate srpB bytes")
+ }
+
+ // Parse srpUserID as UUID
+ userUUID, err := uuid.Parse(srpUserID)
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "failed to parse srpUserID")
+ }
+
+ // Store the fake session in the database (adds natural DB timing variance)
+ sessionID, err := c.UserAuthRepo.AddFakeSRPSession(userUUID, convertBytesToString(serverSecret), srpA)
if err != nil {
- return nil, stacktrace.Propagate(err, "failed to generate random bytes")
+ // If storage fails, still return a response to avoid revealing system errors
+ return &ente.CreateSRPSessionResponse{
+ SessionID: uuid.New(),
+ SRPB: convertBytesToString(srpBBytes),
+ }, nil
}
return &ente.CreateSRPSessionResponse{
- SessionID: uuid.New(),
- SRPB: convertBytesToString(srpBBytes[:512]),
+ SessionID: sessionID,
+ SRPB: convertBytesToString(srpBBytes),
}, nil
}
diff --git a/server/pkg/repo/srp.go b/server/pkg/repo/srp.go
index efb7c3bea2..4dbe220460 100644
--- a/server/pkg/repo/srp.go
+++ b/server/pkg/repo/srp.go
@@ -19,6 +19,15 @@ func (repo *UserAuthRepository) AddSRPSession(srpUserID uuid.UUID, serverKey str
return id, stacktrace.Propagate(err, "")
}
+// AddFakeSRPSession inserts a fake SRPSession for user enumeration protection
+func (repo *UserAuthRepository) AddFakeSRPSession(srpUserID uuid.UUID, serverKey string, srpA string) (uuid.UUID, error) {
+ id := uuid.New()
+ _, err := repo.DB.Exec(`
+ INSERT INTO srp_sessions(id, srp_user_id, server_key, srp_a, is_fake)
+ VALUES($1, $2 , $3, $4, true)`, id, srpUserID, serverKey, srpA)
+ return id, stacktrace.Propagate(err, "")
+}
+
func (repo *UserAuthRepository) GetUnverifiedSessionsInLastHour(srpUserID uuid.UUID) (int64, error) {
var count int64
err := repo.DB.QueryRow(`SELECT COUNT(*) FROM srp_sessions WHERE srp_user_id = $1 AND has_verified = false AND created_at > (now_utc_micro_seconds() - (60::BIGINT * 60 * 1000 * 1000))`, srpUserID).Scan(&count)
@@ -153,8 +162,8 @@ func (repo *UserAuthRepository) InsertOrUpdateSRPAuthAndKeyAttr(ctx context.Cont
// GetSrpSessionEntity ...
func (repo *UserAuthRepository) GetSrpSessionEntity(ctx context.Context, sessionID uuid.UUID) (*ente.SRPSessionEntity, error) {
result := ente.SRPSessionEntity{}
- row := repo.DB.QueryRowContext(ctx, `SELECT id, srp_user_id, server_key, srp_a, has_verified, attempt_count FROM srp_sessions WHERE id = $1`, sessionID)
- err := row.Scan(&result.ID, &result.SRPUserID, &result.ServerKey, &result.SRP_A, &result.IsVerified, &result.AttemptCount)
+ row := repo.DB.QueryRowContext(ctx, `SELECT id, srp_user_id, server_key, srp_a, has_verified, attempt_count, COALESCE(is_fake, false) FROM srp_sessions WHERE id = $1`, sessionID)
+ err := row.Scan(&result.ID, &result.SRPUserID, &result.ServerKey, &result.SRP_A, &result.IsVerified, &result.AttemptCount, &result.IsFake)
if err != nil {
return nil, stacktrace.Propagate(err, "")
}
@@ -173,6 +182,24 @@ func (repo *UserAuthRepository) SetSrpSessionVerified(ctx context.Context, sessi
return stacktrace.Propagate(err, "")
}
+// CleanupOldFakeSessions removes fake sessions older than the specified duration
+func (repo *UserAuthRepository) CleanupOldFakeSessions(ctx context.Context, olderThan int64) (int64, error) {
+ // Delete fake sessions older than specified microseconds
+ result, err := repo.DB.ExecContext(ctx, `
+ DELETE FROM srp_sessions
+ WHERE is_fake = true
+ AND created_at < (now_utc_micro_seconds() - $1)`,
+ olderThan)
+ if err != nil {
+ return 0, stacktrace.Propagate(err, "failed to cleanup old fake sessions")
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return 0, stacktrace.Propagate(err, "failed to get rows affected")
+ }
+ return rowsAffected, nil
+}
+
// GetSRPAttributes returns the srp attributes of a user
func (repo *UserAuthRepository) GetSRPAttributes(userID int64) (*ente.GetSRPAttributesResponse, error) {
row := repo.DB.QueryRow(`SELECT srp_user_id, salt, mem_limit, ops_limit, kek_salt, email_mfa FROM srp_auth left join key_attributes on srp_auth.user_id = key_attributes.user_id