Search in sources :

Example 91 with Connection

use of org.forgerock.opendj.ldap.Connection in project ddf by codice.

the class RoleClaimsHandler method retrieveClaims.

@Override
public ClaimsCollection retrieveClaims(ClaimsParameters parameters) {
    String[] attributes = { groupNameAttribute, memberNameAttribute };
    ClaimsCollection claimsColl = new ClaimsCollectionImpl();
    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 ClaimsCollectionImpl();
        }
        connection = connectionFactory.getConnection();
        if (connection != null) {
            BindRequest request = BindMethodChooser.selectBindMethod(bindMethod, bindUserDN, bindUserCredentials, kerberosRealm, kdcAddress);
            BindResult bindResult = connection.bind(request);
            String membershipValue = user;
            String baseDN = attributeMapLoader.getBaseDN(principal, userBaseDn, overrideCertDn);
            AndFilter filter = new AndFilter();
            filter.and(new EqualsFilter(this.getLoginUserAttribute(), user));
            ConnectionEntryReader entryReader = connection.search(baseDN, SearchScope.WHOLE_SUBTREE, filter.toString(), membershipUserAttribute);
            String userDN = String.format("%s=%s,%s", loginUserAttribute, user, baseDN);
            String specificUserBaseDN = baseDN;
            while (entryReader.hasNext()) {
                if (entryReader.isEntry()) {
                    SearchResultEntry entry = entryReader.readEntry();
                    userDN = entry.getName().toString();
                    specificUserBaseDN = userDN.substring(userDN.indexOf(',') + 1);
                    if (!membershipUserAttribute.equals(loginUserAttribute)) {
                        Attribute attr = entry.getAttribute(membershipUserAttribute);
                        if (attr != null) {
                            for (ByteString value : attr) {
                                membershipValue = value.toString();
                            }
                        }
                    }
                } else {
                    // Got a continuation reference
                    LOGGER.debug("Referral ignored while searching for user {}", user);
                    entryReader.readReference();
                }
            }
            filter = new AndFilter();
            filter.and(new EqualsFilter("objectClass", getObjectClass())).and(new OrFilter().or(new EqualsFilter(getMemberNameAttribute(), getMembershipUserAttribute() + "=" + membershipValue + "," + specificUserBaseDN)).or(new EqualsFilter(getMemberNameAttribute(), userDN)));
            if (bindResult.isSuccess()) {
                LOGGER.trace("Executing ldap search with base dn of {} and filter of {}", groupBaseDn, filter);
                entryReader = connection.search(groupBaseDn, SearchScope.WHOLE_SUBTREE, filter.toString(), attributes);
                SearchResultEntry entry;
                while (entryReader.hasNext()) {
                    if (entryReader.isEntry()) {
                        entry = entryReader.readEntry();
                        Attribute attr = entry.getAttribute(groupNameAttribute);
                        if (attr == null) {
                            LOGGER.trace("Claim '{}' is null", roleClaimType);
                        } else {
                            Claim claim = new ClaimImpl(roleClaimType);
                            for (ByteString value : attr) {
                                String itemValue = value.toString();
                                claim.addValue(itemValue);
                            }
                            claimsColl.add(claim);
                        }
                    } else {
                        // Got a continuation reference
                        LOGGER.debug("Referral ignored while searching for user {}", user);
                        entryReader.readReference();
                    }
                }
            } 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 : 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) ClaimImpl(ddf.security.claims.impl.ClaimImpl) ByteString(org.forgerock.opendj.ldap.ByteString) OrFilter(org.springframework.ldap.filter.OrFilter) SearchResultReferenceIOException(org.forgerock.opendj.ldap.SearchResultReferenceIOException) AndFilter(org.springframework.ldap.filter.AndFilter) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) ClaimsCollectionImpl(ddf.security.claims.impl.ClaimsCollectionImpl) ClaimsCollection(ddf.security.claims.ClaimsCollection) BindResult(org.forgerock.opendj.ldap.responses.BindResult) EqualsFilter(org.springframework.ldap.filter.EqualsFilter) LdapException(org.forgerock.opendj.ldap.LdapException) Principal(java.security.Principal) Claim(ddf.security.claims.Claim) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry)

