You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@directory.apache.org by el...@apache.org on 2011/11/13 00:58:42 UTC

svn commit: r1201362 [2/6] - in /directory/apacheds/branches/apacheds-osgi: interceptor-kerberos/ interceptor-kerberos/src/main/java/org/apache/directory/server/core/kerberos/ interceptors/admin/ interceptors/admin/src/main/java/org/apache/directory/se...

Modified: directory/apacheds/branches/apacheds-osgi/interceptors/authn/src/main/java/org/apache/directory/server/core/authn/AuthenticationInterceptor.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/apacheds-osgi/interceptors/authn/src/main/java/org/apache/directory/server/core/authn/AuthenticationInterceptor.java?rev=1201362&r1=1201361&r2=1201362&view=diff
==============================================================================
--- directory/apacheds/branches/apacheds-osgi/interceptors/authn/src/main/java/org/apache/directory/server/core/authn/AuthenticationInterceptor.java (original)
+++ directory/apacheds/branches/apacheds-osgi/interceptors/authn/src/main/java/org/apache/directory/server/core/authn/AuthenticationInterceptor.java Sat Nov 12 23:58:40 2011
@@ -43,20 +43,21 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import org.apache.directory.server.core.shared.DefaultCoreSession;
 import org.apache.directory.server.core.api.CoreSession;
 import org.apache.directory.server.core.api.DirectoryService;
+import org.apache.directory.server.core.api.InterceptorEnum;
 import org.apache.directory.server.core.api.LdapPrincipal;
+import org.apache.directory.server.core.api.authn.ppolicy.PasswordPolicyConfiguration;
+import org.apache.directory.server.core.api.authn.ppolicy.PasswordPolicyException;
 import org.apache.directory.server.core.api.filtering.EntryFilteringCursor;
 import org.apache.directory.server.core.api.interceptor.BaseInterceptor;
 import org.apache.directory.server.core.api.interceptor.Interceptor;
-import org.apache.directory.server.core.api.interceptor.NextInterceptor;
 import org.apache.directory.server.core.api.interceptor.context.AddOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.BindOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.CompareOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.DeleteOperationContext;
-import org.apache.directory.server.core.api.interceptor.context.EntryOperationContext;
-import org.apache.directory.server.core.api.interceptor.context.GetRootDSEOperationContext;
+import org.apache.directory.server.core.api.interceptor.context.HasEntryOperationContext;
+import org.apache.directory.server.core.api.interceptor.context.GetRootDseOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.ListOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.LookupOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.ModifyOperationContext;
@@ -66,9 +67,8 @@ import org.apache.directory.server.core.
 import org.apache.directory.server.core.api.interceptor.context.RenameOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.SearchOperationContext;
 import org.apache.directory.server.core.api.interceptor.context.UnbindOperationContext;
-import org.apache.directory.server.core.api.authn.ppolicy.PasswordPolicyConfiguration;
-import org.apache.directory.server.core.api.authn.ppolicy.PasswordPolicyException;
 import org.apache.directory.server.core.authn.ppolicy.PpolicyConfigContainer;
+import org.apache.directory.server.core.shared.DefaultCoreSession;
 import org.apache.directory.server.i18n.I18n;
 import org.apache.directory.shared.ldap.extras.controls.ppolicy.PasswordPolicy;
 import org.apache.directory.shared.ldap.extras.controls.ppolicy.PasswordPolicyErrorEnum;
@@ -115,7 +115,7 @@ public class AuthenticationInterceptor e
 
     /** A Set of all the existing Authenticator to be used by the bind operation */
     private Set<Authenticator> authenticators = new HashSet<Authenticator>();
-    
+
     /** A map of authenticators associated with the authentication level required */
     private final Map<AuthenticationLevel, Collection<Authenticator>> authenticatorsMapByType = new HashMap<AuthenticationLevel, Collection<Authenticator>>();
 
@@ -150,6 +150,7 @@ public class AuthenticationInterceptor e
      */
     public AuthenticationInterceptor()
     {
+        super( InterceptorEnum.AUTHENTICATION_INTERCEPTOR );
     }
 
 
@@ -167,7 +168,7 @@ public class AuthenticationInterceptor e
         {
             setDefaultAuthenticators();
         }
-        
+
         // Register all authenticators
         for ( Authenticator authenticator : authenticators )
         {
@@ -187,7 +188,7 @@ public class AuthenticationInterceptor e
         {
             authenticators = new HashSet<Authenticator>();
         }
-        
+
         authenticators.clear();
         authenticators.add( new AnonymousAuthenticator() );
         authenticators.add( new SimpleAuthenticator() );
@@ -226,16 +227,16 @@ public class AuthenticationInterceptor e
         {
             throw new IllegalArgumentException( "The given authenticators set is null" );
         }
-        
+
         this.authenticators.clear();
 
-        for (Authenticator authenticator : authenticators) 
+        for (Authenticator authenticator : authenticators)
         {
             this.authenticators.add( authenticator );
         }
     }
-    
-    
+
+
     /**
      * Deinitializes and deregisters all {@link Authenticator}s from this service.
      */
@@ -296,7 +297,10 @@ public class AuthenticationInterceptor e
     }
 
 
-    public void add( NextInterceptor next, AddOperationContext addContext ) throws LdapException
+    /**
+     * {@inheritDoc}
+     */
+    public void add( AddOperationContext addContext ) throws LdapException
     {
         if ( IS_DEBUG )
         {
@@ -306,14 +310,14 @@ public class AuthenticationInterceptor e
         checkAuthenticated( addContext );
 
         Entry entry = addContext.getEntry();
-        
-        
+
+
         if ( !directoryService.isPwdPolicyEnabled() )
         {
-            next.add( addContext );
+            next( addContext );
             return;
         }
-        
+
         PasswordPolicyConfiguration policyConfig = getPwdPolicy( entry );
 
         boolean isPPolicyReqCtrlPresent = addContext.hasRequestControl( PasswordPolicy.OID );
@@ -335,7 +339,7 @@ public class AuthenticationInterceptor e
             {
                 if ( isPPolicyReqCtrlPresent )
                 {
-                    PasswordPolicyDecorator responseControl = 
+                    PasswordPolicyDecorator responseControl =
                         new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
                     responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.get( e.getErrorCode() ) );
                     addContext.addResponseControl( responseControl );
@@ -346,6 +350,7 @@ public class AuthenticationInterceptor e
             }
 
             String pwdChangedTime = DateUtils.getGeneralizedTime();
+
             if ( ( policyConfig.getPwdMinAge() > 0 ) || ( policyConfig.getPwdMaxAge() > 0 ) )
             {
                 Attribute pwdChangedTimeAt = new DefaultAttribute( AT_PWD_CHANGED_TIME );
@@ -369,360 +374,312 @@ public class AuthenticationInterceptor e
             }
         }
 
-        next.add( addContext );
+        next( addContext );
     }
 
 
-    public void delete( NextInterceptor next, DeleteOperationContext deleteContext ) throws LdapException
+    /**
+     * {@inheritDoc}
+     */
+    public void bind( BindOperationContext bindContext ) throws LdapException
     {
         if ( IS_DEBUG )
         {
-            LOG.debug( "Operation Context: {}", deleteContext );
+            LOG.debug( "Operation Context: {}", bindContext );
         }
 
-        checkAuthenticated( deleteContext );
-        checkPwdReset( deleteContext );
-        next.delete( deleteContext );
-        invalidateAuthenticatorCaches( deleteContext.getDn() );
-    }
+        if ( ( bindContext.getSession() != null ) && ( bindContext.getSession().getEffectivePrincipal() != null ) )
+        {
+            // null out the credentials
+            bindContext.setCredentials( null );
+        }
 
+        // pick the first matching authenticator type
+        AuthenticationLevel level = bindContext.getAuthenticationLevel();
 
