org.apache.directory.ldap.client.api.LdapNetworkConnection Java Examples

The following examples show how to use org.apache.directory.ldap.client.api.LdapNetworkConnection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiLdapClientApiOsgiTest.java    From directory-ldap-api with Apache License 2.0 6 votes vote down vote up
@Override
protected void useBundleClasses() throws Exception
{
    new LdapNetworkConnection().close();
    new SaslGssApiRequest();
    new Krb5LoginConfiguration();
    new AddFuture( new LdapNetworkConnection(), 2 );
    new LdapConnectionTemplate( new LdapConnectionPool( new DefaultPoolableLdapConnectionFactory(
        new LdapConnectionConfig() ) ) );
    FilterBuilder.and( FilterBuilder.not( FilterBuilder.contains( "cn", "a", "b" ) ) ).toString();

    // Test for DIRAPI-239
    PooledObjectFactory<LdapConnection> factory = new DefaultPoolableLdapConnectionFactory(
        new LdapConnectionConfig() );
    GenericObjectPoolConfig config = new GenericObjectPoolConfig();
    LdapConnectionPool ldapConnectionPool = new LdapConnectionPool( factory, config );
    ldapConnectionPool.getLdapApiService();
    ldapConnectionPool.getTestOnBorrow();
    ldapConnectionPool.close();
}
 
Example #2
Source File: UserService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all Guacamole users accessible to the user currently bound under
 * the given LDAP connection.
 *
 * @param ldapConnection
 *     The current connection to the LDAP server, associated with the
 *     current user.
 *
 * @return
 *     All users accessible to the user currently bound under the given
 *     LDAP connection, as a map of connection identifier to corresponding
 *     user object.
 *
 * @throws GuacamoleException
 *     If an error occurs preventing retrieval of users.
 */
public Map<String, User> getUsers(LdapNetworkConnection ldapConnection)
        throws GuacamoleException {

    // Retrieve all visible user objects
    Collection<String> attributes = confService.getUsernameAttributes();
    List<Entry> results = queryService.search(ldapConnection,
            confService.getUserBaseDN(),
            confService.getUserSearchFilter(),
            attributes,
            null);

    // Convert retrieved users to map of identifier to Guacamole user object
    return queryService.asMap(results, entry -> {

        // Get username from record
        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;
        }

    });

}
 
Example #3
Source File: LdapAuthenticationBaseIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
static LdapConnection setupLdapServer(GenericContainer server, String setupFile) {
  // setup Ldap server 1
  LdapConnection connection = new LdapNetworkConnection(server.getContainerIpAddress(), server.getMappedPort(LDAP_PORT));
  try {
    connection.bind(BIND_DN, BIND_PWD);
    LdifReader reader = new LdifReader(Resources.getResource(setupFile).getFile());
    for (LdifEntry entry : reader) {
      connection.add(entry.getEntry());
    }
  } catch (LdapException e) {
    LOG.error("Setup server 1 failed " + e);
  }
  return connection;
}
 
Example #4
Source File: LDAPApi.java    From mamute with Apache License 2.0 5 votes vote down vote up
private LdapConnection connection(String username, String password) throws LdapException {
	// Manually build the configuration since the convenience constructor in 
	// the LdapNetworkConnection doesn't let us specify a TLS setting			
	LdapConnectionConfig config = new LdapConnectionConfig();
	config.setLdapHost(host);
	config.setLdapPort(port);
	config.setUseTls(useTls);
	config.setUseSsl(useSsl);
       LdapNetworkConnection conn = new LdapNetworkConnection(config);
	
	conn.bind(username, password);
	return conn;
}
 
Example #5
Source File: LdapLoginManager.java    From openmeetings with Apache License 2.0 5 votes vote down vote up
public LdapWorker(Long domainId) {
	this.domainId = domainId;
	ldapCfg = ldapConfigDao.get(domainId);
	loadLdapConf(ldapCfg.getConfigFileName(), config);
	options = new LdapOptions(config);

	conn = new LdapNetworkConnection(options.host, options.port, options.secure);
}
 
Example #6
Source File: ConnectionService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an LDAP search filter which queries all connections accessible
 * by the user having the given DN.
 *
 * @param userDN
 *     DN of the user to search for associated guacConfigGroup connections.
 *
 * @param ldapConnection
 *     LDAP connection to use if additional information must be queried to
 *     produce the filter, such as groups driving RBAC.
 *
 * @return
 *     An LDAP search filter which queries all guacConfigGroup objects
 *     accessible by the user having the given DN.
 *
 * @throws LdapException
 *     If an error occurs preventing retrieval of user groups.
 *
 * @throws GuacamoleException
 *     If an error occurs retrieving the group base DN.
 */
