use of org.forgerock.opendj.ldap.ByteString in project OpenAM by OpenRock.
the class DataLayer method getAttributeString.
/**
* Returns String values of the attribute.
*
* @param principal Authentication Principal.
* @param guid distinguished name.
* @param attrName attribute name.
*
* @supported.api
*/
public String[] getAttributeString(Principal principal, Guid guid, String attrName) {
String id = guid.getDn();
SearchRequest request = LDAPRequests.newSearchRequest(id, SearchScope.BASE_OBJECT, "(objectclass=*)");
try {
try (ConnectionEntryReader reader = readLDAPEntry(principal, request)) {
Attribute attribute = reader.readEntry().getAttribute(attrName);
Collection<String> values = new ArrayList<>();
for (ByteString byteString : attribute) {
values.add(byteString.toString());
}
return values.toArray(new String[0]);
}
} catch (Exception e) {
if (debug.warningEnabled()) {
debug.warning("Exception in DataLayer.getAttributeString for DN: " + id, e);
}
return null;
}
}
use of org.forgerock.opendj.ldap.ByteString in project OpenAM by OpenRock.
the class UpgradeUtils method getExistingValues.
/**
* Returns a set of valid attributes values for an attribute.
*
* @param subConfig the <code>ServiceConfig</code> object.
* @param attrName the attribute name.
* @param defaultVal set of attribute values to validate with the
* the existing attribute values.
*/
static Set getExistingValues(ServiceConfig subConfig, String attrName, Set defaultVal) {
Set<String> valSet = new HashSet<>();
String classMethod = "UpgradeUtils:getExistingValues : ";
try (Connection conn = getLDAPConnection()) {
if (conn != null) {
String dn = subConfig.getDN();
SearchResultEntry result = conn.searchSingleEntry(LDAPRequests.newSingleEntrySearchRequest(dn));
if (result != null) {
for (Attribute attribute : result.getAllAttributes()) {
String attributeName = attribute.getAttributeDescriptionAsString();
if (attributeName != null && ATTR_SUN_KEY_VALUE.equalsIgnoreCase(attributeName)) {
for (ByteString value : attribute) {
String valueString = value.toString();
int index = valueString.indexOf("=");
if (index != -1) {
String key = valueString.substring(0, index);
if (attributeName.equalsIgnoreCase(key)) {
String v = valueString.substring(index + 1, valueString.length());
if (defaultVal.contains(v)) {
valSet.add(v);
}
}
}
}
}
}
}
}
} catch (Exception e) {
debug.error(classMethod + "Error retreving attribute values ", e);
}
if (debug.messageEnabled()) {
debug.message(classMethod + "Default Values are :" + valSet);
}
return valSet;
}
use of org.forgerock.opendj.ldap.ByteString in project OpenAM by OpenRock.
the class OpenDJUpgrader method findBaseDNs.
private List<DN> findBaseDNs() throws IOException {
final List<DN> baseDNs = new LinkedList<DN>();
final SearchRequest request = LDAPRequests.newSearchRequest("cn=backends,cn=config", SearchScope.WHOLE_SUBTREE, "(objectclass=ds-cfg-backend)", "ds-cfg-base-dn");
try (LDIFEntryReader reader = new LDIFEntryReader(new FileInputStream(installRoot + "/config/config.ldif"))) {
final EntryReader filteredReader = LDIF.search(reader, request);
while (filteredReader.hasNext()) {
final Entry entry = filteredReader.readEntry();
final Attribute values = entry.getAttribute("ds-cfg-base-dn");
if (values != null) {
for (final ByteString value : values) {
baseDNs.add(DN.valueOf(value.toString()));
}
}
}
}
return baseDNs;
}
use of org.forgerock.opendj.ldap.ByteString in project OpenAM by OpenRock.
the class AMCertStore method getCertificate.
/**
* Return matched certificate from ldap certificate store
*/
public X509Certificate getCertificate() {
/*
* Lookup the certificate in the LDAP certificate
* directory and compare the values.
*/
try (Connection ldc = getConnection()) {
if (ldc == null) {
return null;
}
ConnectionEntryReader results = getSearchResults(ldc, USERCERTIFICATE, USERCERTIFICATE_BINARY, CACERTIFICATE, CACERTIFICATE_BINARY);
while (results != null && results.hasNext()) {
// "Found search results for: " + cn , 2);
if (results.isEntry()) {
SearchResultEntry entry = results.readEntry();
/*
* Retrieve the certificate from the store
*/
Attribute certAttribute = entry.getAttribute(USERCERTIFICATE);
if (certAttribute == null) {
certAttribute = entry.getAttribute(USERCERTIFICATE_BINARY);
if (certAttribute == null) {
// an end-entity certificate can be a CA certificate
certAttribute = entry.getAttribute(CACERTIFICATE);
if (certAttribute == null) {
certAttribute = entry.getAttribute(CACERTIFICATE_BINARY);
}
if (certAttribute == null) {
debug.message("AMCertStore.getCertificate: Certificate - get usercertificate is null ");
continue;
}
}
}
for (ByteString value : certAttribute) {
byte[] bytes = value.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
X509Certificate c = null;
try {
c = (X509Certificate) cf.generateCertificate(bis);
} catch (CertificateParsingException e) {
debug.error("AMCertStore.getCertificate : " + "Error in Certificate parsing : ", e);
}
if (c != null) {
return c;
}
}
// inner while
} else {
SearchResultReference reference = results.readReference();
debug.warning("Got an LDAP reference - only expected entries. Ignoring: {}", reference);
}
}
// outer while
} catch (Exception e) {
debug.error("AMCertStore.getCertificate : " + "Certificate - Error finding registered certificate = ", e);
}
return null;
}
use of org.forgerock.opendj.ldap.ByteString 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);
}
}
Aggregations