-    public Entry getRootDSE( NextInterceptor next, GetRootDSEOperationContext getRootDseContext ) throws LdapException
-    {
-        if ( IS_DEBUG )
+        if ( level == AuthenticationLevel.UNAUTHENT )
         {
-            LOG.debug( "Operation Context: {}", getRootDseContext );
+            // This is a case where the Bind request contains a Dn, but no password.
+            // We don't check the Dn, we just return a UnwillingToPerform error
+            // Cf RFC 4513, chap. 5.1.2
+            throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, "Cannot Bind for Dn "
+                + bindContext.getDn().getName() );
         }
 
-        checkAuthenticated( getRootDseContext );
-        checkPwdReset( getRootDseContext );
-        return next.getRootDSE( getRootDseContext );
-    }
-
+        Collection<Authenticator> authenticators = getAuthenticators( level );
 
-    public boolean hasEntry( NextInterceptor next, EntryOperationContext hasEntryContext ) throws LdapException
-    {
-        if ( IS_DEBUG )
+        if ( authenticators == null )
         {
-            LOG.debug( "Operation Context: {}", hasEntryContext );
-        }
+            LOG.debug( "No authenticators found, delegating bind to the nexus." );
 
-        checkAuthenticated( hasEntryContext );
-        checkPwdReset( hasEntryContext );
-        return next.hasEntry( hasEntryContext );
-    }
+            // as a last resort try binding via the nexus
+            next( bindContext );
 
+            LOG.debug( "Nexus succeeded on bind operation." );
 
-    public EntryFilteringCursor list( NextInterceptor next, ListOperationContext listContext ) throws LdapException
-    {
-        if ( IS_DEBUG )
-        {
-            LOG.debug( "Operation Context: {}", listContext );
+            // bind succeeded if we got this far
+            // TODO - authentication level not being set
+            LdapPrincipal principal = new LdapPrincipal( schemaManager, bindContext.getDn(), AuthenticationLevel.SIMPLE );
+            CoreSession session = new DefaultCoreSession( principal, directoryService );
+            bindContext.setSession( session );
+
+            // remove creds so there is no security risk
+            bindContext.setCredentials( null );
+            return;
         }
 
-        checkAuthenticated( listContext );
-        checkPwdReset( listContext );
-        return next.list( listContext );
-    }
+        boolean isPPolicyReqCtrlPresent = bindContext.hasRequestControl( PasswordPolicy.OID );
+        PasswordPolicyDecorator pwdRespCtrl =
+            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
 
+        boolean authenticated = false;
+        PasswordPolicyException ppe = null;
 
-    public Entry lookup( NextInterceptor next, LookupOperationContext lookupContext ) throws LdapException
-    {
-        if ( IS_DEBUG )
+        // TODO : we should refactor that.
+        // try each authenticator
+        for ( Authenticator authenticator : authenticators )
         {
-            LOG.debug( "Operation Context: {}", lookupContext );
-        }
+            try
+            {
+                // perform the authentication
+                LdapPrincipal principal = authenticator.authenticate( bindContext );
 
-        checkAuthenticated( lookupContext );
-        checkPwdReset( lookupContext );
-        
-        return next.lookup( lookupContext );
-    }
+                LdapPrincipal clonedPrincipal = ( LdapPrincipal ) ( principal.clone() );
+
+                // remove creds so there is no security risk
+                bindContext.setCredentials( null );
+                clonedPrincipal.setUserPassword( StringConstants.EMPTY_BYTES );
 
+                // authentication was successful
+                CoreSession session = new DefaultCoreSession( clonedPrincipal, directoryService );
+                bindContext.setSession( session );
 
-    private void invalidateAuthenticatorCaches( Dn principalDn )
-    {
-        for ( AuthenticationLevel authMech : authenticatorsMapByType.keySet() )
-        {
-            Collection<Authenticator> authenticators = getAuthenticators( authMech );
+                authenticated = true;
 
-            // try each authenticator
-            for ( Authenticator authenticator : authenticators )
+                // break out of the loop if the authentication succeeded
+                break;
+            }
+            catch ( PasswordPolicyException e )
             {
-                authenticator.invalidateCache( principalDn );
+                ppe = e;
+                break;
+            }
+            catch ( LdapAuthenticationException e )
+            {
+                // authentication failed, try the next authenticator
+                if ( LOG.isInfoEnabled() )
+                {
+                    LOG.info( "Authenticator {} failed to authenticate: {}", authenticator, bindContext );
+                }
+            }
+            catch ( Exception e )
+            {
+                // Log other exceptions than LdapAuthenticationException
+                if ( LOG.isWarnEnabled() )
+                {
+                    LOG.info( "Unexpected failure for Authenticator {} : {}", authenticator, bindContext );
+                }
             }
         }
-    }
 
-
-    public void modify( NextInterceptor next, ModifyOperationContext modifyContext ) throws LdapException
-    {
-        if ( IS_DEBUG )
+        if ( ppe != null )
         {
-            LOG.debug( "Operation Context: {}", modifyContext );
+            if ( isPPolicyReqCtrlPresent )
+            {
+                pwdRespCtrl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.get( ppe.getErrorCode() ) );
+                bindContext.addResponseControl( pwdRespCtrl );
+            }
+
+            throw ppe;
         }
 
-        checkAuthenticated( modifyContext );
+        Dn dn = bindContext.getDn();
+        Entry userEntry = bindContext.getEntry();
 
-        
-        if ( ! directoryService.isPwdPolicyEnabled() )
+        PasswordPolicyConfiguration policyConfig = getPwdPolicy( userEntry );
+
+        // check if the user entry is null, it will be null
+        // in cases of anonymous bind
+        if ( authenticated && ( userEntry == null ) && directoryService.isAllowAnonymousAccess() )
         {
-            next.modify( modifyContext );
-            invalidateAuthenticatorCaches( modifyContext.getDn() );
             return;
         }
 
-        // handle the case where pwdPolicySubentry AT is about to be deleted in thid modify()
-        PasswordPolicyConfiguration policyConfig = getPwdPolicy( modifyContext.getEntry() );
-        
-        boolean isPPolicyReqCtrlPresent = modifyContext.hasRequestControl( PasswordPolicy.OID );
-        Dn userDn = modifyContext.getSession().getAuthenticatedPrincipal().getDn();
-
-        PwdModDetailsHolder pwdModDetails = null;
-        
-        pwdModDetails = getPwdModDetails( modifyContext, policyConfig );
-
-        if ( pwdModDetails.isPwdModPresent() )
+        if ( !authenticated )
         {
-            if ( pwdResetSet.contains( userDn ) )
+            if ( LOG.isInfoEnabled() )
             {
-                if ( pwdModDetails.isOtherModExists() )
-                {
-                    if ( isPPolicyReqCtrlPresent )
-                    {
-                        PasswordPolicyDecorator responseControl = 
-                            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
-                        responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.CHANGE_AFTER_RESET );
-                        modifyContext.addResponseControl( responseControl );
-                    }
-
-                    throw new LdapNoPermissionException();
-                }
+                LOG.info( "Cannot bind to the server " );
             }
 
-            if ( policyConfig.isPwdSafeModify() )
+            if ( ( policyConfig != null ) && ( userEntry != null ) )
             {
-                if ( pwdModDetails.isAddOrReplace() && !pwdModDetails.isDelete() )
-                {
-                    LOG.debug( "trying to update password attribute without the supplying the old password" );
-                    
-                    if ( isPPolicyReqCtrlPresent )
-                    {
-                        PasswordPolicyDecorator responseControl = 
-                            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
-                        responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.MUST_SUPPLY_OLD_PASSWORD );
-                        modifyContext.addResponseControl( responseControl );
-                    }
+                Attribute pwdFailTimeAt = userEntry.get( PWD_FAILURE_TIME_AT );
 
-                    throw new LdapNoPermissionException();
+                if ( pwdFailTimeAt == null )
+                {
+                    pwdFailTimeAt = new DefaultAttribute( AT_PWD_FAILURE_TIME );
                 }
-            }
-
-            if ( !policyConfig.isPwdAllowUserChange() && !modifyContext.getSession().isAnAdministrator() )
-            {
-                if ( isPPolicyReqCtrlPresent )
+                else
                 {
-                    PasswordPolicyDecorator responseControl = 
-                        new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
-                    responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.PASSWORD_MOD_NOT_ALLOWED );
-                    modifyContext.addResponseControl( responseControl );
+                    PasswordUtil.purgeFailureTimes( policyConfig, pwdFailTimeAt );
                 }
 
