Просмотр исходного кода

fix: make LocalUserLogin take the same time for unknown usernames (#1182)

James Read 1 день назад
Родитель
Сommit
8c9c5f8c77

+ 2 - 15
service/internal/api/api.go

@@ -237,22 +237,9 @@ func (api *oliveTinAPI) applyLocalLoginResult(req *apiv1.LocalUserLoginRequest,
 	}
 }
 
-func (api *oliveTinAPI) localUserLoginEarlyReject(req *connect.Request[apiv1.LocalUserLoginRequest]) *connect.Response[apiv1.LocalUserLoginResponse] {
-	if !api.cfg.AuthLocalUsers.Enabled {
-		return connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: false})
-	}
-
-	if isLocalInteractiveLoginDisabledForUser(api.cfg, req.Msg.Username) {
-		log.WithFields(log.Fields{"username": req.Msg.Username}).Debug("LocalUserLogin: interactive login disabled (no password configured)")
-		return connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: false})
-	}
-
-	return nil
-}
-
 func (api *oliveTinAPI) LocalUserLogin(ctx ctx.Context, req *connect.Request[apiv1.LocalUserLoginRequest]) (*connect.Response[apiv1.LocalUserLoginResponse], error) {
-	if early := api.localUserLoginEarlyReject(req); early != nil {
-		return early, nil
+	if !api.cfg.AuthLocalUsers.Enabled {
+		return connect.NewResponse(&apiv1.LocalUserLoginResponse{Success: false}), nil
 	}
 
 	match, err := checkUserPassword(api.cfg, req.Msg.Username, req.Msg.Password)

+ 35 - 8
service/internal/api/local_user_login.go

@@ -1,8 +1,10 @@
 package api
 
 import (
+	"crypto/rand"
 	"errors"
 	"runtime"
+	"sync"
 
 	config "github.com/OliveTin/OliveTin/internal/config"
 	"github.com/alexedwards/argon2id"
@@ -61,21 +63,46 @@ func comparePasswordAndHash(password, hash string) (bool, error) {
 	return match, nil
 }
 
-func isLocalInteractiveLoginDisabledForUser(cfg *config.Config, username string) bool {
-	user := cfg.FindUserByUsername(username)
-	if user == nil {
-		return false
+// A login for an unknown username, or for a user with no password, still runs
+// one Argon2id comparison against a dummy hash, through the same concurrency
+// limit. Otherwise the response time, and whether the limit is reported as
+// busy, would show which usernames exist.
+// The dummy password is random, so it is not known to anyone, and the result of
+// the comparison is never used.
+var (
+	dummyPassword         string
+	dummyPasswordHash     string
+	dummyPasswordHashErr  error
+	dummyPasswordHashOnce sync.Once
+)
+
+func getDummyPasswordHash() (string, error) {
+	dummyPasswordHashOnce.Do(func() {
+		dummyPassword = rand.Text()
+		dummyPasswordHash, dummyPasswordHashErr = argon2id.CreateHash(dummyPassword, &defaultParams)
+	})
+
+	return dummyPasswordHash, dummyPasswordHashErr
+}
+
+func compareAgainstDummyHash(password string) error {
+	hash, err := getDummyPasswordHash()
+	if err != nil {
+		return err
 	}
 
-	return user.Password == ""
+	_, err = comparePasswordAndHash(password, hash)
+
+	return err
 }
 
 func checkUserPassword(cfg *config.Config, username, password string) (bool, error) {
 	user := cfg.FindUserByUsername(username)
-	if user == nil {
-		log.WithFields(log.Fields{"username": username}).Warn("Failed to check password for user, as username was not found")
-		return false, nil
+	if user == nil || user.Password == "" {
+		log.WithFields(log.Fields{"username": username}).Warn("Failed to check password for user, as the username was not found or has no password")
+		return false, compareAgainstDummyHash(password)
 	}
+
 	return comparePasswordAndLogResult(password, user.Password, username)
 }
 

+ 102 - 0
service/internal/api/local_user_login_enumeration_test.go

@@ -0,0 +1,102 @@
+package api
+
+import (
+	"context"
+	"testing"
+
+	"connectrpc.com/connect"
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	apiv1 "github.com/OliveTin/OliveTin/gen/olivetin/api/v1"
+	apiv1connect "github.com/OliveTin/OliveTin/gen/olivetin/api/v1/apiv1connect"
+	config "github.com/OliveTin/OliveTin/internal/config"
+)
+
+func newEnumerationTestClient(t *testing.T) apiv1connect.OliveTinApiServiceClient {
+	t.Helper()
+
+	hash, err := createHash("correct horse")
+	require.NoError(t, err)
+
+	cfg := config.DefaultConfig()
+	cfg.SetDir(t.TempDir())
+	cfg.AuthLocalUsers.Enabled = true
+	cfg.AuthLocalUsers.Users = []*config.LocalUser{
+		{Username: "alice", Password: hash},
+		{Username: "apikeyonly", ApiKey: "k"},
+	}
+
+	ts, client := getNewTestServerAndClient(cfg)
+	t.Cleanup(ts.Close)
+
+	return client
+}
+
+func loginAttempt(client apiv1connect.OliveTinApiServiceClient, username string, password string) (*connect.Response[apiv1.LocalUserLoginResponse], error) {
+	return client.LocalUserLogin(context.Background(), connect.NewRequest(&apiv1.LocalUserLoginRequest{
+		Username: username,
+		Password: password,
+	}))
+}
+
+func fillArgon2Slots(t *testing.T) {
+	t.Helper()
+
+	for range argon2MaxConcurrent {
+		argon2Sem <- struct{}{}
+	}
+
+	t.Cleanup(func() {
+		for range argon2MaxConcurrent {
+			<-argon2Sem
+		}
+	})
+}
+
+// Not parallel: this test holds every Argon2 slot while it runs.
+func TestLocalUserLoginIsBusyForEveryUsernameWhenArgon2IsBusy(t *testing.T) {
+	client := newEnumerationTestClient(t)
+	_, err := getDummyPasswordHash()
+	require.NoError(t, err)
+
+	fillArgon2Slots(t)
+
+	for _, username := range []string{"alice", "nosuchuser", "apikeyonly"} {
+		_, err := loginAttempt(client, username, "wrong password")
+		require.Error(t, err, username)
+		assert.Equal(t, connect.CodeResourceExhausted, connect.CodeOf(err), "username %q must get the same busy error as every other username", username)
+	}
+}
+
+func TestLocalUserLoginFailsTheSameForUnknownAndPasswordlessUsers(t *testing.T) {
+	client := newEnumerationTestClient(t)
+
+	for _, username := range []string{"alice", "nosuchuser", "apikeyonly"} {
+		resp, err := loginAttempt(client, username, "wrong password")
+		require.NoError(t, err, username)
+		assert.False(t, resp.Msg.GetSuccess(), username)
+		assert.Empty(t, resp.Header().Values("Set-Cookie"), username)
+	}
+}
+
+func TestLocalUserLoginRejectsDummyPasswordForUnknownAndPasswordlessUsers(t *testing.T) {
+	client := newEnumerationTestClient(t)
+	_, err := getDummyPasswordHash()
+	require.NoError(t, err)
+	require.NotEmpty(t, dummyPassword)
+
+	for _, username := range []string{"nosuchuser", "apikeyonly"} {
+		resp, err := loginAttempt(client, username, dummyPassword)
+		require.NoError(t, err, username)
+		assert.False(t, resp.Msg.GetSuccess(), "the dummy password must never log anyone in")
+	}
+}
+
+func TestLocalUserLoginStillAcceptsTheRightPassword(t *testing.T) {
+	client := newEnumerationTestClient(t)
+
+	resp, err := loginAttempt(client, "alice", "correct horse")
+	require.NoError(t, err)
+	assert.True(t, resp.Msg.GetSuccess())
+}