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

Implement forced password change for LDAP federated user (password policy control) - #15253

Merged
pedroigor merged 4 commits into
keycloak:mainfrom
Nordix:ldap-forced-password-change
Feb 20, 2026
Merged

pedroigor merged 4 commits into
keycloak:mainfrom
Nordix:ldap-forced-password-change

Conversation

@tsaarni
@tsaarni tsaarni commented Nov 1, 2022 •
Copy link
Copy Markdown
Contributor

This change adds limited support for LDAP password policy control. The support is limited to prompting user to update their password when the LDAP server indicates that password must be changed. Previously Keycloak let the user in and ignored the mandatory password reset.

After applying this PR there is new optional setting "Enable LDAP password policy" in LDAP advanced settings. It defaults to false. When set to true the PasswordPolicyRequest control is sent during authentication as part of LDAP bind operation, when it is executed on user's behalf (but not for admin connection). The request is marked with criticality=FALSE which means that the server can ignore it if it does not support the LDAP control. If the server processes the control, it may respond with PasswordPolicyResponse with error code value changeAfterReset which is defined by the specification as following

  • bindResponse.resultCode = success (0), passwordPolicyResponse.error = changeAfterReset (2): The user is binding for the first time after the password administrator set the password. In this scenario, the client SHOULD prompt the user to change his password immediately.

With this the LDAP server indicates that the user must update their password. In this case UPDATE_PASSWORD required action is added for the user to trigger existing update password page. The approach follows similar implementation for MSAD.

Following limitations apply:

  • Federation must be configured with edit mode WRITABLE: federated users can only change their passwords when Keycloak is configured to synchronize attributes back to the LDAP server.
  • Federation must be configured with import users enabled: required user actions can be set only for users that exist in Keycloak database.
  • Keycloak changes user passwords using the LDAP administrator credentials configured in federation settings, rather than the user’s old credentials. In some LDAP servers, if pwdMustChange: TRUE is set and an administrator updates a user’s password, the server will set pwdReset: TRUE for that user, forcing another password change. This can cause an infinite reset loop. In current OpenLDAP versions, this behaviour occurs when the administrator has the manage ACL privilege on the password attribute. To prevent it, grant Keycloak’s LDAP account only the write privilege (not manage).

Forced password change is common use case in many organizations. Examples of LDAP servers that are known to support the Password Policy extension:

  • OpenLDAP
  • 389ds

Other uses of this 8000 control are beyond the scope of this PR. For example, in OpenLDAP, a custom password check module can enforce complexity rules during password changes, but only if the control is included in the password update request.

Fixes #14523

@tsaarni tsaarni changed the title Add limited support for LDAP password policy control Implement forced password change for LDAP federated user (password policy control) Nov 1, 2022
@tsaarni
tsaarni force-pushed the ldap-forced-password-change branch 2 times, most recently from f5584dd to 06c23fe Compare November 2, 2022 16:14
@tsaarni
tsaarni force-pushed the ldap-forced-password-change branch 4 times, most recently from e588628 to fee8b17 Compare November 15, 2022 15:59
@tsaarni
tsaarni commented Nov 16, 2022
Copy link
Copy Markdown
Contributor Author

If I understood correctly, LDAP map storage implementation is still not hooked into authentication, so ppolicy support cannot be copied fully to there at this point.

@tsaarni
tsaarni commented Nov 18, 2022
Copy link
Copy Markdown
Contributor Author

Just a friendly ping: this PR is ready for review! @mposolda would you have time to take a look, or other maintainers?

@tsaarni
tsaarni commented Jan 10, 2023
Copy link
Copy Markdown
Contributor Author

Pinging again. Any comments greatly appreciated!

@tsaarni
tsaarni force-pushed the ldap-forced-password-change branch from 565b90a to 2fc6b4b Compare February 22, 2023 09:40
@tsaarni
tsaarni requested a review from a team February 22, 2023 09:40
@tsaarni
tsaarni requested review from a team as code owners February 22, 2023 09:40
@yu-jianshu
Copy link
Copy Markdown

🚀 🚀 🚀 This PR seems to be very useful and we exactly needs the feature for LDAP to pass the password expiry info to keycloak!
Hope maintainers can review this PR and merge it! 🙇