private ExprNode getConnectionSearchFilter(Dn userDN,
        LdapNetworkConnection ldapConnection)
        throws LdapException, GuacamoleException {

    AndNode searchFilter = new AndNode();

    // Add the prefix to the search filter, prefix filter searches for guacConfigGroups with the userDN as the member attribute value
    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<Entry> userGroups = userGroupService.getParentUserGroupEntries(ldapConnection, userDN);
    if (!userGroups.isEmpty()) {
        userGroups.forEach(entry ->
            groupFilter.addNode(new EqualityNode("seeAlso",entry.getDn().toString()))
        );
    }

    // Complete the search filter.
    searchFilter.addNode(groupFilter);

    return searchFilter;
}
 
Example #7
Source File: LDAPConnectionService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of LdapNetworkConnection, configured as required
 * to use the given encryption method to communicate with the LDAP server
 * at the given hostname and port. The returned LdapNetworkConnection is
 * configured for use but is not yet connected nor bound to the LDAP
 * server. It will not be bound until a bind operation is explicitly
 * requested, and will not be connected until it is used in an LDAP
 * operation (such as a bind).
 *
 * @param host
 *     The hostname or IP address of the LDAP server.
 *
 * @param port
 *     The TCP port that the LDAP server is listening on.
 *
 * @param encryptionMethod
 *     The encryption method that should be used to communicate with the
 *     LDAP server.
 *
 * @return
 *     A new instance of LdapNetworkConnection which uses the given
 *     encryption method to communicate with the LDAP server at the given
 *     hostname and port.
 *
 * @throws GuacamoleException
 *     If the requested encryption method is actually not implemented (a
 *     bug).
 */
private LdapNetworkConnection createLDAPConnection(String host, int port,
        EncryptionMethod encryptionMethod) throws GuacamoleException {

    LdapConnectionConfig config = new LdapConnectionConfig();
    config.setLdapHost(host);
    config.setLdapPort(port);

    // Map encryption method to proper connection and socket factory
    switch (encryptionMethod) {

        // Unencrypted LDAP connection
        case NONE:
            logger.debug("Connection to LDAP server without encryption.");
            break;

        // LDAP over SSL (LDAPS)
        case SSL:
            logger.debug("Connecting to LDAP server using SSL/TLS.");
            config.setUseSsl(true);
            break;

        // LDAP + STARTTLS
        case STARTTLS:
            logger.debug("Connecting to LDAP server using STARTTLS.");
            config.setUseTls(true);
            break;

        // The encryption method, though known, is not actually
        // implemented. If encountered, this would be a bug.
        default:
            throw new GuacamoleUnsupportedException("Unimplemented encryption method: " + encryptionMethod);

    }

    return new LdapNetworkConnection(config);

}
 
Example #8
Source File: LDAPConnectionService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of LdapNetworkConnection, configured as required
 * to use the given encryption method to communicate with the LDAP server
 * at the given hostname and port. The returned LdapNetworkConnection is
 * configured for use but is not yet connected nor bound to the LDAP
 * server. It will not be bound until a bind operation is explicitly
 * requested, and will not be connected until it is used in an LDAP
 * operation (such as a bind).
 *
 * @param host
 *     The hostname or IP address of the LDAP server.
 *
 * @param port
 *     The TCP port that the LDAP server is listening on.
 *
 * @param encryptionMethod
 *     The encryption method that should be used to communicate with the
 *     LDAP server.
 *
 * @return
 *     A new instance of LdapNetworkConnection which uses the given
 *     encryption method to communicate with the LDAP server at the given
 *     hostname and port.
 *
 * @throws GuacamoleException
 *     If the requested encryption method is actually not implemented (a
 *     bug).
 */
private LdapNetworkConnection createLDAPConnection(String host, int port,
        EncryptionMethod encryptionMethod) throws GuacamoleException {

    LdapConnectionConfig config = new LdapConnectionConfig();
    config.setLdapHost(host);
    config.setLdapPort(port);

    // Map encryption method to proper connection and socket factory
    switch (encryptionMethod) {

        // Unencrypted LDAP connection
        case NONE:
            logger.debug("Connection to LDAP server without encryption.");
            break;

        // LDAP over SSL (LDAPS)
        case SSL:
            logger.debug("Connecting to LDAP server using SSL/TLS.");
            config.setUseSsl(true);
            break;

        // LDAP + STARTTLS
        case STARTTLS:
            logger.debug("Connecting to LDAP server using STARTTLS.");
            config.setUseTls(true);
            break;

        // The encryption method, though known, is not actually
        // implemented. If encountered, this would be a bug.
        default:
            throw new GuacamoleUnsupportedException("Unimplemented encryption method: " + encryptionMethod);

    }

    return new LdapNetworkConnection(config);

}
 
Example #9
Source File: ConnectionService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an LDAP search filter which queries all connections accessible
 * by the user having the given DN.
 *
 * @param userDN
 *     DN of the user to search for associated guacConfigGroup connections.
 *
 * @param ldapConnection
 *     LDAP connection to use if additional information must be queried to
 *     produce the filter, such as groups driving RBAC.
 *
 * @return
 *     An LDAP search filter which queries all guacConfigGroup objects
 *     accessible by the user having the given DN.
 *
 * @throws LdapException
 *     If an error occurs preventing retrieval of user groups.
 *
 * @throws GuacamoleException
 *     If an error occurs retrieving the group base DN.
 */
