diff --git a/extensions/guacamole-auth-ldap/pom.xml b/extensions/guacamole-auth-ldap/pom.xml index 898deaf9a..2dfa5c75a 100644 --- a/extensions/guacamole-auth-ldap/pom.xml +++ b/extensions/guacamole-auth-ldap/pom.xml @@ -141,11 +141,11 @@ provided - + - com.novell.ldap - jldap - 4.3 + org.apache.directory.api + api-all + 2.0.0.AM2 diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/AuthenticationProviderService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/AuthenticationProviderService.java index 949d1c87d..fd184898f 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/AuthenticationProviderService.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/AuthenticationProviderService.java @@ -21,18 +21,23 @@ package org.apache.guacamole.auth.ldap; import com.google.inject.Inject; import com.google.inject.Provider; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPAttributeSet; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPEntry; -import com.novell.ldap.LDAPException; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.directory.api.ldap.model.entry.Attribute; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.directory.ldap.client.api.LdapConnection; +import org.apache.directory.ldap.client.api.LdapConnectionConfig; +import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.apache.guacamole.GuacamoleException; import org.apache.guacamole.GuacamoleServerException; +import org.apache.guacamole.auth.ldap.conf.ConfigurationService; import org.apache.guacamole.auth.ldap.group.UserGroupService; import org.apache.guacamole.auth.ldap.user.LDAPAuthenticatedUser; import org.apache.guacamole.auth.ldap.user.LDAPUserContext; @@ -113,16 +118,15 @@ public class AuthenticationProviderService { * If required properties are missing, and thus the user DN cannot be * determined. */ - private String getUserBindDN(String username) - throws GuacamoleException { + private Dn getUserBindDN(String username) throws GuacamoleException { // If a search DN is provided, search the LDAP directory for the DN // corresponding to the given username - String searchBindDN = confService.getSearchBindDN(); + Dn searchBindDN = confService.getSearchBindDN(); if (searchBindDN != null) { // Create an LDAP connection using the search account - LDAPConnection searchConnection = ldapService.bindAs( + LdapConnection searchConnection = ldapService.bindAs( searchBindDN, confService.getSearchBindPassword() ); @@ -136,7 +140,7 @@ public class AuthenticationProviderService { try { // Retrieve all DNs associated with the given username - List userDNs = userService.getUserDNs(searchConnection, username); + List userDNs = userService.getUserDNs(searchConnection, username); if (userDNs.isEmpty()) return null; @@ -179,7 +183,7 @@ public class AuthenticationProviderService { * @throws GuacamoleException * If an error occurs while binding to the LDAP server. */ - private LDAPConnection bindAs(Credentials credentials) + private LdapConnection bindAs(Credentials credentials) throws GuacamoleException { // Get username and password from credentials @@ -199,7 +203,7 @@ public class AuthenticationProviderService { } // Determine user DN - String userDN = getUserBindDN(username); + Dn userDN = getUserBindDN(username); if (userDN == null) { logger.debug("Unable to determine DN for user \"{}\".", username); return null; @@ -230,7 +234,7 @@ public class AuthenticationProviderService { throws GuacamoleException { // Attempt bind - LDAPConnection ldapConnection; + LdapConnection ldapConnection; try { ldapConnection = bindAs(credentials); } @@ -246,10 +250,14 @@ public class AuthenticationProviderService { try { + LdapConnectionConfig ldapConnectionConfig = + ((LdapNetworkConnection) ldapConnection).getConfig(); + Dn authDn = new Dn(ldapConnectionConfig.getName()); + // Retrieve group membership of the user that just authenticated Set effectiveGroups = userGroupService.getParentUserGroupIdentifiers(ldapConnection, - ldapConnection.getAuthenticationDN()); + authDn); // Return AuthenticatedUser if bind succeeds LDAPAuthenticatedUser authenticatedUser = authenticatedUserProvider.get(); @@ -257,6 +265,9 @@ public class AuthenticationProviderService { return authenticatedUser; } + catch (LdapInvalidDnException e) { + throw new GuacamoleServerException("Invalid DN trying to bind to server.", e); + } // Always disconnect finally { ldapService.disconnect(ldapConnection); @@ -286,7 +297,7 @@ public class AuthenticationProviderService { * @throws GuacamoleException * If an error occurs retrieving the user DN or the attributes. */ - private Map getAttributeTokens(LDAPConnection ldapConnection, + private Map getAttributeTokens(LdapConnection ldapConnection, String username) throws GuacamoleException { // Get attributes from configuration information @@ -298,29 +309,28 @@ public class AuthenticationProviderService { // Build LDAP query parameters String[] attrArray = attrList.toArray(new String[attrList.size()]); - String userDN = getUserBindDN(username); + Dn userDN = getUserBindDN(username); Map tokens = new HashMap<>(); try { // Get LDAP attributes by querying LDAP - LDAPEntry userEntry = ldapConnection.read(userDN, attrArray); + Entry userEntry = ldapConnection.lookup(userDN, attrArray); if (userEntry == null) return Collections.emptyMap(); - LDAPAttributeSet attrSet = userEntry.getAttributeSet(); - if (attrSet == null) + Collection attributes = userEntry.getAttributes(); + if (attributes == null) return Collections.emptyMap(); // Convert each retrieved attribute into a corresponding token - for (Object attrObj : attrSet) { - LDAPAttribute attr = (LDAPAttribute)attrObj; - tokens.put(TokenName.canonicalize(attr.getName(), - LDAP_ATTRIBUTE_TOKEN_PREFIX), attr.getStringValue()); + for (Attribute attr : attributes) { + tokens.put(TokenName.canonicalize(attr.getId(), + LDAP_ATTRIBUTE_TOKEN_PREFIX), attr.getString()); } } - catch (LDAPException e) { + catch (LdapException e) { throw new GuacamoleServerException("Could not query LDAP user attributes.", e); } @@ -347,7 +357,7 @@ public class AuthenticationProviderService { // Bind using credentials associated with AuthenticatedUser Credentials credentials = authenticatedUser.getCredentials(); - LDAPConnection ldapConnection = bindAs(credentials); + LdapConnection ldapConnection = bindAs(credentials); if (ldapConnection == null) return null; diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/DereferenceAliasesMode.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/DereferenceAliasesMode.java deleted file mode 100644 index 1fd1bea41..000000000 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/DereferenceAliasesMode.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.apache.guacamole.auth.ldap; - -import com.novell.ldap.LDAPSearchConstraints; - -/** - * Data type that handles acceptable values for configuring - * alias dereferencing behavior when querying LDAP servers. - */ -public enum DereferenceAliasesMode { - - /** - * Never dereference aliases. This is the default. - */ - NEVER(LDAPSearchConstraints.DEREF_NEVER), - - /** - * Aliases are dereferenced below the base object, but not to locate - * the base object itself. So, if the base object is itself an alias - * the search will not complete. - */ - SEARCHING(LDAPSearchConstraints.DEREF_SEARCHING), - - /** - * Aliases are only dereferenced to locate the base object, but not - * after that. So, a search against a base object that is an alias will - * find any subordinates of the real object the alias references, but - * further aliases in the search will not be dereferenced. - */ - FINDING(LDAPSearchConstraints.DEREF_FINDING), - - /** - * Aliases will always be dereferenced, both to locate the base object - * and when handling results returned by the search. - */ - ALWAYS(LDAPSearchConstraints.DEREF_ALWAYS); - - /** - * The integer constant as defined in the JLDAP library that - * the LDAPSearchConstraints class uses to define the - * dereferencing behavior during search operations. - */ - public final int DEREF_VALUE; - - /** - * Initializes the dereference aliases object with the integer - * value the setting maps to per the JLDAP implementation. - * - * @param derefValue - * The value associated with this dereference setting - */ - private DereferenceAliasesMode(int derefValue) { - this.DEREF_VALUE = derefValue; - } - -} diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/EscapingService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/EscapingService.java deleted file mode 100644 index 5dce2447e..000000000 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/EscapingService.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.apache.guacamole.auth.ldap; - -/** - * Service for escaping LDAP filters, distinguished names (DN's), etc. - */ -public class EscapingService { - - /** - * Escapes the given string for use within an LDAP search filter. This - * implementation is provided courtesy of OWASP: - * - * https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java - * - * @param filter - * The string to escape such that it has no special meaning within an - * LDAP search filter. - * - * @return - * The escaped string, safe for use within an LDAP search filter. - */ - public String escapeLDAPSearchFilter(String filter) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < filter.length(); i++) { - char curChar = filter.charAt(i); - switch (curChar) { - case '\\': - sb.append("\\5c"); - break; - case '*': - sb.append("\\2a"); - break; - case '(': - sb.append("\\28"); - break; - case ')': - sb.append("\\29"); - break; - case '\u0000': - sb.append("\\00"); - break; - default: - sb.append(curChar); - } - } - return sb.toString(); - } - - /** - * Escapes the given string such that it is safe for use within an LDAP - * distinguished name (DN). This implementation is provided courtesy of - * OWASP: - * - * https://www.owasp.org/index.php/Preventing_LDAP_Injection_in_Java - * - * @param name - * The string to escape such that it has no special meaning within an - * LDAP DN. - * - * @return - * The escaped string, safe for use within an LDAP DN. - */ - public String escapeDN(String name) { - StringBuilder sb = new StringBuilder(); - if ((name.length() > 0) && ((name.charAt(0) == ' ') || (name.charAt(0) == '#'))) { - sb.append('\\'); // add the leading backslash if needed - } - for (int i = 0; i < name.length(); i++) { - char curChar = name.charAt(i); - switch (curChar) { - case '\\': - sb.append("\\\\"); - break; - case ',': - sb.append("\\,"); - break; - case '+': - sb.append("\\+"); - break; - case '"': - sb.append("\\\""); - break; - case '<': - sb.append("\\<"); - break; - case '>': - sb.append("\\>"); - break; - case ';': - sb.append("\\;"); - break; - default: - sb.append(curChar); - } - } - if ((name.length() > 1) && (name.charAt(name.length() - 1) == ' ')) { - sb.insert(sb.length() - 1, '\\'); // add the trailing backslash if needed - } - return sb.toString(); - } - -} diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPAuthenticationProviderModule.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPAuthenticationProviderModule.java index 23decec6d..9cfaadf63 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPAuthenticationProviderModule.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPAuthenticationProviderModule.java @@ -20,6 +20,7 @@ package org.apache.guacamole.auth.ldap; import com.google.inject.AbstractModule; +import org.apache.guacamole.auth.ldap.conf.ConfigurationService; import org.apache.guacamole.auth.ldap.connection.ConnectionService; import org.apache.guacamole.auth.ldap.user.UserService; import org.apache.guacamole.GuacamoleException; @@ -76,7 +77,6 @@ public class LDAPAuthenticationProviderModule extends AbstractModule { // Bind LDAP-specific services bind(ConfigurationService.class); bind(ConnectionService.class); - bind(EscapingService.class); bind(LDAPConnectionService.class); bind(ObjectQueryService.class); bind(UserGroupService.class); diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPConnectionService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPConnectionService.java index 3aaf324c9..a2469c483 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPConnectionService.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/LDAPConnectionService.java @@ -20,14 +20,24 @@ package org.apache.guacamole.auth.ldap; import com.google.inject.Inject; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPConstraints; -import com.novell.ldap.LDAPException; -import com.novell.ldap.LDAPJSSESecureSocketFactory; -import com.novell.ldap.LDAPJSSEStartTLSFactory; -import java.io.UnsupportedEncodingException; +import java.io.IOException; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.filter.ExprNode; +import org.apache.directory.api.ldap.model.message.BindRequest; +import org.apache.directory.api.ldap.model.message.BindRequestImpl; +import org.apache.directory.api.ldap.model.message.SearchRequest; +import org.apache.directory.api.ldap.model.message.SearchRequestImpl; +import org.apache.directory.api.ldap.model.message.SearchScope; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.directory.api.ldap.model.url.LdapUrl; +import org.apache.directory.ldap.client.api.LdapConnection; +import org.apache.directory.ldap.client.api.LdapConnectionConfig; +import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.apache.guacamole.GuacamoleException; +import org.apache.guacamole.GuacamoleServerException; import org.apache.guacamole.GuacamoleUnsupportedException; +import org.apache.guacamole.auth.ldap.conf.ConfigurationService; +import org.apache.guacamole.auth.ldap.conf.EncryptionMethod; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -39,7 +49,7 @@ public class LDAPConnectionService { /** * Logger for this class. */ - private final Logger logger = LoggerFactory.getLogger(LDAPConnectionService.class); + private static final Logger logger = LoggerFactory.getLogger(LDAPConnectionService.class); /** * Service for retrieving LDAP server configuration information. @@ -59,8 +69,11 @@ public class LDAPConnectionService { * If an error occurs while parsing guacamole.properties, or if the * requested encryption method is actually not implemented (a bug). */ - private LDAPConnection createLDAPConnection() throws GuacamoleException { + private LdapNetworkConnection createLDAPConnection() throws GuacamoleException { + String host = confService.getServerHostname(); + int port = confService.getServerPort(); + // Map encryption method to proper connection and socket factory EncryptionMethod encryptionMethod = confService.getEncryptionMethod(); switch (encryptionMethod) { @@ -68,17 +81,17 @@ public class LDAPConnectionService { // Unencrypted LDAP connection case NONE: logger.debug("Connection to LDAP server without encryption."); - return new LDAPConnection(); + return new LdapNetworkConnection(host, port); // LDAP over SSL (LDAPS) case SSL: logger.debug("Connecting to LDAP server using SSL/TLS."); - return new LDAPConnection(new LDAPJSSESecureSocketFactory()); + return new LdapNetworkConnection(host, port, true); // LDAP + STARTTLS case STARTTLS: logger.debug("Connecting to LDAP server using STARTTLS."); - return new LDAPConnection(new LDAPJSSEStartTLSFactory()); + return new LdapNetworkConnection(host, port, false); // The encryption method, though known, is not actually // implemented. If encountered, this would be a bug. @@ -106,47 +119,23 @@ public class LDAPConnectionService { * @throws GuacamoleException * If an error occurs while binding to the LDAP server. */ - public LDAPConnection bindAs(String userDN, String password) + public LdapConnection bindAs(Dn userDN, String password) throws GuacamoleException { - // Obtain appropriately-configured LDAPConnection instance - LDAPConnection ldapConnection = createLDAPConnection(); - - // Configure LDAP connection constraints - LDAPConstraints ldapConstraints = ldapConnection.getConstraints(); - if (ldapConstraints == null) - ldapConstraints = new LDAPConstraints(); - - // Set whether or not we follow referrals - ldapConstraints.setReferralFollowing(confService.getFollowReferrals()); - - // Set referral authentication to use the provided credentials. - if (userDN != null && !userDN.isEmpty()) - ldapConstraints.setReferralHandler(new ReferralAuthHandler(userDN, password)); - - // Set the maximum number of referrals we follow - ldapConstraints.setHopLimit(confService.getMaxReferralHops()); - - // Set timelimit to wait for LDAP operations, converting to ms - ldapConstraints.setTimeLimit(confService.getOperationTimeout() * 1000); - - // Apply the constraints to the connection - ldapConnection.setConstraints(ldapConstraints); + // Obtain appropriately-configured LdapConnection instance + LdapNetworkConnection ldapConnection = createLDAPConnection(); try { // Connect to LDAP server - ldapConnection.connect( - confService.getServerHostname(), - confService.getServerPort() - ); + ldapConnection.connect(); // Explicitly start TLS if requested if (confService.getEncryptionMethod() == EncryptionMethod.STARTTLS) - ldapConnection.startTLS(); + ldapConnection.startTls(); } - catch (LDAPException e) { + catch (LdapException e) { logger.error("Unable to connect to LDAP server: {}", e.getMessage()); logger.debug("Failed to connect to LDAP server.", e); return null; @@ -155,31 +144,16 @@ public class LDAPConnectionService { // Bind using provided credentials try { - byte[] passwordBytes; - try { - - // Convert password into corresponding byte array - if (password != null) - passwordBytes = password.getBytes("UTF-8"); - else - passwordBytes = null; - - } - catch (UnsupportedEncodingException e) { - logger.error("Unexpected lack of support for UTF-8: {}", e.getMessage()); - logger.debug("Support for UTF-8 (as required by Java spec) not found.", e); - disconnect(ldapConnection); - return null; - } - - // Bind as user - ldapConnection.bind(LDAPConnection.LDAP_V3, userDN, passwordBytes); + BindRequest bindRequest = new BindRequestImpl(); + bindRequest.setDn(userDN); + bindRequest.setCredentials(password); + ldapConnection.bind(bindRequest); } // Disconnect if an error occurs during bind - catch (LDAPException e) { - logger.debug("LDAP bind failed.", e); + catch (LdapException e) { + logger.debug("Unable to bind to LDAP server.", e); disconnect(ldapConnection); return null; } @@ -187,6 +161,67 @@ public class LDAPConnectionService { return ldapConnection; } + + /** + * Generate a new LdapConnection object for following a referral + * with the given LdapUrl, and copy the username and password + * from the original connection. + * + * @param referralUrl + * The LDAP URL to follow. + * + * @param ldapConfig + * The connection config to use to retrieve username and + * password. + * + * @param hop + * The current hop number of this referral - once the configured + * limit is reached, this method will throw an exception. + * + * @return + * A LdapConnection object that points at the location + * specified in the referralUrl. + * + * @throws GuacamoleException + * If an error occurs parsing out the LdapUrl object or the + * maximum number of referral hops is reached. + */ + public LdapConnection referralConnection(LdapUrl referralUrl, + LdapConnectionConfig ldapConfig, Integer hop) + throws GuacamoleException { + + if (hop >= confService.getMaxReferralHops()) + throw new GuacamoleServerException("Maximum number of referrals reached."); + + LdapConnectionConfig referralConfig = new LdapConnectionConfig(); + + // Copy bind name and password from original config + referralConfig.setName(ldapConfig.getName()); + referralConfig.setCredentials(ldapConfig.getCredentials()); + + // Look for host - if not there, bail out. + String host = referralUrl.getHost(); + if (host == null || host.isEmpty()) + throw new GuacamoleServerException("Referral URL contains no host."); + + referralConfig.setLdapHost(host); + + // Look for port, or assign a default. + int port = referralUrl.getPort(); + if (port < 1) + referralConfig.setLdapPort(389); + else + referralConfig.setLdapPort(port); + + // Deal with SSL connections + if (referralUrl.getScheme().equals(LdapUrl.LDAPS_SCHEME)) + referralConfig.setUseSsl(true); + else + referralConfig.setUseSsl(false); + + return new LdapNetworkConnection(referralConfig); + + } /** * Disconnects the given LDAP connection, logging any failure to do so @@ -195,19 +230,53 @@ public class LDAPConnectionService { * @param ldapConnection * The LDAP connection to disconnect. */ - public void disconnect(LDAPConnection ldapConnection) { + public void disconnect(LdapConnection ldapConnection) { // Attempt disconnect try { - ldapConnection.disconnect(); + ldapConnection.close(); } // Warn if disconnect unexpectedly fails - catch (LDAPException e) { + catch (IOException e) { logger.warn("Unable to disconnect from LDAP server: {}", e.getMessage()); logger.debug("LDAP disconnect failed.", e); } } + + /** + * Generate a SearchRequest object using the given Base DN and filter + * and retrieving other properties from the LDAP configuration service. + * + * @param baseDn + * The LDAP Base DN at which to search the search. + * + * @param filter + * A string representation of a LDAP filter to use for the search. + * + * @return + * The properly-configured SearchRequest object. + * + * @throws GuacamoleException + * If an error occurs retrieving any of the configuration values. + */ + public SearchRequest getSearchRequest(Dn baseDn, ExprNode filter) + throws GuacamoleException { + + SearchRequest searchRequest = new SearchRequestImpl(); + searchRequest.setBase(baseDn); + searchRequest.setDerefAliases(confService.getDereferenceAliases()); + searchRequest.setScope(SearchScope.SUBTREE); + searchRequest.setFilter(filter); + searchRequest.setSizeLimit(confService.getMaxResults()); + searchRequest.setTimeLimit(confService.getOperationTimeout()); + searchRequest.setTypesOnly(false); + + if (confService.getFollowReferrals()) + searchRequest.followReferrals(); + + return searchRequest; + } } diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ObjectQueryService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ObjectQueryService.java index 2196c2fed..b67bb0a9c 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ObjectQueryService.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ObjectQueryService.java @@ -20,18 +20,32 @@ package org.apache.guacamole.auth.ldap; import com.google.inject.Inject; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPEntry; -import com.novell.ldap.LDAPException; -import com.novell.ldap.LDAPReferralException; -import com.novell.ldap.LDAPSearchResults; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; +import org.apache.directory.api.ldap.model.cursor.CursorException; +import org.apache.directory.api.ldap.model.cursor.SearchCursor; +import org.apache.directory.api.ldap.model.entry.Attribute; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException; +import org.apache.directory.api.ldap.model.filter.AndNode; +import org.apache.directory.api.ldap.model.filter.EqualityNode; +import org.apache.directory.api.ldap.model.filter.ExprNode; +import org.apache.directory.api.ldap.model.filter.OrNode; +import org.apache.directory.api.ldap.model.message.Referral; +import org.apache.directory.api.ldap.model.message.Response; +import org.apache.directory.api.ldap.model.message.SearchRequest; +import org.apache.directory.api.ldap.model.message.SearchResultEntry; +import org.apache.directory.api.ldap.model.message.SearchResultReference; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.directory.api.ldap.model.url.LdapUrl; +import org.apache.directory.ldap.client.api.LdapConnection; +import org.apache.directory.ldap.client.api.LdapConnectionConfig; +import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.apache.guacamole.GuacamoleException; import org.apache.guacamole.GuacamoleServerException; import org.apache.guacamole.net.auth.Identifiable; @@ -50,19 +64,13 @@ public class ObjectQueryService { /** * Logger for this class. */ - private final Logger logger = LoggerFactory.getLogger(ObjectQueryService.class); - + private static final Logger logger = LoggerFactory.getLogger(ObjectQueryService.class); + /** - * Service for escaping parts of LDAP queries. + * Service for connecting to LDAP directory. */ @Inject - private EscapingService escapingService; - - /** - * Service for retrieving LDAP server configuration information. - */ - @Inject - private ConfigurationService confService; + private LDAPConnectionService ldapService; /** * Returns the identifier of the object represented by the given LDAP @@ -86,14 +94,18 @@ public class ObjectQueryService { * The identifier of the object represented by the given LDAP entry, or * null if no attributes declared as containing the identifier of the * object are present on the entry. + * + * @throws LdapInvalidAttributeValueException + * If an error occurs retrieving the value of the identifier attribute. */ - public String getIdentifier(LDAPEntry entry, Collection attributes) { + public String getIdentifier(Entry entry, Collection attributes) + throws LdapInvalidAttributeValueException { // Retrieve the first value of the highest priority identifier attribute for (String identifierAttribute : attributes) { - LDAPAttribute identifier = entry.getAttribute(identifierAttribute); + Attribute identifier = entry.get(identifierAttribute); if (identifier != null) - return identifier.getStringValue(); + return identifier.getString(); } // No identifier attribute is present on the entry @@ -125,42 +137,25 @@ public class ObjectQueryService { * An LDAP query which will search for arbitrary LDAP objects having at * least one of the given attributes set to the specified value. */ - public String generateQuery(String filter, + public ExprNode generateQuery(ExprNode filter, Collection attributes, String attributeValue) { // Build LDAP query for objects having at least one attribute and with // the given search filter - StringBuilder ldapQuery = new StringBuilder(); - ldapQuery.append("(&"); - ldapQuery.append(filter); + AndNode searchFilter = new AndNode(); + searchFilter.addNode(filter); // Include all attributes within OR clause if there are more than one - if (attributes.size() > 1) - ldapQuery.append("(|"); - + OrNode attributeFilter = new OrNode(); + // Add equality comparison for each possible attribute - for (String attribute : attributes) { - ldapQuery.append("("); - ldapQuery.append(escapingService.escapeLDAPSearchFilter(attribute)); + attributes.forEach(attribute -> + attributeFilter.addNode(new EqualityNode(attribute, attributeValue)) + ); - if (attributeValue != null) { - ldapQuery.append("="); - ldapQuery.append(escapingService.escapeLDAPSearchFilter(attributeValue)); - ldapQuery.append(")"); - } - else - ldapQuery.append("=*)"); - - } - - // Close OR clause, if any - if (attributes.size() > 1) - ldapQuery.append(")"); - - // Close overall query (AND clause) - ldapQuery.append(")"); - - return ldapQuery.toString(); + searchFilter.addNode(attributeFilter); + + return searchFilter; } @@ -188,38 +183,42 @@ public class ObjectQueryService { * information required to execute the query cannot be read from * guacamole.properties. */ - public List search(LDAPConnection ldapConnection, - String baseDN, String query) throws GuacamoleException { + public List search(LdapConnection ldapConnection, + Dn baseDN, ExprNode query) throws GuacamoleException { logger.debug("Searching \"{}\" for objects matching \"{}\".", baseDN, query); try { + LdapConnectionConfig ldapConnectionConfig = + ((LdapNetworkConnection) ldapConnection).getConfig(); + // Search within subtree of given base DN - LDAPSearchResults results = ldapConnection.search(baseDN, - LDAPConnection.SCOPE_SUB, query, null, false, - confService.getLDAPSearchConstraints()); + SearchRequest request = ldapService.getSearchRequest(baseDN, + query); + + SearchCursor results = ldapConnection.search(request); // Produce list of all entries in the search result, automatically // following referrals if configured to do so - List entries = new ArrayList<>(results.getCount()); - while (results.hasMore()) { + List entries = new ArrayList<>(); + while (results.next()) { - try { - entries.add(results.next()); + Response response = results.get(); + if (response instanceof SearchResultEntry) { + entries.add(((SearchResultEntry) response).getEntry()); } - - // Warn if referrals cannot be followed - catch (LDAPReferralException e) { - if (confService.getFollowReferrals()) { - logger.error("Could not follow referral: {}", e.getFailedReferral()); - logger.debug("Error encountered trying to follow referral.", e); - throw new GuacamoleServerException("Could not follow LDAP referral.", e); - } - else { - logger.warn("Given a referral, but referrals are disabled. Error was: {}", e.getMessage()); - logger.debug("Got a referral, but configured to not follow them.", e); + else if (response instanceof SearchResultReference && + request.isFollowReferrals()) { + + Referral referral = ((SearchResultReference) response).getReferral(); + int referralHop = 0; + for (String url : referral.getLdapUrls()) { + LdapConnection referralConnection = ldapService.referralConnection( + new LdapUrl(url), ldapConnectionConfig, referralHop++); + entries.addAll(search(referralConnection, baseDN, query)); } + } catch (LDAPException e) { @@ -232,7 +231,7 @@ public class ObjectQueryService { return entries; } - catch (LDAPException | GuacamoleException e) { + catch (CursorException | LdapException e) { throw new GuacamoleServerException("Unable to query list of " + "objects from LDAP directory.", e); } @@ -274,10 +273,10 @@ public class ObjectQueryService { * information required to execute the query cannot be read from * guacamole.properties. */ - public List search(LDAPConnection ldapConnection, String baseDN, - String filter, Collection attributes, String attributeValue) + public List search(LdapConnection ldapConnection, Dn baseDN, + ExprNode filter, Collection attributes, String attributeValue) throws GuacamoleException { - String query = generateQuery(filter, attributes, attributeValue); + ExprNode query = generateQuery(filter, attributes, attributeValue); return search(ldapConnection, baseDN, query); } @@ -302,15 +301,15 @@ public class ObjectQueryService { * {@link Map} under its corresponding identifier. */ public Map - asMap(List entries, Function mapper) { + asMap(List entries, Function mapper) { // Convert each entry to the corresponding Guacamole API object Map objects = new HashMap<>(entries.size()); - for (LDAPEntry entry : entries) { + for (Entry entry : entries) { ObjectType object = mapper.apply(entry); if (object == null) { - logger.debug("Ignoring object \"{}\".", entry.getDN()); + logger.debug("Ignoring object \"{}\".", entry.getDn().toString()); continue; } @@ -320,7 +319,7 @@ public class ObjectQueryService { if (objects.putIfAbsent(identifier, object) != null) logger.warn("Multiple objects ambiguously map to the " + "same identifier (\"{}\"). Ignoring \"{}\" as " - + "a duplicate.", identifier, entry.getDN()); + + "a duplicate.", identifier, entry.getDn().toString()); } diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ReferralAuthHandler.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ReferralAuthHandler.java deleted file mode 100644 index a5e359a66..000000000 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ReferralAuthHandler.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you 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.apache.guacamole.auth.ldap; - -import com.novell.ldap.LDAPAuthHandler; -import com.novell.ldap.LDAPAuthProvider; -import java.io.UnsupportedEncodingException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Class that implements the necessary authentication handling - * for following referrals in LDAP connections. - */ -public class ReferralAuthHandler implements LDAPAuthHandler { - - /** - * Logger for this class. - */ - private final Logger logger = LoggerFactory.getLogger(ReferralAuthHandler.class); - - /** - * The LDAPAuthProvider object that will be set and returned to the referral handler. - */ - private final LDAPAuthProvider ldapAuth; - - /** - * Creates a ReferralAuthHandler object to handle authentication when - * following referrals in a LDAP connection, using the provided dn and - * password. - * - * @param dn - * The distinguished name to use for the referral login. - * - * @param password - * The password to use for the referral login. - */ - public ReferralAuthHandler(String dn, String password) { - byte[] passwordBytes; - try { - - // Convert password into corresponding byte array - if (password != null) - passwordBytes = password.getBytes("UTF-8"); - else - passwordBytes = null; - - } - catch (UnsupportedEncodingException e) { - logger.error("Unexpected lack of support for UTF-8: {}", e.getMessage()); - logger.debug("Support for UTF-8 (as required by Java spec) not found.", e); - throw new UnsupportedOperationException("Unexpected lack of UTF-8 support.", e); - } - ldapAuth = new LDAPAuthProvider(dn, passwordBytes); - } - - @Override - public LDAPAuthProvider getAuthProvider(String host, int port) { - return ldapAuth; - } - -} diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ConfigurationService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/ConfigurationService.java similarity index 88% rename from extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ConfigurationService.java rename to extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/ConfigurationService.java index e8ea0ace5..13e125f1a 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/ConfigurationService.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/ConfigurationService.java @@ -17,27 +17,23 @@ * under the License. */ -package org.apache.guacamole.auth.ldap; +package org.apache.guacamole.auth.ldap.conf; import com.google.inject.Inject; -import com.novell.ldap.LDAPSearchConstraints; import java.util.Collections; import java.util.List; +import org.apache.directory.api.ldap.model.filter.EqualityNode; +import org.apache.directory.api.ldap.model.filter.ExprNode; +import org.apache.directory.api.ldap.model.message.AliasDerefMode; +import org.apache.directory.api.ldap.model.name.Dn; import org.apache.guacamole.GuacamoleException; import org.apache.guacamole.environment.Environment; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * Service for retrieving configuration information regarding the LDAP server. */ public class ConfigurationService { - /** - * Logger for this class. - */ - private final Logger logger = LoggerFactory.getLogger(ConfigurationService.class); - /** * The Guacamole server environment. */ @@ -113,7 +109,7 @@ public class ConfigurationService { * If guacamole.properties cannot be parsed, or if the user base DN * property is not specified. */ - public String getUserBaseDN() throws GuacamoleException { + public Dn getUserBaseDN() throws GuacamoleException { return environment.getRequiredProperty( LDAPGuacamoleProperties.LDAP_USER_BASE_DN ); @@ -132,7 +128,7 @@ public class ConfigurationService { * @throws GuacamoleException * If guacamole.properties cannot be parsed. */ - public String getConfigurationBaseDN() throws GuacamoleException { + public Dn getConfigurationBaseDN() throws GuacamoleException { return environment.getProperty( LDAPGuacamoleProperties.LDAP_CONFIG_BASE_DN ); @@ -168,7 +164,7 @@ public class ConfigurationService { * @throws GuacamoleException * If guacamole.properties cannot be parsed. */ - public String getGroupBaseDN() throws GuacamoleException { + public Dn getGroupBaseDN() throws GuacamoleException { return environment.getProperty( LDAPGuacamoleProperties.LDAP_GROUP_BASE_DN ); @@ -187,7 +183,7 @@ public class ConfigurationService { * @throws GuacamoleException * If guacamole.properties cannot be parsed. */ - public String getSearchBindDN() throws GuacamoleException { + public Dn getSearchBindDN() throws GuacamoleException { return environment.getProperty( LDAPGuacamoleProperties.LDAP_SEARCH_BIND_DN ); @@ -242,7 +238,7 @@ public class ConfigurationService { * @throws GuacamoleException * If guacamole.properties cannot be parsed. */ - private int getMaxResults() throws GuacamoleException { + public int getMaxResults() throws GuacamoleException { return environment.getProperty( LDAPGuacamoleProperties.LDAP_MAX_SEARCH_RESULTS, 1000 @@ -262,10 +258,10 @@ public class ConfigurationService { * @throws GuacamoleException * If guacamole.properties cannot be parsed. */ - private DereferenceAliasesMode getDereferenceAliases() throws GuacamoleException { + public AliasDerefMode getDereferenceAliases() throws GuacamoleException { return environment.getProperty( LDAPGuacamoleProperties.LDAP_DEREFERENCE_ALIASES, - DereferenceAliasesMode.NEVER + AliasDerefMode.NEVER_DEREF_ALIASES ); } @@ -287,27 +283,6 @@ public class ConfigurationService { ); } - /** - * Returns a set of LDAPSearchConstraints to apply globally - * to all LDAP searches. - * - * @return - * A LDAPSearchConstraints object containing constraints - * to be applied to all LDAP search operations. - * - * @throws GuacamoleException - * If guacamole.properties cannot be parsed. - */ - public LDAPSearchConstraints getLDAPSearchConstraints() throws GuacamoleException { - - LDAPSearchConstraints constraints = new LDAPSearchConstraints(); - - constraints.setMaxResults(getMaxResults()); - constraints.setDereference(getDereferenceAliases().DEREF_VALUE); - - return constraints; - } - /** * Returns the maximum number of referral hops to follow. * @@ -338,10 +313,10 @@ public class ConfigurationService { * @throws GuacamoleException * If guacamole.properties cannot be parsed. */ - public String getUserSearchFilter() throws GuacamoleException { + public ExprNode getUserSearchFilter() throws GuacamoleException { return environment.getProperty( LDAPGuacamoleProperties.LDAP_USER_SEARCH_FILTER, - "(objectClass=*)" + new EqualityNode("objectClass","*") ); } diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/DereferenceAliasesProperty.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/DereferenceAliasesProperty.java similarity index 75% rename from extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/DereferenceAliasesProperty.java rename to extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/DereferenceAliasesProperty.java index 60b89c4b6..87a8b7865 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/DereferenceAliasesProperty.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/DereferenceAliasesProperty.java @@ -17,21 +17,22 @@ * under the License. */ -package org.apache.guacamole.auth.ldap; +package org.apache.guacamole.auth.ldap.conf; +import org.apache.directory.api.ldap.model.message.AliasDerefMode; import org.apache.guacamole.GuacamoleException; import org.apache.guacamole.GuacamoleServerException; import org.apache.guacamole.properties.GuacamoleProperty; /** - * A GuacamoleProperty with a value of DereferenceAliases. The possible strings + * A GuacamoleProperty with a value of AliasDerefMode. The possible strings * "never", "searching", "finding", and "always" are mapped to their values as a - * DereferenceAliases enum. Anything else results in a parse error. + * AliasDerefMode object. Anything else results in a parse error. */ -public abstract class DereferenceAliasesProperty implements GuacamoleProperty { +public abstract class DereferenceAliasesProperty implements GuacamoleProperty { @Override - public DereferenceAliasesMode parseValue(String value) throws GuacamoleException { + public AliasDerefMode parseValue(String value) throws GuacamoleException { // No value provided, so return null. if (value == null) @@ -39,19 +40,19 @@ public abstract class DereferenceAliasesProperty implements GuacamoleProperty { + + @Override + public Dn parseValue(String value) throws GuacamoleException { + + if (value == null) + return null; + + try { + return new Dn(value); + } + catch (LdapInvalidDnException e) { + throw new GuacamoleServerException("Invalid DN specified in configuration.", e); + } + + } + +} \ No newline at end of file diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/LdapFilterGuacamoleProperty.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/LdapFilterGuacamoleProperty.java new file mode 100644 index 000000000..d7c2d45d0 --- /dev/null +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/LdapFilterGuacamoleProperty.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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.apache.guacamole.auth.ldap.conf; + +import java.text.ParseException; +import org.apache.directory.api.ldap.model.filter.ExprNode; +import org.apache.directory.api.ldap.model.filter.FilterParser; +import org.apache.guacamole.GuacamoleException; +import org.apache.guacamole.GuacamoleServerException; +import org.apache.guacamole.properties.GuacamoleProperty; + +/** + * A GuacamoleProperty with a value of AliasDerefMode. The possible strings + * "never", "searching", "finding", and "always" are mapped to their values as a + * AliasDerefMode object. Anything else results in a parse error. + */ +public abstract class LdapFilterGuacamoleProperty implements GuacamoleProperty { + + @Override + public ExprNode parseValue(String value) throws GuacamoleException { + + // No value provided, so return null. + if (value == null) + return null; + + try { + return FilterParser.parse(value); + } + catch (ParseException e) { + throw new GuacamoleServerException("Error parsing filter", e); + } + + } + +} diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/StringListProperty.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/StringListProperty.java similarity index 98% rename from extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/StringListProperty.java rename to extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/StringListProperty.java index 908d922f3..f7057e9f6 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/StringListProperty.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/conf/StringListProperty.java @@ -17,7 +17,7 @@ * under the License. */ -package org.apache.guacamole.auth.ldap; +package org.apache.guacamole.auth.ldap.conf; import java.util.Arrays; import java.util.List; diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/connection/ConnectionService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/connection/ConnectionService.java index 2f2b67480..1fce3c6ba 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/connection/ConnectionService.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/connection/ConnectionService.java @@ -20,17 +20,23 @@ package org.apache.guacamole.auth.ldap.connection; import com.google.inject.Inject; -import com.novell.ldap.LDAPAttribute; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPEntry; -import com.novell.ldap.LDAPException; import java.util.Collections; -import java.util.Enumeration; import java.util.List; import java.util.Map; +import org.apache.directory.api.ldap.model.entry.Attribute; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException; +import org.apache.directory.api.ldap.model.filter.AndNode; +import org.apache.directory.api.ldap.model.filter.EqualityNode; +import org.apache.directory.api.ldap.model.filter.ExprNode; +import org.apache.directory.api.ldap.model.filter.OrNode; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.directory.ldap.client.api.LdapConnection; +import org.apache.directory.ldap.client.api.LdapConnectionConfig; +import org.apache.directory.ldap.client.api.LdapNetworkConnection; import org.apache.guacamole.auth.ldap.LDAPAuthenticationProvider; -import org.apache.guacamole.auth.ldap.ConfigurationService; -import org.apache.guacamole.auth.ldap.EscapingService; +import org.apache.guacamole.auth.ldap.conf.ConfigurationService; import org.apache.guacamole.GuacamoleException; import org.apache.guacamole.GuacamoleServerException; import org.apache.guacamole.auth.ldap.ObjectQueryService; @@ -53,13 +59,7 @@ public class ConnectionService { /** * Logger for this class. */ - private final Logger logger = LoggerFactory.getLogger(ConnectionService.class); - - /** - * Service for escaping parts of LDAP queries. - */ - @Inject - private EscapingService escapingService; + private static final Logger logger = LoggerFactory.getLogger(ConnectionService.class); /** * Service for retrieving LDAP server configuration information. @@ -100,65 +100,88 @@ public class ConnectionService { * If an error occurs preventing retrieval of connections. */ public Map getConnections(AuthenticatedUser user, - LDAPConnection ldapConnection) throws GuacamoleException { + LdapConnection ldapConnection) throws GuacamoleException { // Do not return any connections if base DN is not specified - String configurationBaseDN = confService.getConfigurationBaseDN(); + Dn configurationBaseDN = confService.getConfigurationBaseDN(); if (configurationBaseDN == null) return Collections.emptyMap(); try { // Pull the current user DN from the LDAP connection - String userDN = ldapConnection.getAuthenticationDN(); + LdapConnectionConfig ldapConnectionConfig = + ((LdapNetworkConnection) ldapConnection).getConfig(); + Dn userDN = new Dn(ldapConnectionConfig.getName()); // getConnections() will only be called after a connection has been // authenticated (via non-anonymous bind), thus userDN cannot // possibly be null - assert(userDN != null); + assert (userDN != null); // Get the search filter for finding connections accessible by the // current user - String connectionSearchFilter = getConnectionSearchFilter(userDN, ldapConnection); + ExprNode connectionSearchFilter = getConnectionSearchFilter(userDN, ldapConnection); // Find all Guacamole connections for the given user by // looking for direct membership in the guacConfigGroup // and possibly any groups the user is a member of that are // referred to in the seeAlso attribute of the guacConfigGroup. - List results = queryService.search(ldapConnection, configurationBaseDN, connectionSearchFilter); + List results = queryService.search(ldapConnection, configurationBaseDN, connectionSearchFilter); // Return a map of all readable connections return queryService.asMap(results, (entry) -> { // Get common name (CN) - LDAPAttribute cn = entry.getAttribute("cn"); + Attribute cn = entry.get("cn"); + String cnName; + if (cn == null) { logger.warn("guacConfigGroup is missing a cn."); return null; } + + try { + cnName = cn.getString(); + } + catch (LdapInvalidAttributeValueException e) { + logger.error("Invalid value for CN attribute.", e.getMessage()); + return null; + } // Get associated protocol - LDAPAttribute protocol = entry.getAttribute("guacConfigProtocol"); + Attribute protocol = entry.get("guacConfigProtocol"); if (protocol == null) { logger.warn("guacConfigGroup \"{}\" is missing the " + "required \"guacConfigProtocol\" attribute.", - cn.getStringValue()); + cnName); return null; } // Set protocol GuacamoleConfiguration config = new GuacamoleConfiguration(); - config.setProtocol(protocol.getStringValue()); + try { + config.setProtocol(protocol.getString()); + } + catch (LdapInvalidAttributeValueException e) { + logger.error("Invalid value of the protocol entry.", e.getMessage()); + return null; + } // Get parameters, if any - LDAPAttribute parameterAttribute = entry.getAttribute("guacConfigParameter"); + Attribute parameterAttribute = entry.get("guacConfigParameter"); if (parameterAttribute != null) { // For each parameter - Enumeration parameters = parameterAttribute.getStringValues(); - while (parameters.hasMoreElements()) { - - String parameter = (String) parameters.nextElement(); + while (parameterAttribute.size() > 0) { + String parameter; + try { + parameter = parameterAttribute.getString(); + } + catch (LdapInvalidAttributeValueException e) { + return null; + } + parameterAttribute.remove(parameter); // Parse parameter int equals = parameter.indexOf('='); @@ -177,8 +200,7 @@ public class ConnectionService { } // Store connection using cn for both identifier and name - String name = cn.getStringValue(); - Connection connection = new SimpleConnection(name, name, config, true); + Connection connection = new SimpleConnection(cnName, cnName, config, true); connection.setParentIdentifier(LDAPAuthenticationProvider.ROOT_CONNECTION_GROUP); // Inject LDAP-specific tokens only if LDAP handled user @@ -192,7 +214,7 @@ public class ConnectionService { }); } - catch (LDAPException e) { + catch (LdapException e) { throw new GuacamoleServerException("Error while querying for connections.", e); } @@ -219,34 +241,33 @@ public class ConnectionService { * @throws GuacamoleException * If an error occurs retrieving the group base DN. */ - private String getConnectionSearchFilter(String userDN, - LDAPConnection ldapConnection) - throws LDAPException, GuacamoleException { + private ExprNode getConnectionSearchFilter(Dn userDN, + LdapConnection ldapConnection) + throws LdapException, GuacamoleException { - // Create a search filter for the connection search - StringBuilder connectionSearchFilter = new StringBuilder(); + AndNode searchFilter = new AndNode(); // Add the prefix to the search filter, prefix filter searches for guacConfigGroups with the userDN as the member attribute value - connectionSearchFilter.append("(&(objectClass=guacConfigGroup)"); - connectionSearchFilter.append("(|("); - connectionSearchFilter.append(escapingService.escapeLDAPSearchFilter( - confService.getMemberAttribute())); - connectionSearchFilter.append("="); - connectionSearchFilter.append(escapingService.escapeLDAPSearchFilter(userDN)); - connectionSearchFilter.append(")"); + searchFilter.addNode(new EqualityNode("objectClass","guacConfigGroup")); + + // Apply group filters + OrNode groupFilter = new OrNode(); + groupFilter.addNode(new EqualityNode(confService.getMemberAttribute(), + userDN.toString())); // Additionally filter by group membership if the current user is a // member of any user groups - List userGroups = userGroupService.getParentUserGroupEntries(ldapConnection, userDN); + List userGroups = userGroupService.getParentUserGroupEntries(ldapConnection, userDN); if (!userGroups.isEmpty()) { - for (LDAPEntry entry : userGroups) - connectionSearchFilter.append("(seeAlso=").append(escapingService.escapeLDAPSearchFilter(entry.getDN())).append(")"); + userGroups.forEach(entry -> + groupFilter.addNode(new EqualityNode("seeAlso",entry.getDn().toString())) + ); } // Complete the search filter. - connectionSearchFilter.append("))"); + searchFilter.addNode(groupFilter); - return connectionSearchFilter.toString(); + return searchFilter; } } diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/group/UserGroupService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/group/UserGroupService.java index 3315beb78..7d73003f7 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/group/UserGroupService.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/group/UserGroupService.java @@ -20,15 +20,20 @@ package org.apache.guacamole.auth.ldap.group; import com.google.inject.Inject; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPEntry; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.guacamole.auth.ldap.ConfigurationService; +import org.apache.directory.ldap.client.api.LdapConnection; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException; +import org.apache.directory.api.ldap.model.filter.EqualityNode; +import org.apache.directory.api.ldap.model.filter.ExprNode; +import org.apache.directory.api.ldap.model.filter.NotNode; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.guacamole.auth.ldap.conf.ConfigurationService; import org.apache.guacamole.GuacamoleException; import org.apache.guacamole.auth.ldap.ObjectQueryService; import org.apache.guacamole.net.auth.UserGroup; @@ -72,17 +77,17 @@ public class UserGroupService { * @throws GuacamoleException * If guacamole.properties cannot be parsed. */ - private String getGroupSearchFilter() throws GuacamoleException { + private ExprNode getGroupSearchFilter() throws GuacamoleException { // Explicitly exclude guacConfigGroup object class only if it should // be assumed to be defined (query may fail due to no such object // class existing otherwise) if (confService.getConfigurationBaseDN() != null) - return "(!(objectClass=guacConfigGroup))"; + return new NotNode(new EqualityNode("objectClass","guacConfigGroup")); // Read any object as a group if LDAP is not being used for connection // storage (guacConfigGroup) - return "(objectClass=*)"; + return new EqualityNode("objectCalss","*"); } @@ -102,17 +107,17 @@ public class UserGroupService { * @throws GuacamoleException * If an error occurs preventing retrieval of user groups. */ - public Map getUserGroups(LDAPConnection ldapConnection) + public Map getUserGroups(LdapConnection ldapConnection) throws GuacamoleException { // Do not return any user groups if base DN is not specified - String groupBaseDN = confService.getGroupBaseDN(); + Dn groupBaseDN = confService.getGroupBaseDN(); if (groupBaseDN == null) return Collections.emptyMap(); // Retrieve all visible user groups which are not guacConfigGroups Collection attributes = confService.getGroupNameAttributes(); - List results = queryService.search( + List results = queryService.search( ldapConnection, groupBaseDN, getGroupSearchFilter(), @@ -125,13 +130,18 @@ public class UserGroupService { return queryService.asMap(results, entry -> { // Translate entry into UserGroup object having proper identifier - String name = queryService.getIdentifier(entry, attributes); - if (name != null) - return new SimpleUserGroup(name); + try { + String name = queryService.getIdentifier(entry, attributes); + if (name != null) + return new SimpleUserGroup(name); + } + catch (LdapInvalidAttributeValueException e) { + return null; + } // Ignore user groups which lack a name attribute logger.debug("User group \"{}\" is missing a name attribute " - + "and will be ignored.", entry.getDN()); + + "and will be ignored.", entry.getDn().toString()); return null; }); @@ -157,11 +167,11 @@ public class UserGroupService { * @throws GuacamoleException * If an error occurs preventing retrieval of user groups. */ - public List getParentUserGroupEntries(LDAPConnection ldapConnection, - String userDN) throws GuacamoleException { + public List getParentUserGroupEntries(LdapConnection ldapConnection, + Dn userDN) throws GuacamoleException { // Do not return any user groups if base DN is not specified - String groupBaseDN = confService.getGroupBaseDN(); + Dn groupBaseDN = confService.getGroupBaseDN(); if (groupBaseDN == null) return Collections.emptyList(); @@ -172,7 +182,7 @@ public class UserGroupService { groupBaseDN, getGroupSearchFilter(), Collections.singleton(confService.getMemberAttribute()), - userDN + userDN.toString() ); } @@ -196,24 +206,29 @@ public class UserGroupService { * @throws GuacamoleException * If an error occurs preventing retrieval of user groups. */ - public Set getParentUserGroupIdentifiers(LDAPConnection ldapConnection, - String userDN) throws GuacamoleException { + public Set getParentUserGroupIdentifiers(LdapConnection ldapConnection, + Dn userDN) throws GuacamoleException { Collection attributes = confService.getGroupNameAttributes(); - List userGroups = getParentUserGroupEntries(ldapConnection, userDN); + List userGroups = getParentUserGroupEntries(ldapConnection, userDN); Set identifiers = new HashSet<>(userGroups.size()); userGroups.forEach(entry -> { // Determine unique identifier for user group - String name = queryService.getIdentifier(entry, attributes); - if (name != null) - identifiers.add(name); + try { + String name = queryService.getIdentifier(entry, attributes); + if (name != null) + identifiers.add(name); - // Ignore user groups which lack a name attribute - else - logger.debug("User group \"{}\" is missing a name attribute " - + "and will be ignored.", entry.getDN()); + // Ignore user groups which lack a name attribute + else + logger.debug("User group \"{}\" is missing a name attribute " + + "and will be ignored.", entry.getDn().toString()); + } + catch (LdapInvalidAttributeValueException e) { + logger.debug("User group missing identifier.", e.getMessage()); + } }); diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/LDAPUserContext.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/LDAPUserContext.java index 5505f7ec1..5d7e3e73e 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/LDAPUserContext.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/LDAPUserContext.java @@ -20,8 +20,8 @@ package org.apache.guacamole.auth.ldap.user; import com.google.inject.Inject; -import com.novell.ldap.LDAPConnection; import java.util.Collections; +import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.guacamole.auth.ldap.connection.ConnectionService; import org.apache.guacamole.GuacamoleException; import org.apache.guacamole.auth.ldap.LDAPAuthenticationProvider; @@ -39,8 +39,6 @@ import org.apache.guacamole.net.auth.simple.SimpleConnectionGroup; import org.apache.guacamole.net.auth.simple.SimpleDirectory; import org.apache.guacamole.net.auth.simple.SimpleObjectPermissionSet; import org.apache.guacamole.net.auth.simple.SimpleUser; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; /** * An LDAP-specific implementation of UserContext which queries all Guacamole @@ -48,11 +46,6 @@ import org.slf4j.LoggerFactory; */ public class LDAPUserContext extends AbstractUserContext { - /** - * Logger for this class. - */ - private final Logger logger = LoggerFactory.getLogger(LDAPUserContext.class); - /** * Service for retrieving Guacamole connections from the LDAP server. */ @@ -124,7 +117,7 @@ public class LDAPUserContext extends AbstractUserContext { * If associated data stored within the LDAP directory cannot be * queried due to an error. */ - public void init(AuthenticatedUser user, LDAPConnection ldapConnection) + public void init(AuthenticatedUser user, LdapConnection ldapConnection) throws GuacamoleException { // Query all accessible users diff --git a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/UserService.java b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/UserService.java index 3f12ae829..a5fcb4142 100644 --- a/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/UserService.java +++ b/extensions/guacamole-auth-ldap/src/main/java/org/apache/guacamole/auth/ldap/user/UserService.java @@ -20,16 +20,19 @@ package org.apache.guacamole.auth.ldap.user; import com.google.inject.Inject; -import com.novell.ldap.LDAPConnection; -import com.novell.ldap.LDAPEntry; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; -import org.apache.guacamole.auth.ldap.ConfigurationService; -import org.apache.guacamole.auth.ldap.EscapingService; +import org.apache.directory.ldap.client.api.LdapConnection; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; +import org.apache.directory.api.ldap.model.exception.LdapInvalidAttributeValueException; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.guacamole.auth.ldap.conf.ConfigurationService; import org.apache.guacamole.GuacamoleException; -import org.apache.guacamole.auth.ldap.LDAPGuacamoleProperties; +import org.apache.guacamole.GuacamoleServerException; +import org.apache.guacamole.auth.ldap.conf.LDAPGuacamoleProperties; import org.apache.guacamole.auth.ldap.ObjectQueryService; import org.apache.guacamole.net.auth.User; import org.apache.guacamole.net.auth.simple.SimpleUser; @@ -45,13 +48,7 @@ public class UserService { /** * Logger for this class. */ - private final Logger logger = LoggerFactory.getLogger(UserService.class); - - /** - * Service for escaping parts of LDAP queries. - */ - @Inject - private EscapingService escapingService; + private static final Logger logger = LoggerFactory.getLogger(UserService.class); /** * Service for retrieving LDAP server configuration information. @@ -81,12 +78,12 @@ public class UserService { * @throws GuacamoleException * If an error occurs preventing retrieval of users. */ - public Map getUsers(LDAPConnection ldapConnection) + public Map getUsers(LdapConnection ldapConnection) throws GuacamoleException { // Retrieve all visible user objects Collection attributes = confService.getUsernameAttributes(); - List results = queryService.search(ldapConnection, + List results = queryService.search(ldapConnection, confService.getUserBaseDN(), confService.getUserSearchFilter(), attributes, @@ -96,15 +93,20 @@ public class UserService { return queryService.asMap(results, entry -> { // Get username from record - String username = queryService.getIdentifier(entry, attributes); - if (username == null) { - logger.warn("User \"{}\" is missing a username attribute " - + "and will be ignored.", entry.getDN()); + try { + String username = queryService.getIdentifier(entry, attributes); + if (username == null) { + logger.warn("User \"{}\" is missing a username attribute " + + "and will be ignored.", entry.getDn().toString()); + return null; + } + + return new SimpleUser(username); + } + catch (LdapInvalidAttributeValueException e) { return null; } - return new SimpleUser(username); - }); } @@ -130,19 +132,19 @@ public class UserService { * If an error occurs while querying the user DNs, or if the username * attribute property cannot be parsed within guacamole.properties. */ - public List getUserDNs(LDAPConnection ldapConnection, + public List getUserDNs(LdapConnection ldapConnection, String username) throws GuacamoleException { // Retrieve user objects having a matching username - List results = queryService.search(ldapConnection, + List results = queryService.search(ldapConnection, confService.getUserBaseDN(), confService.getUserSearchFilter(), confService.getUsernameAttributes(), username); // Build list of all DNs for retrieved users - List userDNs = new ArrayList<>(results.size()); - results.forEach(entry -> userDNs.add(entry.getDN())); + List userDNs = new ArrayList<>(results.size()); + results.forEach(entry -> userDNs.add(entry.getDn())); return userDNs; @@ -164,7 +166,7 @@ public class UserService { * If required properties are missing, and thus the user DN cannot be * determined. */ - public String deriveUserDN(String username) + public Dn deriveUserDN(String username) throws GuacamoleException { // Pull username attributes from properties @@ -181,10 +183,13 @@ public class UserService { } // Derive user DN from base DN - return - escapingService.escapeDN(usernameAttributes.get(0)) - + "=" + escapingService.escapeDN(username) - + "," + confService.getUserBaseDN(); + try { + return new Dn(usernameAttributes.get(0) + "=" + username + + "," + confService.getUserBaseDN().toString()); + } + catch (LdapInvalidDnException e) { + throw new GuacamoleServerException("Error trying to derive user DN.", e); + } }