8000 Implement forced password change for LDAP federated user (password policy control) by tsaarni · Pull Request #15253 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ This mapper grants a specified {project_name} role to each {project_name} user f
Group Mapper::
This mapper maps LDAP groups from a branch of an LDAP tree into groups within {project_name}. This mapper also propagates user-group mappings from LDAP into user-group mappings in {project_name}.

[[_msad_mapper]]
MSAD User Account Mapper::
This mapper is specific to Microsoft Active Directory (MSAD). It can integrate the MSAD user account state into the {project_name} account state, such as enabled account or expired password. This mapper uses the `userAccountControl`, and `pwdLastSet` LDAP attributes, specific to MSAD and are not the LDAP standard. For example, if the value of `pwdLastSet` is `0`, the {project_name} user must update their password. The result is an UPDATE_PASSWORD required action added to the user. If the value of `userAccountControl` is `514` (disabled account), the {project_name} user is disabled.

Expand All @@ -170,6 +171,30 @@ By default, LDAP servers such as MSAD, RHDS, or FreeIPA hash and salt passwords.
WARNING: Always verify that user passwords are properly hashed and not stored as plaintext by inspecting a changed
directory entry using `ldapsearch` and base64 decode the `userPassword` attribute value.

[[_ldap_password_policy]]
==== Enabling password change after reset

You can force users to change their password after an administrator resets their password. This feature is useful for
security reasons because it prevents users from using the temporary password set by the administrator for a long time.

For that, enable the `Enable LDAP password policy` setting so that a `UPDATE_PASSWORD` required action will be added to
the user whenever the LDAP server indicates that the user must update their password.

{project_name} is usually configured to connect to the LDAP server using an administrator account even when users are
updating their password. In this case, some LDAP servers, if not configured properly, will always force a password change
after the user changes their password because the LDAP server will see that the password was changed by an administrator
account and not by the user itself.

When enabling this feature, make sure your LDAP server is configured to not force users to change their password a
second time after the user changes their password. Not doing so might cause a password change loop where the user is
forced to change their password every time they log in.

[NOTE]
====
This capability is based on https://datatracker.ietf.org/doc/html/draft-behera-ldap-password-policy-11[Password Policy for LDAP Directories (IETF draft-behera-ldap-password-policy)].
For Microsoft Active Directory, use the <<_msad_mapper,MSAD User Account Mapper>> instead.
====

[[_ldap_connection_pool]]
==== Configuring the connection pool