private ExprNode getConnectionSearchFilter(Dn userDN,
        LdapNetworkConnection ldapConnection)
        throws LdapException, GuacamoleException {

    AndNode searchFilter = new AndNode();

    // Add the prefix to the search filter, prefix filter searches for guacConfigGroups with the userDN as the member attribute value
    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<Entry> userGroups = userGroupService.getParentUserGroupEntries(ldapConnection, userDN);
    if (!userGroups.isEmpty()) {
        userGroups.forEach(entry ->
            groupFilter.addNode(new EqualityNode("seeAlso",entry.getDn().toString()))
        );
    }

    // Complete the search filter.
    searchFilter.addNode(groupFilter);

    return searchFilter;
}
 
Example #10
Source File: UserService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all Guacamole users accessible to the user currently bound under
 * the given LDAP connection.
 *
 * @param ldapConnection
 *     The current connection to the LDAP server, associated with the
 *     current user.
 *
 * @return
 *     All users accessible to the user currently bound under the given
 *     LDAP connection, as a map of connection identifier to corresponding
 *     user object.
 *
 * @throws GuacamoleException
 *     If an error occurs preventing retrieval of users.
 */
public Map<String, User> getUsers(LdapNetworkConnection ldapConnection)
        throws GuacamoleException {

    // Retrieve all visible user objects
    Collection<String> attributes = confService.getUsernameAttributes();
    List<Entry> results = queryService.search(ldapConnection,
            confService.getUserBaseDN(),
            confService.getUserSearchFilter(),
            attributes,
            null);

    // Convert retrieved users to map of identifier to Guacamole user object
    return queryService.asMap(results, entry -> {

        // Get username from record
        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;
        }

    });

}
 
Example #11
Source File: UserGroupService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the identifiers of all user groups that the given user is a
 * member of. Only identifiers of user groups which are readable by the
 * current user will be retrieved.
 *
 * @param ldapConnection
 *     The current connection to the LDAP server, associated with the
 *     current user.
 *
 * @param userDN
 *     The DN of the user whose group membership should be retrieved.
 *
 * @return
 *     The identifiers of all readable parent user groups of the user
 *     having the given DN.
 *
 * @throws GuacamoleException
 *     If an error occurs preventing retrieval of user groups.
 */
public Set<String> getParentUserGroupIdentifiers(LdapNetworkConnection ldapConnection,
        Dn userDN) throws GuacamoleException {

    Collection<String> attributes = confService.getGroupNameAttributes();
    List<Entry> userGroups = getParentUserGroupEntries(ldapConnection, userDN);

    Set<String> identifiers = new HashSet<>(userGroups.size());
    userGroups.forEach(entry -> {

        // Determine unique identifier for user group
        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().toString());
        }
        catch (LdapInvalidAttributeValueException e) {
            logger.error("User group missing identifier: {}",
                    e.getMessage());
            logger.debug("LDAP exception while getting group identifier.", e);
        }

    });

    return identifiers;

}
 
Example #12
Source File: AuthenticationProviderService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns parameter tokens generated from LDAP attributes on the user
 * currently bound under the given LDAP connection. The attributes to be
 * converted into parameter tokens must be explicitly listed in
 * guacamole.properties. If no attributes are specified or none are
 * found on the LDAP user object, an empty map is returned.
 *
 * @param ldapConnection
 *     LDAP connection to use to read the attributes of the user.
 *
 * @param username
 *     The username of the user whose attributes are to be queried.
 *
 * @return
 *     A map of parameter tokens generated from attributes on the user
 *     currently bound under the given LDAP connection, as a map of token
 *     name to corresponding value, or an empty map if no attributes are
 *     specified or none are found on the user object.
 *
 * @throws GuacamoleException
 *     If an error occurs retrieving the user DN or the attributes.
 */
private Map<String, String> getAttributeTokens(LdapNetworkConnection ldapConnection,
        Dn userDn) throws GuacamoleException {

    // Get attributes from configuration information
    List<String> attrList = confService.getAttributes();

    // If there are no attributes there is no reason to search LDAP
    if (attrList.isEmpty())
        return Collections.<String, String>emptyMap();

    // Build LDAP query parameters
    String[] attrArray = attrList.toArray(new String[attrList.size()]);

    Map<String, String> tokens = new HashMap<>();
    try {

        // Get LDAP attributes by querying LDAP
        Entry userEntry = ldapConnection.lookup(userDn, attrArray);
        if (userEntry == null)
            return Collections.<String, String>emptyMap();

        Collection<Attribute> attributes = userEntry.getAttributes();
        if (attributes == null)
            return Collections.<String, String>emptyMap();

        // Convert each retrieved attribute into a corresponding token
        for (Attribute attr : attributes) {
            tokens.put(TokenName.canonicalize(attr.getId(),
                    LDAP_ATTRIBUTE_TOKEN_PREFIX), attr.getString());
        }

    }
    catch (LdapException e) {
        throw new GuacamoleServerException("Could not query LDAP user attributes.", e);
    }

    return tokens;

}
 
