Search in sources :

Example 41 with ConnectionEntryReader

use of org.forgerock.opendj.ldif.ConnectionEntryReader in project OpenAM by OpenRock.

the class DataLayer method getAttributes.

/**
     * Returns attributes for the given attribute names.
     * 
     * @param principal Authentication Principal.
     * @param guid Distinguished name.
     * @param attrNames Attribute names.
     * @return collection of Attr.
     *
     * @supported.api
     */
public Collection<Attr> getAttributes(Principal principal, Guid guid, Collection<String> attrNames) {
    String id = guid.getDn();
    SearchRequest request = LDAPRequests.newSearchRequest(id, SearchScope.BASE_OBJECT, "(objectclass=*)", attrNames.toArray(EMPTY_STRING_ARRAY));
    ConnectionEntryReader ldapEntry;
    try {
        ldapEntry = readLDAPEntry(principal, request);
        if (ldapEntry == null) {
            debug.warning("No attributes returned may not have permission to read");
            return Collections.emptySet();
        }
        Collection<Attr> attributes = new ArrayList<>();
        while (ldapEntry.hasNext()) {
            if (ldapEntry.isEntry()) {
                SearchResultEntry entry = ldapEntry.readEntry();
                for (Attribute attr : entry.getAllAttributes()) {
                    attributes.add(new Attr(attr));
                }
            }
        }
        return attributes;
    } catch (Exception e) {
        debug.warning("Exception in DataLayer.getAttributes for DN: {}", id, e);
        return null;
    }
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) Attribute(org.forgerock.opendj.ldap.Attribute) ArrayList(java.util.ArrayList) ByteString(org.forgerock.opendj.ldap.ByteString) Attr(com.iplanet.services.ldap.Attr) LDAPServiceException(com.iplanet.services.ldap.LDAPServiceException) LdapException(org.forgerock.opendj.ldap.LdapException) IOException(java.io.IOException) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 42 with ConnectionEntryReader

use of org.forgerock.opendj.ldif.ConnectionEntryReader in project OpenAM by OpenRock.

the class DataLayer method search.

/**
     * Performs synchronous search based on specified ldap filter. This is low
     * level API which assumes caller knows how to construct a data store filer.
     * 
     * @param principal Authenticated Principal.
     * @param guid Unique identifier for the entry.
     * @param scope Scope can be either <code>SCOPE_ONE</code>,
     *        <code>SCOPE_SUB</code> or <code>SCOPE_BASE</code>.
     * @param searchFilter Search filter for this search.
     * @param attrNames Attribute name for retrieving.
     * @param attrOnly if true, returns the names but not the values of the
     *        attributes found.
     * @param searchControl Search Control.
     * @exception UMSException if failure.
     * @exception InvalidSearchFilterException if failure
     *
     * @supported.api
     */
