use of javax.naming.directory.SearchResult in project cloudstack by apache.
the class OpenLdapUserManagerImpl method searchUsers.
@Override
public List<LdapUser> searchUsers(final String username, final LdapContext context) throws NamingException, IOException {
final SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(_ldapConfiguration.getScope());
searchControls.setReturningAttributes(_ldapConfiguration.getReturnAttributes());
String basedn = _ldapConfiguration.getBaseDn();
if (StringUtils.isBlank(basedn)) {
throw new IllegalArgumentException("ldap basedn is not configured");
}
byte[] cookie = null;
int pageSize = _ldapConfiguration.getLdapPageSize();
context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, Control.NONCRITICAL) });
final List<LdapUser> users = new ArrayList<LdapUser>();
NamingEnumeration<SearchResult> results;
do {
results = context.search(basedn, generateSearchFilter(username), searchControls);
while (results.hasMoreElements()) {
final SearchResult result = results.nextElement();
if (!isUserDisabled(result)) {
users.add(createUser(result));
}
}
Control[] contextControls = context.getResponseControls();
if (contextControls != null) {
for (Control control : contextControls) {
if (control instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) control;
cookie = prrc.getCookie();
}
}
} else {
s_logger.info("No controls were sent from the ldap server");
}
context.setRequestControls(new Control[] { new PagedResultsControl(pageSize, cookie, Control.CRITICAL) });
} while (cookie != null);
return users;
}
use of javax.naming.directory.SearchResult in project jmeter by apache.
the class LDAPExtSampler method sample.
@Override
public SampleResult sample(Entry e) {
XMLBuffer xmlBuffer = new XMLBuffer();
// $NON-NLS-1$
xmlBuffer.openTag("ldapanswer");
SampleResult res = new SampleResult();
res.setResponseData("successfull", null);
// $NON-NLS-1$
res.setResponseMessage("Success");
// $NON-NLS-1$
res.setResponseCode("0");
// $NON-NLS-1$
res.setContentType("text/xml");
boolean isSuccessful = true;
res.setSampleLabel(getName());
DirContext dirContext = ldapContexts.get(getThreadName());
try {
// $NON-NLS-1$
xmlBuffer.openTag("operation");
final String testType = getTest();
// $NON-NLS-1$
xmlBuffer.tag("opertype", testType);
log.debug("performing test: " + testType);
if (testType.equals(UNBIND)) {
res.setSamplerData("Unbind");
// $NON-NLS-1$
xmlBuffer.tag("baseobj", getRootdn());
// $NON-NLS-1$
xmlBuffer.tag("binddn", getUserDN());
unbindOp(dirContext, res);
} else if (testType.equals(BIND)) {
res.setSamplerData("Bind as " + getUserDN());
// $NON-NLS-1$
xmlBuffer.tag("baseobj", getRootdn());
// $NON-NLS-1$
xmlBuffer.tag("binddn", getUserDN());
// $NON-NLS-1$
xmlBuffer.tag("connectionTO", getConnTimeOut());
bindOp(res);
} else if (testType.equals(SBIND)) {
res.setSamplerData("SingleBind as " + getUserDN());
// $NON-NLS-1$
xmlBuffer.tag("baseobj", getRootdn());
// $NON-NLS-1$
xmlBuffer.tag("binddn", getUserDN());
// $NON-NLS-1$
xmlBuffer.tag("connectionTO", getConnTimeOut());
singleBindOp(res);
} else if (testType.equals(COMPARE)) {
res.setSamplerData("Compare " + getPropertyAsString(COMPAREFILT) + " " + getPropertyAsString(COMPAREDN));
// $NON-NLS-1$
xmlBuffer.tag("comparedn", getPropertyAsString(COMPAREDN));
// $NON-NLS-1$
xmlBuffer.tag("comparefilter", getPropertyAsString(COMPAREFILT));
NamingEnumeration<SearchResult> cmp = null;
try {
res.sampleStart();
cmp = LdapExtClient.compare(dirContext, getPropertyAsString(COMPAREFILT), getPropertyAsString(COMPAREDN));
if (!cmp.hasMore()) {
// $NON-NLS-1$
res.setResponseCode("5");
res.setResponseMessage("compareFalse");
isSuccessful = false;
}
} finally {
res.sampleEnd();
if (cmp != null) {
cmp.close();
}
}
} else if (testType.equals(ADD)) {
res.setSamplerData("Add object " + getBaseEntryDN());
// $NON-NLS-1$
xmlBuffer.tag("attributes", getArguments().toString());
// $NON-NLS-1$
xmlBuffer.tag("dn", getBaseEntryDN());
addTest(dirContext, res);
} else if (testType.equals(DELETE)) {
res.setSamplerData("Delete object " + getBaseEntryDN());
// $NON-NLS-1$
xmlBuffer.tag("dn", getBaseEntryDN());
deleteTest(dirContext, res);
} else if (testType.equals(MODIFY)) {
res.setSamplerData("Modify object " + getBaseEntryDN());
// $NON-NLS-1$
xmlBuffer.tag("dn", getBaseEntryDN());
// $NON-NLS-1$
xmlBuffer.tag("attributes", getLDAPArguments().toString());
modifyTest(dirContext, res);
} else if (testType.equals(RENAME)) {
res.setSamplerData("ModDN object " + getPropertyAsString(MODDDN) + " to " + getPropertyAsString(NEWDN));
// $NON-NLS-1$
xmlBuffer.tag("dn", getPropertyAsString(MODDDN));
// $NON-NLS-1$
xmlBuffer.tag("newdn", getPropertyAsString(NEWDN));
renameTest(dirContext, res);
} else if (testType.equals(SEARCH)) {
final String scopeStr = getScope();
final int scope = getScopeAsInt();
final String searchFilter = getPropertyAsString(SEARCHFILTER);
final String searchBase = getPropertyAsString(SEARCHBASE);
final String timeLimit = getTimelim();
final String countLimit = getCountlim();
res.setSamplerData("Search with filter " + searchFilter);
// $NON-NLS-1$
xmlBuffer.tag("searchfilter", StringEscapeUtils.escapeXml10(searchFilter));
// $NON-NLS-1$
xmlBuffer.tag("baseobj", getRootdn());
// $NON-NLS-1$
xmlBuffer.tag("searchbase", searchBase);
// $NON-NLS-1$
xmlBuffer.tag("scope", scopeStr);
// $NON-NLS-1$
xmlBuffer.tag("countlimit", countLimit);
// $NON-NLS-1$
xmlBuffer.tag("timelimit", timeLimit);
NamingEnumeration<SearchResult> srch = null;
try {
res.sampleStart();
srch = LdapExtClient.searchTest(dirContext, searchBase, searchFilter, scope, getCountlimAsLong(), getTimelimAsInt(), getRequestAttributes(getAttrs()), isRetobj(), isDeref());
if (isParseFlag()) {
try {
// $NON-NLS-1$
xmlBuffer.openTag("searchresults");
writeSearchResults(xmlBuffer, srch);
} finally {
// $NON-NLS-1$
xmlBuffer.closeTag("searchresults");
}
} else {
// $NON-NLS-1$
xmlBuffer.tag(// $NON-NLS-1$
"searchresults", // $NON-NLS-1$
"hasElements=" + srch.hasMoreElements());
}
} finally {
if (srch != null) {
srch.close();
}
res.sampleEnd();
}
}
} catch (NamingException ex) {
// TODO: tidy this up
String returnData = ex.toString();
final int indexOfLDAPErrCode = returnData.indexOf("LDAP: error code");
if (indexOfLDAPErrCode >= 0) {
res.setResponseMessage(returnData.substring(indexOfLDAPErrCode + 21, returnData.indexOf(// $NON-NLS-1$
']')));
res.setResponseCode(returnData.substring(indexOfLDAPErrCode + 17, indexOfLDAPErrCode + 19));
} else {
res.setResponseMessage(returnData);
// $NON-NLS-1$
res.setResponseCode("800");
}
isSuccessful = false;
} finally {
// $NON-NLS-1$
xmlBuffer.closeTag("operation");
// $NON-NLS-1$
xmlBuffer.tag("responsecode", res.getResponseCode());
// $NON-NLS-1$
xmlBuffer.tag("responsemessage", res.getResponseMessage());
res.setResponseData(xmlBuffer.toString(), null);
res.setDataType(SampleResult.TEXT);
res.setSuccessful(isSuccessful);
}
return res;
}
use of javax.naming.directory.SearchResult in project nhin-d by DirectProject.
the class LdapCertUtilImpl method ldapSearch.
public Collection<X509Certificate> ldapSearch(String subjectName) {
DirContext ctx = null;
try {
ctx = getInitialDirContext(ldapEnvironment.getEnv());
final SearchControls ctls = getDefaultSearchControls();
NamingEnumeration<SearchResult> searchResult = ctx.search(ldapEnvironment.getLdapSearchBase(), ldapEnvironment.getLdapSearchAttribute() + "=" + subjectName, ctls);
ArrayList<X509Certificate> certificates = new ArrayList<X509Certificate>();
while (searchResult != null && searchResult.hasMoreElements()) {
final SearchResult certEntry = searchResult.nextElement();
if (certEntry != null) {
final Attributes certAttributes = certEntry.getAttributes();
if (certAttributes != null) {
// get only the returning cert attribute (for now, ignore all other attributes)
final Attribute certAttribute = certAttributes.get(ldapEnvironment.getReturningCertAttribute());
if (certAttribute != null) {
NamingEnumeration<? extends Object> allValues = certAttribute.getAll();
// LDAP may contain a collection of certificates.
while (allValues.hasMoreElements()) {
String ksBytes = (String) allValues.nextElement();
Base64 base64 = new Base64();
byte[] decode = base64.decode(ksBytes.getBytes());
ByteArrayInputStream inputStream = new ByteArrayInputStream(decode);
if (certificateFormat.equalsIgnoreCase("pkcs12")) {
try {
processPKCS12FileFormatAndAddToCertificates(inputStream, certificates);
} catch (Exception e) {
closeDirContext(ctx);
throw new NHINDException("", e);
}
} else {
if (certificateFormat.equalsIgnoreCase("X.509") || certificateFormat.equalsIgnoreCase("X509")) {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate addCert = (X509Certificate) cf.generateCertificate(inputStream);
certificates.add(addCert);
} else {
closeDirContext(ctx);
throw new NHINDException("Invalid certificate format requested");
}
}
}
}
}
}
}
return certificates;
} catch (NamingException e) {
closeDirContext(ctx);
throw new NHINDException("", e);
} catch (CertificateException e) {
closeDirContext(ctx);
throw new NHINDException("", e);
}
}
use of javax.naming.directory.SearchResult in project nhin-d by DirectProject.
the class LdapPublicCertUtilImpl method ldapSearch.
/**
* Searches for certificates in public LDAP servers using the subject name.
* @param subjectName The subject's email address or domain name.
* @return Collection of certificates matching the LDAP query for the subject name.
*/
public Collection<X509Certificate> ldapSearch(String subjectName) {
final Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
String domainName;
// find by host
int index;
if ((index = subjectName.indexOf("@")) > -1)
domainName = subjectName.substring(index + 1);
else
domainName = subjectName;
final String lookupName = LDAP_SRV_PREFIX + domainName;
InitialDirContext ctx = null;
try {
ctx = getDirContext(lookupName);
if (ctx != null) {
// discover the naming contexts
List<String> dNs = getBaseNamingContexts(ctx);
if (!dNs.isEmpty()) {
for (String dn : dNs) {
NamingEnumeration<SearchResult> searchResult = ctx.search(dn, EMAIL_ATTRIBUTE + "=" + subjectName, getDefaultSearchControls());
while (searchResult != null && searchResult.hasMore()) {
final SearchResult certEntry = searchResult.nextElement();
if (certEntry != null) {
final Attributes certAttributes = certEntry.getAttributes();
if (certAttributes != null) {
// get only the returning cert attribute (for now, ignore all other attributes)
Attribute certAttribute = certAttributes.get(CERT_ATTRIBUTE_BINARY);
// binary modifier
if (certAttribute == null)
certAttribute = certAttributes.get(CERT_ATTRIBUTE);
if (certAttribute != null) {
NamingEnumeration<? extends Object> allValues = certAttribute.getAll();
// LDAP may contain a collection of certificates.
while (allValues.hasMoreElements()) {
byte[] rawCert = null;
Object obj = allValues.nextElement();
rawCert = (byte[]) obj;
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
final ByteArrayInputStream inputStream = new ByteArrayInputStream(rawCert);
try {
X509Certificate addCert = (X509Certificate) cf.generateCertificate(inputStream);
retVal.add(addCert);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
}
}
}
}
}
}
}
} catch (Exception e) {
throw new NHINDException("", e);
} finally {
this.closeDirContext(ctx);
}
return retVal;
}
use of javax.naming.directory.SearchResult in project simba-os by cegeka.
the class ActiveDirectoryLoginModule method verifyLoginData.
@Override
protected boolean verifyLoginData() throws FailedLoginException {
String[] returnedAtts = { authenticationAttribute };
Encoder encoder = DefaultEncoder.getInstance();
String requestSearchFilter = searchFilter.replaceAll("%USERNAME%", encoder.encodeForLDAP(getUsername()));
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(returnedAtts);
searchCtls.setSearchScope(searchScope);
Hashtable<String, String> env = getEnv();
debug("Verifying credentials for user: " + getUsername());
boolean ldapUser = false;
String userCN = null;
try {
LdapContext ldapContext = getLdapContext(env);
if (ldapContext != null) {
NamingEnumeration<SearchResult> answer = ldapContext.search(searchBase, requestSearchFilter, searchCtls);
while (!ldapUser && answer.hasMoreElements()) {
SearchResult sr = answer.next();
userCN = sr.getName();
Attributes attrs = sr.getAttributes();
if (attrs != null) {
NamingEnumeration<? extends Attribute> ne = attrs.getAll();
ldapUser = ne.hasMore();
ne.close();
}
}
debug("Authentication succeeded");
if (Boolean.TRUE.equals(GlobalContext.locate(ConfigurationServiceImpl.class).getValue(SimbaConfigurationParameter.ENABLE_AD_GROUPS)) && userCN != null) {
updateUserGroups(ldapContext, userCN);
}
}
return ldapUser;
} catch (NamingException ex) {
debug("Authentication failed");
throw new FailedLoginException(ex.getMessage());
}
}
Aggregations