Search in sources :

Example 1 with ModifyRequest

use of org.ldaptive.ModifyRequest in project cas by apereo.

the class LdapTestUtils method modifyLdapEntry.

/**
 * Modify ldap entry.
 *
 * @param serverCon the server con
 * @param dn        the dn
 * @param attr      the attr
 * @param add       the add
 */
public static void modifyLdapEntry(final LDAPConnection serverCon, final String dn, final LdapAttribute attr, final AttributeModificationType add) {
    try {
        final String address = "ldap://" + serverCon.getConnectedAddress() + ':' + serverCon.getConnectedPort();
        try (Connection conn = DefaultConnectionFactory.getConnection(address)) {
            try {
                conn.open();
                final ModifyOperation modify = new ModifyOperation(conn);
                modify.execute(new ModifyRequest(dn, new AttributeModification(add, attr)));
            } catch (final Exception e) {
                LOGGER.debug(e.getMessage(), e);
            }
        }
    } finally {
        serverCon.close();
    }
}
Also used : AttributeModification(org.ldaptive.AttributeModification) LDAPConnection(com.unboundid.ldap.sdk.LDAPConnection) Connection(org.ldaptive.Connection) ModifyOperation(org.ldaptive.ModifyOperation) ModifyRequest(org.ldaptive.ModifyRequest) IOException(java.io.IOException)

Example 2 with ModifyRequest

use of org.ldaptive.ModifyRequest in project cas by apereo.

the class LdapUtils method executePasswordModifyOperation.

/**
 * Execute a password modify operation.
 *
 * @param currentDn         the current dn
 * @param connectionFactory the connection factory
 * @param oldPassword       the old password
 * @param newPassword       the new password
 * @param type              the type
 * @return true /false
 * <p>
 * AD NOTE: Resetting passwords requires binding to AD as user with privileges to reset other users passwords
 * and it does not validate old password or respect directory policies such as history or minimum password age.
 * Changing a password with the old password does respect directory policies and requires no account operator
 * privileges on the bind user. Pass in blank old password if reset is in order (e.g. forgot password) vs.
 * letting user change their own (e.g. expiring) password.
 */
public static boolean executePasswordModifyOperation(final String currentDn, final ConnectionFactory connectionFactory, final String oldPassword, final String newPassword, final AbstractLdapProperties.LdapType type) {
    try {
        val connConfig = connectionFactory.getConnectionConfig();
        val secureLdap = connConfig.getLdapUrl() != null && !connConfig.getLdapUrl().toLowerCase().contains("ldaps://");
        if (connConfig.getUseStartTLS() || secureLdap) {
            LOGGER.warn("Executing password modification op under a non-secure LDAP connection; " + "To modify password attributes, the connection to the LDAP server {} be secured and/or encrypted.", type == AbstractLdapProperties.LdapType.AD ? "MUST" : "SHOULD");
        }
        if (type == AbstractLdapProperties.LdapType.AD) {
            LOGGER.debug("Executing password change op for active directory based on " + "[https://support.microsoft.com/en-us/kb/269190]" + "change type: [{}]", StringUtils.isBlank(oldPassword) ? "reset" : "change");
            val operation = new ModifyOperation(connectionFactory);
            val response = StringUtils.isBlank(oldPassword) ? operation.execute(new ModifyRequest(currentDn, new AttributeModification(AttributeModification.Type.REPLACE, new UnicodePwdAttribute(newPassword)))) : operation.execute(new ModifyRequest(currentDn, new AttributeModification(AttributeModification.Type.DELETE, new UnicodePwdAttribute(oldPassword)), new AttributeModification(AttributeModification.Type.ADD, new UnicodePwdAttribute(newPassword))));
            LOGGER.debug("Result code [{}], message: [{}]", response.getResultCode(), response.getDiagnosticMessage());
            return response.getResultCode() == ResultCode.SUCCESS;
        }
        LOGGER.debug("Executing password modification op for generic LDAP");
        val operation = new ExtendedOperation(connectionFactory);
        val response = operation.execute(new PasswordModifyRequest(currentDn, StringUtils.isNotBlank(oldPassword) ? oldPassword : null, newPassword));
        LOGGER.debug("Result code [{}], message: [{}]", response.getResultCode(), response.getDiagnosticMessage());
        return response.getResultCode() == ResultCode.SUCCESS;
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
    return false;
}
Also used : lombok.val(lombok.val) ExtendedOperation(org.ldaptive.extended.ExtendedOperation) UnicodePwdAttribute(org.ldaptive.ad.UnicodePwdAttribute) AttributeModification(org.ldaptive.AttributeModification) PasswordModifyRequest(org.ldaptive.extended.PasswordModifyRequest) ModifyOperation(org.ldaptive.ModifyOperation) ModifyRequest(org.ldaptive.ModifyRequest) PasswordModifyRequest(org.ldaptive.extended.PasswordModifyRequest) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) LdapException(org.ldaptive.LdapException)

