List of usage examples for javax.naming NamingEnumeration next
public T next() throws NamingException;
From source file:com.funambol.LDAP.security.LDAPUserProvisioningOfficer.java
/** * return the user dn of an ldap entry/*from ww w. j a v a 2 s . c o m*/ * * search: base, filter, attrs, user, pass * @return */ protected SearchResult ldapSearch(String bindUser, String bindPass, String base, String filter, String[] attributes) { SearchResult ret = null; Hashtable<String, Object> bindEnv = new Hashtable<String, Object>(11); bindEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); bindEnv.put(Context.PROVIDER_URL, getLdapUrl()); // remove null attributes List<String> goodAttributes = new ArrayList<String>(); for (String s : attributes) { if (s != null) { goodAttributes.add(s); } } // get the DN DirContext authenticationContext; try { SearchControls ctls = new SearchControls(); ctls.setCountLimit(1); ctls.setReturningObjFlag(true); ctls.setReturningAttributes(goodAttributes.toArray(new String[0])); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Authenticate as User and password if (bindUser != null && bindPass != null) { log.debug("NBinding with credential as user: " + bindUser); bindEnv.put(Context.SECURITY_AUTHENTICATION, "simple"); bindEnv.put(Context.SECURITY_PRINCIPAL, bindUser); bindEnv.put(Context.SECURITY_CREDENTIALS, bindPass); } authenticationContext = new InitialDirContext(bindEnv); // %u, %d in baseDN are still expanded NamingEnumeration<SearchResult> answer; try { answer = authenticationContext.search(base, filter, ctls); if (answer.hasMore()) { ret = (SearchResult) answer.next(); } } catch (NamingException e) { log.warn("Error while searching user with filter [" + filter + "]: " + e.getMessage()); } authenticationContext.close(); return ret; } catch (NamingException e) { log.error("Error while creating context: " + e.getMessage()); if (e.getCause() != null) { log.error("Error is: " + e.getCause().getMessage()); } return null; } }
From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java
/** * Resolves all the groups that the user is in. * * We now use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms680275(v=vs.85).aspx">tokenGroups</a> * attribute, which is a computed attribute that lists all the SIDs of the groups that the user is directly/indirectly in. * We then use that to retrieve all the groups in one query and resolve their canonical names. * * @param userDN//from www . j ava2 s . c o m * User's distinguished name. * @param context Used for making queries. */ private Set<GrantedAuthority> resolveGroups(String domainDN, String userDN, DirContext context) throws NamingException { if (userDN.contains("/")) { userDN = userDN.replace("/", "\\/"); } Set<GrantedAuthority> groups = new HashSet<GrantedAuthority>(); LOGGER.log(Level.FINER, "Looking up group of {0}", userDN); Attributes id = context.getAttributes(userDN, new String[] { "tokenGroups", "memberOf", "CN" }); Attribute tga = id.get("tokenGroups"); if (tga == null) { // tga will be null if you are not using a global catalogue // or if the user is not actually a member of any security groups. LOGGER.log(Level.FINE, "Failed to retrieve tokenGroups for {0}", userDN); // keep on trucking as we can still use memberOf for Distribution Groups. } else { // build up the query to retrieve all the groups StringBuilder query = new StringBuilder("(|"); List<byte[]> sids = new ArrayList<byte[]>(); NamingEnumeration<?> tokenGroups = tga.getAll(); while (tokenGroups.hasMore()) { byte[] gsid = (byte[]) tokenGroups.next(); query.append("(objectSid={" + sids.size() + "})"); sids.add(gsid); } tokenGroups.close(); query.append(")"); NamingEnumeration<SearchResult> renum = new LDAPSearchBuilder(context, domainDN).subTreeScope() .returns("cn").search(query.toString(), sids.toArray()); parseMembers(userDN, groups, renum); renum.close(); } {/* stage 2: use memberOf to find groups that aren't picked up by tokenGroups. This includes distribution groups */ LOGGER.fine("Stage 2: looking up via memberOf"); while (true) { switch (groupLookupStrategy) { case TOKENGROUPS: // no extra lookup - ever. return groups; case AUTO: // try the accurate one first, and if it's too slow fall back to recursive in the hope that it's faster long start = System.nanoTime(); boolean found = false; long duration = 0; try { found = chainGroupLookup(domainDN, userDN, context, groups); duration = TimeUnit2.NANOSECONDS.toSeconds(System.nanoTime() - start); } catch (TimeLimitExceededException e) { LOGGER.log(Level.WARNING, "The LDAP request did not terminate within the specified time limit. AD will fall back to recursive lookup", e); } catch (NamingException e) { if (e.getMessage().contains("LDAP response read timed out")) { LOGGER.log(Level.WARNING, "LDAP response read time out. AD will fall back to recursive lookup", e); } else { throw e; } } if (!found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension timed out after {0} seconds. Falling back to recursive group lookup strategy for this and future queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else if (found && duration >= 10) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension matched user's groups but took {0} seconds to run. Switching to recursive lookup for future group lookup queries", duration); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; return groups; } else if (!found) { LOGGER.log(Level.WARNING, "Group lookup via Active Directory's 'LDAP_MATCHING_RULE_IN_CHAIN' extension failed. Falling back to recursive group lookup strategy for this and future queries"); groupLookupStrategy = GroupLookupStrategy.RECURSIVE; continue; } else { // it run fast enough, so let's stick to it groupLookupStrategy = GroupLookupStrategy.CHAIN; return groups; } case RECURSIVE: recursiveGroupLookup(context, id, groups); return groups; case CHAIN: chainGroupLookup(domainDN, userDN, context, groups); return groups; } } } }
From source file:de.fiz.ddb.aas.utils.LDAPEngineUtility.java
protected Privilege convertLdapGroupToOrganizationPrivilegeWithUsers( NamingEnumeration<SearchResult> pPrivilegesSearchResults) throws NamingException, IllegalAccessException { Privilege vOrgPrivilege = null;/*from www . j a va 2s . c o m*/ try { if ((pPrivilegesSearchResults != null) && (pPrivilegesSearchResults.hasMore())) { vOrgPrivilege = this.convertLdapGroupToOrgPriv(pPrivilegesSearchResults.next()); } } finally { // -- releases this context's resources immediately, instead of // waiting for the garbage collector if (pPrivilegesSearchResults != null) { try { pPrivilegesSearchResults.close(); pPrivilegesSearchResults = null; } catch (NamingException ex) { } } } return vOrgPrivilege; }
From source file:org.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java
public Map<String, String> findLdapUserDetails(String userName) { Properties systemConfig = systemManager.getSystemConfiguration(subjectManager.getOverlord()); HashMap<String, String> userDetails = new HashMap<String, String>(); // Load our LDAP specific properties Properties env = getProperties(systemConfig); // Load the BaseDN String baseDN = (String) systemConfig.get(RHQConstants.LDAPBaseDN); // Load the LoginProperty String loginProperty = (String) systemConfig.get(RHQConstants.LDAPLoginProperty); if (loginProperty == null) { // Use the default loginProperty = "cn"; }/* w w w .j a v a 2 s. c o m*/ // Load any information we may need to bind String bindDN = (String) systemConfig.get(RHQConstants.LDAPBindDN); String bindPW = (String) systemConfig.get(RHQConstants.LDAPBindPW); // Load any search filter String searchFilter = (String) systemConfig.get(RHQConstants.LDAPFilter); if (bindDN != null) { env.setProperty(Context.SECURITY_PRINCIPAL, bindDN); env.setProperty(Context.SECURITY_CREDENTIALS, bindPW); env.setProperty(Context.SECURITY_AUTHENTICATION, "simple"); } try { InitialLdapContext ctx = new InitialLdapContext(env, null); SearchControls searchControls = getSearchControls(); // Add the search filter if specified. This only allows for a single search filter.. i.e. foo=bar. String filter; if ((searchFilter != null) && (searchFilter.length() != 0)) { filter = "(&(" + loginProperty + "=" + userName + ")" + "(" + searchFilter + "))"; } else { filter = "(" + loginProperty + "=" + userName + ")"; } log.debug("Using LDAP filter [" + filter + "] to locate user details for " + userName); // Loop through each configured base DN. It may be useful // in the future to allow for a filter to be configured for // each BaseDN, but for now the filter will apply to all. String[] baseDNs = baseDN.split(BASEDN_DELIMITER); for (int x = 0; x < baseDNs.length; x++) { NamingEnumeration<SearchResult> answer = ctx.search(baseDNs[x], filter, searchControls); if (!answer.hasMoreElements()) { //BZ:582471- ldap api bug change log.debug("User " + userName + " not found for BaseDN " + baseDNs[x]); // Nothing found for this DN, move to the next one if we have one. continue; } // We use the first match SearchResult si = answer.next(); //generate the DN String userDN = null; try { userDN = si.getNameInNamespace(); } catch (UnsupportedOperationException use) { userDN = si.getName(); if (userDN.startsWith("\"")) { userDN = userDN.substring(1, userDN.length()); } if (userDN.endsWith("\"")) { userDN = userDN.substring(0, userDN.length() - 1); } userDN = userDN + "," + baseDNs[x]; } userDetails.put("dn", userDN); // Construct the UserDN NamingEnumeration<String> keys = si.getAttributes().getIDs(); while (keys.hasMore()) { String key = keys.next(); Attribute value = si.getAttributes().get(key); if ((value != null) && (value.get() != null)) { userDetails.put(key, value.get().toString()); } } return userDetails; } return userDetails; } catch (NamingException e) { throw new RuntimeException(e); } }
From source file:net.spfbl.core.Analise.java
public static TreeSet<String> getIPv4Set(String hostname) { TreeSet<String> ipv4Set = new TreeSet<String>(); try {/* ww w . j a va 2 s.com*/ Attributes attributesA = Server.getAttributesDNS(hostname, new String[] { "A" }); if (attributesA != null) { Enumeration enumerationA = attributesA.getAll(); while (enumerationA.hasMoreElements()) { Attribute attributeA = (Attribute) enumerationA.nextElement(); NamingEnumeration enumeration = attributeA.getAll(); while (enumeration.hasMoreElements()) { String address = (String) enumeration.next(); if (SubnetIPv4.isValidIPv4(address)) { address = SubnetIPv4.normalizeIPv4(address); ipv4Set.add(address); } } } } } catch (NameNotFoundException ex) { return null; } catch (NamingException ex) { // Ignore. } return ipv4Set; }
From source file:org.wso2.carbon.directory.server.manager.internal.LDAPServerStoreManager.java
public boolean isValidPassword(String serverName, Object existingCredentials) throws DirectoryServerManagerException { DirContext dirContext;/*from w ww . j a va 2 s. c o m*/ try { dirContext = this.connectionSource.getContext(); } catch (UserStoreException e) { throw new DirectoryServerManagerException("Unable to retrieve directory connection.", e); } //first search the existing user entry. String searchBase = this.realmConfiguration.getUserStoreProperty(LDAPConstants.USER_SEARCH_BASE); String searchFilter = getServicePrincipleFilter(serverName); SearchControls searchControls = new SearchControls(); searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchControls.setReturningAttributes(new String[] { LDAPServerManagerConstants.LDAP_PASSWORD }); try { NamingEnumeration<SearchResult> namingEnumeration = dirContext.search(searchBase, searchFilter, searchControls); // here we assume only one user while (namingEnumeration.hasMore()) { SearchResult searchResult = namingEnumeration.next(); Attributes attributes = searchResult.getAttributes(); Attribute userPassword = attributes.get(LDAPServerManagerConstants.LDAP_PASSWORD); NamingEnumeration passwords = userPassword.getAll(); String passwordHashMethod = null; if (passwords.hasMore()) { byte[] byteArray = (byte[]) passwords.next(); String password = new String(byteArray, StandardCharsets.UTF_8); if (password.startsWith("{")) { passwordHashMethod = password.substring(password.indexOf("{") + 1, password.indexOf("}")); } return password.equals(getPasswordToStore((String) existingCredentials, passwordHashMethod)); } } } catch (NamingException e) { log.error("Failed, validating password. Can not access the directory service", e); throw new DirectoryServerManagerException( "Failed, validating password. " + "Can not access the directory service", e); } finally { try { JNDIUtil.closeContext(dirContext); } catch (UserStoreException e) { log.error("Unable to close directory context.", e); } } return false; }
From source file:net.officefloor.plugin.web.http.security.store.JndiLdapCredentialStoreTest.java
/** * Ensure correct credentials.//from ww w .j a v a 2 s .c o m */ @SuppressWarnings("unchecked") public void testCredentials() throws Exception { // Create the expected credentials final String expectedRaw = "daniel:officefloor:password"; MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(expectedRaw.getBytes(US_ASCII)); final byte[] expectedCredentials = digest.digest(); // Obtain the encoded credentials final String encodedCredentials = Base64.encodeBase64String(expectedCredentials).trim(); assertEquals("Incorrect encoded credentials", "msu723GSLovbwuaPnaLcnQ==", encodedCredentials); // Mocks final NamingEnumeration<SearchResult> searchResults = this.createMock(NamingEnumeration.class); final Attributes attributes = this.createMock(Attributes.class); final Attribute attribute = this.createMock(Attribute.class); final NamingEnumeration<?> userPasswords = this.createMock(NamingEnumeration.class); // Objects final SearchResult searchResult = new SearchResult("uid=daniel", null, attributes); searchResult.setNameInNamespace("uid=daniel,ou=People,dc=officefloor,dc=net"); // Record this.recordReturn(this.context, this.context.search("ou=People,dc=officefloor,dc=net", "(&(objectClass=inetOrgPerson)(uid=daniel))", null), searchResults); this.recordReturn(searchResults, searchResults.hasMore(), true); this.recordReturn(searchResults, searchResults.next(), searchResult); this.recordReturn(this.context, this.context.getAttributes("uid=daniel,ou=People,dc=officefloor,dc=net"), attributes); this.recordReturn(attributes, attributes.get("userPassword"), attribute); this.recordReturn(attribute, attribute.getAll(), userPasswords); this.recordReturn(userPasswords, userPasswords.hasMore(), true); this.recordReturn(userPasswords, userPasswords.next(), "Plain Text Password".getBytes(US_ASCII)); this.recordReturn(userPasswords, userPasswords.hasMore(), true); this.recordReturn(userPasswords, userPasswords.next(), ("{MD5}" + encodedCredentials).getBytes(US_ASCII)); // Test this.replayMockObjects(); CredentialEntry entry = this.store.retrieveCredentialEntry("daniel", "REALM"); byte[] actualCredentials = entry.retrieveCredentials(); this.verifyMockObjects(); // Validate correct value assertEquals("Incorrect credential byte length", expectedCredentials.length, actualCredentials.length); for (int i = 0; i < expectedCredentials.length; i++) { assertEquals("Incorrect credential byte " + i, expectedCredentials[i], actualCredentials[i]); } }
From source file:com.wfp.utils.LDAPUtils.java
public static String getUserImageAsString(String uid) { String base64String = null; if (uid != null && uid != "") { // Specify the attributes to return String searchFilter = "(&" + FILTER_LDAP_USERS + "((uid=" + uid + ")))"; String searchBase = LDAP_FILTER_URL + "uid=" + uid + "," + LDAP_BASE; String returnedAtts[] = { "" + PROPERTY_IMAGE }; // Specify the search scope SearchControls searchCtls = new SearchControls(); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); searchCtls.setReturningAttributes(returnedAtts); // Search for objects using the filter try {/*w w w .j a v a 2s. c o m*/ NamingEnumeration results = getSearchResults(getLDAPContext(), searchCtls, searchFilter, searchBase); while (results.hasMore()) { SearchResult searchResult = (SearchResult) results.next(); Attributes attributes = searchResult.getAttributes(); Attribute attr = attributes.get(PROPERTY_IMAGE); if (attr != null) base64String = new String( org.apache.commons.codec.binary.Base64.encodeBase64((byte[]) attr.get())); } } catch (NamingException e) { Logger.error(" Error occured while fetching user image 1334: getUserImageBytes(String uid):[" + e.getLocalizedMessage() + "]", LDAPUtils.class); } } return base64String; }
From source file:net.spfbl.core.Analise.java
public static TreeSet<String> getIPv6Set(String hostname) { TreeSet<String> ipv6Set = new TreeSet<String>(); try {//ww w . j a v a2 s. co m Attributes attributesAAAA = Server.getAttributesDNS(hostname, new String[] { "AAAA" }); if (attributesAAAA != null) { Enumeration enumerationAAAA = attributesAAAA.getAll(); while (enumerationAAAA.hasMoreElements()) { Attribute attributeAAAA = (Attribute) enumerationAAAA.nextElement(); NamingEnumeration enumeration = attributeAAAA.getAll(); while (enumeration.hasMoreElements()) { String address = (String) enumeration.next(); if (SubnetIPv6.isValidIPv6(address)) { address = SubnetIPv6.normalizeIPv6(address); ipv6Set.add(address); } } } } } catch (NameNotFoundException ex) { return null; } catch (NamingException ex) { // Ignore. } return ipv6Set; }
From source file:ldap.SearchUtility.java
/** * * @param searchBase/*w ww . j a v a 2 s . c o m*/ * @param regexp * @param pageSize * @param pageNumber * @return a list of matching users. * @throws NamingException */ public List<Entry> getUsers(LdapName searchBase, String regexp, int pageSize, int pageNumber, ArrayList<String> attributes, DirContext context) throws NamingException { Pattern pattern = null; if (regexp != null) pattern = Pattern.compile(regexp); /* * Figure out an ldap search filter. Note that unless an ORDERING matching rule is defined on the server * for the attribute we are searching (and they usually aren't, since it requires extra indexing on the * server), we cannot use ldap greater than / less than search filters to find * a range of users, and have to do this search in code using a regular expression. */ //String filter = "(objectClass=" + Config.USER_OBJECTCLASS + ")"; String filter = ""; if (LdapConstants.ldapObjectClassEmployeeEnable) { filter = "(objectClass=" + LdapConstants.ldapObjectClassEmployee + ")"; } SearchControls controls = getSearchControls(); String[] attributesToReturn; if (attributes == null) { attributesToReturn = null; // a JNDI special value that means 'return everything' } else { //attributes.add(Config.USER_NAMING_ATT); attributes.add(LdapConstants.ldapAttrUid); attributesToReturn = attributes.toArray(new String[] {}); } if (controls != null) { controls.setReturningAttributes(attributesToReturn); } else { logger.info("controls is null"); } // do the directory search NamingEnumeration<SearchResult> userResults = context.search(searchBase, filter, controls); if (userResults == null) { logger.info("userResults is Null in getUsers()"); return null; } else { // parse the results, looking for entries that match our regexp ArrayList<Entry> users = new ArrayList<Entry>(); while (userResults.hasMore()) { SearchResult userResult = userResults.next(); Entry userEntry = new Entry(userResult); //String text = userEntry.getValue(Config.USER_NAMING_ATT).toUpperCase(); String text = userEntry.getValue(LdapConstants.ldapAttrUid).toUpperCase(); if (pattern == null) { users.add(userEntry); } else { Matcher matcher = pattern.matcher(text); if (matcher.find()) { users.add(userEntry); } } } // sort them alphabeticaly by user naming attribute Collections.sort(users); // trim the results to the page requested (if any) if (pageSize > 0) { ArrayList<Entry> userPage = new ArrayList<Entry>(pageSize); int startPos = pageSize * pageNumber; int size = users.size(); for (int i = startPos; i < (startPos + pageSize); i++) { if (i < size) { userPage.add(users.get(i)); } } users = userPage; } // add 'synthetic' attributes for for (Entry user : users) { fillInSyntheticAttributes(user); } // return the final user list return users; } // else }