public SearchResults search(java.security.Principal principal, Guid guid, int scope, String searchFilter, String[] attrNames, boolean attrOnly, SearchControl searchControl) throws UMSException {
    String id = guid.getDn();
    // always add "objectclass" to attributes to get, to find the right java
    // class
    String[] attrNames1 = null;
    if (attrNames != null) {
        attrNames1 = new String[attrNames.length + 1];
        System.arraycopy(attrNames, 0, attrNames1, 0, attrNames.length);
        attrNames1[attrNames1.length - 1] = "objectclass";
    } else {
        attrNames1 = new String[] { "objectclass" };
    }
    ConnectionEntryReader ldapResults = null;
    // if searchFilter is null, search for everything under the base
    if (searchFilter == null) {
        searchFilter = "(objectclass=*)";
    }
    ResultCode errorCode;
    try {
        Connection conn = getConnection(principal);
        List<Control> controls = getSearchControls(searchControl);
        // assume replica case when replicaRetryNum is not 0
        if (replicaRetryNum != 0) {
            readLDAPEntry(conn, id, null);
        }
        SearchRequest request = null;
        int retry = 0;
        while (retry <= connNumRetry) {
            if (debug.messageEnabled()) {
                debug.message("DataLayer.search retry: " + retry);
            }
            if (searchControl != null && searchControl.isGetAllReturnAttributesEnabled()) {
                /*
                     * The array {"*"} is used, because LDAPv3 defines
                     * "*" as a special string indicating all
                     * attributes. This gets all the attributes.
                     */
                attrNames1 = new String[] { "*" };
            }
            request = LDAPRequests.newSearchRequest(id, SearchScope.valueOf(scope), searchFilter, attrNames1);
            break;
        }
        for (Control control : controls) {
            request.addControl(control);
        }
        ldapResults = conn.search(request);
        // TODO: need review and see if conn is recorded properly for
        // subsequent use
        //
        SearchResults result = new SearchResults(conn, ldapResults, conn, this);
        result.set(SearchResults.BASE_ID, id);
        result.set(SearchResults.SEARCH_FILTER, searchFilter);
        result.set(SearchResults.SEARCH_SCOPE, scope);
        if ((searchControl != null) && (searchControl.contains(SearchControl.KeyVlvRange) || searchControl.contains(SearchControl.KeyVlvJumpTo))) {
            result.set(SearchResults.EXPECT_VLV_RESPONSE, Boolean.TRUE);
        }
        if (searchControl != null && searchControl.contains(SearchControl.KeySortKeys)) {
            SortKey[] sortKeys = searchControl.getSortKeys();
            if (sortKeys != null && sortKeys.length > 0) {
                result.set(SearchResults.SORT_KEYS, sortKeys);
            }
        }
        return result;
    } catch (LdapException e) {
        errorCode = e.getResult().getResultCode();
        if (debug.warningEnabled()) {
            debug.warning("Exception in DataLayer.search: ", e);
        }
        String msg = i18n.getString(IUMSConstants.SEARCH_FAILED);
        if (ResultCode.TIME_LIMIT_EXCEEDED.equals(errorCode)) {
            int timeLimit = searchControl != null ? searchControl.getTimeOut() : 0;
            throw new TimeLimitExceededException(String.valueOf(timeLimit), e);
        } else if (ResultCode.SIZE_LIMIT_EXCEEDED.equals(errorCode)) {
            int sizeLimit = searchControl != null ? searchControl.getMaxResults() : 0;
            throw new SizeLimitExceededException(String.valueOf(sizeLimit), e);
        } else if (ResultCode.CLIENT_SIDE_PARAM_ERROR.equals(errorCode) || ResultCode.PROTOCOL_ERROR.equals(errorCode)) {
            throw new InvalidSearchFilterException(searchFilter, e);
        } else {
            throw new UMSException(msg, e);
        }
    }
}
Also used : SearchRequest(org.forgerock.opendj.ldap.requests.SearchRequest) Connection(org.forgerock.opendj.ldap.Connection) ByteString(org.forgerock.opendj.ldap.ByteString) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) VirtualListViewRequestControl(org.forgerock.opendj.ldap.controls.VirtualListViewRequestControl) ServerSideSortRequestControl(org.forgerock.opendj.ldap.controls.ServerSideSortRequestControl) ProxiedAuthV1RequestControl(org.forgerock.opendj.ldap.controls.ProxiedAuthV1RequestControl) Control(org.forgerock.opendj.ldap.controls.Control) LdapException(org.forgerock.opendj.ldap.LdapException) ResultCode(org.forgerock.opendj.ldap.ResultCode)

Example 43 with ConnectionEntryReader

use of org.forgerock.opendj.ldif.ConnectionEntryReader in project ddf by codice.

the class LdapClaimsHandler method retrieveClaimValues.