Example 3 with ModifyRequest

use of org.ldaptive.ModifyRequest in project cas by apereo.

the class LdapUtils method executeModifyOperation.

/**
 * Execute modify operation boolean.
 *
 * @param currentDn         the current dn
 * @param connectionFactory the connection factory
 * @param attributes        the attributes
 * @return true/false
 */
public static boolean executeModifyOperation(final String currentDn, final ConnectionFactory connectionFactory, final Map<String, Set<String>> attributes) {
    try {
        val operation = new ModifyOperation(connectionFactory);
        val mods = attributes.entrySet().stream().map(entry -> {
            val values = entry.getValue().toArray(ArrayUtils.EMPTY_STRING_ARRAY);
            val attr = new LdapAttribute(entry.getKey(), values);
            LOGGER.debug("Constructed new attribute [{}]", attr);
            return new AttributeModification(AttributeModification.Type.REPLACE, attr);
        }).toArray(AttributeModification[]::new);
        val request = new ModifyRequest(currentDn, mods);
        val response = operation.execute(request);
        LOGGER.debug("Result code [{}], message: [{}]", response.getResultCode(), response.getDiagnosticMessage());
        return response.getResultCode() == ResultCode.SUCCESS;
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
    return false;
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) ConnectionFactory(org.ldaptive.ConnectionFactory) AllowAnyTrustManager(org.ldaptive.ssl.AllowAnyTrustManager) SearchOperation(org.ldaptive.SearchOperation) SearchResponse(org.ldaptive.SearchResponse) GroovyPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.password.GroovyPasswordPolicyHandlingStrategy) AddRequest(org.ldaptive.AddRequest) AuthenticationPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.AuthenticationPasswordPolicyHandlingStrategy) DnResolver(org.ldaptive.auth.DnResolver) StringUtils(org.apache.commons.lang3.StringUtils) DefaultLdapAccountStateHandler(org.apereo.cas.authentication.support.DefaultLdapAccountStateHandler) ActivePassiveConnectionStrategy(org.ldaptive.ActivePassiveConnectionStrategy) AllowAnyHostnameVerifier(org.ldaptive.ssl.AllowAnyHostnameVerifier) FormatDnResolver(org.ldaptive.auth.FormatDnResolver) CompareConnectionValidator(org.ldaptive.CompareConnectionValidator) Map(java.util.Map) AbstractLdapAuthenticationProperties(org.apereo.cas.configuration.model.support.ldap.AbstractLdapAuthenticationProperties) FreeIPAAuthenticationResponseHandler(org.ldaptive.auth.ext.FreeIPAAuthenticationResponseHandler) ApplicationContextProvider(org.apereo.cas.util.spring.ApplicationContextProvider) SimpleBindAuthenticationHandler(org.ldaptive.auth.SimpleBindAuthenticationHandler) CompareAuthenticationHandler(org.ldaptive.auth.CompareAuthenticationHandler) ConnectionConfig(org.ldaptive.ConnectionConfig) Unchecked(org.jooq.lambda.Unchecked) SaslConfig(org.ldaptive.sasl.SaslConfig) BindConnectionInitializer(org.ldaptive.BindConnectionInitializer) ModifyRequest(org.ldaptive.ModifyRequest) PagedResultsClient(org.ldaptive.control.util.PagedResultsClient) Set(java.util.Set) DnsSrvConnectionStrategy(org.ldaptive.DnsSrvConnectionStrategy) SearchScope(org.ldaptive.SearchScope) StandardCharsets(java.nio.charset.StandardCharsets) Slf4j(lombok.extern.slf4j.Slf4j) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) FilterTemplate(org.ldaptive.FilterTemplate) AddOperation(org.ldaptive.AddOperation) LdapAttribute(org.ldaptive.LdapAttribute) DisposableBean(org.springframework.beans.factory.DisposableBean) LdapEntry(org.ldaptive.LdapEntry) ObjectGuidHandler(org.ldaptive.ad.handler.ObjectGuidHandler) RangeEntryHandler(org.ldaptive.ad.handler.RangeEntryHandler) User(org.ldaptive.auth.User) ActiveDirectoryLdapEntryHandler(org.apereo.services.persondir.support.ldap.ActiveDirectoryLdapEntryHandler) SearchEntryResolver(org.ldaptive.auth.SearchEntryResolver) ArrayList(java.util.ArrayList) UtilityClass(lombok.experimental.UtilityClass) LinkedHashMap(java.util.LinkedHashMap) SearchDnResolver(org.ldaptive.auth.SearchDnResolver) IdlePruneStrategy(org.ldaptive.pool.IdlePruneStrategy) ModifyOperation(org.ldaptive.ModifyOperation) ActiveDirectoryAuthenticationResponseHandler(org.ldaptive.auth.ext.ActiveDirectoryAuthenticationResponseHandler) FollowSearchReferralHandler(org.ldaptive.referral.FollowSearchReferralHandler) CompareRequest(org.ldaptive.CompareRequest) ServicesManager(org.apereo.cas.services.ServicesManager) MergeResultHandler(org.ldaptive.handler.MergeResultHandler) lombok.val(lombok.val) AttributeModification(org.ldaptive.AttributeModification) SearchRequest(org.ldaptive.SearchRequest) DefaultConnectionFactory(org.ldaptive.DefaultConnectionFactory) RoundRobinConnectionStrategy(org.ldaptive.RoundRobinConnectionStrategy) Mechanism(org.ldaptive.sasl.Mechanism) CaseChangeEntryHandler(org.ldaptive.handler.CaseChangeEntryHandler) PasswordExpirationAuthenticationResponseHandler(org.ldaptive.auth.ext.PasswordExpirationAuthenticationResponseHandler) AuthenticationHandlerResponse(org.ldaptive.auth.AuthenticationHandlerResponse) FastBindConnectionInitializer(org.ldaptive.ad.extended.FastBindConnectionInitializer) KeyStoreCredentialConfig(org.ldaptive.ssl.KeyStoreCredentialConfig) LdapException(org.ldaptive.LdapException) PooledConnectionFactory(org.ldaptive.PooledConnectionFactory) LdapAuthenticationHandler(org.apereo.cas.authentication.LdapAuthenticationHandler) SimpleBindRequest(org.ldaptive.SimpleBindRequest) SetFactoryBean(org.springframework.beans.factory.config.SetFactoryBean) SneakyThrows(lombok.SneakyThrows) UnicodePwdAttribute(org.ldaptive.ad.UnicodePwdAttribute) URL(java.net.URL) RequiredArgsConstructor(lombok.RequiredArgsConstructor) PasswordPolicyContext(org.apereo.cas.authentication.support.password.PasswordPolicyContext) PasswordPolicyAuthenticationRequestHandler(org.ldaptive.auth.ext.PasswordPolicyAuthenticationRequestHandler) Beans(org.apereo.cas.configuration.support.Beans) DerefAliases(org.ldaptive.DerefAliases) FunctionUtils(org.apereo.cas.util.function.FunctionUtils) PrincipalFactory(org.apereo.cas.authentication.principal.PrincipalFactory) ScriptResourceCacheManager(org.apereo.cas.util.scripting.ScriptResourceCacheManager) PasswordModifyRequest(org.ldaptive.extended.PasswordModifyRequest) URI(java.net.URI) DeleteRequest(org.ldaptive.DeleteRequest) SslConfig(org.ldaptive.ssl.SslConfig) PrimaryGroupIdHandler(org.ldaptive.ad.handler.PrimaryGroupIdHandler) X509CredentialConfig(org.ldaptive.ssl.X509CredentialConfig) AbstractLdapProperties(org.apereo.cas.configuration.model.support.ldap.AbstractLdapProperties) DefaultHostnameVerifier(org.ldaptive.ssl.DefaultHostnameVerifier) Collectors(java.util.stream.Collectors) LdapAuthenticationProperties(org.apereo.cas.configuration.model.support.ldap.LdapAuthenticationProperties) Objects(java.util.Objects) DnAttributeEntryHandler(org.ldaptive.handler.DnAttributeEntryHandler) List(java.util.List) DeleteOperation(org.ldaptive.DeleteOperation) SearchResultHandler(org.ldaptive.handler.SearchResultHandler) LdapPasswordPolicyProperties(org.apereo.cas.configuration.model.support.ldap.LdapPasswordPolicyProperties) AuthenticationRequestHandler(org.ldaptive.auth.AuthenticationRequestHandler) CoreAuthenticationUtils(org.apereo.cas.authentication.CoreAuthenticationUtils) EDirectoryAuthenticationResponseHandler(org.ldaptive.auth.ext.EDirectoryAuthenticationResponseHandler) IntStream(java.util.stream.IntStream) PasswordEncoderUtils(org.apereo.cas.authentication.support.password.PasswordEncoderUtils) ReturnAttributes(org.ldaptive.ReturnAttributes) AuthenticationResponse(org.ldaptive.auth.AuthenticationResponse) BindConnectionPassivator(org.ldaptive.pool.BindConnectionPassivator) AuthenticationCriteria(org.ldaptive.auth.AuthenticationCriteria) OptionalWarningLdapAccountStateHandler(org.apereo.cas.authentication.support.OptionalWarningLdapAccountStateHandler) ArrayUtils(org.apache.commons.lang3.ArrayUtils) Multimap(com.google.common.collect.Multimap) AuthenticationHandler(org.ldaptive.auth.AuthenticationHandler) HashSet(java.util.HashSet) EntryResolver(org.ldaptive.auth.EntryResolver) QualityOfProtection(org.ldaptive.sasl.QualityOfProtection) AuthenticationResponseHandler(org.ldaptive.auth.AuthenticationResponseHandler) Period(java.time.Period) PasswordPolicyAuthenticationResponseHandler(org.ldaptive.auth.ext.PasswordPolicyAuthenticationResponseHandler) RandomConnectionStrategy(org.ldaptive.RandomConnectionStrategy) ObjectSidHandler(org.ldaptive.ad.handler.ObjectSidHandler) RejectResultCodeLdapPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.RejectResultCodeLdapPasswordPolicyHandlingStrategy) ResultCode(org.ldaptive.ResultCode) WatchableGroovyScriptResource(org.apereo.cas.util.scripting.WatchableGroovyScriptResource) SearchConnectionValidator(org.ldaptive.SearchConnectionValidator) ApplicationContext(org.springframework.context.ApplicationContext) DefaultTrustManager(org.ldaptive.ssl.DefaultTrustManager) Authenticator(org.ldaptive.auth.Authenticator) Credential(org.ldaptive.Credential) MergeAttributeEntryHandler(org.ldaptive.handler.MergeAttributeEntryHandler) LdapSearchEntryHandlersProperties(org.apereo.cas.configuration.model.support.ldap.LdapSearchEntryHandlersProperties) SecurityStrength(org.ldaptive.sasl.SecurityStrength) PrincipalNameTransformerUtils(org.apereo.cas.authentication.principal.PrincipalNameTransformerUtils) DefaultPasswordPolicyHandlingStrategy(org.apereo.cas.authentication.support.password.DefaultPasswordPolicyHandlingStrategy) RecursiveResultHandler(org.ldaptive.handler.RecursiveResultHandler) ExtendedOperation(org.ldaptive.extended.ExtendedOperation) LdapEntryHandler(org.ldaptive.handler.LdapEntryHandler) ExecutableCompiledGroovyScript(org.apereo.cas.util.scripting.ExecutableCompiledGroovyScript) AttributeModification(org.ldaptive.AttributeModification) LdapAttribute(org.ldaptive.LdapAttribute) ModifyOperation(org.ldaptive.ModifyOperation) ModifyRequest(org.ldaptive.ModifyRequest) PasswordModifyRequest(org.ldaptive.extended.PasswordModifyRequest) AccountNotFoundException(javax.security.auth.login.AccountNotFoundException) LdapException(org.ldaptive.LdapException)