Example #13
Source File: AuthenticationProviderService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a UserContext object initialized with data accessible to the
 * given AuthenticatedUser.
 *
 * @param authenticatedUser
 *     The AuthenticatedUser to retrieve data for.
 *
 * @return
 *     A UserContext object initialized with data accessible to the given
 *     AuthenticatedUser.
 *
 * @throws GuacamoleException
 *     If the UserContext cannot be created due to an error.
 */
public LDAPUserContext getUserContext(AuthenticatedUser authenticatedUser)
        throws GuacamoleException {

    // Bind using credentials associated with AuthenticatedUser
    Credentials credentials = authenticatedUser.getCredentials();
    if (authenticatedUser instanceof LDAPAuthenticatedUser) {

        Dn bindDn = ((LDAPAuthenticatedUser) authenticatedUser).getBindDn();
        LdapNetworkConnection ldapConnection = ldapService.bindAs(bindDn, credentials.getPassword());
        if (ldapConnection == null) {
            logger.debug("LDAP bind succeeded for \"{}\" during "
                    + "authentication but failed during data retrieval.",
                    authenticatedUser.getIdentifier());
            throw new GuacamoleInvalidCredentialsException("Invalid login.",
                    CredentialsInfo.USERNAME_PASSWORD);
        }

        try {

            // Build user context by querying LDAP
            LDAPUserContext userContext = userContextProvider.get();
            userContext.init(authenticatedUser, ldapConnection);
            return userContext;

        }

        // Always disconnect
        finally {
            ldapConnection.close();
        }
    }
    return null;

}
 
Example #14
Source File: AuthenticationProviderService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns parameter tokens generated from LDAP attributes on the user
 * currently bound under the given LDAP connection. The attributes to be
 * converted into parameter tokens must be explicitly listed in
 * guacamole.properties. If no attributes are specified or none are
 * found on the LDAP user object, an empty map is returned.
 *
 * @param ldapConnection
 *     LDAP connection to use to read the attributes of the user.
 *
 * @param username
 *     The username of the user whose attributes are to be queried.
 *
 * @return
 *     A map of parameter tokens generated from attributes on the user
 *     currently bound under the given LDAP connection, as a map of token
 *     name to corresponding value, or an empty map if no attributes are
 *     specified or none are found on the user object.
 *
 * @throws GuacamoleException
 *     If an error occurs retrieving the user DN or the attributes.
 */
private Map<String, String> getAttributeTokens(LdapNetworkConnection ldapConnection,
        Dn userDn) throws GuacamoleException {

    // Get attributes from configuration information
    List<String> attrList = confService.getAttributes();

    // If there are no attributes there is no reason to search LDAP
    if (attrList.isEmpty())
        return Collections.<String, String>emptyMap();

    // Build LDAP query parameters
    String[] attrArray = attrList.toArray(new String[attrList.size()]);

    Map<String, String> tokens = new HashMap<>();
    try {

        // Get LDAP attributes by querying LDAP
        Entry userEntry = ldapConnection.lookup(userDn, attrArray);
        if (userEntry == null)
            return Collections.<String, String>emptyMap();

        Collection<Attribute> attributes = userEntry.getAttributes();
        if (attributes == null)
            return Collections.<String, String>emptyMap();

        // Convert each retrieved attribute into a corresponding token
        for (Attribute attr : attributes) {
            tokens.put(TokenName.canonicalize(attr.getId(),
                    LDAP_ATTRIBUTE_TOKEN_PREFIX), attr.getString());
        }

    }
    catch (LdapException e) {
        throw new GuacamoleServerException("Could not query LDAP user attributes.", e);
    }

    return tokens;

}
 
Example #15
Source File: AuthenticationProviderService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a UserContext object initialized with data accessible to the
 * given AuthenticatedUser.
 *
 * @param authenticatedUser
 *     The AuthenticatedUser to retrieve data for.
 *
 * @return
 *     A UserContext object initialized with data accessible to the given
 *     AuthenticatedUser.
 *
 * @throws GuacamoleException
 *     If the UserContext cannot be created due to an error.
 */