@Override
public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
    Principal principal = parameters.getPrincipal();
    String user = AttributeMapLoader.getUser(principal);
    if (user == null) {
        LOGGER.info("Could not determine user name, possible authentication error. Returning no claims.");
        return new ProcessedClaimCollection();
    }
    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();
    Connection connection = null;
    try {
        AndFilter filter = new AndFilter();
        filter.and(new EqualsFilter("objectclass", this.getObjectClass())).and(new EqualsFilter(this.getUserNameAttribute(), user));
        List<String> searchAttributeList = new ArrayList<String>();
        for (Claim claim : claims) {
            if (getClaimsLdapAttributeMapping().keySet().contains(claim.getClaimType().toString())) {
                searchAttributeList.add(getClaimsLdapAttributeMapping().get(claim.getClaimType().toString()));
            } else {
                LOGGER.debug("Unsupported claim: {}", claim.getClaimType());
            }
        }
        String[] searchAttributes = null;
        searchAttributes = searchAttributeList.toArray(new String[searchAttributeList.size()]);
        connection = connectionFactory.getConnection();
        if (connection != null) {
            BindRequest request = BindMethodChooser.selectBindMethod(bindMethod, bindUserDN, bindUserCredentials, kerberosRealm, kdcAddress);
            BindResult bindResult = connection.bind(request);
            if (bindResult.isSuccess()) {
                String baseDN = AttributeMapLoader.getBaseDN(principal, getUserBaseDN(), overrideCertDn);
                LOGGER.trace("Executing ldap search with base dn of {} and filter of {}", baseDN, filter.toString());
                ConnectionEntryReader entryReader = connection.search(baseDN, SearchScope.WHOLE_SUBTREE, filter.toString(), searchAttributes);
                SearchResultEntry entry;
                while (entryReader.hasNext()) {
                    entry = entryReader.readEntry();
                    for (Claim claim : claims) {
                        URI claimType = claim.getClaimType();
                        String ldapAttribute = getClaimsLdapAttributeMapping().get(claimType.toString());
                        Attribute attr = entry.getAttribute(ldapAttribute);
                        if (attr == null) {
                            LOGGER.trace("Claim '{}' is null", claim.getClaimType());
                        } else {
                            ProcessedClaim c = new ProcessedClaim();
                            c.setClaimType(claimType);
                            c.setPrincipal(principal);
                            for (ByteString value : attr) {
                                String itemValue = value.toString();
                                if (this.isX500FilterEnabled()) {
                                    try {
                                        X500Principal x500p = new X500Principal(itemValue);
                                        itemValue = x500p.getName();
                                        int index = itemValue.indexOf('=');
                                        itemValue = itemValue.substring(index + 1, itemValue.indexOf(',', index));
                                    } catch (Exception ex) {
                                        // Ignore, not X500 compliant thus use the whole
                                        // string as the value
                                        LOGGER.debug("Not X500 compliant", ex);
                                    }
                                }
                                c.addValue(itemValue);
                            }
                            claimsColl.add(c);
                        }
                    }
                }
            } else {
                LOGGER.info("LDAP Connection failed.");
            }
        }
    } catch (LdapException e) {
        LOGGER.info("Cannot connect to server, therefore unable to set user attributes. Set log level for \"ddf.security.sts.claimsHandler\" to DEBUG for more information");
        LOGGER.debug("Cannot connect to server, therefore unable to set user attributes.", e);
    } catch (SearchResultReferenceIOException e) {
        LOGGER.info("Unable to set user attributes. Set log level for \"ddf.security.sts.claimsHandler\" to DEBUG for more information");
        LOGGER.debug("Unable to set user attributes.", e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    return claimsColl;
}
Also used : ProcessedClaimCollection(org.apache.cxf.sts.claims.ProcessedClaimCollection) Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) ArrayList(java.util.ArrayList) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) URI(java.net.URI) LdapException(org.forgerock.opendj.ldap.LdapException) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) AndFilter(org.springframework.ldap.filter.AndFilter) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) ProcessedClaim(org.apache.cxf.sts.claims.ProcessedClaim) BindResult(org.forgerock.opendj.ldap.responses.BindResult) X500Principal(javax.security.auth.x500.X500Principal) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) LdapException(org.forgerock.opendj.ldap.LdapException) X500Principal(javax.security.auth.x500.X500Principal) Principal(java.security.Principal) ProcessedClaim(org.apache.cxf.sts.claims.ProcessedClaim) Claim(org.apache.cxf.rt.security.claims.Claim) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 44 with ConnectionEntryReader

use of org.forgerock.opendj.ldif.ConnectionEntryReader in project ddf by codice.

the class RoleClaimsHandlerTest method testRetrieveClaimsValuesNotNullPrincipal.

