SearchControls constraints = new SearchControls(); if (subTreeSearch) { constraints.setSearchScope (SearchControls.SUBTREE_SCOPE); constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); constraints.setReturningAttributes(new String[] { usernameField }); NamingEnumeration answer = ctx.search("", princSearchFilter, new String[] {LdapManager.sanitizeSearchFilter(principal)}, constraints); Log.debug("LdapAuthorizationMapping: ... search finished"); if (answer == null || !answer.hasMoreElements()) { Log.debug("LdapAuthorizationMapping: Username based on principal '" + principal + "' not found."); return principal; Attributes atrs = ((SearchResult)answer.next()).getAttributes(); Attribute usernameAttribute = atrs.get(usernameField); username = (String) usernameAttribute.get(); try { if (ctx != null) { ctx.close();
/** * Look into A-record at a specific DNS address. * * @return resolved IP addresses or null if no A-record was present */ @Nullable public static List<String> resolveARecord(String rootDomainName) { if (isLocalOrIp(rootDomainName)) { return null; } try { Attributes attrs = getDirContext().getAttributes(rootDomainName, new String[]{A_RECORD_TYPE, CNAME_RECORD_TYPE}); Attribute aRecord = attrs.get(A_RECORD_TYPE); Attribute cRecord = attrs.get(CNAME_RECORD_TYPE); if (aRecord != null && cRecord == null) { List<String> result = new ArrayList<>(); NamingEnumeration<String> entries = (NamingEnumeration<String>) aRecord.getAll(); while (entries.hasMore()) { result.add(entries.next()); } return result; } } catch (Exception e) { logger.warn("Cannot load A-record for eureka server address {}", rootDomainName, e); return null; } return null; }
@Override public void modifyAttributes(Name name, ModificationItem[] mods) throws NamingException { delegating.modifyAttributes(name, mods); }
private void returnDirContext(DirContext context) { try { if (binaryAttributesBackup == null) { context.removeFromEnvironment(ENV_BINARY_ATTRIBUTES); } else { context.addToEnvironment(ENV_BINARY_ATTRIBUTES, binaryAttributesBackup); } context.close(); } catch (NamingException e) { throw log.failedToReturnDirContext(e); } }
private DirContext obtainDirContext() { try { DirContext context = dirContextSupplier.get(); binaryAttributesBackup = context.getEnvironment().get(ENV_BINARY_ATTRIBUTES); context.addToEnvironment(ENV_BINARY_ATTRIBUTES, String.join(" ", certificateAttribute, certificateChainAttribute, keyAttribute)); return context; } catch (NamingException e) { throw log.failedToObtainDirContext(e); } }
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); DirContext ctx = new InitialDirContext(env); Attributes attrs = ctx.getAttributes(lookup, new String[] {"PTR"}); for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) { Attribute attr = (Attribute) ae.next(); for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) { Object elem = vals.nextElement(); if ("PTR".equals(attr.getID()) && elem != null) { return elem.toString(); ctx.close(); } catch (Exception e) {
public static List<String> getGroupsFromLdapUser(String host, String user, String base) throws NamingException { String userFilter = "(uniqueMember=" + user + ")"; SearchControls sc = new SearchControls(); sc.setSearchScope(SearchControls.SUBTREE_SCOPE); sc.setReturningAttributes(new String[]{"cn"}); NamingEnumeration<SearchResult> search = getDirContext(host).search(base, userFilter, sc); List<String> resultList = new ArrayList<>(); while (search.hasMore()) { resultList.add((String) search.next().getAttributes().get("cn").get(0)); } return resultList; }
SearchControls controls = new SearchControls(); controls.setSearchScope(SUBTREE_SCOPE); NamingEnumeration<SearchResult> renum = context.search(toDC(domainName), "(& (userPrincipalName=" + principalName + ")(objectClass=user))", controls); if (!renum.hasMore()) { System.out.println("Cannot locate user information for " + username); System.exit(1); SearchResult result = renum.next(); Attribute memberOf = result.getAttributes().get("memberOf"); if (memberOf != null) {// null if this user belongs to no group at all for (int i = 0; i < memberOf.size(); i++) { Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[] { "CN" }); Attribute att = atts.get("CN"); groups.add(new GrantedAuthorityImpl(att.get().toString()));
SearchControls constraints = new SearchControls(); constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); constraints.setReturningAttributes(new String[] { groupNameField }); NamingEnumeration<SearchResult> answer = ctx.search("", filter, constraints); if (answer == null || !answer.hasMoreElements()) { if (debug) { Log.debug("LdapManager: Group DN based on groupname '" + groupname + "' not found."); String groupDN = answer.next().getName(); if (answer.hasMoreElements()) { if (debug) { Log.debug("LdapManager: Search for groupDN based on groupname '" + groupname + "' found multiple " + try { ctx.close(); } catch (Exception ignored) {
NamingEnumeration<SearchResult> results = c.search(userbaseDN, userSearchFilter, new Object[]{user}, SEARCH_CONTROLS); if (!results.hasMoreElements()) { if (LOG.isDebugEnabled()) { LOG.debug("doGetGroups(" + user + ") returned no groups because the " + SearchResult result = results.nextElement(); 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()); NamingEnumeration groupEnumeration = groupDNAttr.getAll(); while (groupEnumeration.hasMore()) { String groupDN = groupEnumeration.next().toString(); groups.add(getRelativeDistinguishedName(groupDN));
doRFC2254Encoding(username) }); SearchControls constraints = new SearchControls(); if (userSearchSubtreeBool) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(USER_BASE), filter, constraints); if (results == null || !results.hasMore()) { log.warn("User " + username + " not found in LDAP."); throw new FailedLoginException("User " + username + " not found in LDAP."); SearchResult result = results.next(); if (results.hasMore()) { if (result.isRelative()) { log.debug("LDAP returned a relative name: {}", result.getName()); NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(getLDAPPropertyValue(USER_BASE)); Name entryName = parser.parse(result.getName()); Name name = contextName.addAll(baseName); name = name.addAll(entryName);
@Override public Enumeration<String> engineAliases() { DirContext context = obtainDirContext(); if (context == null) { log.trace("Unable to obtain DirContext"); return null; } try { NamingEnumeration<SearchResult> results = context.search(searchPath, filterIterate, null, createSearchControl(new String[]{aliasAttribute})); // TODO pagination List<String> aliases = new LinkedList<>(); while (results.hasMore()) { Attribute attribute = results.next().getAttributes().get(aliasAttribute); if (attribute != null) aliases.add((String) attribute.get()); } return Collections.enumeration(aliases); } catch (NamingException e) { throw log.ldapKeyStoreFailedToIterateAliases(e); } finally { returnDirContext(context); } }
Attribute memberAttribute = result.getAttributes().get(permissionGroupMemberAttribute); NamingEnumeration<?> memberAttributeEnum = memberAttribute.getAll(); while (memberAttributeEnum.hasMoreElements()) { String memberDn = (String) memberAttributeEnum.nextElement(); boolean group = false; boolean user = false; memberAttributes = context.getAttributes(memberDn, new String[] { "objectClass", groupNameAttribute, userNameAttribute }); } catch (NamingException e) { LOG.error("Policy not applied! Unknown member {} in policy entry {}", new Object[]{ memberDn, result.getNameInNamespace() }, e); continue; Attribute memberEntryObjectClassAttribute = memberAttributes.get("objectClass"); NamingEnumeration<?> memberEntryObjectClassAttributeEnum = memberEntryObjectClassAttribute.getAll(); while (memberEntryObjectClassAttributeEnum.hasMoreElements()) { String objectClass = (String) memberEntryObjectClassAttributeEnum.nextElement(); Attribute name = memberAttributes.get(groupNameAttribute); if (name == null) { LOG.error("Policy not applied! Group {} does not have name attribute {} under entry {}", new Object[]{ memberDn, groupNameAttribute, result.getNameInNamespace() }); break; principalName = (String) name.get();
}); SearchControls constraints = new SearchControls(); if (roleSearchSubtreeBool) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); NamingEnumeration<SearchResult> results = context.search(getLDAPPropertyValue(ROLE_BASE), filter, constraints); while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); if (expandRolesBool) { haveSeenNames.add(result.getNameInNamespace()); pendingNameExpansion.add(result.getNameInNamespace()); String name = pendingNameExpansion.remove(); filter = expandRolesMatchingFormat.format(new String[]{name}); results = context.search(getLDAPPropertyValue(ROLE_BASE), filter, constraints); while (results.hasMore()) { SearchResult result = results.next(); name = result.getNameInNamespace();
SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); // Search Entire Subtree controls.setCountLimit(1); //Sets the maximum number of entries to be returned as a result of the search controls.setTimeLimit(5000); // Sets the time limit of these SearchControls in milliseconds results = ctx.search("", searchString, controls); Attributes attrs = result.getAttributes(); Attribute dnAttr = attrs.get("distinguishedName"); String dn = (String) dnAttr.get(); try { ctx.close(); } catch (Exception e) { /* Do Nothing */ }
protected List<Address> resolveSRVEntries(String dnsQuery) { List<Address> addresses = new ArrayList<>(); try { // We are parsing this kind of structure: // {srv=SRV: 10 100 8888 9089f34a.jgroups-dns-ping.myproject.svc.cluster.local.} // The frst attribute is the type of record. We are not interested in this. Next are addresses. Attributes attributes = dnsContext.getAttributes(dnsQuery, new String[] { DNSRecordType.SRV.toString() }); if (attributes != null && attributes.getAll().hasMoreElements()) { NamingEnumeration<?> namingEnumeration = attributes.get(DNSRecordType.SRV.toString()).getAll(); while (namingEnumeration.hasMoreElements()) { try { String srvEntry = namingEnumeration.nextElement().toString(); Matcher matcher = SRV_REGEXP.matcher(srvEntry); if (matcher.find()) { String srcPort = matcher.group(1); String srcDNSRecord = matcher.group(2); // The implementation here is not optimal but it's easy to read. SRV discovery will be performed // extremely rarely, only when a fine grained discovery using ports is needed (ie: when using containers). addresses.addAll(resolveAEntries(srcDNSRecord, srcPort)); } } catch (Exception e) { log.trace("non critical DNS resolution error", e); } } } } catch (NamingException ex) { log.trace("no DNS records for query %s, ex: %s", dnsQuery, ex.getMessage()); } return addresses; }
throws NamingException { final DistinguishedName ctxBaseDn = new DistinguishedName( ctx.getNameInNamespace()); final DistinguishedName searchBaseDn = new DistinguishedName(base); final NamingEnumeration<SearchResult> resultsEnum = ctx.search(searchBaseDn, filter, params, buildControls(searchControls)); while (resultsEnum.hasMore()) { SearchResult searchResult = resultsEnum.next(); DirContextAdapter dca = (DirContextAdapter) searchResult.getObject(); Assert.notNull(dca, "No object returned by search, DirContext is not correctly configured");
SearchControls searchCtls = new SearchControls(); searchCtls.setReturningAttributes(returnedAtts); searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, searchFilter, searchCtls); System.out.println(">>>" + sr.getName()); Attributes attrs = sr.getAttributes(); System.out.println(">>>>>>" + attrs.get("samAccountName")); ldapContext.close();
LOG.debug(" base [{}]", base); LOG.debug(" filter [{}]", searchFilter); LOG.debug(" scope [{}]", searchControls.getSearchScope()); NamingEnumeration<SearchResult> results = context.search(base, searchFilter, searchControls); while (results.hasMore()) { addConnector(results.next()); EventDirContext eventContext = (EventDirContext) context.lookup(""); eventContext.addNamingListener(base, searchFilter, searchControls, this); } else { // otherwise close context (i.e. connection as it is no longer needed) context.close();
protected Set<GroupPrincipal> getACLs(String destinationBase, SearchControls constraints, String roleBase, String roleAttribute) { try { Set<GroupPrincipal> roles = new HashSet<GroupPrincipal>(); Set<String> acls = new HashSet<String>(); NamingEnumeration<?> results = context.search(destinationBase, roleBase, constraints); while (results.hasMore()) { SearchResult result = (SearchResult)results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) { continue; } acls = addAttributeValues(roleAttribute, attrs, acls); } for (Iterator<String> iter = acls.iterator(); iter.hasNext();) { String roleName = iter.next(); LdapName ldapname = new LdapName(roleName); Rdn rdn = ldapname.getRdn(ldapname.size() - 1); LOG.debug("Found role: [" + rdn.getValue().toString() + "]"); roles.add(new GroupPrincipal(rdn.getValue().toString())); } return roles; } catch (NamingException e) { LOG.error(e.toString()); return new HashSet<GroupPrincipal>(); } }