public LDAPUserContext getUserContext(AuthenticatedUser authenticatedUser)
        throws GuacamoleException {

    // Bind using credentials associated with AuthenticatedUser
    Credentials credentials = authenticatedUser.getCredentials();
    if (authenticatedUser instanceof LDAPAuthenticatedUser) {

        Dn bindDn = ((LDAPAuthenticatedUser) authenticatedUser).getBindDn();
        LdapNetworkConnection ldapConnection = ldapService.bindAs(bindDn, credentials.getPassword());
        if (ldapConnection == null) {
            logger.debug("LDAP bind succeeded for \"{}\" during "
                    + "authentication but failed during data retrieval.",
                    authenticatedUser.getIdentifier());
            throw new GuacamoleInvalidCredentialsException("Invalid login.",
                    CredentialsInfo.USERNAME_PASSWORD);
        }

        try {

            // Build user context by querying LDAP
            LDAPUserContext userContext = userContextProvider.get();
            userContext.init(authenticatedUser, ldapConnection);
            return userContext;

        }

        // Always disconnect
        finally {
            ldapConnection.close();
        }
    }
    return null;

}
 
Example #16
Source File: UserGroupService.java    From guacamole-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the identifiers of all user groups that the given user is a
 * member of. Only identifiers of user groups which are readable by the
 * current user will be retrieved.
 *
 * @param ldapConnection
 *     The current connection to the LDAP server, associated with the
 *     current user.
 *
 * @param userDN
 *     The DN of the user whose group membership should be retrieved.
 *
 * @return
 *     The identifiers of all readable parent user groups of the user
 *     having the given DN.
 *
 * @throws GuacamoleException
 *     If an error occurs preventing retrieval of user groups.
 */
public Set<String> getParentUserGroupIdentifiers(LdapNetworkConnection ldapConnection,
        Dn userDN) throws GuacamoleException {

    Collection<String> attributes = confService.getGroupNameAttributes();
    List<Entry> userGroups = getParentUserGroupEntries(ldapConnection, userDN);

    Set<String> identifiers = new HashSet<>(userGroups.size());
    userGroups.forEach(entry -> {

        // Determine unique identifier for user group
        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().toString());
        }
        catch (LdapInvalidAttributeValueException e) {
            logger.error("User group missing identifier: {}",
                    e.getMessage());
            logger.debug("LDAP exception while getting group identifier.", e);
        }

    });

    return identifiers;

}
 
Example #17
Source File: AuthenticationProviderService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Determines the DN which corresponds to the user having the given
 * username. The DN will either be derived directly from the user base DN,
 * or queried from the LDAP server, depending on how LDAP authentication
 * has been configured.
 *
 * @param username
 *     The username of the user whose corresponding DN should be returned.
 *
 * @return
 *     The DN which corresponds to the user having the given username.
 *
 * @throws GuacamoleException
 *     If required properties are missing, and thus the user DN cannot be
 *     determined.
 */
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
    Dn searchBindDN = confService.getSearchBindDN();
    if (searchBindDN != null) {

        // Create an LDAP connection using the search account
        LdapNetworkConnection searchConnection = ldapService.bindAs(
            searchBindDN,
            confService.getSearchBindPassword()
        );

        // Warn of failure to find
        if (searchConnection == null) {
            logger.error("Unable to bind using search DN \"{}\"", searchBindDN);
            return null;
        }

        try {

            // Retrieve all DNs associated with the given username
            List<Dn> userDNs = userService.getUserDNs(searchConnection, username);
            if (userDNs.isEmpty())
                return null;

            // Warn if multiple DNs exist for the same user
            if (userDNs.size() != 1) {
                logger.warn("Multiple DNs possible for user \"{}\": {}", username, userDNs);
                return null;
            }

            // Return the single possible DN
            return userDNs.get(0);

        }

        // Always disconnect
        finally {
            searchConnection.close();
        }

    }

    // Otherwise, derive user DN from base DN
    return userService.deriveUserDN(username);

}
 
Example #18
Source File: LDAPUserContext.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes this UserContext using the provided AuthenticatedUser and
 * LdapNetworkConnection.
 *
 * @param user
 *     The AuthenticatedUser representing the user that authenticated. This
 *     user may have been authenticated by a different authentication
 *     provider (not LDAP).
 *
 * @param ldapConnection
 *     The connection to the LDAP server to use when querying accessible
 *     Guacamole users and connections.
 *
 * @throws GuacamoleException
 *     If associated data stored within the LDAP directory cannot be
 *     queried due to an error.
 */
public void init(AuthenticatedUser user, LdapNetworkConnection ldapConnection)
        throws GuacamoleException {

    // Query all accessible users
    userDirectory = new SimpleDirectory<>(
        userService.getUsers(ldapConnection)
    );

    // Query all accessible user groups
    userGroupDirectory = new SimpleDirectory<>(
        userGroupService.getUserGroups(ldapConnection)
    );

    // Query all accessible connections
    connectionDirectory = new SimpleDirectory<>(
        connectionService.getConnections(user, ldapConnection)
    );

    // Root group contains only connections
    rootGroup = new SimpleConnectionGroup(
        LDAPAuthenticationProvider.ROOT_CONNECTION_GROUP,
        LDAPAuthenticationProvider.ROOT_CONNECTION_GROUP,
        connectionDirectory.getIdentifiers(),
        Collections.<String>emptyList()
    );

    // Init self with basic permissions
    self = new SimpleUser(user.getIdentifier()) {

        @Override
        public ObjectPermissionSet getUserPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(userDirectory.getIdentifiers());
        }

        @Override
        public ObjectPermissionSet getUserGroupPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(userGroupDirectory.getIdentifiers());
        }

        @Override
        public ObjectPermissionSet getConnectionPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(connectionDirectory.getIdentifiers());
        }

        @Override
        public ObjectPermissionSet getConnectionGroupPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(Collections.singleton(LDAPAuthenticationProvider.ROOT_CONNECTION_GROUP));
        }

    };

}
 