@tsaarni
tsaarni force-pushed the ldap-forced-password-change branch 2 times, most recently from 68b3150 to bdf043c Compare November 21, 2023 13:15
@ghost ghost added the flaky-test label Nov 21, 2023
@ghost ghost left a comment
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unreported flaky test detected, please review

@ghost
ghost commented Nov 21, 2023
Copy link
Copy Markdown

Unreported flaky test detected

If the below flaky tests below are affected by the changes, please review and update the changes accordingly. Otherwise, a maintainer should report the flaky tests prior to merging the PR.

org.keycloak.testsuite.x509.X509BrowserCRLTest#loginSuccessWithCRLSignedWithIntermediateCA3FromTruststore

Keycloak CI - FIPS IT (non-strict)

java.lang.RuntimeException: Could not create statement
	at org.jboss.arquillian.junit.Arquillian.methodBlock(Arquillian.java:313)
	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
...

Report flaky test

org.keycloak.testsuite.x509.X509BrowserCRLTest#loginFailedWithIntermediateRevocationListFromFile

Keycloak CI - FIPS IT (non-strict)

java.lang.RuntimeException: Could not create statement
	at org.jboss.arquillian.junit.Arquillian.methodBlock(Arquillian.java:313)
	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
...

Report flaky test

org.keycloak.testsuite.x509.X509BrowserCRLTest#loginFailedWithIntermediateRevocationListFromHttp

Keycloak CI - FIPS IT (non-strict)

java.lang.RuntimeException: Could not create statement
	at org.jboss.arquillian.junit.Arquillian.methodBlock(Arquillian.java:313)
	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
...

Report flaky test

org.keycloak.testsuite.x509.X509BrowserCRLTest#loginFailedWithInvalidSignatureCRL

Keycloak CI - FIPS IT (non-strict)

java.lang.RuntimeException: Could not create statement
	at org.jboss.arquillian.junit.Arquillian.methodBlock(Arquillian.java:313)
	at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
...

Report flaky test

@tsaarni
tsaarni commented Nov 22, 2023 •
Copy link
Copy Markdown
Contributor Author

I've updated the PR to catch up the latest changes, including the removal of map-store. Also wanted to say that I'd still be grateful to receive reviews, and happy to implement any requests to help getting the feature included!

@pedroigor pedroigor left a comment
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tsaarni Sorry for the delay. It looks like a great addition.

I would consider adding a (yet another) switch to enable the behavior you are introducing given how sensitive it is to support things across different vendors.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you elaborate why we are removing this line? There is an expectation that this should fail if Start TLS is not possible.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will need to check this again and come back to this

(This was long time ago but I vaguely remember something like this: after adding the LDAP control, it triggered different behavior from Java LDAP implementation and the dummy LDAP search was not required anymore to send StartTLS. Regardless what it was, when we add on/off switch for ppolicy control, this needs to be revisited anyways)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. If this is not breaking starttls, works for me.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've now re-organized the code in a way that startTLS() method is purely for issuing start TLS extended operation and it has no "side effect" of triggering authentication, like the extra LDAP search ldapContext.lookup() did before. For authentication I've added explicit ldapContext.reconnect().

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about removing the lookup, as it was added here #6592 I think for security reasons. I'll check that.

@tsaarni tsaarni Sep 4, 2025 •
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It was originally added for security reasons. Coincidentally, it was something I discovered at the time and even got credited for my only "CVE worthy" finding so far 🎉 Also test cases were added back then to cover this exact scenario and they still are there today. Back in 2019, I worked on this bug together with @mposolda and another person who no longer seems to be involved with Keycloak or work at IBM / Red Hat, so I’ll leave him unmentioned, not to bother him 😀

In the current main, the ldapContext.lookup() call is the very first LDAP operation executed after connecting. Due to the way JDK’s LDAP implementation works, the first operation triggers an LDAP bind to authenticate the connection. The lookup / search is empty, but it is used for its side-effect. The bug back then was that ldapContext.lookup() was wrapped in a try ... catch, which ended up ignoring the exception that authentication depended on. The fix in #6592 was that lookup() was moved outside the try ... catch so that authentication errors would no longer be swallowed inside the startTLS() method.

In this PR, I’ve restructured the code so that startTLS() is strictly responsible for issuing the StartTLS extended operation but not sending LDAP bind yet. For authentication, I’ve added an explicit ldapContext.reconnect() call, which triggers the LDAP bind in a single place regardless of StartTLS being used for the connection or not. The underlying reason for this re-organization was that reconnect() allows adding controls to the LDAP bind, also when StartTLS is used, while lookup() does not allow the same for the "side-effect bind" that it triggers.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A lot of history here, and glad we have people like you helping us during this time :)

