Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-25_0_3.adoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
= Concurrent login requests are blocked by default when brute force is enabled

If an attacker launched many login attempts in parallel then the attacker could have more guesses at a password than the brute force protection configuration permits. This was due to the brute force check occurring before the brute force protector has locked the user. To prevent this race the Brute Force Protector now rejects all login attempts that occur while another login is in progress in the same server.

If, for whatever reason, the new feature wants to be disabled there is a startup factory option:

[source,bash]
----
bin/kc.[sh|bat] start --spi-brute-force-protector-default-brute-force-detector-allow-concurrent-requests=true
----
4 changes: 4 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes.adoc
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
[[migration-changes]]
== Migration Changes

=== Migrating to 25.0.3

include::changes-25_0_3.adoc[leveloffset=3]

=== Migrating to 25.0.2

include::changes-25_0_2.adoc[leveloffset=3]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.services.managers;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;

import org.keycloak.common.ClientConnection;
import org.keycloak.models.AbstractKeycloakTransaction;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.models.RealmModel;
import org.keycloak.models.UserModel;
import org.keycloak.sessions.AuthenticationSessionModel;

public class DefaultBlockingBruteForceProtector extends DefaultBruteForceProtector {

// make this configurable?
private static final int DEFAULT_MAX_CONCURRENT_ATTEMPTS = 1000;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private static final String OFF_THREAD_STARTED = "#brute_force_started";

private final Map<String, String> loginAttempts = Collections.synchronizedMap(new LinkedHashMap<>(100, DEFAULT_LOAD_FACTOR) {
@Override
protected boolean removeEldestEntry(Entry<String, String> eldest) {
return loginAttempts.size() > DEFAULT_MAX_CONCURRENT_ATTEMPTS;
}
});

DefaultBlockingBruteForceProtector(KeycloakSessionFactory factory) {
super(factory);
}

@Override
public boolean isPermanentlyLockedOut(KeycloakSession session, RealmModel realm, UserModel user) {
if (super.isPermanentlyLockedOut(session, realm, user)) {
return true;
}

if (!realm.isPermanentLockout()) return false;

return isLoginInProgress(session, user);
}

@Override
public boolean isTemporarilyDisabled(KeycloakSession session, RealmModel realm, UserModel user) {
if (super.isTemporarilyDisabled(session, realm, user)) {
return true;
}

return isLoginInProgress(session, user);
}

private boolean isLoginInProgress(KeycloakSession session, UserModel user) {
AuthenticationSessionModel authSession = session.getContext().getAuthenticationSession();

if (authSession == null) {
// not authenticating as there is no auth session bound to the session
return false;
}

return !tryEnlistBlockingTransactionOrSameThread(session, user);
}

// Return true if this thread successfully enlisted itself or it was already done by the same thread
private boolean tryEnlistBlockingTransactionOrSameThread(KeycloakSession session, UserModel user) {
AtomicBoolean inserted = new AtomicBoolean(false);
String threadInProgress = loginAttempts.computeIfAbsent(user.getId(), k -> {
inserted.set(true);
return getThreadName();
});

// This means that this thread successfully added itself into the map. We can enlist transaction just in that case
if (inserted.get()) {
session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() {
@Override
protected void commitImpl() {
// remove or wait the brute force thread to finish
loginAttempts.computeIfPresent(user.getId(), (k, v) -> v.endsWith(OFF_THREAD_STARTED)? "" : null);
}

@Override
protected void rollbackImpl() {
// remove on rollback
loginAttempts.remove(user.getId());
}
});

return true;
} else {
return isCurrentThread(threadInProgress);
}
}

private boolean isCurrentThread(String name) {
return name.equals(getThreadName()) || name.equals(getThreadName() + OFF_THREAD_STARTED);
}

private String getThreadName() {
return Thread.currentThread().getName();
}

private void enlistRemoval(KeycloakSession session, String userId) {
session.getTransactionManager().enlistAfterCompletion(new AbstractKeycloakTransaction() {
@Override
protected void commitImpl() {
// remove or wait the main thread to finish
loginAttempts.computeIfPresent(userId, (k, v) -> v.isEmpty()? null : v.substring(0, v.length() - OFF_THREAD_STARTED.length()));
}

@Override
protected void rollbackImpl() {
loginAttempts.remove(userId);
}
});
}