Example 92 with Connection

use of org.forgerock.opendj.ldap.Connection in project ddf by codice.

the class RoleClaimsHandlerTest method testRetrieveClaimsValuesNestedUserOU.

@Test
public void testRetrieveClaimsValuesNestedUserOU() 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);
    LinkedAttribute membershipAttribute = new LinkedAttribute("cn");
    LinkedAttribute groupNameAttribute = new LinkedAttribute("cn");
    ClaimsCollection processedClaims;
    RoleClaimsHandler claimsHandler;
    SearchResultEntry membershipSearchResult = mock(SearchResultEntry.class);
    DN resultDN = DN.valueOf("uid=tstark,OU=nested,");
    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.isEntry()).thenReturn(true);
    when(membershipReader.readEntry()).thenReturn(membershipSearchResult);
    when(membershipSearchResult.getName()).thenReturn(resultDN);
    groupNameAttribute.add(groupName);
    when(groupNameSearchResult.getAttribute(anyString())).thenReturn(groupNameAttribute);
    when(groupNameReader.hasNext()).thenReturn(true, false);
    when(groupNameReader.isEntry()).thenReturn(true);
    when(groupNameReader.readEntry()).thenReturn(groupNameSearchResult);
    when(connection.bind(any())).thenReturn(bindResult);
    when(connection.search(any(), any(), eq("(&(objectClass=groupOfNames)(|(member=cn=tstark,OU=nested,)(member=uid=tstark,OU=nested,)))"), any())).thenReturn(groupNameReader);
    when(connection.search(anyString(), any(), anyString(), matches("cn"))).thenReturn(membershipReader);
    claimsHandler = new RoleClaimsHandler(new AttributeMapLoader(new SubjectUtils()));
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    when(mockConnectionFactory.getConnection()).thenReturn(connection);
    claimsHandler.setLdapConnectionFactory(mockConnectionFactory);
    claimsHandler.setBindMethod("Simple");
    claimsHandler.setBindUserCredentials("foo");
    claimsHandler.setBindUserDN("bar");
    claimsHandler.setMembershipUserAttribute("cn");
    claimsHandler.setLoginUserAttribute("uid");
    claimsParameters = new ClaimsParametersImpl(new UserPrincipal(USER_CN), new HashSet<>(), new HashMap<>());
    processedClaims = claimsHandler.retrieveClaims(claimsParameters);
    assertThat(processedClaims, hasSize(1));
    Claim claim = processedClaims.get(0);
    assertThat(claim.getValues(), hasSize(1));
    assertThat(claim.getValues().get(0), equalTo(groupName));
}
Also used : SubjectUtils(ddf.security.service.impl.SubjectUtils) HashMap(java.util.HashMap) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ClaimsParameters(ddf.security.claims.ClaimsParameters) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) ClaimsParametersImpl(ddf.security.claims.impl.ClaimsParametersImpl) BindResult(org.forgerock.opendj.ldap.responses.BindResult) ClaimsCollection(ddf.security.claims.ClaimsCollection) Claim(ddf.security.claims.Claim) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 93 with Connection

