use of javax.naming.directory.Attribute in project Openfire by igniterealtime.
the class LdapGroupTester method getGroups.
/**
* Returns fist N groups found in LDAP. The returned groups are only able to return their name,
* description and count of members. Count of members is considering all values that were found
* in the member field.
*
* @param maxGroups max number of groups to return.
* @return fist N groups found in the LDAP.
*/
public Collection<Group> getGroups(int maxGroups) {
Collection<Group> groups = new ArrayList<>();
LdapContext ctx = null;
try {
ctx = manager.getContext();
// Sort on group name field.
Control[] searchControl = new Control[] { new SortControl(new String[] { manager.getGroupNameField() }, Control.NONCRITICAL) };
ctx.setRequestControls(searchControl);
SearchControls searchControls = new SearchControls();
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
// Attributes to return for each group
String[] standardAttributes = new String[3];
standardAttributes[0] = manager.getGroupNameField();
standardAttributes[1] = manager.getGroupDescriptionField();
standardAttributes[2] = manager.getGroupMemberField();
searchControls.setReturningAttributes(standardAttributes);
// Limit results to those we'll need to process
searchControls.setCountLimit(maxGroups);
String filter = MessageFormat.format(manager.getGroupSearchFilter(), "*");
NamingEnumeration answer = ctx.search("", filter, searchControls);
while (answer.hasMoreElements()) {
// Get the next group.
Attributes attributes = ((SearchResult) answer.next()).getAttributes();
String groupName = (String) attributes.get(manager.getGroupNameField()).get();
String description = "";
int elements = 0;
try {
description = ((String) attributes.get(manager.getGroupDescriptionField()).get());
} catch (NullPointerException e) {
// Do nothing since the group description field was not found
} catch (Exception e) {
Log.error("Error retrieving group description", e);
}
Attribute memberField = attributes.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
ne.next();
elements = elements + 1;
}
}
// Build Group with found information
groups.add(new Group(groupName, description, elements));
}
// Close the enumeration.
answer.close();
} catch (Exception e) {
Log.error(e.getMessage(), e);
} finally {
try {
if (ctx != null) {
ctx.setRequestControls(null);
ctx.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
return groups;
}
use of javax.naming.directory.Attribute in project Openfire by igniterealtime.
the class LdapAuthorizationPolicy method getAuthorized.
/**
* Returns a String Collection of principals that are authorized to use
* the named user.
*
* @param username the username.
* @return A String Collection of principals that are authorized.
*/
private Collection<String> getAuthorized(String username) {
// Un-escape Node
username = JID.unescapeNode(username);
Collection<String> authorized = new ArrayList<>();
DirContext ctx = null;
try {
String userDN = manager.findUserDN(username);
// Load record.
String[] attributes = new String[] { usernameField, authorizeField };
ctx = manager.getContext();
Attributes attrs = ctx.getAttributes(userDN, attributes);
Attribute authorizeField_a = attrs.get(authorizeField);
if (authorizeField_a != null) {
for (Enumeration e = authorizeField_a.getAll(); e.hasMoreElements(); ) {
authorized.add((String) e.nextElement());
}
}
return authorized;
} catch (Exception e) {
// Ignore.
} finally {
try {
if (ctx != null) {
ctx.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
return authorized;
}
use of javax.naming.directory.Attribute in project Openfire by igniterealtime.
the class LdapGroupProvider method processGroup.
private Group processGroup(LdapContext ctx, Attributes a) throws NamingException {
XMPPServer server = XMPPServer.getInstance();
String serverName = server.getServerInfo().getXMPPDomain();
// Build `3 groups.
// group 1: uid=
// group 2: rest of the text until first comma
// group 3: rest of the text
Pattern pattern = Pattern.compile("(?i)(^" + manager.getUsernameField() + "=)([^,]+)(.+)");
// We have to process Active Directory differently.
boolean isAD = manager.getUsernameField().equals("sAMAccountName");
String[] returningAttributes = isAD ? new String[] { "distinguishedName", manager.getUsernameField() } : new String[] { manager.getUsernameField() };
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(returningAttributes);
// See if recursive searching is enabled. Otherwise, only search one level.
if (manager.isSubTreeSearch()) {
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else {
searchControls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
}
String name;
String description;
try {
name = ((String) ((a.get(manager.getGroupNameField())).get()));
} catch (Exception e) {
name = "";
}
try {
description = ((String) ((a.get(manager.getGroupDescriptionField())).get()));
} catch (Exception e) {
description = "";
}
Set<JID> members = new TreeSet<>();
Attribute memberField = a.get(manager.getGroupMemberField());
if (memberField != null) {
NamingEnumeration ne = memberField.getAll();
while (ne.hasMore()) {
String username = (String) ne.next();
// If not posix mode, each group member is stored as a full DN.
if (!manager.isPosixMode()) {
try {
// Try to find the username with a regex pattern match.
Matcher matcher = pattern.matcher(username);
if (matcher.matches() && matcher.groupCount() == 3) {
// The username is in the DN, no additional search needed
username = matcher.group(2);
} else // The regex pattern match failed. This will happen if the
// the member DN's don't use the standard username field. For
// example, Active Directory has a username field of
// sAMAccountName, but stores group members as "CN=...".
{
// Create an LDAP name with the full DN.
LdapName ldapName = new LdapName(username);
// Turn the LDAP name into something we can use in a
// search by stripping off the comma.
StringBuilder userFilter = new StringBuilder();
userFilter.append("(&(");
userFilter.append(ldapName.get(ldapName.size() - 1));
userFilter.append(')');
userFilter.append(MessageFormat.format(manager.getSearchFilter(), "*"));
userFilter.append(')');
NamingEnumeration usrAnswer = ctx.search("", userFilter.toString(), searchControls);
if (usrAnswer != null && usrAnswer.hasMoreElements()) {
SearchResult searchResult = null;
// Iterate through the entire set to find a matching distinguished name.
while (usrAnswer.hasMoreElements()) {
searchResult = (SearchResult) usrAnswer.nextElement();
Attributes attrs = searchResult.getAttributes();
if (isAD) {
Attribute userdnAttr = attrs.get("distinguishedName");
if (username.equals((String) userdnAttr.get())) {
// Exact match found, use it.
username = (String) attrs.get(manager.getUsernameField()).get();
break;
}
} else {
// No iteration occurs here, which is probably a bug.
username = (String) attrs.get(manager.getUsernameField()).get();
break;
}
}
}
// Close the enumeration.
usrAnswer.close();
}
} catch (Exception e) {
// TODO: A NPE is occuring here
Log.error(e.getMessage(), e);
}
}
// it passes the filter.
try {
JID userJID;
int position = username.indexOf("@" + serverName);
// Create JID of local user if JID does not match a component's JID
if (position == -1) {
// In order to lookup a username from the manager, the username
// must be a properly escaped JID node.
String escapedUsername = JID.escapeNode(username);
if (!escapedUsername.equals(username)) {
// Check if escaped username is valid
userManager.getUser(escapedUsername);
}
// No exception, so the user must exist. Add the user as a group
// member using the escaped username.
userJID = server.createJID(escapedUsername, null);
} else {
// This is a JID of a component or node of a server's component
String node = username.substring(0, position);
String escapedUsername = JID.escapeNode(node);
userJID = new JID(escapedUsername + "@" + serverName);
}
members.add(userJID);
} catch (UserNotFoundException e) {
// So, we want to simply ignore the user as a group member.
if (manager.isDebugEnabled()) {
Log.debug("LdapGroupProvider: User not found: " + username);
}
}
}
// Close the enumeration.
ne.close();
}
if (manager.isDebugEnabled()) {
Log.debug("LdapGroupProvider: Adding group \"" + name + "\" with " + members.size() + " members.");
}
Collection<JID> admins = Collections.emptyList();
return new Group(name, description, members, admins);
}
use of javax.naming.directory.Attribute in project Openfire by igniterealtime.
the class LdapAuthorizationMapping method map.
@Override
public String map(String principal) {
String username = principal;
DirContext ctx = null;
try {
Log.debug("LdapAuthorizationMapping: Starting LDAP search...");
String usernameField = manager.getUsernameField();
//String baseDN = manager.getBaseDN();
boolean subTreeSearch = manager.isSubTreeSearch();
ctx = manager.getContext();
SearchControls constraints = new SearchControls();
if (subTreeSearch) {
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
} else // Otherwise, only search a single level.
{
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();
} catch (Exception e) {
// Ignore.
} finally {
try {
if (ctx != null) {
ctx.close();
}
} catch (Exception ignored) {
// Ignore.
}
}
return username;
}
use of javax.naming.directory.Attribute in project Openfire by igniterealtime.
the class DNSUtil method srvLookup.
/**
* Performs a DNS SRV lookup. Does not take into account any DNS overrides configured in this class.
*
* The results returned by this method are ordered by priority (ascending), and order of equal priority entries is
* randomized by weight, as defined in the DNS SRV specification.
*
* @param service the symbolic name of the desired service (cannot be null).
* @param proto the transport protocol of the desired service; this is usually either TCP or UDP (cannot be null).
* @param name the domain name for which this record is valid (cannot be null).
* @return An ordered of results (possibly empty, never null).
*/
public static List<WeightedHostAddress> srvLookup(String service, String proto, String name) {
if (service == null || proto == null || name == null) {
throw new NullPointerException("DNS lookup can't be null");
}
if (!service.startsWith("_")) {
service = "_" + service;
}
if (!service.endsWith(".")) {
service = service + ".";
}
if (!proto.startsWith("_")) {
proto = "_" + proto;
}
if (!proto.endsWith(".")) {
proto = proto + ".";
}
if (!name.endsWith(".")) {
name = name + ".";
}
// _service._proto.name.
final String lookup = (service + proto + name).toLowerCase();
try {
Attributes dnsLookup = context.getAttributes(lookup, new String[] { "SRV" });
Attribute srvRecords = dnsLookup.get("SRV");
if (srvRecords == null) {
logger.debug("No SRV record found for domain: " + lookup);
return Collections.emptyList();
}
WeightedHostAddress[] hosts = new WeightedHostAddress[srvRecords.size()];
for (int i = 0; i < srvRecords.size(); i++) {
hosts[i] = new WeightedHostAddress(((String) srvRecords.get(i)).split(" "));
}
return prioritize(hosts);
} catch (NameNotFoundException e) {
logger.debug("No SRV record found for: " + lookup, e);
} catch (NamingException e) {
logger.error("Can't process DNS lookup!", e);
}
return Collections.emptyList();
}
Aggregations