Thanks for the details.

@tsaarni
tsaarni commented Apr 26, 2024
Copy link
Copy Markdown
Contributor Author

@tsaarni Sorry for the delay. It looks like a great addition.

I would consider adding a (yet another) switch to enable the behavior you are introducing given how sensitive it is to support things across different vendors.

Great, I will refresh this PR ASAP!

I'll add switch to enable the LDAP control. Would it default to false? Just as comparison, SSSD has it enabled by default (link)

@tsaarni
tsaarni force-pushed the ldap-forced-password-change branch from bdf043c to 3a5a80a Compare June 7, 2024 11:35
@tsaarni
tsaarni requested review from a team as code owners June 7, 2024 11:35
@pedroigor pedroigor left a comment •
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After re-reviewing the PR, I noted that once the user updates the password after required to change password by LDAP, a subsequent attempt to authenticate is still forcing the user to update the password. Is that expected?

I was expecting the user to successfully authenticate after changing the password.
From our side, I think this is the only thing we are catching. Other than that, looks good to us.

I try to avoid additional settings in LDAP as much as possible, but for this one it should be fine. Better make this behavior configurable

If you want, I can send the update I did to the test to cover the scenario after the user resets the password. Basically this:

@Test
    @LDAPPasswordPolicy(mustChange=true)
    public void testForcedPasswordChangeAfterReset() throws Exception {
        // Login with user that has to change password.
        loginPage.open();
        loginPage.login("mustchange", "Password1");

        // Forced password change sends user to update password page.
        passwordUpdatePage.assertCurrent();

        // Repeated login without changing password should still send user to update password page.
        loginPage.open();
        loginPage.login("mustchange", "Password1");
        passwordUpdatePage.assertCurrent();

        passwordUpdatePage.changePassword("changedpassword", "changedpassword");
        appPage.assertCurrent();

        UserRepresentation user = testRealm().users().search("mustchange").get(0);
        testRealm().users().get(user.getId()).logout();
        loginPage.open();
        loginPage.login("mustchange", "changedpassword");
        appPage.assertCurrent();
    }

The last assertion should pass because the user changed the password and is now able to authenticate normally?

@tsaarni
tsaarni commented Feb 6, 2026
Copy link
Copy Markdown
Contributor Author

After re-reviewing the PR, I noted that once the user updates the password after required to change password by LDAP, a subsequent attempt to authenticate is still forcing the user to update the password. Is that expected?

Surely not expected, I will take a look. Thanks for the test case!

@tsaarni
tsaarni commented Feb 6, 2026 •
Copy link
Copy Markdown
Contributor Author

After re-reviewing the PR, I noted that once the user updates the password after required to change password by LDAP, a subsequent attempt to authenticate is still forcing the user to update the password. Is that expected?

Surely not expected, I will take a look. Thanks for the test case!

This issue is caused by the LDAP server. I have successfully tested this scenario with OpenLDAP, but you are correct: it does not work with Apache Directory Server. The test suite uses ApacheDS, which (re)sets the pwdMustChange attribute when a password modification LDAP operation is requested as an administrator instead of the user. See AuthenticationInterceptor.processPasswordPolicydModify() (link)

    if ( policyConfig.isPwdMustChange() )
    {
        if ( modifyContext.getSession().isAnAdministrator() )
        {
            pwdMustChangeAt.add( "TRUE" );
            pwdMustChangeMod = new DefaultModification( REPLACE_ATTRIBUTE, pwdMustChangeAt );
        }
        else
        {
            pwdMustChangeMod = new DefaultModification( REMOVE_ATTRIBUTE, pwdMustChangeAt );
            removePwdReset = true;
        }

Note that only the non-admin branch removes the attribute. As far as I know, Keycloak does not provide an option to modify the password as the user, which would generally be preferable!

Should I try to override how ApacheDS handles password modifications made by an administrator?

EDIT: Added screen recording with OpenLDAP as server
ppolicy-password-change-with-openldap

@tsaarni
tsaarni commented Feb 6, 2026
Copy link
Copy Markdown
Contributor Author

Unrelated to the LDAP server behavior above, I have one change to push:

Previously, I set the required action to the user, which led me to think that user import was a prerequisite for this function, since otherwise the required action could not be persisted. However, after seeing MSAD code again for the same functionality, I learned that required actions can also be set to the session, so no database entry is needed after all.

I made this change last week (here), but I missed removing the import requirement. I'll remove it now.

@tsaarni
tsaarni force-pushed the ldap-forced-password-change branch from ac5d798 to 8df6e67 Compare February 6, 2026 15:42
@pedroigor
pedroigor commented Feb 6, 2026 •
Copy link
Copy Markdown
Contributor

Note that only the non-admin branch removes the attribute. As far as I know, Keycloak does not provide an option to modify the password as the user, which would generally be preferable!

For that, we would need to query the user for the current password when updating the password, right? I'm not sure if we want to introduce such change to the update/reset password flow. I also do not think it is an option to keep passwords in memory during the authentication flow.

I have successfully tested this scenario with OpenLDAP

Does it work in OpenLDAP because of the write vs manage privilege?

Should I try to override how ApacheDS handles password modifications made by an administrator?

That is what is tricky in LDAP ... Different vendors, different behaviors :)

