Search in sources :

Example 26 with NamingException

use of javax.naming.NamingException in project hadoop by apache.

the class LdapGroupsMapping method getGroupNames.

/* Helper function to get group name from search results.
  */
void getGroupNames(SearchResult groupResult, Collection<String> groups, Collection<String> groupDNs, boolean doGetDNs) throws NamingException {
    Attribute groupName = groupResult.getAttributes().get(groupNameAttr);
    if (groupName == null) {
        throw new NamingException("The group object does not have " + "attribute '" + groupNameAttr + "'.");
    }
    groups.add(groupName.get().toString());
    if (doGetDNs) {
        groupDNs.add(groupResult.getNameInNamespace());
    }
}
Also used : Attribute(javax.naming.directory.Attribute) NamingException(javax.naming.NamingException)

Example 27 with NamingException

use of javax.naming.NamingException in project hadoop by apache.

the class LdapGroupsMapping method lookupPosixGroup.

/**
   * Look up groups using posixGroups semantics. Use posix gid/uid to find
   * groups of the user.
   *
   * @param result the result object returned from the prior user lookup.
   * @param c the context object of the LDAP connection.
   * @return an object representing the search result.
   *
   * @throws NamingException if the server does not support posixGroups
   * semantics.
   */
private NamingEnumeration<SearchResult> lookupPosixGroup(SearchResult result, DirContext c) throws NamingException {
    String gidNumber = null;
    String uidNumber = null;
    Attribute gidAttribute = result.getAttributes().get(posixGidAttr);
    Attribute uidAttribute = result.getAttributes().get(posixUidAttr);
    String reason = "";
    if (gidAttribute == null) {
        reason = "Can't find attribute '" + posixGidAttr + "'.";
    } else {
        gidNumber = gidAttribute.get().toString();
    }
    if (uidAttribute == null) {
        reason = "Can't find attribute '" + posixUidAttr + "'.";
    } else {
        uidNumber = uidAttribute.get().toString();
    }
    if (uidNumber != null && gidNumber != null) {
        return c.search(baseDN, "(&" + groupSearchFilter + "(|(" + posixGidAttr + "={0})" + "(" + groupMemberAttr + "={1})))", new Object[] { gidNumber, uidNumber }, SEARCH_CONTROLS);
    }
    throw new NamingException("The server does not support posixGroups " + "semantics. Reason: " + reason + " Returned user object: " + result.toString());
}
Also used : Attribute(javax.naming.directory.Attribute) NamingException(javax.naming.NamingException)

Example 28 with NamingException

use of javax.naming.NamingException in project hadoop by apache.

the class LdapGroupsMapping method doGetGroups.

/**
   * Perform LDAP queries to get group names of a user.
   *
   * Perform the first LDAP query to get the user object using the user's name.
   * If one-query is enabled, retrieve the group names from the user object.
   * If one-query is disabled, or if it failed, perform the second query to
   * get the groups.
   *
   * @param user user name
   * @return a list of group names for the user. If the user can not be found,
   * return an empty string array.
   * @throws NamingException if unable to get group names
   */
List<String> doGetGroups(String user, int goUpHierarchy) throws NamingException {
    DirContext c = getDirContext();
    // Search for the user. We'll only ever need to look at the first result
    NamingEnumeration<SearchResult> results = c.search(baseDN, userSearchFilter, new Object[] { user }, SEARCH_CONTROLS);
    // return empty list if the user can not be found.
    if (!results.hasMoreElements()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("doGetGroups(" + user + ") returned no groups because the " + "user is not found.");
        }
        return new ArrayList<String>();
    }
    SearchResult result = results.nextElement();
    List<String> groups = null;
    if (useOneQuery) {
        try {
            /**
         * For Active Directory servers, the user object has an attribute
         * 'memberOf' that represents the DNs of group objects to which the
         * user belongs. So the second query may be skipped.
         */
            Attribute groupDNAttr = result.getAttributes().get(memberOfAttr);
            if (groupDNAttr == null) {
                throw new NamingException("The user object does not have '" + memberOfAttr + "' attribute." + "Returned user object: " + result.toString());
            }
            groups = new ArrayList<String>();
            NamingEnumeration groupEnumeration = groupDNAttr.getAll();
            while (groupEnumeration.hasMore()) {
                String groupDN = groupEnumeration.next().toString();
                groups.add(getRelativeDistinguishedName(groupDN));
            }
        } catch (NamingException e) {
            // If the first lookup failed, fall back to the typical scenario.
            LOG.info("Failed to get groups from the first lookup. Initiating " + "the second LDAP query using the user's DN.", e);
        }
    }
    if (groups == null || groups.isEmpty() || goUpHierarchy > 0) {
        groups = lookupGroup(result, c, goUpHierarchy);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("doGetGroups(" + user + ") returned " + groups);
    }
    return groups;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) SearchResult(javax.naming.directory.SearchResult) NamingException(javax.naming.NamingException) NamingEnumeration(javax.naming.NamingEnumeration) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext)

Example 29 with NamingException

use of javax.naming.NamingException in project hadoop by apache.

the class TestLdapGroupsMapping method testLdapConnectionTimeout.

