use of org.forgerock.opendj.ldap.SearchScope in project OpenAM by OpenRock.
the class DJLDAPv3Repo method search.
/**
* Performs a search in the directory based on the provided parameters.
* Using the pattern and avPairs parameters an example search filter would look something like:
* <code>(&(|(attr1=value1)(attr2=value2))(searchAttr=pattern)(objectclassfilter))</code>.
*
* @param token Not used.
* @param type The type of the identity.
* @param crestQuery Either a string, coming from something like the CREST endpoint _queryId or a fully
* fledged query filter, coming from a CREST endpoint's _queryFilter
* @param maxTime The time limit for this search (in seconds). When maxTime < 1, the default time limit will
* be used.
* @param maxResults The number of maximum results we should receive for this search. When maxResults < 1 the
* default sizelimit will be used.
* @param returnAttrs The attributes that should be returned from the "search hits".
* @param returnAllAttrs <code>true</code> if all user attribute should be returned.
* @param filterOp When avPairs is provided, this logical operation will be used between them. Use
* {@link IdRepo#AND_MOD} or {@link IdRepo#OR_MOD}.
* @param avPairs Attribute-value pairs based on the search should be performed.
* @param recursive Deprecated setting, not used.
* @return The search results based on the provided parameters.
* @throws IdRepoException Shouldn't be thrown as the returned RepoSearchResults will contain the error code.
*/
@Override
public RepoSearchResults search(SSOToken token, IdType type, CrestQuery crestQuery, int maxTime, int maxResults, Set<String> returnAttrs, boolean returnAllAttrs, int filterOp, Map<String, Set<String>> avPairs, boolean recursive) throws IdRepoException {
if (DEBUG.messageEnabled()) {
DEBUG.message("search invoked with type: " + type + " crestQuery: " + crestQuery + " avPairs: " + avPairs + " maxTime: " + maxTime + " maxResults: " + maxResults + " returnAttrs: " + returnAttrs + " returnAllAttrs: " + returnAllAttrs + " filterOp: " + filterOp + " recursive: " + recursive);
}
DN baseDN = getBaseDN(type);
// Recursive is a deprecated setting on IdSearchControl, hence we should use the searchscope defined in the
// datastore configuration.
SearchScope scope = defaultScope;
String searchAttr = getSearchAttribute(type);
String[] attrs;
Filter first;
if (crestQuery.hasQueryId()) {
first = Filter.valueOf(searchAttr + "=" + crestQuery.getQueryId());
} else {
first = crestQuery.getQueryFilter().accept(new LdapFromJsonQueryFilterVisitor(), null);
}
Filter filter = Filter.and(first, getObjectClassFilter(type));
Filter tempFilter = constructFilter(filterOp, avPairs);
if (tempFilter != null) {
filter = Filter.and(tempFilter, filter);
}
if (returnAllAttrs || (returnAttrs != null && returnAttrs.contains("*"))) {
Set<String> predefinedAttrs = getDefinedAttributes(type);
attrs = predefinedAttrs.toArray(new String[predefinedAttrs.size()]);
returnAllAttrs = true;
} else if (returnAttrs != null && !returnAttrs.isEmpty()) {
returnAttrs.add(searchAttr);
attrs = returnAttrs.toArray(new String[returnAttrs.size()]);
} else {
attrs = new String[] { searchAttr };
}
SearchRequest searchRequest = LDAPRequests.newSearchRequest(baseDN, scope, filter, attrs);
searchRequest.setSizeLimit(maxResults < 1 ? defaultSizeLimit : maxResults);
searchRequest.setTimeLimit(maxTime < 1 ? defaultTimeLimit : maxTime);
Connection conn = null;
Set<String> names = new HashSet<String>();
Map<String, Map<String, Set<String>>> entries = new HashMap<String, Map<String, Set<String>>>();
int errorCode = RepoSearchResults.SUCCESS;
try {
conn = connectionFactory.getConnection();
ConnectionEntryReader reader = conn.search(searchRequest);
while (reader.hasNext()) {
Map<String, Set<String>> attributes = new HashMap<String, Set<String>>();
if (reader.isEntry()) {
SearchResultEntry entry = reader.readEntry();
String name = entry.parseAttribute(searchAttr).asString();
names.add(name);
if (returnAllAttrs) {
for (Attribute attribute : entry.getAllAttributes()) {
LDAPUtils.addAttributeToMapAsString(attribute, attributes);
}
entries.put(name, attributes);
} else if (returnAttrs != null && !returnAttrs.isEmpty()) {
for (String attr : returnAttrs) {
Attribute attribute = entry.getAttribute(attr);
if (attribute != null) {
LDAPUtils.addAttributeToMapAsString(attribute, attributes);
}
}
entries.put(name, attributes);
} else {
//there is no attribute to return, don't populate the entries map
}
} else {
//ignore search result references
reader.readReference();
}
}
} catch (LdapException ere) {
ResultCode resultCode = ere.getResult().getResultCode();
if (resultCode.equals(ResultCode.NO_SUCH_OBJECT)) {
return new RepoSearchResults(new HashSet<String>(0), RepoSearchResults.SUCCESS, Collections.EMPTY_MAP, type);
} else if (resultCode.equals(ResultCode.TIME_LIMIT_EXCEEDED) || resultCode.equals(ResultCode.CLIENT_SIDE_TIMEOUT)) {
errorCode = RepoSearchResults.TIME_LIMIT_EXCEEDED;
} else if (resultCode.equals(ResultCode.SIZE_LIMIT_EXCEEDED)) {
errorCode = RepoSearchResults.SIZE_LIMIT_EXCEEDED;
} else {
DEBUG.error("Unexpected error occurred during search", ere);
errorCode = resultCode.intValue();
}
} catch (SearchResultReferenceIOException srrioe) {
//should never ever happen...
DEBUG.error("Got reference instead of entry", srrioe);
throw newIdRepoException(IdRepoErrorCode.SEARCH_FAILED, CLASS_NAME);
} finally {
IOUtils.closeIfNotNull(conn);
}
return new RepoSearchResults(names, errorCode, entries, type);
}
use of org.forgerock.opendj.ldap.SearchScope in project OpenAM by OpenRock.
the class DynamicGroup method setSearchFilter.
/**
* Sets the search filter used to evaluate this dynamic group.
*
* @param filter Search filter for evaluating members of the group.
*
* @supported.api
*/
public void setSearchFilter(String filter) {
LDAPUrl url = getUrl();
SearchScope scope = url.getScope();
Guid baseGuid = new Guid(url.getName().toString());
try {
setUrl(baseGuid, Filter.valueOf(filter), scope);
} catch (Exception e) {
// TODO - Log Exception
debug.error("DynamicGroup.setSearchFilter : Exception : " + e.getMessage());
}
}
use of org.forgerock.opendj.ldap.SearchScope in project OpenAM by OpenRock.
the class AssignableDynamicGroup method setSearchFilter.
/**
* Sets the search filter used to evaluate this dynamic group. For an
* <code>AssignableDynamicGroup</code>, the filter is always
* <code>"memberof=THIS_DN"</code>, so this method should not generally be
* called outside the package.
*
* @param filter Search filter for evaluating members of the group the
* scope in the filter has to be <code>LDAPv2.SCOPE_ONE</code> or
* <code>LDAPv2.SCOPE_SUB</code>.
*
* @supported.api
*/
public void setSearchFilter(String filter) {
LDAPUrl url = getUrl();
SearchScope scope = url.getScope();
if (SearchScope.SINGLE_LEVEL.equals(scope) && SearchScope.WHOLE_SUBTREE.equals(scope)) {
String msg = i18n.getString(IUMSConstants.ILLEGAL_ADGROUP_SCOPE);
throw new IllegalArgumentException(msg);
}
Guid baseGuid = new Guid(url.getName().toString());
setUrl(baseGuid, Filter.valueOf(filter), scope);
}
use of org.forgerock.opendj.ldap.SearchScope in project ddf by codice.
the class SslLdapLoginModule method doLogin.
protected boolean doLogin() throws LoginException {
// --------- EXTRACT USERNAME AND PASSWORD FOR LDAP LOOKUP -------------
Callback[] callbacks = new Callback[2];
callbacks[0] = new NameCallback("Username: ");
callbacks[1] = new PasswordCallback("Password: ", false);
try {
callbackHandler.handle(callbacks);
} catch (IOException ioException) {
LOGGER.debug("Exception while handling login.", ioException);
throw new LoginException(ioException.getMessage());
} catch (UnsupportedCallbackException unsupportedCallbackException) {
LOGGER.debug("Exception while handling login.", unsupportedCallbackException);
throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
}
user = ((NameCallback) callbacks[0]).getName();
if (user == null) {
return false;
}
user = user.trim();
validateUsername(user);
char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
// this method.
if ("none".equalsIgnoreCase(getBindMethod()) && (tmpPassword != null)) {
LOGGER.debug("Changing from authentication = none to simple since user or password was specified.");
// default to simple so that the provided user/password will get checked
setBindMethod(DEFAULT_AUTHENTICATION);
}
if (tmpPassword == null) {
tmpPassword = new char[0];
}
// ---------------------------------------------------------------------
// RESET OBJECT STATE AND DECLARE LOCAL VARS
principals = new HashSet<>();
Connection connection;
String userDn;
// ------------- CREATE CONNECTION #1 ----------------------------------
try {
connection = ldapConnectionPool.borrowObject();
} catch (Exception e) {
LOGGER.info("Unable to obtain ldap connection from pool", e);
return false;
}
try {
if (connection != null) {
// ------------- BIND #1 (CONNECTION USERNAME & PASSWORD) --------------
try {
BindRequest request;
switch(bindMethod) {
case "Simple":
request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
break;
case "SASL":
request = Requests.newPlainSASLBindRequest(connectionUsername, connectionPassword);
break;
case "GSSAPI SASL":
request = Requests.newGSSAPISASLBindRequest(connectionUsername, connectionPassword);
((GSSAPISASLBindRequest) request).setRealm(realm);
((GSSAPISASLBindRequest) request).setKDCAddress(kdcAddress);
break;
case "Digest MD5 SASL":
request = Requests.newDigestMD5SASLBindRequest(connectionUsername, connectionPassword);
((DigestMD5SASLBindRequest) request).setCipher(DigestMD5SASLBindRequest.CIPHER_HIGH);
((DigestMD5SASLBindRequest) request).getQOPs().clear();
((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_CONF);
((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH_INT);
((DigestMD5SASLBindRequest) request).getQOPs().add(DigestMD5SASLBindRequest.QOP_AUTH);
if (StringUtils.isNotEmpty(realm)) {
((DigestMD5SASLBindRequest) request).setRealm(realm);
}
break;
default:
request = Requests.newSimpleBindRequest(connectionUsername, connectionPassword);
break;
}
LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
BindResult bindResult = connection.bind(request);
if (!bindResult.isSuccess()) {
LOGGER.debug(BIND_FAILURE_MSG);
return false;
}
} catch (LdapException e) {
LOGGER.debug("Unable to bind to LDAP server.", e);
return false;
}
LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
// --------- SEARCH #1, FIND USER DISTINGUISHED NAME -----------
SearchScope scope;
scope = userSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
userFilter = userFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
userFilter = userFilter.replace("\\", "\\\\");
LOGGER.trace("Performing LDAP query for user: {} at {} with filter {}", user, userBaseDN, userFilter);
try (ConnectionEntryReader entryReader = connection.search(userBaseDN, scope, userFilter)) {
while (entryReader.hasNext() && entryReader.isReference()) {
LOGGER.debug("Referral ignored while searching for user {}", user);
entryReader.readReference();
}
if (!entryReader.hasNext()) {
LOGGER.info("User {} not found in LDAP.", user);
return false;
}
SearchResultEntry searchResultEntry = entryReader.readEntry();
userDn = searchResultEntry.getName().toString();
} catch (LdapException | SearchResultReferenceIOException e) {
LOGGER.info("Unable to read contents of LDAP user search.", e);
return false;
}
// Validate user's credentials.
try {
LOGGER.trace("Attempting LDAP bind for user: {}", userDn);
BindResult bindResult = connection.bind(userDn, tmpPassword);
if (!bindResult.isSuccess()) {
LOGGER.info(BIND_FAILURE_MSG);
return false;
}
} catch (Exception e) {
LOGGER.info("Unable to bind user: {} to LDAP server.", userDn, e);
return false;
}
LOGGER.trace("LDAP bind successful for user: {}", userDn);
// ---------- ADD USER AS PRINCIPAL --------------------------------
principals.add(new UserPrincipal(user));
// ----- BIND #3 (CONNECTION USERNAME & PASSWORD) --------------
try {
LOGGER.trace("Attempting LDAP bind for administrator: {}", connectionUsername);
BindResult bindResult = connection.bind(connectionUsername, connectionPassword);
if (!bindResult.isSuccess()) {
LOGGER.info(BIND_FAILURE_MSG);
return false;
}
} catch (LdapException e) {
LOGGER.info("Unable to bind to LDAP server.", e);
return false;
}
LOGGER.trace("LDAP bind successful for administrator: {}", connectionUsername);
// --------- SEARCH #3, GET ROLES ------------------------------
scope = roleSearchSubtree ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
roleFilter = roleFilter.replaceAll(Pattern.quote("%u"), Matcher.quoteReplacement(user));
roleFilter = roleFilter.replaceAll(Pattern.quote("%dn"), Matcher.quoteReplacement(userBaseDN));
roleFilter = roleFilter.replaceAll(Pattern.quote("%fqdn"), Matcher.quoteReplacement(userDn));
roleFilter = roleFilter.replace("\\", "\\\\");
LOGGER.trace("Performing LDAP query for roles for user: {} at {} with filter {} for role attribute {}", user, roleBaseDN, roleFilter, roleNameAttribute);
// ------------- ADD ROLES AS NEW PRINCIPALS -------------------
try (ConnectionEntryReader entryReader = connection.search(roleBaseDN, scope, roleFilter, roleNameAttribute)) {
SearchResultEntry entry;
while (entryReader.hasNext()) {
if (entryReader.isEntry()) {
entry = entryReader.readEntry();
Attribute attr = entry.getAttribute(roleNameAttribute);
if (attr == null) {
throw new LoginException("No attributes returned for [" + roleNameAttribute + " : " + roleBaseDN + "]");
}
for (ByteString role : attr) {
principals.add(new RolePrincipal(role.toString()));
}
} else {
// Got a continuation reference.
final SearchResultReference ref = entryReader.readReference();
LOGGER.debug("Skipping result reference: {}", ref.getURIs());
}
}
} catch (Exception e) {
LOGGER.debug("Exception while getting roles for [" + user + "].", e);
throw new LoginException("Can't get roles for [" + user + "]: " + e.getMessage());
}
} else {
LOGGER.trace("LDAP Connection was null could not authenticate user.");
return false;
}
succeeded = true;
commitSucceeded = true;
return true;
} finally {
ldapConnectionPool.returnObject(connection);
}
}
use of org.forgerock.opendj.ldap.SearchScope in project OpenAM by OpenRock.
the class SMSEmbeddedLdapObject method searchSubOrganizationNames.
private Set<String> searchSubOrganizationNames(String dn, String filter, int numOfEntries, boolean sortResults, boolean ascendingOrder, boolean recursive) throws SMSException, SSOException {
SearchScope scope = (recursive) ? SearchScope.WHOLE_SUBTREE : SearchScope.SINGLE_LEVEL;
InternalSearchOperation iso = searchObjects(dn, filter, scope, numOfEntries, sortResults, ascendingOrder);
ResultCode resultCode = iso.getResultCode();
if (resultCode == ResultCode.NO_SUCH_OBJECT) {
if (debug.messageEnabled()) {
debug.message("SMSEmbeddedLdapObject." + "searchSubOrganizationNames: suborg not present:" + dn);
}
} else if (resultCode == ResultCode.SIZE_LIMIT_EXCEEDED) {
if (debug.messageEnabled()) {
debug.message("SMSEmbeddedLdapObject." + "searchSubOrganizationNames: size limit exceeded. " + "numOfEntries = " + numOfEntries + ", dn = " + dn);
}
} else if (resultCode != ResultCode.SUCCESS) {
if (debug.warningEnabled()) {
debug.warning("SMSEmbeddedLdapObject." + "searchSubOrganizationNames: Unable to search. dn = " + dn + ", filter = " + filter + ", resultCode = " + resultCode);
}
throw new SMSException("", "sms-suborg-cannot-search");
}
Set<String> answer = new LinkedHashSet<>();
for (SearchResultEntry entry : iso.getSearchEntries()) {
String edn = entry.getName().toString();
answer.add(edn);
}
if (debug.messageEnabled()) {
debug.message("SMSEmbeddedLdapObject.searchSubOrganizationName: " + "Successfully obtained suborganization names for : " + dn);
debug.message("SMSEmbeddedLdapObject.searchSubOrganizationName: " + "Successfully obtained suborganization names : " + answer.toString());
}
return answer;
}
Aggregations