-                throw new LdapNoPermissionException();
-            }
-
-            Entry entry = modifyContext.getEntry();
+                String failureTime = DateUtils.getGeneralizedTime();
+                pwdFailTimeAt.add( failureTime );
+                Modification pwdFailTimeMod = new DefaultModification( ADD_ATTRIBUTE, pwdFailTimeAt );
 
-            if ( isPwdTooYoung( entry, policyConfig ) )
-            {
-                if ( isPPolicyReqCtrlPresent )
-                {
-                    PasswordPolicyDecorator responseControl = 
-                        new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
-                    responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.PASSWORD_TOO_YOUNG );
-                    modifyContext.addResponseControl( responseControl );
-                }
+                List<Modification> mods = new ArrayList<Modification>();
+                mods.add( pwdFailTimeMod );
 
-                throw new LdapOperationException( ResultCodeEnum.CONSTRAINT_VIOLATION,
-                    "password is too young to update" );
-            }
+                int numFailures = pwdFailTimeAt.size();
 
-            byte[] newPassword = null;
-            
-            if ( ( pwdModDetails != null ) )
-            {
-                newPassword = pwdModDetails.getNewPwd();
-                
-                try
-                {
-                    String userName = entry.getDn().getRdn().getUpValue().getString();
-                    check( userName, newPassword, policyConfig );
-                }
-                catch ( PasswordPolicyException e )
+                if ( policyConfig.isPwdLockout() && ( numFailures >= policyConfig.getPwdMaxFailure() ) )
                 {
-                    if ( isPPolicyReqCtrlPresent )
+                    Attribute pwdAccountLockedTimeAt = new DefaultAttribute( AT_PWD_ACCOUNT_LOCKED_TIME );
+
+                    // if zero, lockout permanently, only admin can unlock it
+                    if ( policyConfig.getPwdLockoutDuration() == 0 )
                     {
-                        PasswordPolicyDecorator responseControl = 
-                            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
-                        responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.get( e.getErrorCode() ) );
-                        modifyContext.addResponseControl( responseControl );
+                        pwdAccountLockedTimeAt.add( "000001010000Z" );
+                    }
+                    else
+                    {
+                        pwdAccountLockedTimeAt.add( failureTime );
                     }
 
-                    // throw exception if userPassword quality checks fail
-                    throw new LdapOperationException( ResultCodeEnum.CONSTRAINT_VIOLATION, e.getMessage(), e );
-                }
-            }
+                    Modification pwdAccountLockedMod = new DefaultModification( ADD_ATTRIBUTE, pwdAccountLockedTimeAt );
+                    mods.add( pwdAccountLockedMod );
 
-            int histSize = policyConfig.getPwdInHistory();
-            Modification pwdRemHistMod = null;
-            Modification pwdAddHistMod = null;
-            String pwdChangedTime = DateUtils.getGeneralizedTime();
-
-            if ( histSize > 0 )
-            {
-                Attribute pwdHistoryAt = entry.get( PWD_HISTORY_AT );
-                
-                if ( pwdHistoryAt == null )
-                {
-                    pwdHistoryAt = new DefaultAttribute( AT_PWD_HISTORY );
+                    pwdRespCtrl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.ACCOUNT_LOCKED );
                 }
-                
-                List<PasswordHistory> pwdHistLst = new ArrayList<PasswordHistory>();
-
-                for ( Value<?> value : pwdHistoryAt  )
+                else if ( policyConfig.getPwdMinDelay() > 0 )
                 {
-                    PasswordHistory pwdh = new PasswordHistory( Strings.utf8ToString( value.getBytes() ) );
-
-                    boolean matched = Arrays.equals( newPassword, pwdh.getPassword() );
-
-                    if ( matched )
+                    int numDelay = numFailures * policyConfig.getPwdMinDelay();
+                    int maxDelay = policyConfig.getPwdMaxDelay();
+                    if ( numDelay > maxDelay )
                     {
-                        if ( isPPolicyReqCtrlPresent )
-                        {
-                            PasswordPolicyDecorator responseControl = 
-                                new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
-                            responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.PASSWORD_IN_HISTORY );
-                            modifyContext.addResponseControl( responseControl );
-                        }
-
-                        throw new LdapOperationException( ResultCodeEnum.CONSTRAINT_VIOLATION,
-                            "invalid reuse of password present in password history" );
+                        numDelay = maxDelay;
                     }
 
-                    pwdHistLst.add( pwdh );
+                    try
+                    {
+                        Thread.sleep( numDelay * 1000 );
+                    }
+                    catch ( InterruptedException e )
+                    {
+                        LOG.warn(
+                            "Interrupted while delaying to send the failed authentication response for the user {}",
+                            dn, e );
+                    }
                 }
 
-                if ( pwdHistLst.size() >= histSize )
-                {
-                    // see the javadoc of PasswordHistory
-                    Collections.sort( pwdHistLst );
-                   
-                    // remove the oldest value
-                    PasswordHistory remPwdHist = ( PasswordHistory ) pwdHistLst.toArray()[histSize - 1];
-                    Attribute tempAt = new DefaultAttribute( AT_PWD_HISTORY );
-                    tempAt.add( remPwdHist.getHistoryValue() );
-                    pwdRemHistMod = new DefaultModification( REMOVE_ATTRIBUTE, tempAt );
-                }
-                
-                pwdHistoryAt.clear();
-                PasswordHistory newPwdHist = new PasswordHistory( pwdChangedTime, newPassword );
-                pwdHistoryAt.clear();
-                pwdHistoryAt.add( newPwdHist.getHistoryValue() );
-                pwdAddHistMod = new DefaultModification( ADD_ATTRIBUTE, pwdHistoryAt );
+                //adminSession.modify( dn, Collections.singletonList( pwdFailTimeMod ) );
+                ModifyOperationContext bindModCtx = new ModifyOperationContext( adminSession );
+                bindModCtx.setDn( dn );
+                bindModCtx.setModItems( mods );
+                directoryService.getPartitionNexus().modify( bindModCtx );
             }
 