Example #19
Source File: AuthenticationProviderService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Returns an AuthenticatedUser representing the user authenticated by the
 * given credentials. Also adds custom LDAP attributes to the
 * AuthenticatedUser.
 *
 * @param credentials
 *     The credentials to use for authentication.
 *
 * @return
 *     An AuthenticatedUser representing the user authenticated by the
 *     given credentials.
 *
 * @throws GuacamoleException
 *     If an error occurs while authenticating the user, or if access is
 *     denied.
 */
public LDAPAuthenticatedUser authenticateUser(Credentials credentials)
        throws GuacamoleException {
    
    String username = credentials.getUsername();
    String password = credentials.getPassword();
    
    // Username and password are required
    if (username == null
            || username.isEmpty()
            || password == null
            || password.isEmpty()) {
        throw new GuacamoleInvalidCredentialsException(
                "Anonymous bind is not currently allowed by the LDAP"
                + " authentication provider.", CredentialsInfo.USERNAME_PASSWORD);
    }
    
    Dn bindDn = getUserBindDN(username);
    if (bindDn == null || bindDn.isEmpty()) {
        throw new GuacamoleInvalidCredentialsException("Unable to determine"
                + " DN of user " + username, CredentialsInfo.USERNAME_PASSWORD);
    }
    
    // Attempt bind
    LdapNetworkConnection ldapConnection = ldapService.bindAs(bindDn, password);
    if (ldapConnection == null)
        throw new GuacamoleInvalidCredentialsException("Invalid login.",
                CredentialsInfo.USERNAME_PASSWORD);

    try {

        // Retrieve group membership of the user that just authenticated
        Set<String> effectiveGroups =
                userGroupService.getParentUserGroupIdentifiers(ldapConnection,
                        bindDn);

        // Return AuthenticatedUser if bind succeeds
        LDAPAuthenticatedUser authenticatedUser = authenticatedUserProvider.get();
        authenticatedUser.init(credentials, getAttributeTokens(ldapConnection,
                bindDn), effectiveGroups, bindDn);

        return authenticatedUser;

    }

    // Always disconnect
    finally {
        ldapConnection.close();
    }

}
 
Example #20
Source File: LdapDirectoryServerConnectionTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
public void testUserCreation() {
        LdapConnection connection = new LdapNetworkConnection( "localhost", 10389 );
        try {
            connection.bind( "uid=admin,ou=system", "secret" );

            connection.add(new DefaultEntry(
                    "ou=acsadmins,ou=users,ou=system",
            "objectClass: organizationalUnit",
// might also need to be           objectClass: top
            "ou: acsadmins"
            ));
            connection.add(new DefaultEntry(
                    "uid=dahn,ou=acsadmins,ou=users,ou=system",
                    "objectClass: inetOrgPerson",
                    "objectClass: top",
                    "cn: dahn",
                    "sn: Hoogland",
                    "givenName: Daan",
                    "mail: [email protected]",
                    "uid: dahn"
            ));

            connection.add(
                    new DefaultEntry(
                            "cn=JuniorAdmins,ou=groups,ou=system", // The Dn
                            "objectClass: groupOfUniqueNames",
                            "ObjectClass: top",
                            "cn: JuniorAdmins",
                            "uniqueMember: uid=dahn,ou=acsadmins,ou=system,ou=users") );

            assertTrue( connection.exists( "cn=JuniorAdmins,ou=groups,ou=system" ) );
            assertTrue( connection.exists( "uid=dahn,ou=acsadmins,ou=users,ou=system" ) );

            Entry ourUser = connection.lookup("uid=dahn,ou=acsadmins,ou=users,ou=system");
            ourUser.add("memberOf", "cn=JuniorAdmins,ou=groups,ou=system");
            AddRequest addRequest = new AddRequestImpl();
            addRequest.setEntry( ourUser );
            AddResponse response = connection.add( addRequest );
            assertNotNull( response );
            // We would need to either
//            assertEquals( ResultCodeEnum.SUCCESS, response.getLdapResult().getResultCode() );
            // or have the automatic virtual attribute

            List<LdapUser> usahs = ldapManager.getUsers(1L);
            assertEquals("now an admin and a normal user should be present",2, usahs.size());

        } catch (LdapException | NoLdapUserMatchingQueryException e) {
            fail(e.getLocalizedMessage());
        }
    }
 
