8000 Use an original domain name of Kerberos Principal in UserModel attrib… by mposolda · Pull Request #22819 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
8000
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 @@ -71,6 +71,11 @@ public class KerberosConstants {
public static final String SERVER_PRINCIPAL = "serverPrincipal";
public static final String KEYTAB = "keyTab";
public static final String DEBUG = "debug";
public static final String KERBEROS_PRINCIPAL_ATTRIBUTE = "krbPrincipalAttribute";
public static final String KERBEROS_PRINCIPAL_LDAP_ATTRIBUTE_KRB5_PRINCIPAL_NAME = "krb5PrincipalName"; // Used for instance in ApacheDS
public static final String KERBEROS_PRINCIPAL_LDAP_ATTRIBUTE_KRB_PRINCIPAL_NAME = "krbPrincipalName"; // Used for instance in FreeIPA
public static final String KERBEROS_PRINCIPAL_LDAP_ATTRIBUTE_USER_PRINCIPAL_NAME = "userPrincipalName"; // Used for instance in MSAD

public static final String ALLOW_PASSWORD_AUTHENTICATION = "allowPasswordAuthentication";
public static final String UPDATE_PROFILE_FIRST_LOGIN = "updateProfileFirstLogin";
public static final String USE_KERBEROS_FOR_PASSWORD_AUTHENTICATION = "useKerberosForPasswordAuthentication";
Expand All @@ -97,4 +102,9 @@ public class KerberosConstants {
* to lookup it in his LDAP tree. In this case, LDAP lookup might be performed by other providers in the chain.
*/
public static final String AUTHENTICATED_SPNEGO_CONTEXT = "authenticatedSpnegoContext";

/*
* User attribute for kerberos principal used for users from Kerberos/LDAP providers
*/
public static final String KERBEROS_PRINCIPAL = "KERBEROS_PRINCIPAL";
}
2 changes: 1 addition & 1 deletion docs/documentation/release_notes/topics/22_0_2.adoc
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
= Improvements in LDAP and Kerberos integration

Keycloak now supports multiple LDAP providers in a realm, which support Kerberos integration with the same Kerberos realm. When an LDAP provider is not able to find the user which was authenticated through
Kerberos/SPNEGO, Keycloak ties to fallback to the next LDAP provider.
Kerberos/SPNEGO, Keycloak ties to fallback to the next LDAP provider. Keycloak has also better support for the case when single LDAP provider supports multiple Kerberos realms, which are in trust with each other.
Original file line number Diff line number Diff line change
Expand Up @@ -197,14 +197,17 @@ The cross-realm trust is unidirectional by default. You must add the principal `

** When using an LDAP storage provider with Kerberos support, configure the server principal for realm B, as in this example: `HTTP/mydomain.com@B`. The LDAP server must find the users from realm A if users from realm A are to successfully authenticate to {project_name}, because {project_name} must perform the SPNEGO flow and then find the users.

For example, Kerberos principal user `john@A` must be available in the LDAP under an LDAP DN such as `uid=john,ou=People,dc=example,dc=com`. If you want users from realm A and B to authenticate, ensure that LDAP can find users from both realms A and B.
Finding users is based on the LDAP storage provider option `Kerberos principal attribute`. When this is configured for instance with value like `userPrincipalName`, then
after SPNEGO authentication of user `john@A`, {project_name} will try to lookup LDAP user with attribute `userPrincipalName` equivalent to `john@A`. If `Kerberos principal attribute` is left
empty, then {project_name} will lookup the LDAP user based on the prefix of his kerberos principal with the realm omitted.
For example, Kerberos principal user `john@A` must be available in the LDAP under username `john`, so typically under an LDAP DN such as `uid=john,ou=People,dc=example,dc=com`. If you want users from realm A and B to authenticate, ensure that LDAP can find users from both realms A and B.

** When using a Kerberos user storage provider (typically, Kerberos without LDAP integration), configure the server principal as `HTTP/mydomain.com@B`, and users from Kerberos realms A and B must be able to authenticate.

[WARNING]
====
When using the Kerberos user storage provider, there cannot be conflicting users among Kerberos realms. If conflicting users exist, {project_name} maps them to the same user.
====
Users from multiple Kerberos realms are allowed to authenticate as every user would have attribute `KERBEROS_PRINCIPAL` referring to the kerberos principal used for authentication and this is used
for further lookups of this user. To avoid conflicts when there is user `john` in both kerberos realms `A` and `B`, the username of the {project_name} user might contain the kerberos realm
lowercased. For instance username would be `john@a`. Just in case when realm matches with the configured `Kerberos realm`, the realm suffix might be omitted from the generated username. For
instance username would be `john` for the Kerberos principal `john@A` as long as the `Kerberos realm` is configured on the Kerberos provider is `A`.

==== Troubleshooting

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
import java.util.Map;
import java.util.stream.Stream;

import javax.security.auth.login.LoginException;

/**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/
Expand All @@ -58,7 +60,7 @@ public class KerberosFederationProvider implements UserStorageProvider,
ImportedUserValidation {

private static final Logger logger = Logger.getLogger(KerberosFederationProvider.class);
public static final String KERBEROS_PRINCIPAL = "KERBEROS_PRINCIPAL";
public static final String KERBEROS_PRINCIPAL = KerberosConstants.KERBEROS_PRINCIPAL;

protected KeycloakSession session;
protected UserStorageProviderModel model;
Expand All @@ -74,10 +76,6 @@ public KerberosFederationProvider(KeycloakSession session, UserStorageProviderMo

@Override
public UserModel validate(RealmModel realm, UserModel user) {
if (!isValid(realm, user)) {
return null;
}

if (kerberosConfig.getEditMode() == EditMode.READ_ONLY) {
return new ReadOnlyKerberosUserModelDelegate(user, this);
} else {
Expand All @@ -89,12 +87,12 @@ public UserModel validate(RealmModel realm, UserModel user) {
public UserModel getUserByUsername(RealmModel realm, String username) {
KerberosUsernamePasswordAuthenticator authenticator = factory.createKerberosUsernamePasswordAuthenticator(kerberosConfig);
if (authenticator.isUserAvailable(username)) {
// Case when method was called with username including kerberos realm like john@REALM.ORG . Authenticator already checked that kerberos realm was correct
if (username.contains("@")) {
username = username.split("@")[0];
try {
String kerberosPrincipal = authenticator.getKerberosPrincipal(username);
return findOrCreateAuthenticatedUser(realm, new KerberosPrincipal(kerberosPrincipal));
} catch (LoginException le) {
throw new IllegalStateException("Should not happen", le);
}

return findOrCreateAuthenticatedUser(realm, username);
} else {
return null;
}
Expand Down Expand Up @@ -125,13 +123,6 @@ public void preRemove(RealmModel realm, GroupModel group) {

}

public boolean isValid(RealmModel realm, UserModel local) {
// KerberosUsernamePasswordAuthenticator.isUserAvailable is an overhead, so avoid it for now

String kerberosPrincipal = local.getUsername() + "@" + kerberosConfig.getKerberosRealm();
return kerberosPrincipal.equalsIgnoreCase(local.getFirstAttribute(KERBEROS_PRINCIPAL));
}

@Override
public boolean updateCredential(RealmModel realm, UserModel user, CredentialInput input) {
if (!(input instanceof UserCredentialModel) || !PasswordCredentialModel.TYPE.equals(input.getType())) return false;
Expand Down Expand Up @@ -170,16 +161,16 @@ public boolean isConfiguredFor(RealmModel realm, UserModel user, String credenti
public boolean isValid(RealmModel realm, UserModel user, CredentialInput input) {
if (!(input instanceof UserCredentialModel)) return false;
if (input.getType().equals(PasswordCredentialModel.TYPE) && !((LegacyUserCredentialManager) user.credentialManager()).isConfiguredLocally(PasswordCredentialModel.TYPE)) {
return validPassword(user.getUsername(), input.getChallengeResponse());
return validPassword(user.getFirstAttribute(KERBEROS_PRINCIPAL), input.getChallengeResponse());
} else {
return false; // invalid cred type
}
}

protected boolean validPassword(String username, String password) {
protected boolean validPassword(String kerberosPrincipal, String password) {
if (kerberosConfig.isAllowPasswordAuthentication()) {
KerberosUsernamePasswordAuthenticator authenticator = factory.createKerberosUsernamePasswordAuthenticator(kerberosConfig);
return authenticator.validUser(username, password);
return authenticator.validUser(kerberosPrincipal, password);
} else {
return false;
}
Expand All @@ -192,7 +183,7 @@ public CredentialValidationOutput authenticate(RealmModel realm, CredentialInput
if (credential.getType().equals(UserCredentialModel.KERBEROS)) {
SPNEGOAuthenticator spnegoAuthenticator = (SPNEGOAuthenticator) credential.getNote(KerberosConstants.AUTHENTICATED_SPNEGO_CONTEXT);
if (spnegoAuthenticator != null) {
logger.debugf("SPNEGO authentication already performed by previous provider. Provider '%s' will try to lookup user with principal kerberos principal '%s'", this, spnegoAuthenticator.getAuthenticatedUsername());
logger.debugf("SPNEGO authentication already performed by previous provider. Provider '%s' will try to lookup user with kerberos principal '%s'", this, spnegoAuthenticator.getAuthenticatedKerberosPrincipal());
} else {
String spnegoToken = credential.getChallengeResponse();
spnegoAuthenticator = factory.createSPNEGOAuthenticator(spnegoToken, kerberosConfig);
Expand All @@ -202,8 +193,8 @@ public CredentialValidationOutput authenticate(RealmModel realm, CredentialInput

Map<String, String> state = new HashMap<>();
if (spnegoAuthenticator.isAuthenticated()) {
String username = spnegoAuthenticator.getAuthenticatedUsername();
UserModel user = findOrCreateAuthenticatedUser(realm, username);
KerberosPrincipal kerberosPrincipal = spnegoAuthenticator.getAuthenticatedKerberosPrincipal();
UserModel user = findOrCreateAuthenticatedUser(realm, kerberosPrincipal);
if (user == null) {
// Adding the authenticated SPNEGO, in case that other LDAP/Kerberos providers in the chain are able to lookup user from their LDAP
// This can be the case with more complex setup (like MSAD Forest Trust environment)
Expand Down Expand Up @@ -243,45 +234,49 @@ public void close() {
* Called after successful authentication
*
* @param realm realm
* @param username username without realm prefix
* @param kerberosPrincipal
* @return user if found or successfully created. Null if user with same username already exists, but is not linked to this provider
*/
protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, String username) {
UserModel user = UserStoragePrivateUtil.userLocalStorage(session).getUserByUsername(realm, username);
protected UserModel findOrCreateAuthenticatedUser(RealmModel realm, KerberosPrincipal kerberosPrincipal) {
UserModel user = UserStoragePrivateUtil.userLocalStorage(session).searchForUserByUserAttributeStream(realm, KerberosConstants.KERBEROS_PRINCIPAL, kerberosPrincipal.toString())
.findFirst().orElse(null);

if (user != null) {
user = session.users().getUserById(realm, user.getId()); // make sure we get a cached instance
logger.debug("Kerberos authenticated user " + username + " found in Keycloak storage");
logger.debug("Kerberos authenticated user " + kerberosPrincipal + " found in Keycloak storage");

if (!model.getId().equals(user.getFederationLink())) {
logger.warn("User with username " + username + " already exists, but is not linked to provider [" + model.getName() + "]");
logger.warn("User with username " + kerberosPrincipal + " already exists, but is not linked to provider [" + model.getName() + "]");
return null;
} else {
UserModel proxied = validate(realm, user);
if (proxied != null) {
return proxied;
} else {
logger.warn("User with username " + username + " already exists and is linked to provider [" + model.getName() +
logger.warn("User with username " + kerberosPrincipal.getPrefix() + " already exists and is linked to provider [" + model.getName() +
"] but kerberos principal is not correct. Kerberos principal on user is: " + user.getFirstAttribute(KERBEROS_PRINCIPAL));
logger.warn("Will re-create user");
new UserManager(session).removeUser(realm, user, UserStoragePrivateUtil.userLocalStorage(session));
}
}
}

logger.debug("Kerberos authenticated user " + username + " not in Keycloak storage. Creating him");
return importUserToKeycloak(realm, username);
logger.debug("Kerberos authenticated user " + kerberosPrincipal + " not in Keycloak storage. Creating him");
return importUserToKeycloak(realm, kerberosPrincipal);
}

protected UserModel importUserToKeycloak(RealmModel realm, String username) {
protected UserModel importUserToKeycloak(RealmModel realm, KerberosPrincipal kerberosPrincipal) {
// Just guessing email from kerberos realm
String email = username + "@" + kerberosConfig.getKerberosRealm().toLowerCase();
String email = kerberosPrincipal.getPrefix() + "@" + kerberosPrincipal.getRealm().toLowerCase();
// In case that kerberos realm is same like configured realm, create just username as prefix (EG. "john"). Otherwise for trusted realms, use the full kerberos principal (EG. "john@TRUSTED_REALM.ORG")
String username = (kerberosPrincipal.getRealm().equalsIgnoreCase(kerberosConfig.getKerberosRealm())) ? kerberosPrincipal.getPrefix() : email;

logger.debugf("Creating kerberos user: %s, email: %s to local Keycloak storage", username, email);
logger.debugf("Creating kerberos user %s with username: %s, email: %s to local Keycloak storage", kerberosPrincipal, username, email);
UserModel user = UserStoragePrivateUtil.userLocalSt 10BC8 orage(session).addUser(realm, username);
user.setEnabled(true);
user.setEmail(email);
user.setFederationLink(model.getId());
user.setSingleAttribute(KERBEROS_PRINCIPAL, username + "@" + kerberosConfig.getKerberosRealm());
user.setSingleAttribute(KERBEROS_PRINCIPAL, kerberosPrincipal.toString());

if (kerberosConfig.isUpdateProfileFirstLogin()) {
if (Profile.isFeatureEnabled(Profile.Feature.UPDATE_EMAIL)) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2023 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.federation.kerberos;

/**
* @author <a href="mailto:mposolda@redhat.com">Marek Posolda</a>
*/
public class KerberosPrincipal {

// Full principal name like "john@KEYCLOAK.ORG"
private final String kerberosPrincipal;
private final String prefix; // Something like "john"
private final String realm; // Something like "KEYCLOAK.ORG"
public KerberosPrincipal(String kerberosPrincipal) {
String[] parts = kerberosPrincipal.split("@");
if (parts.length != 2) {
throw new IllegalArgumentException("Kerberos principal '" + kerberosPrincipal + "' not valid");
}
this.prefix = parts[0];
this.realm = parts[1].toUpperCase();
this.kerberosPrincipal = prefix + "@" + realm;
}

public String getKerberosPrincipal() {
return kerberosPrincipal;
}

public String getPrefix() {
return prefix;
}

public String getRealm() {
return realm;
}

@Override
public String toString() {
return this.kerberosPrincipal;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import 10BC8 org.jboss.logging.Logger;
import org.keycloak.common.util.KerberosJdkProvider;
import org.keycloak.federation.kerberos.CommonKerberosConfig;
import org.keycloak.federation.kerberos.KerberosPrincipal;
import org.keycloak.models.ModelException;

import javax.security.auth.Subject;
Expand Down Expand Up @@ -136,7 +137,7 @@ public Subject authenticateSubject(String username, String password) throws Logi
createJaasConfiguration());

loginContext.login();
logger.debug("Principal " + principal + " authenticated succesfully");
logger.debug("Principal " + principal + " authenticated successfully");
return loginContext.getSubject();
}

Expand All @@ -152,20 +153,12 @@ public void logoutSubject() {
}


protected String getKerberosPrincipal(String username) throws LoginException {
public String getKerberosPrincipal(String username) throws LoginException {
if (username.contains("@")) {
String[] tokens = username.split("@");

String kerberosRealm = tokens[1];
if (!kerberosRealm.toUpperCase().equals(config.getKerberosRealm())) {
logger.warn("Invalid kerberos realm. Expected realm: " + config.getKerberosRealm() + ", username: " + username);
throw new LoginException("Client not found");
}

username = tokens[0];
return new KerberosPrincipal(username).toString();
} else {
return username + "@" + config.getKerberosRealm();
}

return username + "@" + config.getKerberosRealm();
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.keycloak.common.util.Base64;
import org.keycloak.common.util.KerberosSerializationUtils;
import org.keycloak.federation.kerberos.CommonKerberosConfig;
import org.keycloak.federation.kerberos.KerberosPrincipal;

import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosTicket;
Expand Down Expand Up @@ -110,12 +111,10 @@ public String getSerializedDelegationCredential() {
}

/**
* @return username to be used in Keycloak. Username is authenticated kerberos principal without realm name
* @return kerberos principal to be used in Keycloak
*/
public String getAuthenticatedUsername() {
String[] tokens = authenticatedKerberosPrincipal.split("@");
String username = tokens[0];
return username;
public KerberosPrincipal getAuthenticatedKerberosPrincipal() {
return new KerberosPrincipal(authenticatedKerberosPrincipal);
}


Expand Down
45E3 Loading
0