Skip to content
Draft
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
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ public class RealmRepresentation {
protected Integer maxDeltaTimeSeconds;
protected Integer failureFactor;
protected Integer maxSecondaryAuthFailures;
protected List<String> bruteForceProtectedUserProperties;
protected BruteForceLockPolicy bruteForceLockPolicy;
//--- end brute force settings

@Deprecated
Expand Down Expand Up @@ -865,6 +867,22 @@ public void setMaxSecondaryAuthFailures(Integer maxSecondaryAuthFailures) {
this.maxSecondaryAuthFailures = maxSecondaryAuthFailures;
}

public List<String> getBruteForceProtectedUserProperties() {
return bruteForceProtectedUserProperties;
}

public void setBruteForceProtectedUserProperties(List<String> bruteForceProtectedUserProperties) {
this.bruteForceProtectedUserProperties = bruteForceProtectedUserProperties;
}

public BruteForceLockPolicy getBruteForceLockPolicy() {
return bruteForceLockPolicy;
}

public void setBruteForceLockPolicy(BruteForceLockPolicy bruteForceLockPolicy) {
this.bruteForceLockPolicy = bruteForceLockPolicy;
}

public Boolean isEventsEnabled() {
return eventsEnabled;
}
Expand Down Expand Up @@ -1566,4 +1584,13 @@ public Boolean isScimApiEnabled() {
public enum BruteForceStrategy {
LINEAR, MULTIPLE;
}

/**
* Controls which brute-force counters are allowed to disable login.
* {@link #USER} locks only the account that failed. {@link #PROPERTIES} locks
* by the selected user properties only.
*/
public enum BruteForceLockPolicy {
USER, PROPERTIES;
}
}
6 changes: 6 additions & 0 deletions docs/documentation/release_notes/topics/26_8_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ If you are upgrading from a previous release, https://www.keycloak.org/docs/late

= Security and Standards

== Lock brute-force attacks by user properties

Brute-force detection can now maintain counters for selected built-in or custom user properties. Failed logins can increment only the submitted identifier, giving email, phone number, and custom attributes independent attempt budgets. The existing per-user behavior remains the default.

== Impersonation audit improvements

== Verifiable Credential Issuance promoted to preview with credential management and revocation
// https://github.com/keycloak/keycloak/issues/52813

Expand Down
33 changes: 33 additions & 0 deletions docs/documentation/server_admin/topics/threat/brute-force.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,39 @@ To enable this protection:
.Brute force detection
image:images/brute-force.png[]

==== Lock by user properties
By default, brute force detection counts failures per user id and locks only that account (*This user only*). You can also count failures against the identifier the user submitted -- built-in fields such as `username` and `email`, or any custom user profile attribute.

A failed login increments:

* the per-user counter, when the lock policy is *This user only*
* only the selected property whose current value matches the submitted identifier, when the lock policy is *Shared properties only*

*Max login failures* is the threshold for the per-user counter or each identifier counter. Reaching an identifier threshold blocks only that identifier, so a locked email does not prevent login with a phone number or username.

Users that share a property value (for example the same email) share that identifier counter. The existing user unlock action clears all current identifier counters for that user.

*Lock policy* chooses which counters increment:

* *This user only* -- increment the per-user counter. Selected properties are ignored.
* *Shared properties only* -- increment the submitted identifier. The per-user counter is used only if `id` is selected or the list is empty.

[WARNING]
====
Use shared properties only when locking every user with the same value is intended. Include the identifiers users actually type (for example `username` or `email`); a custom attribute is incremented only when the login form submits that value.

Property counters belong to the property value, not to an individual user. Changing a user's property does not delete the counter for the old value, and the user inherits any existing counter for the new value. Select `id` instead when protection must follow the stable user id.
====

Locking by user property does not create separate counters for authentication methods or delivery channels. For example, email OTP and SMS OTP attempts are not counted independently.

To configure this:

. Enable a brute force mode other than *Disabled*.
. Choose a *Lock policy*.
. If the policy is not *This user only*, select one or more property ids in *Lock by user properties*.
. Click *Save*.

==== Lockout permanently
{project_name} disables a user account (blocking log in attempts) until an administrator re-enables it.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@
Breaking changes are identified as those that might require changes for existing users to their configurations or applications.
In minor or patch releases, {project_name} will only introduce breaking changes to fix bugs.

=== Client scope assignment now enforces client scope permissions

The client scope assignment endpoints on a specific client now require the caller to have `manage` permission on client scopes, in addition to the existing `manage` permission on the target client.
The listing endpoints for default and optional client scopes now return an empty list if the caller lacks `view` permission on client scopes.

If you have delegated administrators that assign client scopes using Fine-Grained Admin Permissions, ensure they also have the `manage-clients` realm admin role or a type-level `manage` permission on the Clients resource type.

=== Client secret no longer returned for view-only client permissions
// https://github.com/keycloak/keycloak/issues/49220

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -732,6 +732,13 @@ enableSSL=Enable SSL
general=General
failureFactor=Max login failures
maxSecondaryAuthFailures=Maximum Secondary Authentication Failures
bruteForceProtectedUserProperties=Lock by user properties
bruteForceProtectedUserPropertiesHelp=Select user properties by id (username, email, or any user profile attribute). A failed login increments only the property that matches the submitted identifier. Users that share that property value share that counter. Required when the lock policy is "Shared properties only".
bruteForceProtectedUserPropertiesPlaceholder=Select property ids
bruteForceLockPolicy=Lock policy
bruteForceLockPolicyHelp=Choose whether failures count against the user or against each submitted identifier independently.
bruteForceLockPolicy.USER=This user only
bruteForceLockPolicy.PROPERTIES=Shared properties only
updateClientPoliciesSuccess=The client policies configuration was updated
advancedSettings=Advanced settings
organizationSettings=Organization settings
Expand Down Expand Up @@ -1966,7 +1973,7 @@ always=Always
pkceEnabledHelp=Use PKCE (Proof of Key-code exchange) for IdP Brokering
settings=Settings
webAuthnPolicyUserVerificationRequirement=User verification requirement
failureFactorHelp=Number of failures before wait is triggered.
failureFactorHelp=Number of per-user failures before wait is triggered.
maxSecondaryAuthFailuresHelp=Maximum number of secondary authentication failures before permanent lockout is triggered. Account will be locked even in temporary lockout brute force modes. Value of 0 means the behavior is disabled.
unlinkAccountTitle=Unlink account from {{provider}}?
noNodes=No nodes registered
Expand Down
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
import type RealmRepresentation from "@keycloak/keycloak-admin-client/lib/defs/realmRepresentation";
import type { UserProfileConfig } from "@keycloak/keycloak-admin-client/lib/defs/userProfileMetadata";
import {
HelpItem,
KeycloakSelect,
NumberControl,
SelectVariant,
SelectControl,
useFetch,
} from "@keycloak/keycloak-ui-shared";
import {
ActionGroup,
Button,
FormGroup,
SelectOption,
} from "@patternfly/react-core";
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { FormProvider, useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useAdminClient } from "../../admin-client";
import { FormAccess } from "../../components/form/FormAccess";
import { convertToFormValues } from "../../util";
import { Time } from "./Time";

const BUILT_IN_USER_PROPERTIES = [
"id",
"username",
"email",
"firstName",
"lastName",
];

type BruteForceDetectionProps = {
realm: RealmRepresentation;
save: (realm: RealmRepresentation) => void;
Expand All @@ -29,6 +40,7 @@ export const BruteForceDetection = ({
save,
}: BruteForceDetectionProps) => {
const { t } = useTranslation();
const { adminClient } = useAdminClient();
const form = useForm();
const {
setValue,
Expand All @@ -38,6 +50,22 @@ export const BruteForceDetection = ({

const [isBruteForceModeOpen, setIsBruteForceModeOpen] = useState(false);
const [isBruteForceModeUpdated, setIsBruteForceModeUpdated] = useState(false);
const [userProfile, setUserProfile] = useState<UserProfileConfig>();

useFetch(() => adminClient.users.getProfile(), setUserProfile, []);

const lockPropertyOptions = useMemo(() => {
const names = new Set(BUILT_IN_USER_PROPERTIES);
userProfile?.attributes?.forEach((attribute) => {
if (attribute.name) {
names.add(attribute.name);
}
});
realm.bruteForceProtectedUserProperties?.forEach((property) =>
names.add(property),
);
return [...names];
}, [userProfile, realm.bruteForceProtectedUserProperties]);

enum BruteForceMode {
Disabled = "Disabled",
Expand All @@ -54,13 +82,17 @@ export const BruteForceDetection = ({
];

const bruteForceStrategyTypes = ["MULTIPLE", "LINEAR"];
const bruteForceLockPolicies = ["USER", "PROPERTIES"] as const;

const setupForm = () => {
convertToFormValues(realm, setValue);
setValue("bruteForceLockPolicy", realm.bruteForceLockPolicy ?? "USER");
setIsBruteForceModeUpdated(false);
};
useEffect(setupForm, [realm]);

const lockPolicy = form.watch("bruteForceLockPolicy") ?? "USER";

const bruteForceMode = (() => {
if (!form.getValues("bruteForceProtected")) {
return BruteForceMode.Disabled;
Expand Down Expand Up @@ -152,6 +184,37 @@ export const BruteForceDetection = ({
rules: { required: t("required"), min: 0 },
}}
/>
<SelectControl
name="bruteForceLockPolicy"
label={t("bruteForceLockPolicy")}
labelIcon={t("bruteForceLockPolicyHelp")}
controller={{ defaultValue: "USER" }}
options={bruteForceLockPolicies.map((key) => ({
key,
value: t(`bruteForceLockPolicy.${key}`),
}))}
/>
{lockPolicy !== "USER" && (
<SelectControl
name="bruteForceProtectedUserProperties"
label={t("bruteForceProtectedUserProperties")}
labelIcon={t("bruteForceProtectedUserPropertiesHelp")}
controller={{
defaultValue: [],
rules: { required: t("required") },
}}
variant={SelectVariant.typeaheadMulti}
placeholderText={t(
"bruteForceProtectedUserPropertiesPlaceholder",
)}
chipGroupProps={{
numChips: 3,
expandedText: t("hide"),
collapsedText: t("showRemaining"),
}}
options={lockPropertyOptions}
/>
)}
{bruteForceMode ===
BruteForceMode.PermanentAfterTemporaryLockout && (
<NumberControl
Expand Down
2 changes: 2 additions & 0 deletions js/libs/keycloak-admin-client/src/defs/realmRepresentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ export default interface RealmRepresentation {
browserFlow?: string;
browserSecurityHeaders?: Record<string, any>;
bruteForceProtected?: boolean;
bruteForceProtectedUserProperties?: string[];
bruteForceLockPolicy?: "USER" | "PROPERTIES";
clientAuthenticationFlow?: string;
clientScopeMappings?: Record<string, any>;
// ClientScopeRepresentation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ public void importRealm(RealmRepresentation rep, RealmModel newRealm, Runnable u
if (rep.getMaxDeltaTimeSeconds() != null) newRealm.setMaxDeltaTimeSeconds(checkNonNegativeNumber(rep.getMaxDeltaTimeSeconds(),"Maximum delta time seconds"));
if (rep.getFailureFactor() != null) newRealm.setFailureFactor(checkNonNegativeNumber(rep.getFailureFactor(),"Failure factor"));
if (rep.getMaxSecondaryAuthFailures() != null) newRealm.setMaxSecondaryAuthFailures(checkNonNegativeNumber(rep.getMaxSecondaryAuthFailures(),"Maximum secondary authentication failures"));
if (rep.getBruteForceProtectedUserProperties() != null) newRealm.setBruteForceProtectedUserProperties(rep.getBruteForceProtectedUserProperties());
if (rep.getBruteForceLockPolicy() != null) newRealm.setBruteForceLockPolicy(rep.getBruteForceLockPolicy());
if (rep.isEventsEnabled() != null) newRealm.setEventsEnabled(rep.isEventsEnabled());
if (rep.getEnabledEventTypes() != null)
newRealm.setEnabledEventTypes(new HashSet<>(rep.getEnabledEventTypes()));
Expand Down Expand Up @@ -838,6 +840,8 @@ public void updateRealm(RealmRepresentation rep, RealmModel realm) {
if (rep.getMaxDeltaTimeSeconds() != null) realm.setMaxDeltaTimeSeconds(checkNonNegativeNumber(rep.getMaxDeltaTimeSeconds(),"Maximum delta time seconds"));
if (rep.getFailureFactor() != null) realm.setFailureFactor(checkNonNegativeNumber(rep.getFailureFactor(),"Failure factor"));
if (rep.getMaxSecondaryAuthFailures() != null) realm.setMaxSecondaryAuthFailures(checkNonNegativeNumber(rep.getMaxSecondaryAuthFailures(), "Maximum secondary authentication failures"));
if (rep.getBruteForceProtectedUserProperties() != null) realm.setBruteForceProtectedUserProperties(rep.getBruteForceProtectedUserProperties());
if (rep.getBruteForceLockPolicy() != null) realm.setBruteForceLockPolicy(rep.getBruteForceLockPolicy());
if (rep.isRegistrationAllowed() != null) realm.setRegistrationAllowed(rep.isRegistrationAllowed());
if (rep.isRegistrationEmailAsUsername() != null)
realm.setRegistrationEmailAsUsername(rep.isRegistrationEmailAsUsername());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
import org.keycloak.models.UserModel;
import org.keycloak.models.utils.ModelToRepresentation;
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.services.managers.BruteForceProtector;
import org.keycloak.services.managers.BruteForceUserProperty;
import org.keycloak.services.resources.admin.fgap.AdminPermissionEvaluator;
import org.keycloak.services.resources.admin.fgap.UserPermissionEvaluator;
import org.keycloak.utils.SearchQueryUtils;
Expand Down Expand Up @@ -176,51 +178,48 @@ private Stream<BruteUser> toRepresentation(RealmModel realm, UserPermissionEvalu
return userModels.map(user -> {
UserRepresentation userRep = ModelToRepresentation.toRepresentation(session, user, briefRep);
userRep.setAccess(usersEvaluator.getAccessForListing(user));
return userRep;
}).map(this::getBruteForceStatus);
return getBruteForceStatus(user, userRep);
});
}

private BruteUser getBruteForceStatus(UserRepresentation user) {
BruteUser bruteUser = new BruteUser(user);
private BruteUser getBruteForceStatus(UserModel user, UserRepresentation representation) {
BruteUser bruteUser = new BruteUser(representation);
Map<String, Object> data = new HashMap<>();
data.put("disabled", false);
data.put("numFailures", 0);
data.put("lastFailure", 0);
data.put("lastIPFailure", "n/a");
if (!realm.isBruteForceProtected())
bruteUser.setBruteForceStatus(data);

UserLoginFailureModel model = session.loginFailures().getUserLoginFailure(realm, user.getId());
if (model == null) {
if (!realm.isBruteForceProtected()) {
bruteUser.setBruteForceStatus(data);
return bruteUser;
}

boolean disabled;
disabled = isTemporarilyDisabled(session, realm, user);
if (disabled) {
data.put("disabled", true);
UserLoginFailureModel latestFailure = null;
boolean disabled = session.getProvider(BruteForceProtector.class)
.isPermanentlyLockedOut(session, realm, user)
|| BruteForceUserProperty.isLocked(session, realm, user);
data.put("disabled", disabled);
int currentTime = Time.currentTime();
for (UserLoginFailureModel model : BruteForceUserProperty.getLoginFailures(session, realm, user).toList()) {
data.put("numFailures", Math.max((int) data.get("numFailures"), model.getNumFailures()));
if (latestFailure == null || model.getLastFailure() > latestFailure.getLastFailure()) {
latestFailure = model;
}
if (currentTime < model.getFailedLoginNotBefore()) {
logger.debugv("Current: {0} notBefore: {1}", currentTime, model.getFailedLoginNotBefore());
disabled = true;
}
}

data.put("numFailures", model.getNumFailures());
data.put("lastFailure", model.getLastFailure());
data.put("lastIPFailure", model.getLastIPFailure());
if (latestFailure == null) {
bruteUser.setBruteForceStatus(data);
return bruteUser;
}
data.put("disabled", disabled);
data.put("lastFailure", latestFailure.getLastFailure());
data.put("lastIPFailure", latestFailure.getLastIPFailure());
bruteUser.setBruteForceStatus(data);

return bruteUser;
}

public boolean isTemporarilyDisabled(KeycloakSession session, RealmModel realm, UserRepresentation user) {
UserLoginFailureModel failure = session.loginFailures().getUserLoginFailure(realm, user.getId());
if (failure != null) {
int currTime = (int)(Time.currentTimeMillis() / 1000L);
int failedLoginNotBefore = failure.getFailedLoginNotBefore();
if (currTime < failedLoginNotBefore) {
logger.debugv("Current: {0} notBefore: {1}", currTime, failedLoginNotBefore);
return true;
}
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ public class ModelToRepresentation {
REALM_EXCLUDED_ATTRIBUTES.add("maxDeltaTimeSeconds");
REALM_EXCLUDED_ATTRIBUTES.add("failureFactor");
REALM_EXCLUDED_ATTRIBUTES.add("maxSecondaryAuthFailures");
REALM_EXCLUDED_ATTRIBUTES.add("bruteForceProtectedUserProperties");
REALM_EXCLUDED_ATTRIBUTES.add("bruteForceLockPolicy");
REALM_EXCLUDED_ATTRIBUTES.add("actionTokenGeneratedByAdminLifespan");
REALM_EXCLUDED_ATTRIBUTES.add("actionTokenGeneratedByUserLifespan");
REALM_EXCLUDED_ATTRIBUTES.add("offlineSessionMaxLifespanEnabled");
Expand Down Expand Up @@ -514,6 +516,8 @@ public static RealmRepresentation toRepresentation(KeycloakSession session, Real
rep.setMaxDeltaTimeSeconds(realm.getMaxDeltaTimeSeconds());
rep.setFailureFactor(realm.getFailureFactor());
rep.setMaxSecondaryAuthFailures(realm.getMaxSecondaryAuthFailures());
rep.setBruteForceProtectedUserProperties(realm.getBruteForceProtectedUserProperties());
rep.setBruteForceLockPolicy(realm.getBruteForceLockPolicy());
if (Profile.isFeatureEnabled(Profile.Feature.AUTHORIZATION)) {
rep.setUserManagedAccessAllowed(realm.isUserManagedAccessAllowed());
} else {
Expand Down
Loading
Loading