Example 4 with ModifyRequest

use of org.ldaptive.ModifyRequest in project cas by apereo.

the class LdapTestUtils method modifyLdapEntry.

/**
 * Modify ldap entry.
 *
 * @param serverCon the server con
 * @param dn        the dn
 * @param attr      the attr
 * @param add       the add
 * @param connInit  the connection initializer
 */
public static void modifyLdapEntry(final LDAPConnection serverCon, final String dn, final LdapAttribute attr, final AttributeModification.Type add, final BindConnectionInitializer connInit) {
    val address = "ldap://" + serverCon.getConnectedAddress() + ':' + serverCon.getConnectedPort();
    val config = new ConnectionConfig(address);
    if (connInit != null) {
        config.setConnectionInitializers(connInit);
    }
    LOGGER.debug("Created modification request connection configuration [{}] for [{}]", config, address);
    val connectionFactory = new DefaultConnectionFactory(config);
    try {
        val modify = new ModifyOperation(connectionFactory);
        val request = new ModifyRequest(dn, new AttributeModification(add, attr));
        LOGGER.debug("Executing modification request [{}] with type [{}] for [{}]", request, add, dn);
        val result = modify.execute(request);
        if (!result.isSuccess()) {
            LOGGER.warn("Result [{}]:[{}]", result.getResultCode(), result.getDiagnosticMessage());
        }
    } catch (final Exception e) {
        LOGGER.info(e.getMessage(), e);
    } finally {
        connectionFactory.close();
    }
}
Also used : lombok.val(lombok.val) DefaultConnectionFactory(org.ldaptive.DefaultConnectionFactory) AttributeModification(org.ldaptive.AttributeModification) ModifyOperation(org.ldaptive.ModifyOperation) ModifyRequest(org.ldaptive.ModifyRequest) ConnectionConfig(org.ldaptive.ConnectionConfig) LDAPException(com.unboundid.ldap.sdk.LDAPException) IOException(java.io.IOException)