-            next.modify( modifyContext );
-            
-            invalidateAuthenticatorCaches( modifyContext.getDn() );
-
+            String upDn = ( dn == null ? "" : dn.getName() );
+            throw new LdapAuthenticationException( I18n.err( I18n.ERR_229, upDn ) );
+        }
+        else if ( policyConfig != null )
+        {
             List<Modification> mods = new ArrayList<Modification>();
-            
-            if ( ( policyConfig.getPwdMinAge() > 0 ) || ( policyConfig.getPwdMaxAge() > 0 ) )
+
+            if ( policyConfig.getPwdMaxIdle() > 0 )
             {
-                Attribute pwdChangedTimeAt = new DefaultAttribute( AT_PWD_CHANGED_TIME );
-                pwdChangedTimeAt.add( pwdChangedTime );
-                Modification pwdChangedTimeMod = new DefaultModification( REPLACE_ATTRIBUTE, pwdChangedTimeAt );
-                mods.add( pwdChangedTimeMod );
+                Attribute pwdLastSuccesTimeAt = new DefaultAttribute( AT_PWD_LAST_SUCCESS );
+                pwdLastSuccesTimeAt.add( DateUtils.getGeneralizedTime() );
+                Modification pwdLastSuccesTimeMod = new DefaultModification( REPLACE_ATTRIBUTE, pwdLastSuccesTimeAt );
+                mods.add( pwdLastSuccesTimeMod );
             }
 
-            if ( pwdAddHistMod != null )
+            Attribute pwdFailTimeAt = userEntry.get( AT_PWD_FAILURE_TIME );
+
+            if ( pwdFailTimeAt != null )
             {
-                mods.add( pwdAddHistMod );
+                Modification pwdFailTimeMod = new DefaultModification( REMOVE_ATTRIBUTE, pwdFailTimeAt );
+                mods.add( pwdFailTimeMod );
             }
 
-            if ( pwdRemHistMod != null )
+            Attribute pwdAccLockedTimeAt = userEntry.get( AT_PWD_ACCOUNT_LOCKED_TIME );
+
+            if ( pwdAccLockedTimeAt != null )
             {
-                mods.add( pwdRemHistMod );
+                Modification pwdAccLockedTimeMod = new DefaultModification( REMOVE_ATTRIBUTE, pwdAccLockedTimeAt );
+                mods.add( pwdAccLockedTimeMod );
             }
 
-            boolean removeFromPwdResetSet = false;
-            
-            if ( policyConfig.isPwdMustChange() )
+            // checking the expiration time *after* performing authentication, do we need to care about millisecond precision?
+            if ( ( policyConfig.getPwdMaxAge() > 0 ) && ( policyConfig.getPwdGraceAuthNLimit() > 0 ) )
             {
-                Attribute pwdMustChangeAt = new DefaultAttribute( AT_PWD_RESET );
-                Modification pwdMustChangeMod = null;
+                Attribute pwdChangeTimeAttr = userEntry.get( PWD_CHANGED_TIME_AT );
 
-                if ( modifyContext.getSession().isAnAdministrator() )
-                {
-                    pwdMustChangeAt.add( "TRUE" );
-                    pwdMustChangeMod = new DefaultModification( REPLACE_ATTRIBUTE, pwdMustChangeAt );
-                }
-                else
+                if ( pwdChangeTimeAttr != null )
                 {
-                    pwdMustChangeMod = new DefaultModification( REMOVE_ATTRIBUTE, pwdMustChangeAt );
-                    removeFromPwdResetSet = true;
-                }
+                    boolean expired = PasswordUtil.isPwdExpired( pwdChangeTimeAttr.getString(),
+                        policyConfig.getPwdMaxAge() );
 
-                mods.add( pwdMustChangeMod );
-            }
+                    if ( expired )
+                    {
+                        Attribute pwdGraceUseAttr = userEntry.get( PWD_GRACE_USE_TIME_AT );
+                        int numGraceAuth = 0;
 
-            Attribute pwdFailureTimeAt = entry.get( PWD_FAILURE_TIME_AT );
-            
-            if ( pwdFailureTimeAt != null )
-            {
-                mods.add( new DefaultModification( REMOVE_ATTRIBUTE, pwdFailureTimeAt ) );
+                        if ( pwdGraceUseAttr != null )
+                        {
+                            numGraceAuth = policyConfig.getPwdGraceAuthNLimit() - ( pwdGraceUseAttr.size() + 1 );
+                        }
+                        else
+                        {
+                            pwdGraceUseAttr = new DefaultAttribute( AT_PWD_GRACE_USE_TIME );
+                            numGraceAuth = policyConfig.getPwdGraceAuthNLimit() - 1;
+                        }
+
+                        pwdRespCtrl.getResponse().setGraceAuthNsRemaining( numGraceAuth );
+
+                        pwdGraceUseAttr.add( DateUtils.getGeneralizedTime() );
+                        Modification pwdGraceUseMod = new DefaultModification( ADD_ATTRIBUTE, pwdGraceUseAttr );
+                        mods.add( pwdGraceUseMod );
+                    }
+                }
             }
 
-            Attribute pwdGraceUseTimeAt = entry.get( PWD_GRACE_USE_TIME_AT );
-            
-            if ( pwdGraceUseTimeAt != null )
+            if ( !mods.isEmpty() )
             {
-                mods.add( new DefaultModification( REMOVE_ATTRIBUTE, pwdGraceUseTimeAt ) );
+                //adminSession.modify( dn, mods );
+                ModifyOperationContext bindModCtx = new ModifyOperationContext( adminSession );
+                bindModCtx.setDn( dn );
+                bindModCtx.setModItems( mods );
+                directoryService.getPartitionNexus().modify( bindModCtx );
             }
 
-            directoryService.getAdminSession().modify( modifyContext.getDn(), mods );
-
-            if ( removeFromPwdResetSet )
+            if ( isPPolicyReqCtrlPresent )
             {
-                pwdResetSet.remove( userDn );
-            }
-        }
-        else
-        {
-            next.modify( modifyContext );
-            invalidateAuthenticatorCaches( modifyContext.getDn() );
-        }
-    }
+                int expiryWarnTime = getPwdTimeBeforeExpiry( userEntry, policyConfig );
 
+                if ( expiryWarnTime > 0 )
+                {
+                    pwdRespCtrl.getResponse().setTimeBeforeExpiration( expiryWarnTime );
+                }
 
-    public void rename( NextInterceptor next, RenameOperationContext renameContext ) throws LdapException
-    {
-        if ( IS_DEBUG )
-        {
-            LOG.debug( "Operation Context: {}", renameContext );
-        }
+                if ( isPwdMustReset( userEntry ) )
+                {
+                    pwdRespCtrl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.CHANGE_AFTER_RESET );
+                    pwdResetSet.add( dn );
+                }
 
-        checkAuthenticated( renameContext );
-        checkPwdReset( renameContext );
-        next.rename( renameContext );
-        invalidateAuthenticatorCaches( renameContext.getDn() );
+                bindContext.addResponseControl( pwdRespCtrl );
+            }
+        }
     }
 
 
     /**
      * {@inheritDoc}
      */