Example #21
Source File: UserGroupService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Returns all Guacamole user groups accessible to the user currently bound
 * under the given LDAP connection.
 *
 * @param ldapConnection
 *     The current connection to the LDAP server, associated with the
 *     current user.
 *
 * @return
 *     All user groups accessible to the user currently bound under the
 *     given LDAP connection, as a map of user group identifier to
 *     corresponding UserGroup object.
 *
 * @throws GuacamoleException
 *     If an error occurs preventing retrieval of user groups.
 */
public Map<String, UserGroup> getUserGroups(LdapNetworkConnection ldapConnection)
        throws GuacamoleException {

    // Do not return any user groups if base DN is not specified
    Dn groupBaseDN = confService.getGroupBaseDN();
    if (groupBaseDN == null)
        return Collections.emptyMap();

    // Retrieve all visible user groups which are not guacConfigGroups
    Collection<String> attributes = confService.getGroupNameAttributes();
    List<Entry> results = queryService.search(
        ldapConnection,
        groupBaseDN,
        getGroupSearchFilter(),
        attributes,
        null
    );

    // Convert retrieved user groups to map of identifier to Guacamole
    // user group object
    return queryService.asMap(results, entry -> {

        // Translate entry into UserGroup object having proper identifier
        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().toString());
        return null;

    });

}
 
Example #22
Source File: UserGroupService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the LDAP entries representing all user groups that the given
 * user is a member of. Only user groups which are readable by the current
 * user will be retrieved.
 *
 * @param ldapConnection
 *     The current connection to the LDAP server, associated with the
 *     current user.
 *
 * @param userDN
 *     The DN of the user whose group membership should be retrieved.
 *
 * @return
 *     The LDAP entries representing all readable parent user groups of the
 *     user having the given DN.
 *
 * @throws GuacamoleException
 *     If an error occurs preventing retrieval of user groups.
 */
public List<Entry> getParentUserGroupEntries(LdapNetworkConnection ldapConnection,
        Dn userDN) throws GuacamoleException {

    // Do not return any user groups if base DN is not specified
    Dn groupBaseDN = confService.getGroupBaseDN();
    if (groupBaseDN == null)
        return Collections.emptyList();

    // memberAttribute specified in properties could contain DN or username 
    MemberAttributeType memberAttributeType = confService.getMemberAttributeType();
    String userIDorDN = userDN.toString();
    if (memberAttributeType == MemberAttributeType.UID) {
        // Retrieve user objects with userDN
        List<Entry> userEntries = queryService.search(
            ldapConnection,
            userDN,
            confService.getUserSearchFilter(),
            0);
        // ... there can surely only be one
        if (userEntries.size() != 1)
            logger.warn("user DN \"{}\" does not return unique value "
                    + "and will be ignored", userDN.toString());
        else {
            // determine unique identifier for user
            Entry userEntry = userEntries.get(0);
            Collection<String> userAttributes = confService.getUsernameAttributes();
            try {
                userIDorDN = queryService.getIdentifier(userEntry,
                                     userAttributes);
            }
            catch (LdapInvalidAttributeValueException e) {
                logger.error("User group missing identifier: {}",
                        e.getMessage());
                logger.debug("LDAP exception while getting "
                        + "group identifier.", e);
            }
        }
    }

    // Get all groups the user is a member of starting at the groupBaseDN,
    // excluding guacConfigGroups
    return queryService.search(
        ldapConnection,
        groupBaseDN,
        getGroupSearchFilter(),
        Collections.singleton(confService.getMemberAttribute()),
        userIDorDN
    );

}
 
Example #23
Source File: CachedLDAPAuthorizationModuleLegacyTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
protected LdapConnection getLdapConnection() throws LdapException, IOException {
   LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort());
   connection.bind(new Dn("uid=admin,ou=system"), "secret");
   return connection;
}
 
Example #24
Source File: CachedLDAPAuthorizationModuleOpenLDAPTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
protected LdapConnection getLdapConnection() throws LdapException, IOException {
   LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT);
   connection.bind(new Dn(LDAP_USER), LDAP_PASS);
   return connection;
}
 
Example #25
Source File: CachedLDAPAuthorizationModuleLegacyOpenLDAPTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
protected LdapConnection getLdapConnection() throws LdapException, IOException {
   LdapConnection connection = new LdapNetworkConnection(LDAP_HOST, LDAP_PORT);
   connection.bind(new Dn(LDAP_USER), LDAP_PASS);
   return connection;
}
 
Example #26
Source File: CachedLDAPAuthorizationModuleTest.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
@Override
protected LdapConnection getLdapConnection() throws Exception {
   LdapConnection connection = new LdapNetworkConnection("localhost", getLdapServer().getPort());
   connection.bind(new Dn("uid=admin,ou=system"), "secret");
   return connection;
}
 