/**
   * Test that if the {@link LdapGroupsMapping#CONNECTION_TIMEOUT} is set in the
   * configuration, the LdapGroupsMapping connection will timeout by this value
   * if it does not get a LDAP response from the server.
   * @throws IOException
   * @throws InterruptedException
   */
@Test(timeout = 30000)
public void testLdapConnectionTimeout() throws IOException, InterruptedException {
    // 3s
    final int connectionTimeoutMs = 3 * 1000;
    try (ServerSocket serverSock = new ServerSocket(0)) {
        final CountDownLatch finLatch = new CountDownLatch(1);
        // Below we create a LDAP server which will accept a client request;
        // but it will never reply to the bind (connect) request.
        // Client of this LDAP server is expected to get a connection timeout.
        final Thread ldapServer = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    try (Socket ignored = serverSock.accept()) {
                        finLatch.await();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        ldapServer.start();
        final LdapGroupsMapping mapping = new LdapGroupsMapping();
        final Configuration conf = new Configuration();
        conf.set(LdapGroupsMapping.LDAP_URL_KEY, "ldap://localhost:" + serverSock.getLocalPort());
        conf.setInt(CONNECTION_TIMEOUT, connectionTimeoutMs);
        mapping.setConf(conf);
        try {
            mapping.doGetGroups("hadoop", 1);
            fail("The LDAP query should have timed out!");
        } catch (NamingException ne) {
            LOG.debug("Got the exception while LDAP querying: ", ne);
            assertExceptionContains("LDAP response read timed out, timeout used:" + connectionTimeoutMs + "ms", ne);
            assertFalse(ne.getMessage().contains("remaining name"));
        } finally {
            finLatch.countDown();
        }
        ldapServer.join();
    }
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) ServerSocket(java.net.ServerSocket) NamingException(javax.naming.NamingException) CountDownLatch(java.util.concurrent.CountDownLatch) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) NamingException(javax.naming.NamingException) IOException(java.io.IOException) CommunicationException(javax.naming.CommunicationException) Test(org.junit.Test)

Example 30 with NamingException

use of javax.naming.NamingException in project hadoop by apache.

the class TestLdapGroupsMapping method testLdapReadTimeout.

/**
   * Test that if the {@link LdapGroupsMapping#READ_TIMEOUT} is set in the
   * configuration, the LdapGroupsMapping query will timeout by this value if
   * it does not get a LDAP response from the server.
   *
   * @throws IOException
   * @throws InterruptedException
   */
@Test(timeout = 30000)
public void testLdapReadTimeout() throws IOException, InterruptedException {
    // 4s
    final int readTimeoutMs = 4 * 1000;
    try (ServerSocket serverSock = new ServerSocket(0)) {
        final CountDownLatch finLatch = new CountDownLatch(1);
        // Below we create a LDAP server which will accept a client request,
        // authenticate it successfully; but it will never reply to the following
        // query request.
        // Client of this LDAP server is expected to get a read timeout.
        final Thread ldapServer = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    try (Socket clientSock = serverSock.accept()) {
                        IOUtils.skipFully(clientSock.getInputStream(), 1);
                        clientSock.getOutputStream().write(AUTHENTICATE_SUCCESS_MSG);
                        finLatch.await();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        ldapServer.start();
        final LdapGroupsMapping mapping = new LdapGroupsMapping();
        final Configuration conf = new Configuration();
        conf.set(LdapGroupsMapping.LDAP_URL_KEY, "ldap://localhost:" + serverSock.getLocalPort());
        conf.setInt(READ_TIMEOUT, readTimeoutMs);
        mapping.setConf(conf);
        try {
            mapping.doGetGroups("hadoop", 1);
            fail("The LDAP query should have timed out!");
        } catch (NamingException ne) {
            LOG.debug("Got the exception while LDAP querying: ", ne);
            assertExceptionContains("LDAP response read timed out, timeout used:" + readTimeoutMs + "ms", ne);
            assertExceptionContains("remaining name", ne);
        } finally {
            finLatch.countDown();
        }
        ldapServer.join();
    }
}
Also used : Configuration(org.apache.hadoop.conf.Configuration) ServerSocket(java.net.ServerSocket) NamingException(javax.naming.NamingException) CountDownLatch(java.util.concurrent.CountDownLatch) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) NamingException(javax.naming.NamingException) IOException(java.io.IOException) CommunicationException(javax.naming.CommunicationException) Test(org.junit.Test)

Aggregations

NamingException (javax.naming.NamingException)1246 InitialContext (javax.naming.InitialContext)417 Context (javax.naming.Context)259 IOException (java.io.IOException)163 Attribute (javax.naming.directory.Attribute)111 DirContext (javax.naming.directory.DirContext)100 SearchResult (javax.naming.directory.SearchResult)98 ArrayList (java.util.ArrayList)95 SQLException (java.sql.SQLException)93 NameNotFoundException (javax.naming.NameNotFoundException)88 Attributes (javax.naming.directory.Attributes)85 DataSource (javax.sql.DataSource)84 Properties (java.util.Properties)77 Reference (javax.naming.Reference)77 InitialDirContext (javax.naming.directory.InitialDirContext)77 Test (org.junit.Test)75 Hashtable (java.util.Hashtable)73 SearchControls (javax.naming.directory.SearchControls)73 HashMap (java.util.HashMap)55 LdapContext (javax.naming.ldap.LdapContext)55