-    public boolean compare( NextInterceptor next, CompareOperationContext compareContext ) throws LdapException
+    public boolean compare( CompareOperationContext compareContext ) throws LdapException
     {
         if ( IS_DEBUG )
         {
@@ -731,373 +688,440 @@ public class AuthenticationInterceptor e
 
         checkAuthenticated( compareContext );
         checkPwdReset( compareContext );
-        boolean result = next.compare( compareContext );
+        boolean result = next( compareContext );
         invalidateAuthenticatorCaches( compareContext.getDn() );
 
         return result;
     }
 
 
-    public void moveAndRename( NextInterceptor next, MoveAndRenameOperationContext moveAndRenameContext )
-        throws LdapException
+    /**
+     * {@inheritDoc}
+     */
+    public void delete( DeleteOperationContext deleteContext ) throws LdapException
     {
         if ( IS_DEBUG )
         {
-            LOG.debug( "Operation Context: {}", moveAndRenameContext );
+            LOG.debug( "Operation Context: {}", deleteContext );
         }
 
-        checkAuthenticated( moveAndRenameContext );
-        checkPwdReset( moveAndRenameContext );
-        next.moveAndRename( moveAndRenameContext );
-        invalidateAuthenticatorCaches( moveAndRenameContext.getDn() );
+        checkAuthenticated( deleteContext );
+        checkPwdReset( deleteContext );
+        next( deleteContext );
+        invalidateAuthenticatorCaches( deleteContext.getDn() );
     }
 
 
     /**
      * {@inheritDoc}
      */
-    public void move( NextInterceptor next, MoveOperationContext moveContext ) throws LdapException
+    public Entry getRootDse( GetRootDseOperationContext getRootDseContext ) throws LdapException
     {
         if ( IS_DEBUG )
         {
-            LOG.debug( "Operation Context: {}", moveContext );
+            LOG.debug( "Operation Context: {}", getRootDseContext );
         }
 
-        checkAuthenticated( moveContext );
-        checkPwdReset( moveContext );
-        next.move( moveContext );
-        invalidateAuthenticatorCaches( moveContext.getDn() );
+        checkAuthenticated( getRootDseContext );
+        checkPwdReset( getRootDseContext );
+
+        return next( getRootDseContext );
     }
 
 
-    public EntryFilteringCursor search( NextInterceptor next, SearchOperationContext searchContext )
-        throws LdapException
+    /**
+     * {@inheritDoc}
+     */
+    public boolean hasEntry( HasEntryOperationContext hasEntryContext ) throws LdapException
     {
         if ( IS_DEBUG )
         {
-            LOG.debug( "Operation Context: {}", searchContext );
+            LOG.debug( "Operation Context: {}", hasEntryContext );
         }
 
-        checkAuthenticated( searchContext );
-        checkPwdReset( searchContext );
-        return next.search( searchContext );
+        checkAuthenticated( hasEntryContext );
+        checkPwdReset( hasEntryContext );
+
+        return next( hasEntryContext );
     }
 
 
     /**
-     * Check if the current operation has a valid PrincipalDN or not.
-     *
-     * @param operation the operation type
-     * @throws Exception
+     * {@inheritDoc}
      */
-    private void checkAuthenticated( OperationContext operation ) throws LdapException
+    public EntryFilteringCursor list( ListOperationContext listContext ) throws LdapException
     {
-        if ( operation.getSession().isAnonymous() && !directoryService.isAllowAnonymousAccess()
-            && !operation.getDn().isEmpty() )
+        if ( IS_DEBUG )
         {
-            String msg = I18n.err( I18n.ERR_5, operation.getName() );
-            LOG.error( msg );
-            throw new LdapNoPermissionException( msg );
+            LOG.debug( "Operation Context: {}", listContext );
         }
+
+        checkAuthenticated( listContext );
+        checkPwdReset( listContext );
+
+        return next( listContext );
     }
 
 
-    public void bind( NextInterceptor next, BindOperationContext bindContext ) throws LdapException
+    /**
+     * {@inheritDoc}
+     */
+    public Entry lookup( LookupOperationContext lookupContext ) throws LdapException
     {
         if ( IS_DEBUG )
         {
-            LOG.debug( "Operation Context: {}", bindContext );
+            LOG.debug( "Operation Context: {}", lookupContext );
         }
 
-        if ( ( bindContext.getSession() != null ) && ( bindContext.getSession().getEffectivePrincipal() != null ) )
-        {
-            // null out the credentials
-            bindContext.setCredentials( null );
-        }
+        checkAuthenticated( lookupContext );
+        checkPwdReset( lookupContext );
 
-        // pick the first matching authenticator type
-        AuthenticationLevel level = bindContext.getAuthenticationLevel();
+        return next( lookupContext );
+    }
 
-        if ( level == AuthenticationLevel.UNAUTHENT )
+
+    private void invalidateAuthenticatorCaches( Dn principalDn )
+    {
+        for ( AuthenticationLevel authMech : authenticatorsMapByType.keySet() )
         {
-            // This is a case where the Bind request contains a Dn, but no password.
-            // We don't check the Dn, we just return a UnwillingToPerform error
-            // Cf RFC 4513, chap. 5.1.2
-            throw new LdapUnwillingToPerformException( ResultCodeEnum.UNWILLING_TO_PERFORM, "Cannot Bind for Dn "
-                + bindContext.getDn().getName() );
+            Collection<Authenticator> authenticators = getAuthenticators( authMech );
+
+            // try each authenticator
+            for ( Authenticator authenticator : authenticators )
+            {
+                authenticator.invalidateCache( principalDn );
+            }
         }
+    }
 
-        Collection<Authenticator> authenticators = getAuthenticators( level );
 
-        if ( authenticators == null )
+    /**
+     * {@inheritDoc}
+     */
+    public void modify( ModifyOperationContext modifyContext ) throws LdapException
+    {
+        if ( IS_DEBUG )
         {
-            LOG.debug( "No authenticators found, delegating bind to the nexus." );
-
-            // as a last resort try binding via the nexus
-            next.bind( bindContext );
+            LOG.debug( "Operation Context: {}", modifyContext );
+        }
 
-            LOG.debug( "Nexus succeeded on bind operation." );
+        checkAuthenticated( modifyContext );
 
-            // bind succeeded if we got this far
-            // TODO - authentication level not being set
-            LdapPrincipal principal = new LdapPrincipal( schemaManager, bindContext.getDn(), AuthenticationLevel.SIMPLE );
-            CoreSession session = new DefaultCoreSession( principal, directoryService );
-            bindContext.setSession( session );
 
-            // remove creds so there is no security risk
-            bindContext.setCredentials( null );
+        if ( ! directoryService.isPwdPolicyEnabled() )
+        {
+            next( modifyContext );
+            invalidateAuthenticatorCaches( modifyContext.getDn() );
             return;
         }
 
-        boolean isPPolicyReqCtrlPresent = bindContext.hasRequestControl( PasswordPolicy.OID );
-        PasswordPolicyDecorator pwdRespCtrl = 
-            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
-
-        boolean authenticated = false;
-        PasswordPolicyException ppe = null;
+        // handle the case where pwdPolicySubentry AT is about to be deleted in thid modify()
+        PasswordPolicyConfiguration policyConfig = getPwdPolicy( modifyContext.getEntry() );
 
-        // TODO : we should refactor that.
-        // try each authenticator
-        for ( Authenticator authenticator : authenticators )
-        {
-            try
-            {
-                // perform the authentication
-                LdapPrincipal principal = authenticator.authenticate( bindContext );
-                
-                LdapPrincipal clonedPrincipal = ( LdapPrincipal ) ( principal.clone() );
+        boolean isPPolicyReqCtrlPresent = modifyContext.hasRequestControl( PasswordPolicy.OID );
+        Dn userDn = modifyContext.getSession().getAuthenticatedPrincipal().getDn();
 
-                // remove creds so there is no security risk
-                bindContext.setCredentials( null );
-                clonedPrincipal.setUserPassword( StringConstants.EMPTY_BYTES );
+        PwdModDetailsHolder pwdModDetails = null;
 
-                // authentication was successful
-                CoreSession session = new DefaultCoreSession( clonedPrincipal, directoryService );
-                bindContext.setSession( session );
+        pwdModDetails = getPwdModDetails( modifyContext, policyConfig );
 
-                authenticated = true;
-                
-                // break out of the loop if the authentication succeeded
-                break;
-            }
-            catch ( PasswordPolicyException e )
-            {
-                ppe = e;
-                break;
-            }
-            catch ( LdapAuthenticationException e )
+        if ( pwdModDetails.isPwdModPresent() )
+        {
+            if ( pwdResetSet.contains( userDn ) )
             {
-                // authentication failed, try the next authenticator
-                if ( LOG.isInfoEnabled() )
+                if ( pwdModDetails.isOtherModExists() )
                 {
-                    LOG.info( "Authenticator {} failed to authenticate: {}", authenticator, bindContext );
+                    if ( isPPolicyReqCtrlPresent )
+                    {
+                        PasswordPolicyDecorator responseControl =
+                            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
+                        responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.CHANGE_AFTER_RESET );
+                        modifyContext.addResponseControl( responseControl );
+                    }
+
+                    throw new LdapNoPermissionException();
                 }
             }
-            catch ( Exception e )
+
+            if ( policyConfig.isPwdSafeModify() )
             {
-                // Log other exceptions than LdapAuthenticationException
-                if ( LOG.isWarnEnabled() )
+                if ( pwdModDetails.isAddOrReplace() && !pwdModDetails.isDelete() )
                 {
-                    LOG.info( "Unexpected failure for Authenticator {} : {}", authenticator, bindContext );
+                    LOG.debug( "trying to update password attribute without the supplying the old password" );
+
+                    if ( isPPolicyReqCtrlPresent )
+                    {
+                        PasswordPolicyDecorator responseControl =
+                            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
+                        responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.MUST_SUPPLY_OLD_PASSWORD );
+                        modifyContext.addResponseControl( responseControl );
+                    }
+
+                    throw new LdapNoPermissionException();
                 }
             }
-        }
 
-        if ( ppe != null )
-        {
-            if ( isPPolicyReqCtrlPresent )
+            if ( !policyConfig.isPwdAllowUserChange() && !modifyContext.getSession().isAnAdministrator() )
             {
-                pwdRespCtrl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.get( ppe.getErrorCode() ) );
-                bindContext.addResponseControl( pwdRespCtrl );
-            }
+                if ( isPPolicyReqCtrlPresent )
+                {
+                    PasswordPolicyDecorator responseControl =
+                        new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
+                    responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.PASSWORD_MOD_NOT_ALLOWED );
+                    modifyContext.addResponseControl( responseControl );
+                }
 