use of org.forgerock.opendj.ldap.Connection 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);
    LinkedAttribute membershipAttribute = new LinkedAttribute("uid");
    LinkedAttribute groupNameAttribute = new LinkedAttribute("cn");
    ClaimsCollection processedClaims;
    RoleClaimsHandler claimsHandler;
    SearchResultEntry membershipSearchResult = mock(SearchResultEntry.class);
    DN resultDN = DN.valueOf("uid=tstark,");
    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.isEntry()).thenReturn(true);
    when(membershipReader.readEntry()).thenReturn(membershipSearchResult);
    when(membershipSearchResult.getName()).thenReturn(resultDN);
    groupNameAttribute.add(groupName);
    when(groupNameSearchResult.getAttribute(anyString())).thenReturn(groupNameAttribute);
    when(groupNameReader.hasNext()).thenReturn(true, false);
    when(groupNameReader.isEntry()).thenReturn(true);
    when(groupNameReader.readEntry()).thenReturn(groupNameSearchResult);
    when(connection.bind(any())).thenReturn(bindResult);
    when(connection.search(any(), any(), eq("(&(objectClass=groupOfNames)(|(member=uid=tstark,)(member=uid=tstark,)))"), any())).thenReturn(groupNameReader);
    when(connection.search(anyString(), any(), anyString(), matches("uid"))).thenReturn(membershipReader);
    claimsHandler = new RoleClaimsHandler(new AttributeMapLoader(new SubjectUtils()));
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    when(mockConnectionFactory.getConnection()).thenReturn(connection);
    claimsHandler.setLdapConnectionFactory(mockConnectionFactory);
    claimsHandler.setBindMethod("Simple");
    claimsHandler.setBindUserCredentials("foo");
    claimsHandler.setBindUserDN("bar");
    claimsParameters = new ClaimsParametersImpl(new UserPrincipal(USER_CN), new HashSet<>(), new HashMap<>());
    processedClaims = claimsHandler.retrieveClaims(claimsParameters);
    assertThat(processedClaims, hasSize(1));
    Claim claim = processedClaims.get(0);
    assertThat(claim.getValues(), hasSize(1));
    assertThat(claim.getValues().get(0), equalTo(groupName));
}
Also used : SubjectUtils(ddf.security.service.impl.SubjectUtils) HashMap(java.util.HashMap) Connection(org.forgerock.opendj.ldap.Connection) DN(org.forgerock.opendj.ldap.DN) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) ClaimsParameters(ddf.security.claims.ClaimsParameters) LinkedAttribute(org.forgerock.opendj.ldap.LinkedAttribute) ConnectionEntryReader(org.forgerock.opendj.ldif.ConnectionEntryReader) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) ClaimsParametersImpl(ddf.security.claims.impl.ClaimsParametersImpl) BindResult(org.forgerock.opendj.ldap.responses.BindResult) ClaimsCollection(ddf.security.claims.ClaimsCollection) Claim(ddf.security.claims.Claim) SearchResultEntry(org.forgerock.opendj.ldap.responses.SearchResultEntry) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 94 with Connection

use of org.forgerock.opendj.ldap.Connection in project admin-console-beta by connexta.

the class LdapTestClaimMappings method performFunction.