@Test
public void testRetrieveClaimsValuesNotNullPrincipal() throws LdapException, SearchResultReferenceIOException {
    BindResult bindResult = mock(BindResult.class);
    ClaimsParameters claimsParameters;
    Connection connection = mock(Connection.class);
    ConnectionEntryReader membershipReader = mock(ConnectionEntryReader.class);
    ConnectionEntryReader groupNameReader = mock(ConnectionEntryReader.class);
    LDAPConnectionFactory connectionFactory = PowerMockito.mock(LDAPConnectionFactory.class);
    LinkedAttribute membershipAttribute = new LinkedAttribute("uid");
    LinkedAttribute groupNameAttribute = new LinkedAttribute("cn");
    ProcessedClaimCollection processedClaims;
    RoleClaimsHandler claimsHandler;
    SearchResultEntry membershipSearchResult = mock(SearchResultEntry.class);
    SearchResultEntry groupNameSearchResult = mock(SearchResultEntry.class);
    String groupName = "avengers";
    when(bindResult.isSuccess()).thenReturn(true);
    membershipAttribute.add("tstark");
    when(membershipSearchResult.getAttribute(anyString())).thenReturn(membershipAttribute);
    // hasNext() returns 'true' the first time, then 'false' every time after.
    when(membershipReader.hasNext()).thenReturn(true, false);
    when(membershipReader.readEntry()).thenReturn(membershipSearchResult);
    groupNameAttribute.add(groupName);
    when(groupNameSearchResult.getAttribute(anyString())).thenReturn(groupNameAttribute);
    when(groupNameReader.hasNext()).thenReturn(true, false);
    when(groupNameReader.readEntry()).thenReturn(groupNameSearchResult);
    when(connection.bind(anyObject())).thenReturn(bindResult);
    when(connection.search(anyObject(), anyObject(), eq("(&(objectClass=groupOfNames)(member=uid=tstark,))"), anyVararg())).thenReturn(groupNameReader);
    when(connection.search(anyString(), anyObject(), anyString(), matches("uid"))).thenReturn(membershipReader);
    when(connectionFactory.getConnection()).thenReturn(connection);
    claimsHandler = new RoleClaimsHandler();
    claimsHandler.setLdapConnectionFactory(connectionFactory);
    claimsHandler.setBindMethod("Simple");
    claimsHandler.setBindUserCredentials("foo");
    claimsHandler.setBindUserDN("bar");
    claimsParameters = new ClaimsParameters();
    claimsParameters.setPrincipal(new UserPrincipal(USER_CN));
    ClaimCollection claimCollection = new ClaimCollection();
    processedClaims = claimsHandler.retrieveClaimValues(claimCollection, claimsParameters);
    assertThat(processedClaims, hasSize(1));
    ProcessedClaim claim = processedClaims.get(0);
    assertThat(claim.getPrincipal(), equalTo(new UserPrincipal(USER_CN)));
    assertThat(claim.getValues(), hasSize(1));
    assertThat(claim.getValues().get(0), equalTo(groupName));
}
Also used : ProcessedClaimCollection(org.apache.cxf.sts.claims.ProcessedClaimCollection) Connection(org.forgerock.opendj.ldap.Connection) Matchers.anyString(org.mockito.Matchers.anyString) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ClaimsParameters(org.apache.cxf.sts.claims.ClaimsParameters) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) ProcessedClaim(org.apache.cxf.sts.claims.ProcessedClaim) BindResult(org.forgerock.opendj.ldap.responses.BindResult) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) ClaimCollection(org.apache.cxf.rt.security.claims.ClaimCollection) ProcessedClaimCollection(org.apache.cxf.sts.claims.ProcessedClaimCollection) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 45 with ConnectionEntryReader

use of org.forgerock.opendj.ldif.ConnectionEntryReader in project ddf by codice.

the class RoleClaimsHandler method retrieveClaimValues.