-            throw ppe;
-        }
+                throw new LdapNoPermissionException();
+            }
 
-        Dn dn = bindContext.getDn();
-        Entry userEntry = bindContext.getEntry();
-        
-        PasswordPolicyConfiguration policyConfig = getPwdPolicy( userEntry );
-        
-        // check if the user entry is null, it will be null
-        // in cases of anonymous bind
-        if ( authenticated && ( userEntry == null ) && directoryService.isAllowAnonymousAccess() ) 
-        {
-            return;
-        }
+            Entry entry = modifyContext.getEntry();
 
-        if ( !authenticated )
-        {
-            if ( LOG.isInfoEnabled() )
+            if ( isPwdTooYoung( entry, policyConfig ) )
             {
-                LOG.info( "Cannot bind to the server " );
+                if ( isPPolicyReqCtrlPresent )
+                {
+                    PasswordPolicyDecorator responseControl =
+                        new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
+                    responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.PASSWORD_TOO_YOUNG );
+                    modifyContext.addResponseControl( responseControl );
+                }
+
+                throw new LdapOperationException( ResultCodeEnum.CONSTRAINT_VIOLATION,
+                    "password is too young to update" );
             }
 
-            if ( ( policyConfig != null ) && ( userEntry != null ) )
+            byte[] newPassword = null;
+
+            if ( ( pwdModDetails != null ) )
             {
-                Attribute pwdFailTimeAt = userEntry.get( PWD_FAILURE_TIME_AT );
-                if ( pwdFailTimeAt == null )
+                newPassword = pwdModDetails.getNewPwd();
+
+                try
                 {
-                    pwdFailTimeAt = new DefaultAttribute( AT_PWD_FAILURE_TIME );
+                    String userName = entry.getDn().getRdn().getUpValue().getString();
+                    check( userName, newPassword, policyConfig );
                 }
-                else
+                catch ( PasswordPolicyException e )
                 {
-                    PasswordUtil.purgeFailureTimes( policyConfig, pwdFailTimeAt );
+                    if ( isPPolicyReqCtrlPresent )
+                    {
+                        PasswordPolicyDecorator responseControl =
+                            new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
+                        responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.get( e.getErrorCode() ) );
+                        modifyContext.addResponseControl( responseControl );
+                    }
+
+                    // throw exception if userPassword quality checks fail
+                    throw new LdapOperationException( ResultCodeEnum.CONSTRAINT_VIOLATION, e.getMessage(), e );
                 }
+            }
 
-                String failureTime = DateUtils.getGeneralizedTime();
-                pwdFailTimeAt.add( failureTime );
-                Modification pwdFailTimeMod = new DefaultModification( ADD_ATTRIBUTE, pwdFailTimeAt );
+            int histSize = policyConfig.getPwdInHistory();
+            Modification pwdRemHistMod = null;
+            Modification pwdAddHistMod = null;
+            String pwdChangedTime = DateUtils.getGeneralizedTime();
 
-                List<Modification> mods = new ArrayList<Modification>();
-                mods.add( pwdFailTimeMod );
+            if ( histSize > 0 )
+            {
+                Attribute pwdHistoryAt = entry.get( PWD_HISTORY_AT );
 
-                int numFailures = pwdFailTimeAt.size();
+                if ( pwdHistoryAt == null )
+                {
+                    pwdHistoryAt = new DefaultAttribute( AT_PWD_HISTORY );
+                }
 
-                if ( policyConfig.isPwdLockout() && ( numFailures >= policyConfig.getPwdMaxFailure() ) )
+                List<PasswordHistory> pwdHistLst = new ArrayList<PasswordHistory>();
+
+                for ( Value<?> value : pwdHistoryAt  )
                 {
-                    Attribute pwdAccountLockedTimeAt = new DefaultAttribute( AT_PWD_ACCOUNT_LOCKED_TIME );
+                    PasswordHistory pwdh = new PasswordHistory( Strings.utf8ToString( value.getBytes() ) );
 
-                    // if zero, lockout permanently, only admin can unlock it
-                    if ( policyConfig.getPwdLockoutDuration() == 0 )
-                    {
-                        pwdAccountLockedTimeAt.add( "000001010000Z" );
-                    }
-                    else
+                    boolean matched = Arrays.equals( newPassword, pwdh.getPassword() );
+
+                    if ( matched )
                     {
-                        pwdAccountLockedTimeAt.add( failureTime );
+                        if ( isPPolicyReqCtrlPresent )
+                        {
+                            PasswordPolicyDecorator responseControl =
+                                new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
+                            responseControl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.PASSWORD_IN_HISTORY );
+                            modifyContext.addResponseControl( responseControl );
+                        }
+
+                        throw new LdapOperationException( ResultCodeEnum.CONSTRAINT_VIOLATION,
+                            "invalid reuse of password present in password history" );
                     }
-                    
-                    Modification pwdAccountLockedMod = new DefaultModification( ADD_ATTRIBUTE, pwdAccountLockedTimeAt );
-                    mods.add( pwdAccountLockedMod );
 
-                    pwdRespCtrl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.ACCOUNT_LOCKED );
+                    pwdHistLst.add( pwdh );
                 }
-                else if ( policyConfig.getPwdMinDelay() > 0 )
+
+                if ( pwdHistLst.size() >= histSize )
                 {
-                    int numDelay = numFailures * policyConfig.getPwdMinDelay();
-                    int maxDelay = policyConfig.getPwdMaxDelay();
-                    if ( numDelay > maxDelay )
-                    {
-                        numDelay = maxDelay;
-                    }
+                    // see the javadoc of PasswordHistory
+                    Collections.sort( pwdHistLst );
 
-                    try
-                    {
-                        Thread.sleep( numDelay * 1000 );
-                    }
-                    catch ( InterruptedException e )
-                    {
-                        LOG.warn(
-                            "Interrupted while delaying to send the failed authentication response for the user {}",
-                            dn, e );
-                    }
+                    // remove the oldest value
+                    PasswordHistory remPwdHist = ( PasswordHistory ) pwdHistLst.toArray()[histSize - 1];
+                    Attribute tempAt = new DefaultAttribute( AT_PWD_HISTORY );
+                    tempAt.add( remPwdHist.getHistoryValue() );
+                    pwdRemHistMod = new DefaultModification( REMOVE_ATTRIBUTE, tempAt );
                 }
 
-                //adminSession.modify( dn, Collections.singletonList( pwdFailTimeMod ) );
-                ModifyOperationContext bindModCtx = new ModifyOperationContext( adminSession );
-                bindModCtx.setDn( dn );
-                bindModCtx.setModItems( mods );
-                directoryService.getPartitionNexus().modify( bindModCtx );
+                pwdHistoryAt.clear();
+                PasswordHistory newPwdHist = new PasswordHistory( pwdChangedTime, newPassword );
+                pwdHistoryAt.clear();
+                pwdHistoryAt.add( newPwdHist.getHistoryValue() );
+                pwdAddHistMod = new DefaultModification( ADD_ATTRIBUTE, pwdHistoryAt );
             }
 
