Skip to content

Commit 44b6770

Browse files
authored
fix: 增强认证逻辑安全性 (#169)
1 parent 6c5f66e commit 44b6770

File tree

2 files changed

+13
-10
lines changed

2 files changed

+13
-10
lines changed

internal/handler/handler.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
package handler
33

44
import (
5+
"crypto/subtle"
56
"net/http"
67
"time"
78

@@ -83,15 +84,17 @@ func (s *Server) Login(c *gin.Context) {
8384

8485
authConfig := s.config.GetAuthConfig()
8586

86-
if req.AuthKey == authConfig.Key {
87+
isValid := subtle.ConstantTimeCompare([]byte(req.AuthKey), []byte(authConfig.Key)) == 1
88+
89+
if isValid {
8790
c.JSON(http.StatusOK, LoginResponse{
8891
Success: true,
8992
Message: "Authentication successful",
9093
})
9194
} else {
9295
c.JSON(http.StatusUnauthorized, LoginResponse{
9396
Success: false,
94-
Message: "Invalid authentication key",
97+
Message: "Authentication failed",
9598
})
9699
}
97100
}

internal/middleware/middleware.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
package middleware
33

44
import (
5+
"crypto/subtle"
56
"fmt"
67
"strings"
78
"time"
@@ -126,7 +127,9 @@ func Auth(authConfig types.AuthConfig) gin.HandlerFunc {
126127

127128
key := extractAuthKey(c)
128129

129-
if key == "" || key != authConfig.Key {
130+
isValid := key != "" && subtle.ConstantTimeCompare([]byte(key), []byte(authConfig.Key)) == 1
131+
132+
if !isValid {
130133
response.Error(c, app_errors.ErrUnauthorized)
131134
c.Abort()
132135
return
@@ -154,14 +157,11 @@ func ProxyAuth(gm *services.GroupManager) gin.HandlerFunc {
154157
return
155158
}
156159

157-
// Then check System-wide keys (O(1) lookup)
158-
if _, ok := group.EffectiveConfig.ProxyKeysMap[key]; ok {
159-
c.Next()
160-
return
161-
}
160+
// Check both key collections to prevent timing attacks
161+
_, existsInEffective := group.EffectiveConfig.ProxyKeysMap[key]
162+
_, existsInGroup := group.ProxyKeysMap[key]
162163

163-
// Check Group keys first (O(1) lookup)
164-
if _, ok := group.ProxyKeysMap[key]; ok {
164+
if existsInEffective || existsInGroup {
165165
c.Next()
166166
return
167167
}

0 commit comments

Comments
 (0)