@Override
public ProcessedClaimCollection retrieveClaimValues(ClaimCollection claims, ClaimsParameters parameters) {
    String[] attributes = { groupNameAttribute, memberNameAttribute };
    ProcessedClaimCollection claimsColl = new ProcessedClaimCollection();
    Connection connection = null;
    try {
        Principal principal = parameters.getPrincipal();
        String user = AttributeMapLoader.getUser(principal);
        if (user == null) {
            LOGGER.info("Could not determine user name, possible authentication error. Returning no claims.");
            return new ProcessedClaimCollection();
        }
        connection = connectionFactory.getConnection();
        if (connection != null) {
            BindRequest request = BindMethodChooser.selectBindMethod(bindMethod, bindUserDN, bindUserCredentials, kerberosRealm, kdcAddress);
            BindResult bindResult = connection.bind(request);
            String membershipValue = user;
            AndFilter filter;
            ConnectionEntryReader entryReader;
            if (!membershipUserAttribute.equals(loginUserAttribute)) {
                String baseDN = AttributeMapLoader.getBaseDN(principal, userBaseDn, overrideCertDn);
                filter = new AndFilter();
                filter.and(new EqualsFilter(this.getLoginUserAttribute(), user));
                entryReader = connection.search(baseDN, SearchScope.WHOLE_SUBTREE, filter.toString(), membershipUserAttribute);
                while (entryReader.hasNext()) {
                    SearchResultEntry entry = entryReader.readEntry();
                    Attribute attr = entry.getAttribute(membershipUserAttribute);
                    if (attr != null) {
                        for (ByteString value : attr) {
                            membershipValue = value.toString();
                        }
                    }
                }
            }
            filter = new AndFilter();
            String userBaseDN = AttributeMapLoader.getBaseDN(principal, getUserBaseDn(), overrideCertDn);
            filter.and(new EqualsFilter("objectClass", getObjectClass())).and(new EqualsFilter(getMemberNameAttribute(), getMembershipUserAttribute() + "=" + membershipValue + "," + userBaseDN));
            if (bindResult.isSuccess()) {
                LOGGER.trace("Executing ldap search with base dn of {} and filter of {}", groupBaseDn, filter.toString());
                entryReader = connection.search(groupBaseDn, SearchScope.WHOLE_SUBTREE, filter.toString(), attributes);
                SearchResultEntry entry;
                while (entryReader.hasNext()) {
                    entry = entryReader.readEntry();
                    Attribute attr = entry.getAttribute(groupNameAttribute);
                    if (attr == null) {
                        LOGGER.trace("Claim '{}' is null", roleClaimType);
                    } else {
                        ProcessedClaim c = new ProcessedClaim();
                        c.setClaimType(getRoleURI());
                        c.setPrincipal(principal);
                        for (ByteString value : attr) {
                            String itemValue = value.toString();
                            c.addValue(itemValue);
                        }
                        claimsColl.add(c);
                    }
                }
            } else {
                LOGGER.info("LDAP Connection failed.");
            }
        }
    } catch (LdapException e) {
        LOGGER.info("Cannot connect to server, therefore unable to set role claims. Set log level for \"ddf.security.sts.claimsHandler\" to DEBUG for more information.");
        LOGGER.debug("Cannot connect to server, therefore unable to set role claims.", e);
    } catch (SearchResultReferenceIOException e) {
        LOGGER.info("Unable to set role claims. Set log level for \"ddf.security.sts.claimsHandler\" to DEBUG for more information.");
        LOGGER.debug("Unable to set role claims.", e);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    return claimsColl;
}
Also used : ProcessedClaimCollection(org.apache.cxf.sts.claims.ProcessedClaimCollection) Attribute(org.forgerock.opendj.ldap.Attribute) ByteString(org.forgerock.opendj.ldap.ByteString) Connection(org.forgerock.opendj.ldap.Connection) BindRequest(org.forgerock.opendj.ldap.requests.BindRequest) ByteString(org.forgerock.opendj.ldap.ByteString) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) AndFilter(org.springframework.ldap.filter.AndFilter) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) ProcessedClaim(org.apache.cxf.sts.claims.ProcessedClaim) BindResult(org.forgerock.opendj.ldap.responses.BindResult) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) LdapException(org.forgerock.opendj.ldap.LdapException) Principal(java.security.Principal) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Aggregations

ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)48 LdapException (org.forgerock.opendj.ldap.LdapException)38 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)38 Connection (org.forgerock.opendj.ldap.Connection)35 ByteString (org.forgerock.opendj.ldap.ByteString)26 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)26 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)19 ResultCode (org.forgerock.opendj.ldap.ResultCode)18 HashSet (java.util.HashSet)17 Attribute (org.forgerock.opendj.ldap.Attribute)16 PolicyException (com.sun.identity.policy.PolicyException)12 SSOException (com.iplanet.sso.SSOException)11 IOException (java.io.IOException)10 InvalidNameException (com.sun.identity.policy.InvalidNameException)9 NameNotFoundException (com.sun.identity.policy.NameNotFoundException)9 SMSException (com.sun.identity.sm.SMSException)7 ArrayList (java.util.ArrayList)7 LinkedHashSet (java.util.LinkedHashSet)7 DN (org.forgerock.opendj.ldap.DN)7 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)5