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
11 changes: 11 additions & 0 deletions docs/documentation/upgrading/topics/keycloak/changes-22_0_12.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,14 @@
When a client scope or the full realm are deleted the associated user consents should also be removed. A new index over the table `USER_CONSENT_CLIENT_SCOPE` has been added to increase the performance.

Note that, if the table contains more than 300.000 entries, by default {project_name} skips the creation of the indexes during the automatic schema migration and logs the SQL statements to the console instead. The statements must be run manually in the DB after {project_name}'s startup. Check the link:{upgradingguide_link}[{upgradingguide_name}] for details on how to configure a different limit.

= 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
----
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 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(KeycloakSession session, LoginEvent event) {
// mark the off-thread is started for this request
loginAttempts.computeIfPresent(event.userId, (k, v) -> v + OFF_THREAD_STARTED);
super.processLogin(session, event);
}

@Override
protected void failure(KeycloakSession session, LoginEvent event) {
// remove the user from concurrent login attemps once it's processed
enlistRemoval(session, event.userId);
super.failure(session, event);
}

@Override
protected void success(KeycloakSession session, LoginEvent event) {
// remove the user from concurrent login attemps once it's processed
enlistRemoval(session, event.userId);
super.success(session, event);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -217,12 +217,10 @@ public void run() {
session.getTransactionManager().begin();
try {
for (LoginEvent event : events) {
if (event instanceof FailedLogin) {
failure(session, event);
} else if (event instanceof SuccessfulLogin) {
success(session, event);
} else if (event instanceof ShutdownEvent) {
if (event instanceof ShutdownEvent) {
run = false;
} else {
processLogin(session, event);
}
}
} catch (Exception e) {
Expand Down Expand Up @@ -299,6 +297,14 @@ public void successfulLogin(final RealmModel realm, final UserModel user, final
logger.trace("sent success event");
}

protected void processLogin(KeycloakSession session, LoginEvent event) {
if (event instanceof SuccessfulLogin) {
success(session, event);
} else {
failure(session, event);
}
}

@Override
public boolean isTemporarilyDisabled(KeycloakSession session, RealmModel realm, UserModel user) {
UserLoginFailureModel failure = session.loginFailures().getUserLoginFailure(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,21 +31,23 @@
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);
protector.start();

}

@Override
Expand All @@ -55,4 +60,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 @@ -97,7 +97,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 @@ -377,13 +377,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 @@ -608,6 +608,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() throws Exception {
expectTemporarilyDisabled("test-user@localhost", null, "password");
}
Expand Down