@Override
public BooleanField performFunction() {
    try (LdapConnectionAttempt connectionAttempt = utils.bindUserToLdapConnection(conn, bindInfo)) {
        addErrorMessages(connectionAttempt);
        if (containsErrorMsgs()) {
            return new BooleanField(false);
        }
        Connection ldapConnection = connectionAttempt.getResult();
        addErrorMessages(utils.checkDirExists(baseUserDn, ldapConnection));
        // Short-circuit return here, if either the user or group directory does not exist
        if (containsErrorMsgs()) {
            return new BooleanField(false);
        }
        claimMappings.getList().stream().map(ClaimsMapEntry::claimValueField).filter(claim -> !mappingAttributeFound(ldapConnection, claim.getValue())).forEach(claim -> addErrorMessage(userAttributeNotFoundError(claim.getPath())));
    } catch (IOException e) {
        LOGGER.warn("Error closing LDAP connection", e);
    }
    return new BooleanField(!containsErrorMsgs());
}
Also used : Connection(org.forgerock.opendj.ldap.Connection) LdapBindUserInfo(org.codice.ddf.admin.ldap.fields.connection.LdapBindUserInfo) Filter(org.forgerock.opendj.ldap.Filter) LoggerFactory(org.slf4j.LoggerFactory) SearchScope(org.forgerock.opendj.ldap.SearchScope) TestFunctionField(org.codice.ddf.admin.common.fields.base.function.TestFunctionField) LdapConnectionAttempt(org.codice.ddf.admin.ldap.commons.LdapConnectionAttempt) ImmutableList(com.google.common.collect.ImmutableList) BooleanField(org.codice.ddf.admin.common.fields.base.scalar.BooleanField) LdapDistinguishedName(org.codice.ddf.admin.ldap.fields.LdapDistinguishedName) LdapTestingUtils(org.codice.ddf.admin.ldap.commons.LdapTestingUtils) FunctionField(org.codice.ddf.admin.api.fields.FunctionField) LdapConnectionField(org.codice.ddf.admin.ldap.fields.connection.LdapConnectionField) Field(org.codice.ddf.admin.api.Field) ImmutableSet(com.google.common.collect.ImmutableSet) ClaimsMapEntry(org.codice.ddf.admin.security.common.fields.wcpm.ClaimsMapEntry) Logger(org.slf4j.Logger) LdapAttributeName(org.codice.ddf.admin.ldap.fields.LdapAttributeName) Set(java.util.Set) StringField(org.codice.ddf.admin.common.fields.base.scalar.StringField) StsServiceProperties(org.codice.ddf.admin.security.common.services.StsServiceProperties) IOException(java.io.IOException) ConfiguratorSuite(org.codice.ddf.internal.admin.configurator.actions.ConfiguratorSuite) LdapMessages(org.codice.ddf.admin.ldap.commons.LdapMessages) Collectors(java.util.stream.Collectors) SecurityMessages(org.codice.ddf.admin.security.common.SecurityMessages) List(java.util.List) LdapMessages.userAttributeNotFoundError(org.codice.ddf.admin.ldap.commons.LdapMessages.userAttributeNotFoundError) DefaultMessages(org.codice.ddf.admin.common.report.message.DefaultMessages) SecurityValidation(org.codice.ddf.admin.security.common.SecurityValidation) BooleanField(org.codice.ddf.admin.common.fields.base.scalar.BooleanField) ClaimsMapEntry(org.codice.ddf.admin.security.common.fields.wcpm.ClaimsMapEntry) Connection(org.forgerock.opendj.ldap.Connection) IOException(java.io.IOException) LdapConnectionAttempt(org.codice.ddf.admin.ldap.commons.LdapConnectionAttempt)

Aggregations

Connection (org.forgerock.opendj.ldap.Connection)94 LdapException (org.forgerock.opendj.ldap.LdapException)72 ByteString (org.forgerock.opendj.ldap.ByteString)47 SearchResultEntry (org.forgerock.opendj.ldap.responses.SearchResultEntry)46 ConnectionEntryReader (org.forgerock.opendj.ldif.ConnectionEntryReader)39 ResultCode (org.forgerock.opendj.ldap.ResultCode)29 Attribute (org.forgerock.opendj.ldap.Attribute)27 HashSet (java.util.HashSet)26 SearchRequest (org.forgerock.opendj.ldap.requests.SearchRequest)20 SearchResultReferenceIOException (org.forgerock.opendj.ldap.SearchResultReferenceIOException)19 IOException (java.io.IOException)18 SSOException (com.iplanet.sso.SSOException)15 PolicyException (com.sun.identity.policy.PolicyException)14 SMSException (com.sun.identity.sm.SMSException)13 LinkedAttribute (org.forgerock.opendj.ldap.LinkedAttribute)13 ModifyRequest (org.forgerock.opendj.ldap.requests.ModifyRequest)12 BindResult (org.forgerock.opendj.ldap.responses.BindResult)12 DN (org.forgerock.opendj.ldap.DN)11 CaseInsensitiveHashSet (com.sun.identity.common.CaseInsensitiveHashSet)10 InvalidNameException (com.sun.identity.policy.InvalidNameException)10