I do not feel comfortable overriding and ignoring the default Apache DS behavior. Would be possible to cover both situations and have our testsuite covering both cases where the server is configured or not, to not force a password update when in a "administrative" context?

We should definitely update docs to make it clear and avoid confusion in case you enter a loop when authenticating.

@pedroigor
Copy link
Copy Markdown
Contributor

I made this change last week (here), but I missed removing the import requirement. I'll remove it now.

Yeah, I noted it when testing. Thanks for highlighting it. However, most of the time, we are going to have an authentication session in place when the user is updating their password. AFAIK, it should always be the case.

I would say that adding a required action to the user is redundant because with this new capability, we are basically delegating to the LDAP server whether or not the password should be updated. The realm administrator does not have any control on it, right?

@tsaarni
tsaarni commented Feb 6, 2026 •
Copy link
Copy Markdown
Contributor Author

Yes, exactly. There would need to be a single password change page where both the current and new passwords are requested.

There would be actually more reasons for doing this at some point: #12943. Some security standards require this approach and the current workaround is not ideal: #24300 (comment). However, this would be a significant change and is out of scope.

LDAP ppolicy spec states:

4.2.6. Password Change after Reset

This policy forces the user to update her password after it has been set for the first time, or has been reset by a password administrator.

This makes sense: if a password administrator resets a user's password, the user must change it at the next login.
Since Keycloak uses admin credentials, every password change is treated as a reset by a password administrator. 🤔

In OpenLDAP, the password administrator is anyone with manage permission for the user's password. From the OpenLDAP ppolicy manual (SLAPO_PPOLICY(5)):

During password update, an identity with manage access to the userPassword attribute is considered a password administrator where relevant to the IETF Password Policy proposal.

We cannot determine whether the admin user Keycloak uses is a password administrator. This behaviour determined by the LDAP server.

I think the best we can do is document that Keycloak uses LDAP admin credentials for password changes, rather than user credentials as most LDAP administrators might expect. If the LDAP server is set to require a password change after an "admin reset," this functionality cannot be enabled in Keycloak, as this would result in a password reset loop. Currently the admin guide's LDAP section does not contain much details about protocol level behaviour.