-            String upDn = ( dn == null ? "" : dn.getName() );
-            throw new LdapAuthenticationException( I18n.err( I18n.ERR_229, upDn ) );
-        }
-        else if ( policyConfig != null )
-        {
+            next( modifyContext );
+
+            invalidateAuthenticatorCaches( modifyContext.getDn() );
+
             List<Modification> mods = new ArrayList<Modification>();
 
-            if ( policyConfig.getPwdMaxIdle() > 0 )
+            if ( ( policyConfig.getPwdMinAge() > 0 ) || ( policyConfig.getPwdMaxAge() > 0 ) )
             {
-                Attribute pwdLastSuccesTimeAt = new DefaultAttribute( AT_PWD_LAST_SUCCESS );
-                pwdLastSuccesTimeAt.add( DateUtils.getGeneralizedTime() );
-                Modification pwdLastSuccesTimeMod = new DefaultModification( REPLACE_ATTRIBUTE, pwdLastSuccesTimeAt );
-                mods.add( pwdLastSuccesTimeMod );
+                Attribute pwdChangedTimeAt = new DefaultAttribute( AT_PWD_CHANGED_TIME );
+                pwdChangedTimeAt.add( pwdChangedTime );
+                Modification pwdChangedTimeMod = new DefaultModification( REPLACE_ATTRIBUTE, pwdChangedTimeAt );
+                mods.add( pwdChangedTimeMod );
             }
 
-            Attribute pwdFailTimeAt = userEntry.get( AT_PWD_FAILURE_TIME );
-            if ( pwdFailTimeAt != null )
+            if ( pwdAddHistMod != null )
             {
-                Modification pwdFailTimeMod = new DefaultModification( REMOVE_ATTRIBUTE, pwdFailTimeAt );
-                mods.add( pwdFailTimeMod );
+                mods.add( pwdAddHistMod );
             }
 
-            Attribute pwdAccLockedTimeAt = userEntry.get( AT_PWD_ACCOUNT_LOCKED_TIME );
-            if ( pwdAccLockedTimeAt != null )
+            if ( pwdRemHistMod != null )
             {
-                Modification pwdAccLockedTimeMod = new DefaultModification( REMOVE_ATTRIBUTE, pwdAccLockedTimeAt );
-                mods.add( pwdAccLockedTimeMod );
+                mods.add( pwdRemHistMod );
             }
 
-            // checking the expiration time *after* performing authentication, do we need to care about millisecond precision?
-            if ( ( policyConfig.getPwdMaxAge() > 0 ) && ( policyConfig.getPwdGraceAuthNLimit() > 0 ) )
+            boolean removeFromPwdResetSet = false;
+
+            if ( policyConfig.isPwdMustChange() )
             {
-                Attribute pwdChangeTimeAttr = userEntry.get( PWD_CHANGED_TIME_AT );
-                
-                if ( pwdChangeTimeAttr != null )
-                {
-                    boolean expired = PasswordUtil.isPwdExpired( pwdChangeTimeAttr.getString(),
-                        policyConfig.getPwdMaxAge() );
-                    
-                    if ( expired )
-                    {
-                        Attribute pwdGraceUseAttr = userEntry.get( PWD_GRACE_USE_TIME_AT );
-                        int numGraceAuth = 0;
-                        
-                        if ( pwdGraceUseAttr != null )
-                        {
-                            numGraceAuth = policyConfig.getPwdGraceAuthNLimit() - ( pwdGraceUseAttr.size() + 1 );
-                        }
-                        else
-                        {
-                            pwdGraceUseAttr = new DefaultAttribute( AT_PWD_GRACE_USE_TIME );
-                            numGraceAuth = policyConfig.getPwdGraceAuthNLimit() - 1;
-                        }
-                        
-                        pwdRespCtrl.getResponse().setGraceAuthNsRemaining( numGraceAuth );
+                Attribute pwdMustChangeAt = new DefaultAttribute( AT_PWD_RESET );
+                Modification pwdMustChangeMod = null;
 
-                        pwdGraceUseAttr.add( DateUtils.getGeneralizedTime() );
-                        Modification pwdGraceUseMod = new DefaultModification( ADD_ATTRIBUTE, pwdGraceUseAttr );
-                        mods.add( pwdGraceUseMod );
-                    }
+                if ( modifyContext.getSession().isAnAdministrator() )
+                {
+                    pwdMustChangeAt.add( "TRUE" );
+                    pwdMustChangeMod = new DefaultModification( REPLACE_ATTRIBUTE, pwdMustChangeAt );
+                }
+                else
+                {
+                    pwdMustChangeMod = new DefaultModification( REMOVE_ATTRIBUTE, pwdMustChangeAt );
+                    removeFromPwdResetSet = true;
                 }
+
+                mods.add( pwdMustChangeMod );
             }
 
-            if ( !mods.isEmpty() )
+            Attribute pwdFailureTimeAt = entry.get( PWD_FAILURE_TIME_AT );
+
+            if ( pwdFailureTimeAt != null )
             {
-                //adminSession.modify( dn, mods );
-                ModifyOperationContext bindModCtx = new ModifyOperationContext( adminSession );
-                bindModCtx.setDn( dn );
-                bindModCtx.setModItems( mods );
-                directoryService.getPartitionNexus().modify( bindModCtx );
+                mods.add( new DefaultModification( REMOVE_ATTRIBUTE, pwdFailureTimeAt ) );
             }
 
-            if ( isPPolicyReqCtrlPresent )
+            Attribute pwdGraceUseTimeAt = entry.get( PWD_GRACE_USE_TIME_AT );
+
+            if ( pwdGraceUseTimeAt != null )
             {
-                int expiryWarnTime = getPwdTimeBeforeExpiry( userEntry, policyConfig );
-                
-                if ( expiryWarnTime > 0 )
-                {
-                    pwdRespCtrl.getResponse().setTimeBeforeExpiration( expiryWarnTime );
-                }
+                mods.add( new DefaultModification( REMOVE_ATTRIBUTE, pwdGraceUseTimeAt ) );
+            }
 
-                if ( isPwdMustReset( userEntry ) )
-                {
-                    pwdRespCtrl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.CHANGE_AFTER_RESET );
-                    pwdResetSet.add( dn );
-                }
+            directoryService.getAdminSession().modify( modifyContext.getDn(), mods );
 
-                bindContext.addResponseControl( pwdRespCtrl );
+            if ( removeFromPwdResetSet )
+            {
+                pwdResetSet.remove( userDn );
             }
         }