Example #27
Source File: LdapUserManager.java    From azkaban-ldap-usermanager with MIT License 4 votes vote down vote up
private LdapConnection getLdapConnection() throws LdapException {
    LdapConnection connection = new LdapNetworkConnection(ldapHost, ldapPort, useSsl);
    connection.bind(ldapBindAccount, ldapBindPassword);
    return connection;
}
 
Example #28
Source File: UserService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of all DNs corresponding to the users having the given
 * username. If multiple username attributes are defined, or if uniqueness
 * is not enforced across the username attribute, it is possible that this
 * will return multiple DNs.
 *
 * @param ldapConnection
 *     The connection to the LDAP server to use when querying user DNs.
 *
 * @param username
 *     The username of the user whose corresponding user account DNs are
 *     to be retrieved.
 *
 * @return
 *     A list of all DNs corresponding to the users having the given
 *     username. If no such DNs exist, this list will be empty.
 *
 * @throws GuacamoleException
 *     If an error occurs while querying the user DNs, or if the username
 *     attribute property cannot be parsed within guacamole.properties.
 */
public List<Dn> getUserDNs(LdapNetworkConnection ldapConnection,
        String username) throws GuacamoleException {

    // Retrieve user objects having a matching username
    List<Entry> results = queryService.search(ldapConnection,
            confService.getUserBaseDN(),
            confService.getUserSearchFilter(),
            confService.getUsernameAttributes(),
            username);

    // Build list of all DNs for retrieved users
    List<Dn> userDNs = new ArrayList<>(results.size());
    results.forEach(entry -> userDNs.add(entry.getDn()));

    return userDNs;

}
 
Example #29
Source File: UserService.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a list of all DNs corresponding to the users having the given
 * username. If multiple username attributes are defined, or if uniqueness
 * is not enforced across the username attribute, it is possible that this
 * will return multiple DNs.
 *
 * @param ldapConnection
 *     The connection to the LDAP server to use when querying user DNs.
 *
 * @param username
 *     The username of the user whose corresponding user account DNs are
 *     to be retrieved.
 *
 * @return
 *     A list of all DNs corresponding to the users having the given
 *     username. If no such DNs exist, this list will be empty.
 *
 * @throws GuacamoleException
 *     If an error occurs while querying the user DNs, or if the username
 *     attribute property cannot be parsed within guacamole.properties.
 */
public List<Dn> getUserDNs(LdapNetworkConnection ldapConnection,
        String username) throws GuacamoleException {

    // Retrieve user objects having a matching username
    List<Entry> results = queryService.search(ldapConnection,
            confService.getUserBaseDN(),
            confService.getUserSearchFilter(),
            confService.getUsernameAttributes(),
            username);

    // Build list of all DNs for retrieved users
    List<Dn> userDNs = new ArrayList<>(results.size());
    results.forEach(entry -> userDNs.add(entry.getDn()));

    return userDNs;

}
 
Example #30
Source File: LDAPUserContext.java    From guacamole-client with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes this UserContext using the provided AuthenticatedUser and
 * LdapNetworkConnection.
 *
 * @param user
 *     The AuthenticatedUser representing the user that authenticated. This
 *     user may have been authenticated by a different authentication
 *     provider (not LDAP).
 *
 * @param ldapConnection
 *     The connection to the LDAP server to use when querying accessible
 *     Guacamole users and connections.
 *
 * @throws GuacamoleException
 *     If associated data stored within the LDAP directory cannot be
 *     queried due to an error.
 */
public void init(AuthenticatedUser user, LdapNetworkConnection ldapConnection)
        throws GuacamoleException {

    // Query all accessible users
    userDirectory = new SimpleDirectory<>(
        userService.getUsers(ldapConnection)
    );

    // Query all accessible user groups
    userGroupDirectory = new SimpleDirectory<>(
        userGroupService.getUserGroups(ldapConnection)
    );

    // Query all accessible connections
    connectionDirectory = new SimpleDirectory<>(
        connectionService.getConnections(user, ldapConnection)
    );

    // Root group contains only connections
    rootGroup = new SimpleConnectionGroup(
        LDAPAuthenticationProvider.ROOT_CONNECTION_GROUP,
        LDAPAuthenticationProvider.ROOT_CONNECTION_GROUP,
        connectionDirectory.getIdentifiers(),
        Collections.<String>emptyList()
    );

    // Init self with basic permissions
    self = new SimpleUser(user.getIdentifier()) {

        @Override
        public ObjectPermissionSet getUserPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(userDirectory.getIdentifiers());
        }

        @Override
        public ObjectPermissionSet getUserGroupPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(userGroupDirectory.getIdentifiers());
        }

        @Override
        public ObjectPermissionSet getConnectionPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(connectionDirectory.getIdentifiers());
        }

        @Override
        public ObjectPermissionSet getConnectionGroupPermissions() throws GuacamoleException {
            return new SimpleObjectPermissionSet(Collections.singleton(LDAPAuthenticationProvider.ROOT_CONNECTION_GROUP));
        }

    };

}