Compare commits

..
Author SHA1 Message Date
Stavros 5c2cb08a7a fix: use constant time in user lookups 2026-07-14 15:14:26 +03:00
9 changed files with 76 additions and 85 deletions
+2 -2
View File
@@ -23,7 +23,7 @@ jobs:
REPO: ${{ github.event.repository.name }}
- name: Create release
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
with:
prerelease: true
tag_name: nightly
@@ -476,7 +476,7 @@ jobs:
merge-multiple: true
- name: Release
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
with:
files: binaries/*
tag_name: nightly
+1 -1
View File
@@ -449,6 +449,6 @@ jobs:
merge-multiple: true
- name: Release
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
uses: softprops/action-gh-release@718ea10b132b3b2eba29c1007bb80653f286566b # v3
with:
files: binaries/*
+29 -34
View File
@@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
@@ -344,31 +343,27 @@ func (controller *OIDCController) authorizeComplete(c *gin.Context) {
// Create the authorization code
code := controller.oidc.CreateCode(*authorizeReq, *userContext)
cu, err := url.Parse(authorizeReq.RedirectURI)
queries, err := query.Values(AuthorizeCallback{
Code: code,
State: authorizeReq.State,
})
if err != nil {
controller.authorizeError(c, authorizeErrorParams{
err: err,
reason: "Failed to parse redirect URI",
reasonPublic: "Failed to parse redirect URI",
json: true,
err: err,
reason: "Failed to build query",
reasonPublic: "Failed to build query",
callback: authorizeReq.RedirectURI,
callbackError: "server_error",
state: authorizeReq.State,
json: true,
})
return
}
q := cu.Query()
q.Set("code", code)
if authorizeReq.State != "" {
q.Set("state", authorizeReq.State)
}
cu.RawQuery = q.Encode()
c.JSON(200, gin.H{
"status": 200,
"redirect_uri": cu.String(),
"redirect_uri": fmt.Sprintf("%s?%s", authorizeReq.RedirectURI, queries.Encode()),
})
}
@@ -644,37 +639,37 @@ func (controller *OIDCController) authorizeError(c *gin.Context, params authoriz
controller.log.App.Error().Err(params.err).Str("reason", params.reason).Msg("Authorization error")
if params.callback != "" {
cu, err := url.Parse(params.callback)
errorQueries := CallbackError{
Error: params.callbackError,
}
if params.reasonPublic != "" {
errorQueries.ErrorDescription = params.reasonPublic
}
if params.state != "" {
errorQueries.State = params.state
}
queries, err := query.Values(errorQueries)
if err != nil {
controller.log.App.Error().Err(err).Msg("Failed to parse callback URL")
controller.log.App.Error().Err(err).Msg("Failed to build callback error query")
c.AbortWithStatus(http.StatusInternalServerError)
return
}
q := cu.Query()
q.Set("error", params.callbackError)
if params.reasonPublic != "" {
q.Set("error_description", params.reasonPublic)
}
if params.state != "" {
q.Set("state", params.state)
}
cu.RawQuery = q.Encode()
redirectUrl := fmt.Sprintf("%s?%s", params.callback, queries.Encode())
if params.json {
c.JSON(200, gin.H{
"status": 200,
"redirect_uri": cu.String(),
"redirect_uri": redirectUrl,
})
return
}
c.Redirect(http.StatusFound, cu.String())
c.Redirect(http.StatusFound, redirectUrl)
return
}
+1 -3
View File
@@ -708,7 +708,7 @@ func TestProxyController(t *testing.T) {
Log: log,
})
authService, err := service.NewAuthService(service.AuthServiceInput{
authService := service.NewAuthService(service.AuthServiceInput{
Log: log,
Config: &cfg,
Runtime: &runtime,
@@ -721,8 +721,6 @@ func TestProxyController(t *testing.T) {
PolicyEngine: policyEngine,
})
require.NoError(t, err)
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
router := gin.Default()
+39 -16
View File
@@ -89,22 +89,30 @@ func (controller *UserController) loginHandler(c *gin.Context) {
search, err := controller.auth.SearchUser(req.Username)
if err != nil {
if errors.Is(err, service.ErrUserNotFound) {
controller.auth.DummyPasswordCheck(req.Password)
controller.log.App.Warn().Str("username", req.Username).Msg("User not found during login attempt")
controller.auth.RecordLoginAttempt(req.Username, false)
controller.log.AuditLoginFailure(req.Username, "unknown", c.ClientIP(), "user not found")
c.JSON(401, gin.H{
"status": 401,
"message": "Unauthorized",
})
return
}
controller.log.App.Error().Err(err).Str("username", req.Username).Msg("Error searching for user during login attempt")
c.JSON(500, gin.H{
"status": 500,
"message": "Internal Server Error",
})
controller.constantTime(func() constantTimeRes {
if errors.Is(err, service.ErrUserNotFound) {
controller.log.App.Warn().Str("username", req.Username).Msg("User not found during login attempt")
controller.auth.RecordLoginAttempt(req.Username, false)
controller.log.AuditLoginFailure(req.Username, "unknown", c.ClientIP(), "user not found")
return constantTimeRes{
Code: 401,
Res: gin.H{
"status": 401,
"message": "Unauthorized",
},
}
}
controller.log.App.Error().Err(err).Str("username", req.Username).Msg("Error searching for user during login attempt")
return constantTimeRes{
Code: 500,
Res: gin.H{
"status": 500,
"message": "Internal Server Error",
},
}
}, func(res constantTimeRes) {
c.JSON(res.Code, res.Res)
}, time.Millisecond*45)
return
}
@@ -467,3 +475,18 @@ func (controller *UserController) tailscaleHandler(c *gin.Context) {
"message": "Login successful",
})
}
type constantTimeRes struct {
Code int
Res any
}
func (controller *UserController) constantTime(f func() constantTimeRes, rf func(res constantTimeRes), targetTime time.Duration) {
tStart := time.Now()
res := f()
tEnd := time.Now()
if tEnd.Sub(tStart) < targetTime {
time.Sleep(targetTime - tEnd.Sub(tStart))
}
rf(res)
}
+1 -4
View File
@@ -542,8 +542,7 @@ func TestUserController(t *testing.T) {
Runtime: &runtime,
Ctx: ctx,
})
authService, err := service.NewAuthService(service.AuthServiceInput{
authService := service.NewAuthService(service.AuthServiceInput{
Log: log,
Config: &cfg,
Runtime: &runtime,
@@ -556,8 +555,6 @@ func TestUserController(t *testing.T) {
PolicyEngine: policyEngine,
})
require.NoError(t, err)
beforeEach := func() {
// Clear failed login attempts before each test
authService.ClearLoginAttempts()
@@ -2,7 +2,6 @@ package middleware
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
@@ -245,9 +244,6 @@ func (m *ContextMiddleware) basicAuth(username string, password string) (*model.
search, err := m.auth.SearchUser(username)
if err != nil {
if errors.Is(err, service.ErrUserNotFound) {
m.auth.DummyPasswordCheck(password)
}
return nil, nil, fmt.Errorf("error searching for user: %w", err)
}
@@ -264,8 +264,7 @@ func TestContextMiddleware(t *testing.T) {
Runtime: &runtime,
Ctx: ctx,
})
authService, err := service.NewAuthService(service.AuthServiceInput{
authService := service.NewAuthService(service.AuthServiceInput{
Log: log,
Config: &cfg,
Runtime: &runtime,
@@ -278,8 +277,6 @@ func TestContextMiddleware(t *testing.T) {
PolicyEngine: policyEngine,
})
require.NoError(t, err)
contextMiddleware := NewContextMiddleware(ContextMiddlewareInput{
Log: log,
RuntimeConfig: &runtime,
+2 -17
View File
@@ -69,8 +69,6 @@ type AuthService struct {
tailscale *TailscaleService
policyEngine *PolicyEngine
dummyHash string
lockdown struct {
active bool
until time.Time
@@ -103,7 +101,7 @@ type AuthServiceInput struct {
PolicyEngine *PolicyEngine
}
func NewAuthService(i AuthServiceInput) (*AuthService, error) {
func NewAuthService(i AuthServiceInput) *AuthService {
service := &AuthService{
log: i.Log,
runtime: i.Runtime,
@@ -125,15 +123,6 @@ func NewAuthService(i AuthServiceInput) (*AuthService, error) {
loginCacheSize = service.maxLoginLimits
}
// dummy hash
dummyHash, err := bcrypt.GenerateFromPassword([]byte(utils.GenerateString(8)), bcrypt.DefaultCost)
if err != nil {
return nil, fmt.Errorf("failed to generate dummy hash: %w", err)
}
service.dummyHash = string(dummyHash)
// caches setup
oauthCache := NewCacheStore[OAuthPendingSession](256)
loginCache := NewCacheStore[LoginAttempt](loginCacheSize)
@@ -159,11 +148,7 @@ func NewAuthService(i AuthServiceInput) (*AuthService, error) {
}
}, ding.RingMinor)
return service, nil
}
func (auth *AuthService) DummyPasswordCheck(password string) {
bcrypt.CompareHashAndPassword([]byte(auth.dummyHash), []byte(password))
return service
}
func (auth *AuthService) SearchUser(username string) (*model.UserSearch, error) {