Regarding setting the required action in session vs user: I can drop setting it to user but that fallback came directly from MSAD implementation (here in #8300). I don't know why it was added and I simply kept it just for "symmetry" with the MSAD implementation.

@pedroigor
Copy link
Copy Markdown
Contributor

Thanks for the additional details, @tsaarni.

There would be actually more reasons for doing this at some point: #12943. Some security standards require this approach and the current workaround is not ideal: #24300 (comment). However, this would be a significant change and is out of scope.

It is out of scope, and I agreethat the workaround is not yet solving the original requirement.

I think the best we can do is document that Keycloak uses LDAP admin credentials for password changes, rather than user credentials as most LDAP administrators might expect. If the LDAP server is set to require a password change after an "admin reset," this functionality cannot be enabled in Keycloak, as this would result in a password reset loop. Currently the admin guide's LDAP section does not contain much details about protocol level behaviour.

Is it possible to know whether or not the LDAP server is set to require a password change after an admin reset so that we can introduce validations when enabling the setting?

If not, I think yes, the best we can do is update the documentation and make very explicit that it depends on the LDAP server and additional configuration.

Other than that, I think we can move forward.

@pedroigor
pedroigor commented Feb 13, 2026 •
Copy link
Copy Markdown
Contributor

In regards to tests, do you think it is possible to have a test for ApacheDS that skip forcing a reset password when resetting the password using an administrator context?

We are not running tests against OpenLDAP in our CI and have this setting covered (even if with a hack to ApacheDS) would be nice.

@tsaarni
tsaarni commented Feb 13, 2026 •
Copy link
Copy Markdown
Contributor Author

Is it possible to know whether or not the LDAP server is set to require a password change after an admin reset so that we can introduce validations when enabling the setting?

No, unfortunately this cannot be determined in advance. The logic for identifying an admin and enforcing a password change after an admin reset is internal to the LDAP server. We will only find out when the user attempts to log in again.

In regards to tests, do you think it is possible to have a test for ApacheDS that skip forcing a reset password when resetting the password using an administrator context?

A workaround is possible, and I have added a commit for this. The password reset test is now run by configuring the federation's bind DN as uid=keycloak-admin,dc=keycloak,dc=org instead of the default ApacheDS admin user uid=admin,ou=system. ApacheDS access control must be disabled so the non-admin DN can perform modifications but as a result, changing a user's password no longer sets pwdReset in ApacheDS (since it is not admin reset anymore) and the modified test case #15253 (review) works.

Would this workaround be acceptable, or is it too much?

@pedroigor
Copy link
Copy Markdown
Contributor

@tsaarni Thanks, it works for me.

I tried to update your branch with an update to the documentation, but I'm lacking access to do so. Does it make sense to add this to the LDAP documentation:

[[_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.

This capability is based on https://datatracker.ietf.org/doc/html/draft-behera-ldap-password-policy-10[Password Policy for LDAP Directories].

This commit contains following changes

1. Refactored StartTLS with LDAP.

Refactor initialization of LDAP context into explicit separate steps:

a. Initialize context with LDAP connection properties only
b. Optionally send StartTLS extended request
c. Send bind

Previously both connection and authentication properties were set together
which triggers implicit authentication in the JDK LDAP and it happened
differently depending if StartTLS was used or not.

This change moves bind into explicit context.reconnect() call, which also
makes is possible in future to send LDAP control messages with bind.
That is not possible with implicit bind.

2. Add limited support for LDAP password policy control

Send password policy control during LDAP bind operation and receive response
according to chapter 9.1 of [1].  When server responds with error
"changeAfterReset" then prompt user to update their password by adding
UPDATE_PASSWORD required action

Following preconditions need to be met:

- edit mode is set writable, so that users can modify their passwords.

3. Implement ASN1 decoding for ppolicy control

[1] https://datatracker.ietf.org/doc/html/draft-behera-ldap-password-policy-11

Signed-off-by: Tero Saarni <tero.saarni@est.tech>
10BC8
Signed-off-by: Tero Saarni <tero.saarni@est.tech>
Signed-off-by: Tero Saarni <tero.saarni@est.tech>
Signed-off-by: Tero Saarni <tero.saarni@est.tech>
@tsaarni
tsaarni force-pushed the ldap-forced-password-change branch from 21adab0 to 138b779 Compare February 20, 2026 09:07
@tsaarni
tsaarni commented Feb 20, 2026 •
Copy link
Copy Markdown
Contributor Author

I tried to update your branch with an update to the documentation, but I'm lacking access to do so. Does it make sense to add this to the LDAP documentation:

Looks perfect, thank you @pedroigor! I included it as you suggested, but added a note label and a link to the corresponding functionality in the MSAD chapter in case people get confused by the similar functions in different LDAP vendors. Hope that is ok!

Here is how it looks:

image

In addition to updating the documentation, I fixed Unexpected end of input error message from the BER parser,
138b779. By coincidence, it did not have any functional impact, but it was incorrect and caused the error to be printed. Sorry for not noticing it earlier!

@pedroigor
pedroigor merged commit 128384c into keycloak:main Feb 20, 2026
83 checks passed
@pedroigor
Copy link
Copy Markdown
Contributor

Thanks, @tsaarni !

@tsaarni
tsaarni commented Feb 20, 2026
Copy link
Copy Markdown
Contributor Author

Thank you @pedroigor!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for enforced password change with LDAP federation

6 participants

0