Example 5 with ModifyRequest

use of org.ldaptive.ModifyRequest in project cas by apereo.

the class LdapPasswordSynchronizationAuthenticationPostProcessor method process.

@Override
public void process(final AuthenticationBuilder builder, final AuthenticationTransaction transaction) throws AuthenticationException {
    val primaryCredential = transaction.getPrimaryCredential();
    if (primaryCredential.isEmpty()) {
        LOGGER.warn("Current authentication transaction does not have a primary credential");
        return;
    }
    try {
        val credential = UsernamePasswordCredential.class.cast(primaryCredential.get());
        val filter = LdapUtils.newLdaptiveSearchFilter(ldapProperties.getSearchFilter(), LdapUtils.LDAP_SEARCH_FILTER_DEFAULT_PARAM_NAME, Collections.singletonList(credential.getUsername()));
        LOGGER.trace("Constructed LDAP filter [{}] to locate user and update password", filter);
        val response = LdapUtils.executeSearchOperation(searchFactory, ldapProperties.getBaseDn(), filter, this.ldapProperties.getPageSize());
        LOGGER.debug("LDAP response is [{}]", response);
        if (LdapUtils.containsResultEntry(response)) {
            val dn = response.getEntry().getDn();
            LOGGER.trace("Updating account password for [{}]", dn);
            val operation = new ModifyOperation(searchFactory);
            val mod = new AttributeModification(AttributeModification.Type.REPLACE, getLdapPasswordAttribute(credential));
            val updateResponse = operation.execute(new ModifyRequest(dn, mod));
            LOGGER.trace("Result code [{}], message: [{}]", response.getResultCode(), response.getDiagnosticMessage());
            val result = updateResponse.getResultCode() == ResultCode.SUCCESS;
            if (result) {
                LOGGER.info("Updated the LDAP entry's password for [{}] and base DN [{}]", filter.format(), ldapProperties.getBaseDn());
            } else {
                LOGGER.warn("Could not update the LDAP entry's password for [{}] and base DN [{}]", filter.format(), ldapProperties.getBaseDn());
            }
        } else {
            LOGGER.error("Could not locate an LDAP entry for [{}] and base DN [{}]", filter.format(), ldapProperties.getBaseDn());
        }
    } catch (final Exception e) {
        LoggingUtils.error(LOGGER, e);
    }
}
Also used : lombok.val(lombok.val) AttributeModification(org.ldaptive.AttributeModification) ModifyOperation(org.ldaptive.ModifyOperation) ModifyRequest(org.ldaptive.ModifyRequest)

Aggregations

AttributeModification (org.ldaptive.AttributeModification)5 ModifyOperation (org.ldaptive.ModifyOperation)5 ModifyRequest (org.ldaptive.ModifyRequest)5 lombok.val (lombok.val)4 IOException (java.io.IOException)2 AccountNotFoundException (javax.security.auth.login.AccountNotFoundException)2 ConnectionConfig (org.ldaptive.ConnectionConfig)2 DefaultConnectionFactory (org.ldaptive.DefaultConnectionFactory)2 LdapException (org.ldaptive.LdapException)2 UnicodePwdAttribute (org.ldaptive.ad.UnicodePwdAttribute)2 ExtendedOperation (org.ldaptive.extended.ExtendedOperation)2 PasswordModifyRequest (org.ldaptive.extended.PasswordModifyRequest)2 Multimap (com.google.common.collect.Multimap)1 LDAPConnection (com.unboundid.ldap.sdk.LDAPConnection)1 LDAPException (com.unboundid.ldap.sdk.LDAPException)1 URI (java.net.URI)1 URL (java.net.URL)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Period (java.time.Period)1 ArrayList (java.util.ArrayList)1