Expand Down Expand Up @@ -243,6 +268,3 @@ with your LDAP server.
in your environment. For example if login of some user takes lot of time, you can consider attach his LDAP entry showing count of `member` attributes
of various "group" entries. In this case, it might be useful to add if those group entries are mapped to some Group LDAP mapper (or Role LDAP Mapper)
in {project_name} and so on.



Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,8 @@ public static void testLDAP(TestLdapConnectionRepresentation config, KeycloakSes
// is not needed anymore
try (LDAPContextManager ldapContextManager = LDAPContextManager.create(session, ldapConfig)) {
LdapContext ldapContext = ldapContextManager.getLdapContext();
if (TEST_AUTHENTICATION.equals(config.getAction()) && LDAPConstants.AUTH_TYPE_NONE.equals(config.getAuthType())) {
// reconnect to force an anonymous bind operation
if (TEST_AUTHENTICATION.equals(config.getAction())) {
// Reconnect to force bind operation.
ldapContext.reconnect(null);
}
} catch (Exception ne) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,11 @@ public String getReferral() {
return config.getFirst(LDAPConstants.REFERRAL);
}

public boolean isEnableLdapPasswordPolicy() {
String enableLdapPasswordPolicy = config.getFirst(LDAPConstants.ENABLE_LDAP_PASSWORD_POLICY);
return Boolean.parseBoolean(enableLdapPasswordPolicy);
}

public void addBinaryAttribute(String attrName) {
binaryAttributeNames.add(attrName);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
import org.keycloak.models.utils.ReadOnlyUserModelDelegate;
import org.keycloak.policy.PasswordPolicyManagerProvider;
import org.keycloak.policy.PolicyError;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.storage.DatastoreProvider;
import org.keycloak.storage.ReadOnlyException;
import org.keycloak.storage.StorageId;
Expand All @@ -85,6 +86,7 @@
import org.keycloak.storage.ldap.idm.query.internal.LDAPQuery;
import org.keycloak.storage.ldap.idm.query.internal.LDAPQueryConditionsBuilder;
import org.keycloak.storage.ldap.idm.store.ldap.LDAPIdentityStore;
import org.keycloak.storage.ldap.idm.store.ldap.control.PasswordPolicyPasswordChangeException;
import org.keycloak.storage.ldap.kerberos.LDAPProviderKerberosConfig;
import org.keycloak.storage.ldap.mappers.LDAPMappersComparator;
import org.keycloak.storage.ldap.mappers.LDAPOperationDecorator;
Expand Down Expand Up @@ -822,6 +824,30 @@ public boolean validPassword(RealmModel realm, UserModel user, String password)
try {
ldapIdentityStore.validatePassword(ldapUser, password);
return true;
} catch (PasswordPolicyPasswordChangeException e) {
// LDAP password policy requires a forced password change.
// Check for edit mode writable, so that user can modify LDAP password.
if (editMode != EditMode.WRITABLE) {
logger.debugf("User '%s' in realm '%s' is forced to change password but editMode is not writable. Failing login.", user.getUsername(), realm.getName());
return false;
}
if (user.getRequiredActionsStream()
.noneMatch(action -> Objects.equals(action, UserModel.RequiredAction.UPDATE_PASSWORD.name()))) {
AuthenticationSessionModel authSession = session.getContext().getAuthenticationSession();
if (authSession != null) {
if (authSession.getRequiredActions().stream().noneMatch(action -> Objects.equals(action, UserModel.RequiredAction.UPDATE_PASSWORD.name()))) {
logger.debugf("Adding requiredAction UPDATE_PASSWORD to the authenticationSession of user %s", user.getUsername());
authSession.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
}
} else {
// Just a fallback. It should not happen during normal authentication process
logger.debugf("Adding requiredAction UPDATE_PASSWORD to the user %s", user.getUsername());
user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
}
} else {
logger.tracef("Skip adding required action UPDATE_PASSWORD. It was already set on user '%s' in realm '%s'", user.getUsername(), realm.getName());
}
return true;
} catch (AuthenticationException ae) {
AtomicReference<Boolean> processed = new AtomicReference<>(false);
realm.getComponentsStream(model.getId(), LDAPStorageMapper.class.getName())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,10 @@ private static List<ProviderConfigProperty> getConfigProps(ComponentModel parent
.type(ProviderConfigProperty.BOOLEAN_TYPE)
.defaultValue("false")
.add()
.property().name(LDAPConstants.ENABLE_LDAP_PASSWORD_POLICY)
.type(ProviderConfigProperty.BOOLEAN_TYPE)
.defaultValue("false")
.add()
.build();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* Copyright 2024 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.storage.ldap.idm.store.ldap;

import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;


/**
* A decoder for the ASN.1 BER encoding.
*
* Very limited implementation, only supports what is needed by the current LDAP extension controls.
*/
public class BERDecoder {
// Universal tags.
public static final int TAG_SEQUENCE = 0x30;

// Tag classes.
public static final int TAG_CLASS_CONTEXT_SPECIFIC = 0x80;

// Tag forms.
public static final int TAG_FORM_PRIMITIVE = 0x00;

private ByteBuffer encoded;

public BERDecoder(byte[] encodedValue) {
this.encoded = ByteBuffer.wrap(encodedValue);
}

/**
* Start decoding a sequence.
*/
public void startSequence() throws DecodeException {
try {
byte tag = encoded.get();
if (tag != TAG_SEQUENCE) {
throw new DecodeException("Expected SEQUENCE (" + TAG_SEQUENCE + ") but got " + tag);
}
readLength();
} catch (BufferUnderflowException e) {
throw new DecodeException("Unexpected end of input");
}
}

/**
* Check if the next element matches with the given tag, but do not consume it.
* Returns false if there is no more data.
*/
public boolean isNextTag(int clazz, int form, int tag) {
// Check if there is more data to read (e.g. to allow empty SEQUENCE).
if (!encoded.hasRemaining()) {
return false;
}
encoded.mark();
try {
int expected = clazz | form | tag;
int unsignedTag = encoded.get() & 0xFF;
return unsignedTag == expected;
} finally {
encoded.reset();
}
}

/**
* Skip over the next element.
*/
public void skipElement() throws DecodeException {
try {
encoded.get(); // Consume tag.
int length = readLength();
encoded.position(encoded.position() + length);
} catch (BufferUnderflowException e) {
throw new DecodeException("Unexpected end of input");
}
}

/**
* Drain the value bytes of the next element.
*/
public byte[] drainElementValue() throws DecodeException {
try {
encoded.get(); // Consume tag.
int length = readLength();
byte[] value = new byte[length];
encoded.get(value);
return value;
} catch (BufferUnderflowException e) {
throw new DecodeException("Unexpected end of input");
}
}

private int readLength() throws DecodeException {
int length = encoded.get() & 0xFF;

// Short form.
if ((length & 0x80) == 0) {
return length;
}

// Long form.
int numBytes = length & 0x7F;
if (numBytes > 4) {
throw new DecodeException("Cannot handle more than 4 bytes of length, got " + numBytes + " bytes");
}

length = 0;
for (int i = 0; i < numBytes; i++) {
length = (length << 8) | (encoded.get() & 0xFF);
}

return length;
}

public static final class DecodeException extends IOException {
DecodeException(String message) {
super(message);
}
}

}
Loading
Loading
0