+        else
+        {
+            next( modifyContext );
+            invalidateAuthenticatorCaches( modifyContext.getDn() );
+        }
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void move( MoveOperationContext moveContext ) throws LdapException
+    {
+        if ( IS_DEBUG )
+        {
+            LOG.debug( "Operation Context: {}", moveContext );
+        }
+
+        checkAuthenticated( moveContext );
+        checkPwdReset( moveContext );
+        next( moveContext );
+        invalidateAuthenticatorCaches( moveContext.getDn() );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void moveAndRename( MoveAndRenameOperationContext moveAndRenameContext ) throws LdapException
+    {
+        if ( IS_DEBUG )
+        {
+            LOG.debug( "Operation Context: {}", moveAndRenameContext );
+        }
+
+        checkAuthenticated( moveAndRenameContext );
+        checkPwdReset( moveAndRenameContext );
+        next( moveAndRenameContext );
+        invalidateAuthenticatorCaches( moveAndRenameContext.getDn() );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public void rename( RenameOperationContext renameContext ) throws LdapException
+    {
+        if ( IS_DEBUG )
+        {
+            LOG.debug( "Operation Context: {}", renameContext );
+        }
+
+        checkAuthenticated( renameContext );
+        checkPwdReset( renameContext );
+        next( renameContext );
+        invalidateAuthenticatorCaches( renameContext.getDn() );
+    }
+
+
+    /**
+     * {@inheritDoc}
+     */
+    public EntryFilteringCursor search( SearchOperationContext searchContext ) throws LdapException
+    {
+        if ( IS_DEBUG )
+        {
+            LOG.debug( "Operation Context: {}", searchContext );
+        }
+
+        checkAuthenticated( searchContext );
+        checkPwdReset( searchContext );
+
+        return next( searchContext );
     }
 
 
-    @Override
-    public void unbind( NextInterceptor next, UnbindOperationContext unbindContext ) throws LdapException
+    /**
+     * {@inheritDoc}
+     */
+    public void unbind( UnbindOperationContext unbindContext ) throws LdapException
     {
-        super.unbind( next, unbindContext );
+        next( unbindContext );
 
         // remove the Dn from the password reset Set
         // we do not perform a check to see if the reset flag in the associated ppolicy is enabled
@@ -1110,6 +1134,24 @@ public class AuthenticationInterceptor e
 
 
     /**
+     * Check if the current operation has a valid PrincipalDN or not.
+     *
+     * @param operation the operation type
+     * @throws Exception
+     */
+    private void checkAuthenticated( OperationContext operation ) throws LdapException
+    {
+        if ( operation.getSession().isAnonymous() && !directoryService.isAllowAnonymousAccess()
+            && !operation.getDn().isEmpty() )
+        {
+            String msg = I18n.err( I18n.ERR_5, operation.getName() );
+            LOG.error( msg );
+            throw new LdapNoPermissionException( msg );
+        }
+    }
+
+
+    /**
      * Initialize the PasswordPolicy attributeTypes
      * 
      * @throws LdapException If the initialization failed
@@ -1143,7 +1185,6 @@ public class AuthenticationInterceptor e
 
 
     // ---------- private methods ----------------
-
     private void check( String username, byte[] password, PasswordPolicyConfiguration policyConfig ) throws LdapException
     {
         final int qualityVal = policyConfig.getPwdCheckQuality();
@@ -1171,10 +1212,10 @@ public class AuthenticationInterceptor e
         }
 
         String strPassword = Strings.utf8ToString(password);
-        
+
         // perform the length validation
         validatePasswordLength( strPassword, policyConfig );
-        
+
         policyConfig.getPwdValidator().validate( strPassword, username );
     }
 
@@ -1217,7 +1258,7 @@ public class AuthenticationInterceptor e
         }
 
         int warningAge = policyConfig.getPwdExpireWarning();
-        
+
         if ( warningAge <= 0 )
         {
             return 0;
@@ -1228,14 +1269,14 @@ public class AuthenticationInterceptor e
 
         long currentTime = DateUtils.getDate( DateUtils.getGeneralizedTime() ).getTime();
         int pwdAge = ( int ) ( currentTime - changedTime ) / 1000;
-        
+
         if ( pwdAge > policyConfig.getPwdMaxAge() )
         {
             return 0;
         }
 
         warningAge = policyConfig.getPwdMaxAge() - warningAge;
-        
+
         if ( pwdAge >= warningAge )
         {
             return policyConfig.getPwdMaxAge() - pwdAge;
@@ -1260,14 +1301,14 @@ public class AuthenticationInterceptor e
         }
 
         Attribute pwdChangedTimeAt = userEntry.get( PWD_CHANGED_TIME_AT );
-        
+
         if ( pwdChangedTimeAt != null )
         {
             long changedTime = DateUtils.getDate( pwdChangedTimeAt.getString() ).getTime();
             changedTime += policyConfig.getPwdMinAge() * 1000;
-        
+
             long currentTime = DateUtils.getDate( DateUtils.getGeneralizedTime() ).getTime();
-            
+
             if ( changedTime > currentTime )
             {
                 return true;
@@ -1290,6 +1331,7 @@ public class AuthenticationInterceptor e
         boolean mustChange = false;
 
         Attribute pwdResetAt = userEntry.get( PWD_RESET_AT );
+
         if ( pwdResetAt != null )
         {
             mustChange = Boolean.parseBoolean( pwdResetAt.getString() );
@@ -1304,6 +1346,7 @@ public class AuthenticationInterceptor e
         PwdModDetailsHolder pwdModDetails = new PwdModDetailsHolder();
 
         List<Modification> mods = modifyContext.getModItems();
+
         for ( Modification m : mods )
         {
             Attribute at = m.getAttribute();
@@ -1354,7 +1397,7 @@ public class AuthenticationInterceptor e
                     .hasRequestControl( PasswordPolicy.OID );
                 if ( isPPolicyReqCtrlPresent )
                 {
-                    PasswordPolicyDecorator pwdRespCtrl = 
+                    PasswordPolicyDecorator pwdRespCtrl =
                         new PasswordPolicyDecorator( directoryService.getLdapCodecService(), true );
                     pwdRespCtrl.getResponse().setPasswordPolicyError( PasswordPolicyErrorEnum.CHANGE_AFTER_RESET );
                     opContext.addResponseControl( pwdRespCtrl );
@@ -1365,7 +1408,7 @@ public class AuthenticationInterceptor e
         }
     }
 
-    
+
     private static class PwdModDetailsHolder
     {
         private boolean pwdModPresent = false;
@@ -1438,10 +1481,10 @@ public class AuthenticationInterceptor e
             this.newPwd = newPwd;
         }
     }
-    
+
 
     /**
-     * Gets the effective password policy of the given entry. 
+     * Gets the effective password policy of the given entry.
      * If the entry has defined a custom password policy by setting "pwdPolicySubentry" attribute
      * then the password policy associated with the Dn specified at the above attribute's value will be returned.
      * Otherwise the default password policy will be returned (if present)
@@ -1456,27 +1499,27 @@ public class AuthenticationInterceptor e
         {
             return null;
         }
-        
+
         if ( pwdPolicyContainer.hasCustomConfigs() )
         {
             Attribute pwdPolicySubentry = userEntry.get( pwdPolicySubentryAT );
-            
+
             if ( pwdPolicySubentry != null )
             {
                 Dn configDn = adminSession.getDirectoryService().getDnFactory().create( pwdPolicySubentry.getString() );
-                
+
                 return pwdPolicyContainer.getPolicyConfig( configDn );
             }
         }
-        
+
         return pwdPolicyContainer.getDefaultPolicy();
     }
-    
-    
+
+
     /**
      * set all the password policies to be used by the server.
      * This includes a default(i.e applicable to all entries) and custom(a.k.a per user) password policies
-     *  
+     * 
      * @param policyContainer the container holding all the password policies
      */
     public void setPwdPolicies( PpolicyConfigContainer policyContainer )
@@ -1490,8 +1533,8 @@ public class AuthenticationInterceptor e
      */
     public boolean isPwdPolicyEnabled()
     {
-        return ( ( pwdPolicyContainer != null ) 
-                && ( ( pwdPolicyContainer.getDefaultPolicy() != null ) 
+        return ( ( pwdPolicyContainer != null )
+            && ( ( pwdPolicyContainer.getDefaultPolicy() != null )
                 || ( pwdPolicyContainer.hasCustomConfigs() ) ) );
     }
 

Propchange: directory/apacheds/branches/apacheds-osgi/interceptors/authz/
------------------------------------------------------------------------------
--- svn:mergeinfo (added)
+++ svn:mergeinfo Sat Nov 12 23:58:40 2011
@@ -0,0 +1,10 @@
+/directory/apacheds/branches/apacheds-codec-merge/interceptors/authz:982369-987590
+/directory/apacheds/branches/apacheds-config/interceptors/authz:1023442-1029077
+/directory/apacheds/branches/apacheds-kerberos-codec-2.0/interceptors/authz:1040956-1043765
+/directory/apacheds/branches/apacheds-replication/interceptors/authz:749790-764110
+/directory/apacheds/branches/apacheds-schema/interceptors/authz:806623-896441
+/directory/apacheds/branches/apacheds-subtree/interceptors/authz:965203-965686
+/directory/apacheds/branches/milestones/interceptors/authz:1072812-1075328
+/directory/apacheds/branches/xdbm-refactoring/interceptors/authz:945827-946347
+/directory/apacheds/trunk/interceptors/authz:1066126-1067785,1068026-1072718,1072800-1075329,1185681-1201349
+/directory/studio/trunk/interceptors/authz:1067786-1067997