@Override
protected void processLogin(RealmModel realm, UserModel user, ClientConnection clientConnection, boolean success) {
// mark the off-thread is started for this request
loginAttempts.computeIfPresent(user.getId(), (k, v) -> v + OFF_THREAD_STARTED);
super.processLogin(realm, user, clientConnection, success);
}

@Override
protected void failure(KeycloakSession session, RealmModel realm, String userId, String remoteAddr, long failureTime) {
// remove the user from concurrent login attemps once it's processed
enlistRemoval(session, userId);
super.failure(session, realm, userId, remoteAddr, failureTime);
}

@Override
protected void success(KeycloakSession session, RealmModel realm, String userId) {
// remove the user from concurrent login attemps once it's processed
enlistRemoval(session, userId);
super.success(session, realm, userId);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -180,10 +180,11 @@ public void successfulLogin(RealmModel realm, UserModel user, ClientConnection c
logger.trace("sent success event");
}

private void processLogin(RealmModel realm, UserModel user, ClientConnection clientConnection, boolean success) {
KeycloakSession session = factory.create();
ExecutorsProvider provider = session.getProvider(ExecutorsProvider.class);
ExecutorService executor = provider.getExecutor("bruteforce");
protected void processLogin(RealmModel realm, UserModel user, ClientConnection clientConnection, boolean success) {
ExecutorService executor = KeycloakModelUtils.runJobInTransactionWithResult(factory, session -> {
ExecutorsProvider provider = session.getProvider(ExecutorsProvider.class);
return provider.getExecutor("bruteforce");
});
executor.execute(() -> KeycloakModelUtils.runJobInTransaction(factory, s -> {
if (success) {
success(s, realm, user.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@

package org.keycloak.services.managers;

import java.util.List;
import org.keycloak.Config;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.provider.ProviderConfigurationBuilder;

/**
* @author <a href="mailto:[email protected]">Bill Burke</a>
Expand All @@ -28,19 +31,22 @@
public class DefaultBruteForceProtectorFactory implements BruteForceProtectorFactory {
DefaultBruteForceProtector protector;

private boolean allowConcurrentRequests;

@Override
public BruteForceProtector create(KeycloakSession session) {
return protector;
}

@Override
public void init(Config.Scope config) {

// this can be a brute force setting?
this.allowConcurrentRequests = config.getBoolean("allowConcurrentRequests", Boolean.FALSE);
}

@Override
public void postInit(KeycloakSessionFactory factory) {
protector = new DefaultBruteForceProtector(factory);
protector = allowConcurrentRequests ? new DefaultBruteForceProtector(factory) : new DefaultBlockingBruteForceProtector(factory);
}

@Override
Expand All @@ -52,4 +58,16 @@ public void close() {
public String getId() {
return "default-brute-force-detector";
}

@Override
public List<ProviderConfigProperty> getConfigMetadata() {
return ProviderConfigurationBuilder.create()
.property()
.name("allowConcurrentRequests")
.type("boolean")
.helpText("If concurrent logins are allowed by the brute force protection.")
.defaultValue(false)
.add()
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public class BruteForceTest extends AbstractTestRealmKeycloakTest {

private int lifespan;

private static final Integer failureFactor= 2;
private static final Integer failureFactor = 2;

@Override
public void configureTestRealm(RealmRepresentation testRealm) {
Expand Down Expand Up @@ -380,13 +380,13 @@ public void testNumberOfFailuresForPermanentlyDisabledUsersWithPasswordGrantType
assertUserNumberOfFailures(user.getId(), failureFactor);

events.clear();
} finally {
realm.setPermanentLockout(false);
testRealm().update(realm);
UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0);
user.setEnabled(true);
updateUser(user);
}
} finally {
realm.setPermanentLockout(false);
testRealm().update(realm);
UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0);
user.setEnabled(true);
updateUser(user);
}
}

@Test
Expand Down Expand Up @@ -416,7 +416,7 @@ public void testFailureResetForTemporaryLockout() throws Exception {
loginInvalidPassword();

//Wait for brute force executor to process the login and then wait for delta time
waitForExecutors(numExecutors+1);
waitForExecutors(numExecutors + 1);
testingClient.testing().setTimeOffset(Collections.singletonMap("offset", String.valueOf(5)));

loginInvalidPassword();
Expand All @@ -438,7 +438,7 @@ public void testNoFailureResetForPermanentLockout() throws Exception {
loginInvalidPassword();

//Wait for brute force executor to process the login and then wait for delta time
waitForExecutors(numExecutors+1);
waitForExecutors(numExecutors + 1);
testingClient.testing().setTimeOffset(Collections.singletonMap("offset", String.valueOf(5)));

loginInvalidPassword();
Expand Down Expand Up @@ -468,10 +468,11 @@ private void waitForExecutors(long numExecutors) {
ExecutorsProvider provider = session.getProvider(ExecutorsProvider.class);
ExecutorService executor = provider.getExecutor("bruteforce");
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
while(!threadPoolExecutor.getQueue().isEmpty()) {
while (!threadPoolExecutor.getQueue().isEmpty()) {
try {
Thread.sleep(1000);
} catch (Exception e) {}
} catch (Exception e) {
}
}
assertEquals(numExecutors, threadPoolExecutor.getCompletedTaskCount());
});
Expand Down Expand Up @@ -753,6 +754,87 @@ public void testResetPassword() throws Exception {
events.clear();
}

@Test
public void testRaceAttackTemporaryLockout() throws Exception {
RealmRepresentation realm = testRealm().toRepresentation();
UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0);
try {
realm.setWaitIncrementSeconds(120);
realm.setQuickLoginCheckMilliSeconds(120000L);
testRealm().update(realm);
clearUserFailures();
clearAllUserFailures();
user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0);
user.setEnabled(true);
testRealm().users().get(user.getId()).update(user);
String totpSecret = totp.generateTOTP("totpSecret");
OAuthClient.AccessTokenResponse response = getTestToken("password", totpSecret);
Assert.assertNotNull(response.getAccessToken());
raceAttack(user);
} finally {
realm.setWaitIncrementSeconds(5);
realm.setQuickLoginCheckMilliSeconds(100L);
testRealm().update(realm);
user.setEnabled(true);
updateUser(user);
}
}

@Test
public void testRaceAttackPermanentLockout() throws Exception {
RealmRepresentation realm = testRealm().toRepresentation();
UserRepresentation user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0);
try {
realm.setPermanentLockout(true);
testRealm().update(realm);
raceAttack(user);
clearUserFailures();
clearAllUserFailures();
user = adminClient.realm("test").users().search("test-user@localhost", 0, 1).get(0);
user.setEnabled(true);
testRealm().users().get(user.getId()).update(user);
String totpSecret = totp.generateTOTP("totpSecret");
OAuthClient.AccessTokenResponse response = getTestToken("password", totpSecret);
Assert.assertNotNull(response.getAccessToken());
} finally {
realm.setPermanentLockout(false);
testRealm().update(realm);
user.setEnabled(true);
updateUser(user);
}
}

private void raceAttack(UserRepresentation user) throws Exception {
int num = 100;
LoginThread[] threads = new LoginThread[num];
for (int i = 0; i < num; ++i) {
threads[i] = new LoginThread();
}
for (int i = 0; i < num; ++i) {
threads[i].start();
}
for (int i = 0; i < num; ++i) {
threads[i].join();
}
int invalidCount = (int) adminClient.realm("test").attackDetection().bruteForceUserStatus(user.getId()).get("numFailures");
assertTrue("Invalid count should be less than or equal 2 but was: " + invalidCount, invalidCount <= 2);
}

public class LoginThread extends Thread {

public void run() {
try {
String totpSecret = totp.generateTOTP("totpSecret");
OAuthClient.AccessTokenResponse response = getTestToken("invalid", totpSecret);
Assert.assertNull(response.getAccessToken());
Assert.assertEquals(response.getError(), "invalid_grant");
Assert.assertEquals(response.getErrorDescription(), "Invalid user credentials");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

public void expectTemporarilyDisabled() {
expectTemporarilyDisabled("test-user@localhost", null, "password");
}
Expand Down