]> git.sur5r.net Git - openldap/blobdiff - servers/slapd/overlays/ppolicy.c
Revert prev commit. There's no solid justification for it, and it
[openldap] / servers / slapd / overlays / ppolicy.c
index 857240fb7038e1cb9bc517a82594035d679f1c3c..2c68c9d0afa5bfbb9a619fddcb47d66b8c54cc33 100644 (file)
@@ -1,7 +1,9 @@
 /* $OpenLDAP$ */
 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
  *
- * Copyright 2004 Howard Chu, Symas Corporation.
+ * Copyright 2004-2007 The OpenLDAP Foundation.
+ * Portions Copyright 2004-2005 Howard Chu, Symas Corporation.
+ * Portions Copyright 2004 Hewlett-Packard Company.
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * top-level directory of the distribution or, alternatively, at
  * <http://www.OpenLDAP.org/license.html>.
  */
+/* ACKNOWLEDGEMENTS:
+ * This work was developed by Howard Chu for inclusion in
+ * OpenLDAP Software, based on prior work by Neil Dunbar (HP).
+ * This work was sponsored by the Hewlett-Packard Company.
+ */
 
 #include "portable.h"
 
 /* This file implements "Password Policy for LDAP Directories",
- * based on draft behera-ldap-password-policy-07
+ * based on draft behera-ldap-password-policy-09
  */
 
 #ifdef SLAPD_OVER_PPOLICY
 
-#if SLAPD_OVER_PPOLICY == SLAPD_MOD_DYNAMIC
-#define        SLAPD_IMPORT
-#endif
-
 #include <ldap.h>
 #include "lutil.h"
 #include "slap.h"
+#if SLAPD_MODULES
+#define LIBLTDL_DLL_IMPORT     /* Win32: don't re-export libltdl's symbols */
 #include <ltdl.h>
+#endif
 #include <ac/errno.h>
 #include <ac/time.h>
 #include <ac/string.h>
+#include <ac/ctype.h>
+#include "config.h"
 
 #ifndef MODULE_NAME_SZ
 #define MODULE_NAME_SZ 256
 typedef struct pp_info {
        struct berval def_policy;       /* DN of default policy subentry */
        int use_lockout;                /* send AccountLocked result? */
+       int hash_passwords;             /* transparently hash cleartext pwds */
 } pp_info;
 
 /* Our per-connection info - note, it is not per-instance, it is 
  * used by all instances
  */
 typedef struct pw_conn {
-       int restrict;           /* TRUE if connection is restricted */
+       struct berval dn;       /* DN of restricted user */
 } pw_conn;
 
 static pw_conn *pwcons;
+static int ppolicy_cid;
 
 typedef struct pass_policy {
        AttributeDescription *ad; /* attribute to which the policy applies */
@@ -62,7 +72,7 @@ typedef struct pass_policy {
        int pwdMinLength; /* minimum number of chars in password */
        int pwdExpireWarning; /* number of seconds that warning controls are
                                                        sent before a password expires */
-       int pwdGraceLoginLimit; /* number of times you can log in with an
+       int pwdGraceAuthNLimit; /* number of times you can log in with an
                                                        expired password */
        int pwdLockout; /* 0 = do not lockout passwords, 1 = lock them out */
        int pwdLockoutDuration; /* time in seconds a password is locked out for */
@@ -89,8 +99,8 @@ typedef struct pw_hist {
 
 /* Operational attributes */
 static AttributeDescription *ad_pwdChangedTime, *ad_pwdAccountLockedTime,
-       *ad_pwdExpirationWarned, *ad_pwdFailureTime, *ad_pwdHistory,
-       *ad_pwdGraceUseTime, *ad_pwdReset, *ad_pwdPolicySubentry;
+       *ad_pwdFailureTime, *ad_pwdHistory, *ad_pwdGraceUseTime, *ad_pwdReset,
+       *ad_pwdPolicySubentry;
 
 static struct schema_info {
        char *def;
@@ -102,7 +112,7 @@ static struct schema_info {
                "EQUALITY generalizedTimeMatch "
                "ORDERING generalizedTimeOrderingMatch "
                "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
-               "SINGLE-VALUE USAGE directoryOperation )",
+               "SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation )",
                &ad_pwdChangedTime },
        {       "( 1.3.6.1.4.1.42.2.27.8.1.17 "
                "NAME ( 'pwdAccountLockedTime' ) "
@@ -110,37 +120,34 @@ static struct schema_info {
                "EQUALITY generalizedTimeMatch "
                "ORDERING generalizedTimeOrderingMatch "
                "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
-               "SINGLE-VALUE USAGE directoryOperation )",
+               "SINGLE-VALUE "
+#if 0
+               /* Not until MANAGEDIT control is released */
+               "NO-USER-MODIFICATION "
+#endif
+               "USAGE directoryOperation )",
                &ad_pwdAccountLockedTime },
-       {       "( 1.3.6.1.4.1.42.2.27.8.1.18 "
-               "NAME ( 'pwdExpirationWarned' ) "
-               "DESC 'The time the user was first warned about the coming expiration of the password' "
-               "EQUALITY generalizedTimeMatch "
-               "ORDERING generalizedTimeOrderingMatch "
-               "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
-               "SINGLE-VALUE USAGE directoryOperation )",
-               &ad_pwdExpirationWarned },
        {       "( 1.3.6.1.4.1.42.2.27.8.1.19 "
                "NAME ( 'pwdFailureTime' ) "
                "DESC 'The timestamps of the last consecutive authentication failures' "
                "EQUALITY generalizedTimeMatch "
                "ORDERING generalizedTimeOrderingMatch "
                "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
-               "USAGE directoryOperation )",
+               "NO-USER-MODIFICATION USAGE directoryOperation )",
                &ad_pwdFailureTime },
        {       "( 1.3.6.1.4.1.42.2.27.8.1.20 "
                "NAME ( 'pwdHistory' ) "
                "DESC 'The history of users passwords' "
                "EQUALITY octetStringMatch "
                "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 "
-               "USAGE directoryOperation )",
+               "NO-USER-MODIFICATION USAGE directoryOperation )",
                &ad_pwdHistory },
        {       "( 1.3.6.1.4.1.42.2.27.8.1.21 "
                "NAME ( 'pwdGraceUseTime' ) "
                "DESC 'The timestamps of the grace login once the password has expired' "
                "EQUALITY generalizedTimeMatch "
                "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
-               "USAGE directoryOperation )",
+               "NO-USER-MODIFICATION USAGE directoryOperation )",
                &ad_pwdGraceUseTime }, 
        {       "( 1.3.6.1.4.1.42.2.27.8.1.22 "
                "NAME ( 'pwdReset' ) "
@@ -154,7 +161,12 @@ static struct schema_info {
                "DESC 'The pwdPolicy subentry in effect for this object' "
                "EQUALITY distinguishedNameMatch "
                "SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 "
-               "SINGLE-VALUE USAGE directoryOperation )",
+               "SINGLE-VALUE "
+#if 0
+               /* Not until MANAGEDIT control is released */
+               "NO-USER-MODIFICATION "
+#endif
+               "USAGE directoryOperation )",
                &ad_pwdPolicySubentry },
        { NULL, NULL }
 };
@@ -162,7 +174,7 @@ static struct schema_info {
 /* User attributes */
 static AttributeDescription *ad_pwdMinAge, *ad_pwdMaxAge, *ad_pwdInHistory,
        *ad_pwdCheckQuality, *ad_pwdMinLength, *ad_pwdMaxFailure, 
-       *ad_pwdGraceLoginLimit, *ad_pwdExpireWarning, *ad_pwdLockoutDuration,
+       *ad_pwdGraceAuthNLimit, *ad_pwdExpireWarning, *ad_pwdLockoutDuration,
        *ad_pwdFailureCountInterval, *ad_pwdCheckModule, *ad_pwdLockout,
        *ad_pwdMustChange, *ad_pwdAllowUserChange, *ad_pwdSafeModify,
        *ad_pwdAttribute;
@@ -177,7 +189,7 @@ static struct schema_info pwd_UsSchema[] = {
        TAB(pwdCheckQuality),
        TAB(pwdMinLength),
        TAB(pwdMaxFailure),
-       TAB(pwdGraceLoginLimit),
+       TAB(pwdGraceAuthNLimit),
        TAB(pwdExpireWarning),
        TAB(pwdLockout),
        TAB(pwdLockoutDuration),
@@ -191,68 +203,107 @@ static struct schema_info pwd_UsSchema[] = {
 
 static ldap_pvt_thread_mutex_t chk_syntax_mutex;
 
-static time_t
-ppolicy_timegm( struct tm *t )
-{
-       static int moffset[12] = {
-               0, 31, 59, 90, 120,
-               151, 181, 212, 243,
-               273, 304, 334 }; 
-       time_t ret; 
-
-       /* t->tm_year is years since 1900 */
-       /* calculate days from years since 1970 (epoch) */ 
-       ret = t->tm_year - 70; 
-       ret *= 365L; 
-
-       /* count leap days in preceding years */ 
-       ret += ((t->tm_year -69) >> 2); 
-
-       /* calculate days from months */ 
-       ret += moffset[t->tm_mon]; 
-
-       /* add in this year's leap day, if any */ 
-       if (((t->tm_year & 3) == 0) && (t->tm_mon > 1)) { 
-               ret ++; 
-       } 
-
-       /* add in days in this month */ 
-       ret += (t->tm_mday - 1); 
+enum {
+       PPOLICY_DEFAULT = 1,
+       PPOLICY_HASH_CLEARTEXT,
+       PPOLICY_USE_LOCKOUT
+};
 
-       /* convert to hours */ 
-       ret *= 24L; 
-       ret += t->tm_hour; 
+static ConfigDriver ppolicy_cf_default;
+
+static ConfigTable ppolicycfg[] = {
+       { "ppolicy_default", "policyDN", 2, 2, 0,
+         ARG_DN|ARG_MAGIC|PPOLICY_DEFAULT, ppolicy_cf_default,
+         "( OLcfgOvAt:12.1 NAME 'olcPPolicyDefault' "
+         "DESC 'DN of a pwdPolicy object for uncustomized objects' "
+         "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
+       { "ppolicy_hash_cleartext", "on|off", 1, 2, 0,
+         ARG_ON_OFF|ARG_OFFSET|PPOLICY_HASH_CLEARTEXT,
+         (void *)offsetof(pp_info,hash_passwords),
+         "( OLcfgOvAt:12.2 NAME 'olcPPolicyHashCleartext' "
+         "DESC 'Hash passwords on add or modify' "
+         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
+       { "ppolicy_use_lockout", "on|off", 1, 2, 0,
+         ARG_ON_OFF|ARG_OFFSET|PPOLICY_USE_LOCKOUT,
+         (void *)offsetof(pp_info,use_lockout),
+         "( OLcfgOvAt:12.3 NAME 'olcPPolicyUseLockout' "
+         "DESC 'Warn clients with AccountLocked' "
+         "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
+       { NULL, NULL, 0, 0, 0, ARG_IGNORED }
+};
 
-       /* convert to minutes */ 
-       ret *= 60L; 
-       ret += t->tm_min; 
+static ConfigOCs ppolicyocs[] = {
+       { "( OLcfgOvOc:12.1 "
+         "NAME 'olcPPolicyConfig' "
+         "DESC 'Password Policy configuration' "
+         "SUP olcOverlayConfig "
+         "MAY ( olcPPolicyDefault $ olcPPolicyHashCleartext $ "
+         "olcPPolicyUseLockout ) )",
+         Cft_Overlay, ppolicycfg },
+       { NULL, 0, NULL }
+};
 
-       /* convert to seconds */ 
-       ret *= 60L; 
-       ret += t->tm_sec; 
+static int
+ppolicy_cf_default( ConfigArgs *c )
+{
+       slap_overinst *on = (slap_overinst *)c->bi;
+       pp_info *pi = (pp_info *)on->on_bi.bi_private;
+       BackendDB *be = (BackendDB *)c->be;
+       const char *text;
+       int rc = ARG_BAD_CONF;
+
+       assert ( c->type == PPOLICY_DEFAULT );
+       Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default\n", 0, 0, 0);
+
+       switch ( c->op ) {
+       case SLAP_CONFIG_EMIT:
+               Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default emit\n", 0, 0, 0);
+               rc = 0;
+               if ( !BER_BVISEMPTY( &pi->def_policy )) {
+                       rc = value_add_one( &c->rvalue_vals,
+                                           &pi->def_policy );
+                       if ( rc ) return rc;
+                       rc = value_add_one( &c->rvalue_nvals,
+                                           &pi->def_policy );
+               }
+               break;
+       case LDAP_MOD_DELETE:
+               Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default delete\n", 0, 0, 0);
+               if ( pi->def_policy.bv_val ) {
+                       ber_memfree ( pi->def_policy.bv_val );
+                       pi->def_policy.bv_val = NULL;
+               }
+               pi->def_policy.bv_len = 0;
+               rc = 0;
+               break;
+       case SLAP_CONFIG_ADD:
+               /* fallthrough to LDAP_MOD_ADD */
+       case LDAP_MOD_ADD:
+               Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default add\n", 0, 0, 0);
+               if ( pi->def_policy.bv_val )
+                       ber_memfree ( pi->def_policy.bv_val );
+               pi->def_policy = c->value_ndn;
+               rc = 0;
+               break;
+       default:
+               abort ();
+       }
 
-       /* return the result */ 
-       return ret; 
+       return rc;
 }
 
 static time_t
 parse_time( char *atm )
 {
-       struct tm tm;
+       struct lutil_tm tm;
+       struct lutil_timet tt;
+       time_t ret = (time_t)-1;
 
-       if (!atm) return (time_t)-1;
-
-       /*
-        * special case - if the lowest allowable GeneralizedTime is here, return
-        * this is as zero time. Note: this might also be the case if the value stored
-        * is equivalent to the start of the epoch (ie, Jan 1, 1970 at midnight.
-        */
-       if (strcmp(atm, "00000101000000Z") == 0) return (time_t)0;
-       /*
-        * else parse the time and return it's time_t value.
-        */
-       strptime( atm, "%Y%m%d%H%M%SZ", &tm );
-       return ppolicy_timegm( &tm );
+       if ( lutil_parsetime( atm, &tm ) == 0) {
+               lutil_tm2time( &tm, &tt );
+               ret = tt.tt_sec;
+       }
+       return ret;
 }
 
 static int
@@ -260,10 +311,8 @@ account_locked( Operation *op, Entry *e,
                PassPolicy *pp, Modifications **mod ) 
 {
        Attribute       *la;
-       int rc;
-       Entry *de;
 
-       assert(mod);
+       assert(mod != NULL);
 
        if ( (la = attr_find( e->e_attrs, ad_pwdAccountLockedTime )) != NULL ) {
                BerVarray vals = la->a_nvals;
@@ -274,9 +323,11 @@ account_locked( Operation *op, Entry *e,
                 */
                if (vals[0].bv_val != NULL) {
                        time_t then, now;
-                       struct berval bv;
                        Modifications *m;
 
+                       if (!pp->pwdLockoutDuration)
+                               return 1;
+
                        if ((then = parse_time( vals[0].bv_val )) == (time_t)0)
                                return 1;
 
@@ -287,6 +338,7 @@ account_locked( Operation *op, Entry *e,
 
                        m = ch_calloc( sizeof(Modifications), 1 );
                        m->sml_op = LDAP_MOD_DELETE;
+                       m->sml_flags = 0;
                        m->sml_type = ad_pwdAccountLockedTime->ad_cname;
                        m->sml_desc = ad_pwdAccountLockedTime;
                        m->sml_next = *mod;
@@ -297,11 +349,14 @@ account_locked( Operation *op, Entry *e,
        return 0;
 }
 
-#define PPOLICY_WARNING 0xa0L
-#define PPOLICY_ERROR 0xa1L
+/* IMPLICIT TAGS, all context-specific */
+#define PPOLICY_WARNING 0xa0L  /* constructed + 0 */
+#define PPOLICY_ERROR 0x81L            /* primitive + 1 */
  
-#define PPOLICY_EXPIRE 0xa0L
-#define PPOLICY_GRACE  0xa1L
+#define PPOLICY_EXPIRE 0x80L   /* primitive + 0 */
+#define PPOLICY_GRACE  0x81L   /* primitive + 1 */
+
+static const char ppolicy_ctrl_oid[] = LDAP_CONTROL_PASSWORDPOLICYRESPONSE;
 
 static LDAPControl *
 create_passcontrol( int exptime, int grace, LDAPPasswordPolicyError err )
@@ -311,25 +366,29 @@ create_passcontrol( int exptime, int grace, LDAPPasswordPolicyError err )
        LDAPControl *c;
        struct berval bv;
 
-       if ((c = ch_calloc( sizeof( LDAPControl ), 1 )) == NULL) return NULL;
-       c->ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYRESPONSE;
+       c = ch_calloc( sizeof( LDAPControl ), 1 );
+       if ( c == NULL ) {
+               return NULL;
+       }
+       c->ldctl_oid = (char *)ppolicy_ctrl_oid;
        c->ldctl_iscritical = 0;
-       c->ldctl_value.bv_val = NULL;
-       c->ldctl_value.bv_len = 0;
+       BER_BVZERO( &c->ldctl_value );
 
        ber_init2( ber, NULL, LBER_USE_DER );
-       ber_printf(ber, "{" /*}*/ );
+       ber_printf( ber, "{" /*}*/ );
 
-       if (exptime >= 0) {
+       if ( exptime >= 0 ) {
                ber_init2( b2, NULL, LBER_USE_DER );
                ber_printf( b2, "ti", PPOLICY_EXPIRE, exptime );
                ber_flatten2( b2, &bv, 1 );
+               (void)ber_free_buf(b2);
                ber_printf( ber, "tO", PPOLICY_WARNING, &bv );
                ch_free( bv.bv_val );
-       } else if (grace > 0) {
+       } else if ( grace > 0 ) {
                ber_init2( b2, NULL, LBER_USE_DER );
                ber_printf( b2, "ti", PPOLICY_GRACE, grace );
                ber_flatten2( b2, &bv, 1 );
+               (void)ber_free_buf(b2);
                ber_printf( ber, "tO", PPOLICY_WARNING, &bv );
                ch_free( bv.bv_val );
        }
@@ -341,13 +400,41 @@ create_passcontrol( int exptime, int grace, LDAPPasswordPolicyError err )
 
        if (ber_flatten2( ber, &(c->ldctl_value), 1 ) == LBER_DEFAULT) {
                ch_free(c);
-               (void)ber_free_buf(ber);
-               return NULL;
+               c = NULL;
        }
        (void)ber_free_buf(ber);
        return c;
 }
 
+static LDAPControl **
+add_passcontrol( Operation *op, SlapReply *rs, LDAPControl *ctrl )
+{
+       LDAPControl **ctrls, **oldctrls = rs->sr_ctrls;
+       int n;
+
+       n = 0;
+       if ( oldctrls ) {
+               for ( ; oldctrls[n]; n++ )
+                       ;
+       }
+       n += 2;
+
+       ctrls = op->o_tmpcalloc( sizeof( LDAPControl * ), n, op->o_tmpmemctx );
+
+       n = 0;
+       if ( oldctrls ) {
+               for ( ; oldctrls[n]; n++ ) {
+                       ctrls[n] = oldctrls[n];
+               }
+       }
+       ctrls[n] = ctrl;
+       ctrls[n+1] = NULL;
+
+       rs->sr_ctrls = ctrls;
+
+       return oldctrls;
+}
+
 static void
 ppolicy_get( Operation *op, Entry *e, PassPolicy *pp )
 {
@@ -355,16 +442,19 @@ ppolicy_get( Operation *op, Entry *e, PassPolicy *pp )
        pp_info *pi = on->on_bi.bi_private;
        Attribute *a;
        BerVarray vals;
-       int i, rc, nent;
+       int rc;
        Entry *pe = NULL;
-       AttributeDescription *oca = slap_schema.si_ad_objectClass;
+#if 0
        const char *text;
-       AttributeDescription *ad;
-       struct berval bv;
-       void *opr = op->o_private;
+#endif
 
        memset( pp, 0, sizeof(PassPolicy) );
 
+       pp->ad = slap_schema.si_ad_userPassword;
+
+       /* Users can change their own password by default */
+       pp->pwdAllowUserChange = 1;
+
        if ((a = attr_find( e->e_attrs, ad_pwdPolicySubentry )) == NULL) {
                /*
                 * entry has no password policy assigned - use default
@@ -375,19 +465,12 @@ ppolicy_get( Operation *op, Entry *e, PassPolicy *pp )
        } else {
                vals = a->a_nvals;
                if (vals[0].bv_val == NULL) {
-#ifdef NEW_LOGGING
-                       LDAP_LOG( OPERATION, ERR,
-                               "ppolicy_get: NULL value for policySubEntry\n", 0, 0, 0 );
-#else
                        Debug( LDAP_DEBUG_ANY,
                                "ppolicy_get: NULL value for policySubEntry\n", 0, 0, 0 );
-#endif
                        goto defaultpol;
                }
        }
 
-       /* back-bdb stores lock info in o_private */
-       op->o_private = NULL;
        op->o_bd->bd_info = (BackendInfo *)on->on_info;
        rc = be_entry_get_rw( op, vals, NULL, NULL, 0, &pe );
        op->o_bd->bd_info = (BackendInfo *)on;
@@ -397,62 +480,63 @@ ppolicy_get( Operation *op, Entry *e, PassPolicy *pp )
 #if 0  /* Only worry about userPassword for now */
        if ((a = attr_find( pe->e_attrs, ad_pwdAttribute )))
                slap_bv2ad( &a->a_vals[0], &pp->ad, &text );
-#else
-       pp->ad = slap_schema.si_ad_userPassword;
 #endif
 
-       if ((a = attr_find( pe->e_attrs, ad_pwdMinAge )))
-               pp->pwdMinAge = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdMaxAge )))
-               pp->pwdMaxAge = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdInHistory )))
-               pp->pwdInHistory = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdCheckQuality )))
-               pp->pwdCheckQuality = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdMinLength )))
-               pp->pwdMinLength = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdMaxFailure )))
-               pp->pwdMaxFailure = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdGraceLoginLimit )))
-               pp->pwdGraceLoginLimit = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdExpireWarning )))
-               pp->pwdExpireWarning = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdFailureCountInterval )))
-               pp->pwdFailureCountInterval = atoi(a->a_vals[0].bv_val );
-       if ((a = attr_find( pe->e_attrs, ad_pwdLockoutDuration )))
-               pp->pwdLockoutDuration = atoi(a->a_vals[0].bv_val );
-
-       if ((a = attr_find( pe->e_attrs, ad_pwdCheckModule ))) {
-               strncpy(pp->pwdCheckModule, a->a_vals[0].bv_val,
-                       sizeof(pp->pwdCheckModule));
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdMinAge ) )
+                       && lutil_atoi( &pp->pwdMinAge, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdMaxAge ) )
+                       && lutil_atoi( &pp->pwdMaxAge, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdInHistory ) )
+                       && lutil_atoi( &pp->pwdInHistory, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdCheckQuality ) )
+                       && lutil_atoi( &pp->pwdCheckQuality, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdMinLength ) )
+                       && lutil_atoi( &pp->pwdMinLength, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdMaxFailure ) )
+                       && lutil_atoi( &pp->pwdMaxFailure, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdGraceAuthNLimit ) )
+                       && lutil_atoi( &pp->pwdGraceAuthNLimit, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdExpireWarning ) )
+                       && lutil_atoi( &pp->pwdExpireWarning, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdFailureCountInterval ) )
+                       && lutil_atoi( &pp->pwdFailureCountInterval, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdLockoutDuration ) )
+                       && lutil_atoi( &pp->pwdLockoutDuration, a->a_vals[0].bv_val ) != 0 )
+               goto defaultpol;
+
+       if ( ( a = attr_find( pe->e_attrs, ad_pwdCheckModule ) ) ) {
+               strncpy( pp->pwdCheckModule, a->a_vals[0].bv_val,
+                       sizeof(pp->pwdCheckModule) );
                pp->pwdCheckModule[sizeof(pp->pwdCheckModule)-1] = '\0';
        }
 
        if ((a = attr_find( pe->e_attrs, ad_pwdLockout )))
-       pp->pwdLockout = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
+               pp->pwdLockout = bvmatch( &a->a_nvals[0], &slap_true_bv );
        if ((a = attr_find( pe->e_attrs, ad_pwdMustChange )))
-       pp->pwdMustChange = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
+               pp->pwdMustChange = bvmatch( &a->a_nvals[0], &slap_true_bv );
        if ((a = attr_find( pe->e_attrs, ad_pwdAllowUserChange )))
-       pp->pwdAllowUserChange = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
+               pp->pwdAllowUserChange = bvmatch( &a->a_nvals[0], &slap_true_bv );
        if ((a = attr_find( pe->e_attrs, ad_pwdSafeModify )))
-       pp->pwdSafeModify = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
+               pp->pwdSafeModify = bvmatch( &a->a_nvals[0], &slap_true_bv );
     
        op->o_bd->bd_info = (BackendInfo *)on->on_info;
        be_entry_release_r( op, pe );
        op->o_bd->bd_info = (BackendInfo *)on;
 
-       op->o_private = opr;
        return;
 
 defaultpol:
-#ifdef NEW_LOGGING
-       LDAP_LOG( OPERATION, DETAIL1,
-               "ppolicy_get: using default policy\n", 0, 0, 0 );
-#else
-       Debug( LDAP_DEBUG_ANY,
+       Debug( LDAP_DEBUG_TRACE,
                "ppolicy_get: using default policy\n", 0, 0, 0 );
-#endif
-       op->o_private = opr;
        return;
 }
 
@@ -473,14 +557,13 @@ password_scheme( struct berval *cred, struct berval *sch )
 
        for(e = 1; cred->bv_val[e] && cred->bv_val[e] != '}'; e++);
        if (cred->bv_val[e]) {
-               char *sc = ch_calloc( sizeof(char), e + 2);
-               sc[e + 1] = '\0'; /* terminate string */
-               strncpy( sc, cred->bv_val, e + 1);
-               e = lutil_passwd_scheme( sc );
-               free( sc );
-               if (e && sch) {
-                       sch->bv_val = cred->bv_val;
-                       sch->bv_len = e;
+               int rc;
+               rc = lutil_passwd_scheme( cred->bv_val );
+               if (rc) {
+                       if (sch) {
+                               sch->bv_val = cred->bv_val;
+                               sch->bv_len = e;
+                       }
                        return LDAP_SUCCESS;
                }
        }
@@ -488,11 +571,10 @@ password_scheme( struct berval *cred, struct berval *sch )
 }
 
 static int
-check_password_quality( struct berval *cred, PassPolicy *pp, LDAPPasswordPolicyError *err )
+check_password_quality( struct berval *cred, PassPolicy *pp, LDAPPasswordPolicyError *err, Entry *e )
 {
        int rc = LDAP_SUCCESS, ok = LDAP_SUCCESS;
        char *ptr = cred->bv_val;
-       char *modpath;
        struct berval sch;
 
        assert( cred != NULL );
@@ -534,63 +616,49 @@ check_password_quality( struct berval *cred, PassPolicy *pp, LDAPPasswordPolicyE
        }
 
        rc = LDAP_SUCCESS;
-    
+
        if (pp->pwdCheckModule[0]) {
+#if SLAPD_MODULES
                lt_dlhandle mod;
                const char *err;
                
                if ((mod = lt_dlopen( pp->pwdCheckModule )) == NULL) {
                        err = lt_dlerror();
 
-#ifdef NEW_LOGGING
-                       LDAP_LOG( SLAPD, CRIT,
-                       "check_password_quality: lt_dlopen failed: (%s) %s.\n",
-                               pp->pwdCheckModule, err, 0 );
-#else
                        Debug(LDAP_DEBUG_ANY,
                        "check_password_quality: lt_dlopen failed: (%s) %s.\n",
                                pp->pwdCheckModule, err, 0 );
-#endif
                        ok = LDAP_OTHER; /* internal error */
                } else {
-                       int (*prog)( char *passwd, char **text, void *arg );
+                       int (*prog)( char *passwd, char **text, Entry *ent );
 
                        if ((prog = lt_dlsym( mod, "check_password" )) == NULL) {
                                err = lt_dlerror();
                            
-#ifdef NEW_LOGGING
-                               LDAP_LOG( SLAPD, CRIT,
-                                       "check_password_quality: lt_dlsym failed: (%s) %s.\n",
-                                       pp->pwdCheckModule, err, 0 );
-#else
                                Debug(LDAP_DEBUG_ANY,
                                        "check_password_quality: lt_dlsym failed: (%s) %s.\n",
                                        pp->pwdCheckModule, err, 0 );
-#endif
                                ok = LDAP_OTHER;
                        } else {
                                char *txt = NULL;
 
                                ldap_pvt_thread_mutex_lock( &chk_syntax_mutex );
-                               ok = prog( cred->bv_val, &txt, NULL );
+                               ok = prog( cred->bv_val, &txt, e );
                                ldap_pvt_thread_mutex_unlock( &chk_syntax_mutex );
-                               if (txt) {
-#ifdef NEW_LOGGING
-                                       LDAP_LOG( SLAPD, CRIT,
-                                               "check_password_quality: module error (%s) %s[%d].\n",
-                                               pp->pwdCheckModule, txt, ok );
-#else
+                               if (ok != LDAP_SUCCESS) {
                                        Debug(LDAP_DEBUG_ANY,
                                                "check_password_quality: module error: (%s) %s.[%d]\n",
-                                               pp->pwdCheckModule, txt, ok );
-#endif
+                                               pp->pwdCheckModule, txt ? txt : "", ok );
                                        free(txt);
-                               } else
-                                       ok = LDAP_SUCCESS;
+                               }
                        }
                            
                        lt_dlclose( mod );
                }
+#else
+       Debug(LDAP_DEBUG_ANY, "check_password_quality: external modules not "
+               "supported. pwdCheckModule ignored.\n", 0, 0, 0);
+#endif /* SLAPD_MODULES */
        }
                
                    
@@ -611,50 +679,75 @@ parse_pwdhistory( struct berval *bv, char **oid, time_t *oldtime, struct berval
        
        assert (bv && (bv->bv_len > 0) && (bv->bv_val) && oldtime && oldpw );
 
-       if ( oid ) *oid = 0;
+       if ( oid ) {
+               *oid = 0;
+       }
        *oldtime = (time_t)-1;
-       oldpw->bv_val = NULL;
-       oldpw->bv_len = 0;
+       BER_BVZERO( oldpw );
        
        ber_dupbv( &nv, bv );
 
        /* first get the time field */
-       for(i=0; (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++);
-       if ( i == nv.bv_len) goto exit_failure; /* couldn't locate the '#' separator */
+       for ( i = 0; (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++ )
+               ;
+       if ( i == nv.bv_len ) {
+               goto exit_failure; /* couldn't locate the '#' separator */
+       }
        nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
        ptr = nv.bv_val;
        *oldtime = parse_time( ptr );
-       if (*oldtime == (time_t)-1) goto exit_failure;
+       if (*oldtime == (time_t)-1) {
+               goto exit_failure;
+       }
 
        /* get the OID field */
-       for(ptr = &(nv.bv_val[i]);(i < nv.bv_len) && (nv.bv_val[i] != '#'); i++);
-       if ( i == nv.bv_len) goto exit_failure; /* couldn't locate the '#' separator */
+       for (ptr = &(nv.bv_val[i]); (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++ )
+               ;
+       if ( i == nv.bv_len ) {
+               goto exit_failure; /* couldn't locate the '#' separator */
+       }
        nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
-       if ( oid ) *oid = ber_strdup( ptr );
+       if ( oid ) {
+               *oid = ber_strdup( ptr );
+       }
        
        /* get the length field */
-       for(ptr = &(nv.bv_val[i]);(i < nv.bv_len) && (nv.bv_val[i] != '#'); i++);
-       if ( i == nv.bv_len) goto exit_failure; /* couldn't locate the '#' separator */
+       for ( ptr = &(nv.bv_val[i]); (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++ )
+               ;
+       if ( i == nv.bv_len ) {
+               goto exit_failure; /* couldn't locate the '#' separator */
+       }
        nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
        oldpw->bv_len = strtol( ptr, NULL, 10 );
-       if (errno == ERANGE) goto exit_failure;
+       if (errno == ERANGE) {
+               goto exit_failure;
+       }
 
        /* lastly, get the octets of the string */
-       for(j=i, ptr = &(nv.bv_val[i]);i < nv.bv_len; i++);
-       if (i-j != oldpw->bv_len) goto exit_failure; /* length is wrong */
+       for ( j = i, ptr = &(nv.bv_val[i]); i < nv.bv_len; i++ )
+               ;
+       if ( i - j != oldpw->bv_len) {
+               goto exit_failure; /* length is wrong */
+       }
 
        npw.bv_val = ptr;
        npw.bv_len = oldpw->bv_len;
        ber_dupbv( oldpw, &npw );
+       ber_memfree( nv.bv_val );
        
        return LDAP_SUCCESS;
-exit_failure:
-       if (oid && *oid) { ber_memfree(*oid); *oid = NULL; }
-       if (oldpw->bv_val) {
-               ber_memfree( oldpw->bv_val); oldpw->bv_val = NULL;
-               oldpw->bv_len = 0;
+
+exit_failure:;
+       if ( oid && *oid ) {
+               ber_memfree(*oid);
+               *oid = NULL;
        }
-       ber_memfree(nv.bv_val);
+       if ( oldpw->bv_val ) {
+               ber_memfree( oldpw->bv_val);
+               BER_BVZERO( oldpw );
+       }
+       ber_memfree( nv.bv_val );
+
        return LDAP_OTHER;
 }
 
@@ -698,9 +791,9 @@ make_pwd_history_value( char *timebuf, struct berval *bv, Attribute *pa )
        int nlen;
 
        snprintf( str, MAX_PWD_HISTORY_SZ,
-                 "%s#%s#%d#", timebuf,
+                 "%s#%s#%lu#", timebuf,
                  pa->a_desc->ad_type->sat_syntax->ssyn_oid,
-                 pa->a_nvals[0].bv_len );
+                 (unsigned long) pa->a_nvals[0].bv_len );
        str[MAX_PWD_HISTORY_SZ-1] = 0;
        nlen = strlen(str);
 
@@ -742,24 +835,60 @@ free_pwd_history_list( pw_hist **l )
 typedef struct ppbind {
        slap_overinst *on;
        int send_ctrl;
+       LDAPControl **oldctrls;
        Modifications *mod;
        LDAPPasswordPolicyError pErr;
        PassPolicy pp;
 } ppbind;
 
+static void
+ctrls_cleanup( Operation *op, SlapReply *rs, LDAPControl **oldctrls )
+{
+       int n;
+
+       assert( rs->sr_ctrls != NULL );
+       assert( rs->sr_ctrls[0] != NULL );
+
+       for ( n = 0; rs->sr_ctrls[n]; n++ ) {
+               if ( rs->sr_ctrls[n]->ldctl_oid == ppolicy_ctrl_oid ) {
+                       ch_free( rs->sr_ctrls[n]->ldctl_value.bv_val );
+                       ch_free( rs->sr_ctrls[n] );
+                       rs->sr_ctrls[n] = (LDAPControl *)(-1);
+                       break;
+               }
+       }
+
+       if ( rs->sr_ctrls[n] == NULL ) {
+               /* missed? */
+       }
+
+       op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
+
+       rs->sr_ctrls = oldctrls;
+}
+
 static int
-ppolicy_bind_resp( Operation *op, SlapReply *rs )
+ppolicy_ctrls_cleanup( Operation *op, SlapReply *rs )
+{
+       ppbind *ppb = op->o_callback->sc_private;
+       if ( ppb->send_ctrl ) {
+               ctrls_cleanup( op, rs, ppb->oldctrls );
+       }
+       return SLAP_CB_CONTINUE;
+}
+
+static int
+ppolicy_bind_response( Operation *op, SlapReply *rs )
 {
        ppbind *ppb = op->o_callback->sc_private;
        slap_overinst *on = ppb->on;
        Modifications *mod = ppb->mod, *m;
        int pwExpired = 0;
-       int ngut = -1, warn = -1, age, rc, i;
+       int ngut = -1, warn = -1, age, rc;
        Attribute *a;
-       struct tm *tm;
-       time_t now, then, pwtime = (time_t)-1;
-       const char *txt;
+       time_t now, pwtime = (time_t)-1;
        char nowstr[ LDAP_LUTIL_GENTIME_BUFSIZE ];
+       struct berval timestamp;
        BackendInfo *bi = op->o_bd->bd_info;
        Entry *e;
 
@@ -777,21 +906,23 @@ ppolicy_bind_resp( Operation *op, SlapReply *rs )
        }
 
        now = slap_get_time(); /* stored for later consideration */
-       ldap_pvt_thread_mutex_lock( &gmtime_mutex );
-       tm = gmtime(&now);
-       lutil_gentime( nowstr, sizeof(nowstr), tm );
-       ldap_pvt_thread_mutex_unlock( &gmtime_mutex );
+       timestamp.bv_val = nowstr;
+       timestamp.bv_len = sizeof(nowstr);
+       slap_timestamp( &now, &timestamp );
 
        if ( rs->sr_err == LDAP_INVALID_CREDENTIALS ) {
                int i = 0, fc = 0;
 
                m = ch_calloc( sizeof(Modifications), 1 );
                m->sml_op = LDAP_MOD_ADD;
+               m->sml_flags = 0;
                m->sml_type = ad_pwdFailureTime->ad_cname;
                m->sml_desc = ad_pwdFailureTime;
                m->sml_values = ch_calloc( sizeof(struct berval), 2 );
+               m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
 
-               ber_str2bv( nowstr, 0, 1, &m->sml_values[0] );
+               ber_dupbv( &m->sml_values[0], &timestamp );
+               ber_dupbv( &m->sml_nvalues[0], &timestamp );
                m->sml_next = mod;
                mod = m;
 
@@ -833,10 +964,13 @@ ppolicy_bind_resp( Operation *op, SlapReply *rs )
                         */
                        m = ch_calloc( sizeof(Modifications), 1 );
                        m->sml_op = LDAP_MOD_REPLACE;
+                       m->sml_flags = 0;
                        m->sml_type = ad_pwdAccountLockedTime->ad_cname;
                        m->sml_desc = ad_pwdAccountLockedTime;
                        m->sml_values = ch_calloc( sizeof(struct berval), 2 );
-                       ber_str2bv( nowstr, 0, 1, &m->sml_values[0] );
+                       m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
+                       ber_dupbv( &m->sml_values[0], &timestamp );
+                       ber_dupbv( &m->sml_nvalues[0], &timestamp );
                        m->sml_next = mod;
                        mod = m;
                }
@@ -848,6 +982,7 @@ ppolicy_bind_resp( Operation *op, SlapReply *rs )
                if ( attr_find( e->e_attrs, ad_pwdFailureTime )) {
                        m = ch_calloc( sizeof(Modifications), 1 );
                        m->sml_op = LDAP_MOD_DELETE;
+                       m->sml_flags = 0;
                        m->sml_type = ad_pwdFailureTime->ad_cname;
                        m->sml_desc = ad_pwdFailureTime;
                        m->sml_next = mod;
@@ -859,14 +994,16 @@ ppolicy_bind_resp( Operation *op, SlapReply *rs )
                 */
                if ( ppb->pp.pwdMustChange &&
                        (a = attr_find( e->e_attrs, ad_pwdReset )) &&
-                       !strcmp( a->a_nvals[0].bv_val, "TRUE" ) ) {
+                       bvmatch( &a->a_nvals[0], &slap_true_bv ) )
+               {
                        /*
                         * need to inject client controls here to give
                         * more information. For the moment, we ensure
                         * that we are disallowed from doing anything
                         * other than change password.
                         */
-                       pwcons[op->o_conn->c_conn_idx].restrict = 1;
+                       ber_dupbv( &pwcons[op->o_conn->c_conn_idx].dn,
+                               &op->o_conn->c_ndn );
 
                        ppb->pErr = PP_changeAfterReset;
 
@@ -876,32 +1013,12 @@ ppolicy_bind_resp( Operation *op, SlapReply *rs )
                         * we now check whether the password has expired.
                         *
                         * We can skip this bit if passwords don't age in
-                        * the policy.
+                        * the policy. Also, if there was no pwdChangedTime
+                        * attribute in the entry, the password never expires.
                         */
                        if (ppb->pp.pwdMaxAge == 0) goto grace;
 
-                       if (pwtime == (time_t)-1) {
-                               /*
-                                * Hmm. No password changed time on the
-                                * entry. This is odd - it should have
-                                * been provided when the attribute was added.
-                                *
-                                * However, it's possible that it could be
-                                * missing if the DIT was established via
-                                * an import process.
-                                */
-#ifdef NEW_LOGGING
-                               LDAP_LOG( OPERATION, ERR,
-                                       "ppolicy_bind: Entry %s does not have valid pwdChangedTime attribute - assuming password expired\n",
-                                       e->e_name.bv_val, 0, 0);
-#else
-                               Debug( LDAP_DEBUG_ANY,
-                                       "ppolicy_bind: Entry %s does not have valid pwdChangedTime attribute - assuming password expired\n",
-                                       e->e_name.bv_val, 0, 0);
-                               
-#endif
-                               pwExpired = 1;
-                       } else {
+                       if (pwtime != (time_t)-1) {
                                /*
                                 * Check: was the last change time of
                                 * the password older than the maximum age
@@ -915,24 +1032,18 @@ grace:
                if (!pwExpired) goto check_expiring_password;
                
                if ((a = attr_find( e->e_attrs, ad_pwdGraceUseTime )) == NULL)
-                       ngut = ppb->pp.pwdGraceLoginLimit;
+                       ngut = ppb->pp.pwdGraceAuthNLimit;
                else {
                        for(ngut=0; a->a_nvals[ngut].bv_val; ngut++);
-                       ngut = ppb->pp.pwdGraceLoginLimit - ngut;
+                       ngut = ppb->pp.pwdGraceAuthNLimit - ngut;
                }
 
                /*
                 * ngut is the number of remaining grace logins
                 */
-#ifdef NEW_LOGGING
-               LDAP_LOG( OPERATION, ERR,
-                       "ppolicy_bind: Entry %s has an expired password: %d grace logins\n",
-                       e->e_name.bv_val, ngut, 0);
-#else
                Debug( LDAP_DEBUG_ANY,
                        "ppolicy_bind: Entry %s has an expired password: %d grace logins\n",
                        e->e_name.bv_val, ngut, 0);
-#endif
                
                if (ngut < 1) {
                        ppb->pErr = PP_passwordExpired;
@@ -945,10 +1056,13 @@ grace:
                 */
                m = ch_calloc( sizeof(Modifications), 1 );
                m->sml_op = LDAP_MOD_ADD;
+               m->sml_flags = 0;
                m->sml_type = ad_pwdGraceUseTime->ad_cname;
                m->sml_desc = ad_pwdGraceUseTime;
                m->sml_values = ch_calloc( sizeof(struct berval), 2 );
-               ber_str2bv( nowstr, 0, 1, &m->sml_values[0] );
+               m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
+               ber_dupbv( &m->sml_values[0], &timestamp );
+               ber_dupbv( &m->sml_nvalues[0], &timestamp );
                m->sml_next = mod;
                mod = m;
 
@@ -976,31 +1090,14 @@ check_expiring_password:
                 */
                if (ppb->pp.pwdMaxAge - age < ppb->pp.pwdExpireWarning ) {
                        /*
-                        * Set the warning value, add expiration warned timestamp to the entry.
+                        * Set the warning value.
                         */
-                       if ((a = attr_find( e->e_attrs, ad_pwdExpirationWarned )) == NULL) {
-                               m = ch_calloc( sizeof(Modifications), 1 );
-                               m->sml_op = LDAP_MOD_ADD;
-                               m->sml_type = ad_pwdExpirationWarned->ad_cname;
-                               m->sml_desc = ad_pwdExpirationWarned;
-                               m->sml_values = ch_calloc( sizeof(struct berval), 2 );
-                               ber_str2bv( nowstr, 0, 1, &m->sml_values[0] );
-                               m->sml_next = mod;
-                               mod = m;
-                       }
-                       
                        warn = ppb->pp.pwdMaxAge - age; /* seconds left until expiry */
                        if (warn < 0) warn = 0; /* something weird here - why is pwExpired not set? */
                        
-#ifdef NEW_LOGGING
-                       LDAP_LOG( OPERATIONS, DETAIL1,
-                               "ppolicy_bind: Setting warning for password expiry for %s = %d seconds\n",
-                               op->o_req_dn.bv_val, warn, 0 );
-#else
                        Debug( LDAP_DEBUG_ANY,
                                "ppolicy_bind: Setting warning for password expiry for %s = %d seconds\n",
                                op->o_req_dn.bv_val, warn, 0 );
-#endif
                }
        }
 
@@ -1024,21 +1121,20 @@ locked:
                op2.o_ndn = op->o_bd->be_rootndn;
                op2.o_bd->bd_info = (BackendInfo *)on->on_info;
                rc = op->o_bd->be_modify( &op2, &r2 );
-               slap_mods_free( mod );
+               slap_mods_free( mod, 1 );
        }
 
        if ( ppb->send_ctrl ) {
-               LDAPControl **ctrls = NULL;
+               LDAPControl *ctrl = NULL;
                pp_info *pi = on->on_bi.bi_private;
 
                /* Do we really want to tell that the account is locked? */
                if ( ppb->pErr == PP_accountLocked && !pi->use_lockout ) {
                        ppb->pErr = PP_noError;
                }
-               ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
-               ctrls[0] = create_passcontrol( warn, ngut, ppb->pErr );
-               ctrls[1] = NULL;
-               rs->sr_ctrls = ctrls;
+               ctrl = create_passcontrol( warn, ngut, ppb->pErr );
+               ppb->oldctrls = add_passcontrol( op, rs, ctrl );
+               op->o_callback->sc_cleanup = ppolicy_ctrls_cleanup;
        }
        op->o_bd->bd_info = bi;
        return SLAP_CB_CONTINUE;
@@ -1049,10 +1145,16 @@ ppolicy_bind( Operation *op, SlapReply *rs )
 {
        slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
 
+       /* Reset lockout status on all Bind requests */
+       if ( !BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
+               ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
+               BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
+       }
+
        /* Root bypasses policy */
-       if ( !be_isroot( op->o_bd, &op->o_req_ndn )) {
+       if ( !be_isroot_dn( op->o_bd, &op->o_req_ndn )) {
                Entry *e;
-               int i, rc;
+               int rc;
                ppbind *ppb;
                slap_callback *cb;
 
@@ -1071,17 +1173,14 @@ ppolicy_bind( Operation *op, SlapReply *rs )
 
                /* Setup a callback so we can munge the result */
 
-               cb->sc_response = ppolicy_bind_resp;
+               cb->sc_response = ppolicy_bind_response;
                cb->sc_next = op->o_callback->sc_next;
                cb->sc_private = ppb;
                op->o_callback->sc_next = cb;
 
                /* Did we receive a password policy request control? */
-               for ( i=0; op->o_ctrls && op->o_ctrls[i]; i++ ) {
-                       if ( !strcmp( op->o_ctrls[i]->ldctl_oid, LDAP_CONTROL_PASSWORDPOLICYREQUEST ) ) {
-                               ppb->send_ctrl = 1;
-                               break;
-                       }
+               if ( op->o_ctrlflag[ppolicy_cid] ) {
+                       ppb->send_ctrl = 1;
                }
 
                op->o_bd->bd_info = (BackendInfo *)on;
@@ -1104,11 +1203,14 @@ ppolicy_bind( Operation *op, SlapReply *rs )
        return SLAP_CB_CONTINUE;
 }
 
-/* Reset the restrict flag for the next session on this connection */
+/* Reset the restricted info for the next session on this connection */
 static int
-ppolicy_unbind( Operation *op, SlapReply *rs )
+ppolicy_connection_destroy( BackendDB *bd, Connection *conn )
 {
-       pwcons[op->o_conn->c_conn_idx].restrict = 0;
+       if ( !BER_BVISEMPTY( &pwcons[conn->c_conn_idx].dn )) {
+               ch_free( pwcons[conn->c_conn_idx].dn.bv_val );
+               BER_BVZERO( &pwcons[conn->c_conn_idx].dn );
+       }
        return SLAP_CB_CONTINUE;
 }
 
@@ -1119,36 +1221,39 @@ ppolicy_restrict(
        SlapReply *rs )
 {
        slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
-       int i, send_ctrl = 0;
+       int send_ctrl = 0;
 
        /* Did we receive a password policy request control? */
-       for ( i=0; op->o_ctrls && op->o_ctrls[i]; i++ ) {
-               if ( !strcmp( op->o_ctrls[i]->ldctl_oid,
-                       LDAP_CONTROL_PASSWORDPOLICYREQUEST ) ) {
-                       send_ctrl = 1;
-                       break;
-               }
+       if ( op->o_ctrlflag[ppolicy_cid] ) {
+               send_ctrl = 1;
        }
 
-       if ( op->o_conn && pwcons[op->o_conn->c_conn_idx].restrict ) {
-#ifdef NEW_LOGGING
-               LDAP_LOG( OPERATION, ENTRY,
-                       "connection restricted to password changing only\n", 0, 0, 0 );
-#else
+       if ( op->o_conn && !BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
+               LDAPControl **oldctrls;
+               /* if the current authcDN doesn't match the one we recorded,
+                * then an intervening Bind has succeeded and the restriction
+                * no longer applies. (ITS#4516)
+                */
+               if ( !dn_match( &op->o_conn->c_ndn,
+                               &pwcons[op->o_conn->c_conn_idx].dn )) {
+                       ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
+                       BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
+                       return SLAP_CB_CONTINUE;
+               }
+
                Debug( LDAP_DEBUG_TRACE,
                        "connection restricted to password changing only\n", 0, 0, 0);
-#endif
                if ( send_ctrl ) {
-                       LDAPControl **ctrls = NULL;
-
-                       ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
-                       ctrls[0] = create_passcontrol( -1, -1, PP_changeAfterReset );
-                       ctrls[1] = NULL;
-                       rs->sr_ctrls = ctrls;
+                       LDAPControl *ctrl = NULL;
+                       ctrl = create_passcontrol( -1, -1, PP_changeAfterReset );
+                       oldctrls = add_passcontrol( op, rs, ctrl );
                }
                op->o_bd->bd_info = (BackendInfo *)on->on_info;
-               send_ldap_error( op, rs, LDAP_UNWILLING_TO_PERFORM,
+               send_ldap_error( op, rs, LDAP_INSUFFICIENT_ACCESS, 
                        "Operations are restricted to bind/unbind/abandon/StartTLS/modify password" );
+               if ( send_ctrl ) {
+                       ctrls_cleanup( op, rs, oldctrls );
+               }
                return rs->sr_err;
        }
 
@@ -1161,85 +1266,141 @@ ppolicy_add(
        SlapReply *rs )
 {
        slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
+       pp_info *pi = on->on_bi.bi_private;
        PassPolicy pp;
-       int pw;
        Attribute *pa;
+       const char *txt;
 
        if ( ppolicy_restrict( op, rs ) != SLAP_CB_CONTINUE )
                return rs->sr_err;
 
+       /* If this is a replica, assume the master checked everything */
+       if ( be_shadow_update( op ))
+               return SLAP_CB_CONTINUE;
+
        /* Check for password in entry */
-       if ((pa = attr_find( op->oq_add.rs_e->e_attrs, slap_schema.si_ad_userPassword ))) {
+       if ((pa = attr_find( op->oq_add.rs_e->e_attrs,
+               slap_schema.si_ad_userPassword )))
+       {
+               assert( pa->a_vals );
+               assert( !BER_BVISNULL( &pa->a_vals[ 0 ] ) );
+
+               if ( !BER_BVISNULL( &pa->a_vals[ 1 ] ) ) {
+                       send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION, "Password policy only allows one password value" );
+                       return rs->sr_err;
+               }
+
                /*
                 * new entry contains a password - if we're not the root user
                 * then we need to check that the password fits in with the
                 * security policy for the new entry.
                 */
-               ppolicy_get( op, op->oq_add.rs_e, &pp );
-               if (pp.pwdCheckQuality > 0 && !be_isroot( op->o_bd, &op->o_ndn )) {
+               ppolicy_get( op, op->ora_e, &pp );
+               if (pp.pwdCheckQuality > 0 && !be_isroot( op )) {
                        struct berval *bv = &(pa->a_vals[0]);
-                       int rc, i, send_ctrl = 0; 
+                       int rc, send_ctrl = 0;
                        LDAPPasswordPolicyError pErr = PP_noError;
 
                        /* Did we receive a password policy request control? */
-                       for ( i=0; op->o_ctrls && op->o_ctrls[i]; i++ ) {
-                               if ( !strcmp( op->o_ctrls[i]->ldctl_oid,
-                                       LDAP_CONTROL_PASSWORDPOLICYREQUEST ) ) {
-                                       send_ctrl = 1;
-                                       break;
-                               }
+                       if ( op->o_ctrlflag[ppolicy_cid] ) {
+                               send_ctrl = 1;
                        }
-                       rc = check_password_quality( bv, &pp, &pErr );
+                       rc = check_password_quality( bv, &pp, &pErr, op->ora_e );
                        if (rc != LDAP_SUCCESS) {
+                               LDAPControl **oldctrls = NULL;
                                op->o_bd->bd_info = (BackendInfo *)on->on_info;
                                if ( send_ctrl ) {
-                                       LDAPControl **ctrls = NULL;
-
-                                       ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
-                                       ctrls[0] = create_passcontrol( -1, -1, pErr );
-                                       ctrls[1] = NULL;
-                                       rs->sr_ctrls = ctrls;
+                                       LDAPControl *ctrl = NULL;
+                                       ctrl = create_passcontrol( -1, -1, pErr );
+                                       oldctrls = add_passcontrol( op, rs, ctrl );
                                }
                                send_ldap_error( op, rs, rc, "Password fails quality checking policy" );
+                               if ( send_ctrl ) {
+                                       ctrls_cleanup( op, rs, oldctrls );
+                               }
+                               return rs->sr_err;
+                       }
+               }
+                       /*
+                        * A controversial bit. We hash cleartext
+                        * passwords provided via add and modify operations
+                        * You're not really supposed to do this, since
+                        * the X.500 model says "store attributes" as they
+                        * get provided. By default, this is what we do
+                        *
+                        * But if the hash_passwords flag is set, we hash
+                        * any cleartext password attribute values via the
+                        * default password hashing scheme.
+                        */
+               if ((pi->hash_passwords) &&
+                       (password_scheme( &(pa->a_vals[0]), NULL ) != LDAP_SUCCESS)) {
+                       struct berval hpw;
+
+                       slap_passwd_hash( &(pa->a_vals[0]), &hpw, &txt );
+                       if (hpw.bv_val == NULL) {
+                               /*
+                                * hashing didn't work. Emit an error.
+                                */
+                               rs->sr_err = LDAP_OTHER;
+                               rs->sr_text = txt;
+                               send_ldap_error( op, rs, LDAP_OTHER, "Password hashing failed" );
                                return rs->sr_err;
                        }
+
+                       memset( pa->a_vals[0].bv_val, 0, pa->a_vals[0].bv_len);
+                       ber_memfree( pa->a_vals[0].bv_val );
+                       pa->a_vals[0].bv_val = hpw.bv_val;
+                       pa->a_vals[0].bv_len = hpw.bv_len;
                }
+
                /* If password aging is in effect, set the pwdChangedTime */
                if ( pp.pwdMaxAge || pp.pwdMinAge ) {
                        struct berval timestamp;
                        char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
-                       struct tm *ltm;
                        time_t now = slap_get_time();
 
-                       ldap_pvt_thread_mutex_lock( &gmtime_mutex );
-                       ltm = gmtime( &now );
-                       lutil_gentime( timebuf, sizeof(timebuf), ltm );
-                       ldap_pvt_thread_mutex_unlock( &gmtime_mutex );
-
                        timestamp.bv_val = timebuf;
-                       timestamp.bv_len = strlen(timebuf);
+                       timestamp.bv_len = sizeof(timebuf);
+                       slap_timestamp( &now, &timestamp );
 
-                       attr_merge_one( op->ora_e, ad_pwdChangedTime, &timestamp, NULL );
+                       attr_merge_one( op->ora_e, ad_pwdChangedTime, &timestamp, &timestamp );
                }
        }
        return SLAP_CB_CONTINUE;
 }
 
+static int
+ppolicy_mod_cb( Operation *op, SlapReply *rs )
+{
+       slap_callback *sc = op->o_callback;
+       op->o_callback = sc->sc_next;
+       if ( rs->sr_err == LDAP_SUCCESS ) {
+               ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
+               BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
+       }
+       op->o_tmpfree( sc, op->o_tmpmemctx );
+       return SLAP_CB_CONTINUE;
+}
+
 static int
 ppolicy_modify( Operation *op, SlapReply *rs )
 {
-       slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
-       int                             i, rc, mod_pw_only, pwmod, pwmop, deladd, hsize = 0;
+       slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
+       pp_info                 *pi = on->on_bi.bi_private;
+       int                     i, rc, mod_pw_only, pwmod, pwmop = -1, deladd,
+                               hsize = 0;
        PassPolicy              pp;
-       Modifications   *mods = NULL, *modtail, *ml, *delmod, *addmod;
-       Attribute               *pa, *ha, *ra, at;
-       int                             repl_user = be_isupdate( op->o_bd, &op->o_ndn );
+       Modifications           *mods = NULL, *modtail = NULL,
+                               *ml, *delmod, *addmod;
+       Attribute               *pa, *ha, at;
        const char              *txt;
        pw_hist                 *tl = NULL, *p;
-       int                             zapReset, send_ctrl = 0;
+       int                     zapReset, send_ctrl = 0;
        Entry                   *e;
-       struct berval   newpw = { 0, NULL }, oldpw = { 0, NULL }, *bv, cr[2];
+       struct berval           newpw = BER_BVNULL, oldpw = BER_BVNULL,
+                               *bv, cr[2];
        LDAPPasswordPolicyError pErr = PP_noError;
+       LDAPControl             **oldctrls = NULL;
 
        op->o_bd->bd_info = (BackendInfo *)on->on_info;
        rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
@@ -1247,13 +1408,101 @@ ppolicy_modify( Operation *op, SlapReply *rs )
 
        if ( rc != LDAP_SUCCESS ) return SLAP_CB_CONTINUE;
 
-       /* Did we receive a password policy request control? */
-       for ( i=0; op->o_ctrls && op->o_ctrls[i]; i++ ) {
-               if ( !strcmp( op->o_ctrls[i]->ldctl_oid,
-                       LDAP_CONTROL_PASSWORDPOLICYREQUEST ) ) {
-                       send_ctrl = 1;
-                       break;
+       /* If this is a replica, we may need to tweak some of the
+        * master's modifications. Otherwise, just pass it through.
+        */
+       if ( be_shadow_update( op )) {
+               Modifications **prev;
+               int got_del_grace = 0, got_del_lock = 0, got_pw = 0, got_del_fail = 0;
+               Attribute *a_grace, *a_lock, *a_fail;
+
+               a_grace = attr_find( e->e_attrs, ad_pwdGraceUseTime );
+               a_lock = attr_find( e->e_attrs, ad_pwdAccountLockedTime );
+               a_fail = attr_find( e->e_attrs, ad_pwdFailureTime );
+
+               for( prev = &op->orm_modlist, ml = *prev; ml; ml = *prev ) {
+
+                       if ( ml->sml_desc == slap_schema.si_ad_userPassword )
+                               got_pw = 1;
+
+                       /* If we're deleting an attr that didn't exist,
+                        * drop this delete op
+                        */
+                       if ( ml->sml_op == LDAP_MOD_DELETE ) {
+                               int drop = 0;
+
+                               if ( ml->sml_desc == ad_pwdGraceUseTime ) {
+                                       got_del_grace = 1;
+                                       if ( !a_grace )
+                                               drop = 1;
+                               } else
+                               if ( ml->sml_desc == ad_pwdAccountLockedTime ) {
+                                       got_del_lock = 1;
+                                       if ( !a_lock )
+                                               drop = 1;
+                               } else
+                               if ( ml->sml_desc == ad_pwdFailureTime ) {
+                                       got_del_fail = 1;
+                                       if ( !a_fail )
+                                               drop = 1;
+                               }
+                               if ( drop ) {
+                                       *prev = ml->sml_next;
+                                       ml->sml_next = NULL;
+                                       slap_mods_free( ml, 1 );
+                                       continue;
+                               }
+                       }
+                       prev = &ml->sml_next;
+               }
+
+               /* If we're resetting the password, make sure grace, accountlock,
+                * and failure also get removed.
+                */
+               if ( got_pw ) {
+                       if ( a_grace && !got_del_grace ) {
+                               ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
+                               ml->sml_op = LDAP_MOD_DELETE;
+                               ml->sml_flags = SLAP_MOD_INTERNAL;
+                               ml->sml_type.bv_val = NULL;
+                               ml->sml_desc = ad_pwdGraceUseTime;
+                               ml->sml_values = NULL;
+                               ml->sml_nvalues = NULL;
+                               ml->sml_next = NULL;
+                               *prev = ml;
+                               prev = &ml->sml_next;
+                       }
+                       if ( a_lock && !got_del_lock ) {
+                               ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
+                               ml->sml_op = LDAP_MOD_DELETE;
+                               ml->sml_flags = SLAP_MOD_INTERNAL;
+                               ml->sml_type.bv_val = NULL;
+                               ml->sml_desc = ad_pwdAccountLockedTime;
+                               ml->sml_values = NULL;
+                               ml->sml_nvalues = NULL;
+                               ml->sml_next = NULL;
+                               *prev = ml;
+                       }
+                       if ( a_fail && !got_del_fail ) {
+                               ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
+                               ml->sml_op = LDAP_MOD_DELETE;
+                               ml->sml_flags = SLAP_MOD_INTERNAL;
+                               ml->sml_type.bv_val = NULL;
+                               ml->sml_desc = ad_pwdFailureTime;
+                               ml->sml_values = NULL;
+                               ml->sml_nvalues = NULL;
+                               ml->sml_next = NULL;
+                               *prev = ml;
+                       }
                }
+               op->o_bd->bd_info = (BackendInfo *)on->on_info;
+               be_entry_release_r( op, e );
+               return SLAP_CB_CONTINUE;
+       }
+
+       /* Did we receive a password policy request control? */
+       if ( op->o_ctrlflag[ppolicy_cid] ) {
+               send_ctrl = 1;
        }
 
        /* See if this is a pwdModify exop. If so, we can
@@ -1275,29 +1524,55 @@ ppolicy_modify( Operation *op, SlapReply *rs )
 
        ppolicy_get( op, e, &pp );
 
-       for(ml = op->oq_modify.rs_modlist,
+       for ( ml = op->orm_modlist,
                        pwmod = 0, mod_pw_only = 1,
                        deladd = 0, delmod = NULL,
                        addmod = NULL,
                        zapReset = 1;
-               ml != NULL; modtail = ml, ml = ml->sml_next ) {
+               ml != NULL; modtail = ml, ml = ml->sml_next )
+       {
                if ( ml->sml_desc == pp.ad ) {
                        pwmod = 1;
                        pwmop = ml->sml_op;
                        if ((deladd == 0) && (ml->sml_op == LDAP_MOD_DELETE) &&
-                               (ml->sml_values) && (ml->sml_values[0].bv_val != NULL)) {
+                               (ml->sml_values) && !BER_BVISNULL( &ml->sml_values[0] ))
+                       {
                                deladd = 1;
                                delmod = ml;
                        }
 
                        if ((deladd == 1) && ((ml->sml_op == LDAP_MOD_ADD) ||
-                                                                 (ml->sml_op == LDAP_MOD_REPLACE)))
+                                 (ml->sml_op == LDAP_MOD_REPLACE)))
+                       {
                                deladd = 2;
+                       }
 
                        if ((ml->sml_op == LDAP_MOD_ADD) ||
                                (ml->sml_op == LDAP_MOD_REPLACE))
+                       {
                                addmod = ml;
-               } else if (! is_at_operational( ml->sml_desc->ad_type )) {
+
+                               /* FIXME: there's no easy way to ensure
+                                * that add does not cause multiple
+                                * userPassword values; one way (that 
+                                * would be consistent with the single
+                                * password constraint) would be to turn
+                                * add into replace); another would be
+                                * to disallow add.
+                                *
+                                * Let's check at least that a single value
+                                * is being added
+                                */
+                               assert( addmod->sml_values != NULL );
+                               assert( !BER_BVISNULL( &addmod->sml_values[ 0 ] ) );
+                               if ( !BER_BVISNULL( &addmod->sml_values[ 1 ] ) ) {
+                                       rs->sr_err = LDAP_CONSTRAINT_VIOLATION; 
+                                       rs->sr_text = "Password policy only allows one password value";
+                                       goto return_results;
+                               }
+                       }
+
+               } else if ( !is_at_operational( ml->sml_desc->ad_type ) ) {
                        mod_pw_only = 0;
                        /* modifying something other than password */
                }
@@ -1319,18 +1594,19 @@ ppolicy_modify( Operation *op, SlapReply *rs )
                }
        }
        
-       if (pwcons[op->o_conn->c_conn_idx].restrict && !mod_pw_only) {
-#ifdef NEW_LOGGING
-               LDAP_LOG( OPERATION, ENTRY,
-                       "connection restricted to password changing only\n", 0, 0, 0 );
-#else
-               Debug( LDAP_DEBUG_TRACE,
-                       "connection restricted to password changing only\n", 0, 0, 0 );
-#endif
-               rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
-               rs->sr_text = "Operations are restricted to bind/unbind/abandon/StartTLS/modify password";
-               pErr = PP_changeAfterReset;
-               goto return_results;
+       if (!BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn ) && !mod_pw_only ) {
+               if ( dn_match( &op->o_conn->c_ndn,
+                               &pwcons[op->o_conn->c_conn_idx].dn )) {
+                       Debug( LDAP_DEBUG_TRACE,
+                               "connection restricted to password changing only\n", 0, 0, 0 );
+                       rs->sr_err = LDAP_INSUFFICIENT_ACCESS; 
+                       rs->sr_text = "Operations are restricted to bind/unbind/abandon/StartTLS/modify password";
+                       pErr = PP_changeAfterReset;
+                       goto return_results;
+               } else {
+                       ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
+                       BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
+               }
        }
 
        /*
@@ -1350,13 +1626,8 @@ ppolicy_modify( Operation *op, SlapReply *rs )
        if (!addmod) {
                rs->sr_err = LDAP_OTHER;
                rs->sr_text = "Internal Error";
-#ifdef NEW_LOGGING
-               LDAP_LOG( OPERATION, ENTRY,
-                       "cannot locate modification supplying new password\n", 0, 0, 0 );
-#else
                Debug( LDAP_DEBUG_TRACE,
                        "cannot locate modification supplying new password\n", 0, 0, 0 );
-#endif
                goto return_results;
        }
 
@@ -1368,7 +1639,6 @@ ppolicy_modify( Operation *op, SlapReply *rs )
        if (pp.pwdInHistory > 0 && (ha = attr_find( e->e_attrs, ad_pwdHistory ))) {
                struct berval oldpw;
                time_t oldtime;
-               char *oid;
 
                for(i=0; ha->a_nvals[i].bv_val; i++) {
                        rc = parse_pwdhistory( &(ha->a_nvals[i]), NULL,
@@ -1386,22 +1656,21 @@ ppolicy_modify( Operation *op, SlapReply *rs )
                for(p=tl; p; p=p->next, hsize++); /* count history size */
        }
 
-       if (be_isroot( op->o_bd, &op->o_ndn)) goto do_modify;
+       if (be_isroot( op )) goto do_modify;
 
        /* This is a pwdModify exop that provided the old pw.
         * We need to create a Delete mod for this old pw and 
         * let the matching value get found later
         */
        if (pp.pwdSafeModify && oldpw.bv_val ) {
-               ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
+               ml = (Modifications *)ch_calloc( sizeof( Modifications ), 1 );
                ml->sml_op = LDAP_MOD_DELETE;
+               ml->sml_flags = SLAP_MOD_INTERNAL;
                ml->sml_desc = pp.ad;
                ml->sml_type = pp.ad->ad_cname;
                ml->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
                ber_dupbv( &ml->sml_values[0], &oldpw );
-               ml->sml_values[1].bv_len = 0;
-               ml->sml_values[1].bv_val = NULL;
-               ml->sml_nvalues = NULL;
+               BER_BVZERO( &ml->sml_values[1] );
                ml->sml_next = op->orm_modlist;
                op->orm_modlist = ml;
                delmod = ml;
@@ -1409,29 +1678,26 @@ ppolicy_modify( Operation *op, SlapReply *rs )
        }
 
        if (pp.pwdSafeModify && deladd != 2) {
-#ifdef NEW_LOGGING
-               LDAP_LOG( OPERATION, ENTRY,
-                       "change password must use DELETE followed by ADD/REPLACE\n",
-                       0, 0, 0 );
-#else
                Debug( LDAP_DEBUG_TRACE,
                        "change password must use DELETE followed by ADD/REPLACE\n",
                        0, 0, 0 );
-#endif
-               rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
+               rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
                rs->sr_text = "Must supply old password to be changed as well as new one";
                pErr = PP_mustSupplyOldPassword;
                goto return_results;
        }
 
        if (!pp.pwdAllowUserChange) {
-               rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
+               rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
                rs->sr_text = "User alteration of password is not allowed";
                pErr = PP_passwordModNotAllowed;
                goto return_results;
        }
 
-       if (pp.pwdMinAge > 0) {
+       /* Check age, but only if pwdReset is not TRUE */
+       pa = attr_find( e->e_attrs, ad_pwdReset );
+       if ((!pa || !bvmatch( &pa->a_nvals[0], &slap_true_bv )) &&
+               pp.pwdMinAge > 0) {
                time_t pwtime = (time_t)-1, now;
                int age;
 
@@ -1440,29 +1706,26 @@ ppolicy_modify( Operation *op, SlapReply *rs )
                now = slap_get_time();
                age = (int)(now - pwtime);
                if ((pwtime != (time_t)-1) && (age < pp.pwdMinAge)) {
-                       rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
+                       rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
                        rs->sr_text = "Password is too young to change";
                        pErr = PP_passwordTooYoung;
                        goto return_results;
                }
        }
 
-       if (delmod && (pa = attr_find( e->e_attrs, pp.ad )) != NULL) {
+       /* pa is used in password history check below, be sure it's set */
+       if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL && delmod) {
                /*
                 * we have a password to check
                 */
                const char *txt;
                
                bv = oldpw.bv_val ? &oldpw : delmod->sml_values;
-               rc = slap_passwd_check( op->o_conn, pa, bv, &txt );
+               /* FIXME: no access checking? */
+               rc = slap_passwd_check( op, NULL, pa, bv, &txt );
                if (rc != LDAP_SUCCESS) {
-#ifdef NEW_LOGGING
-                       LDAP_LOG( OPERATION, ENTRY,
-                               "old password check failed: %s\n", txt, 0, 0 );
-#else
                        Debug( LDAP_DEBUG_TRACE,
                                "old password check failed: %s\n", txt, 0, 0 );
-#endif
                        
                        rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
                        rs->sr_text = "Must supply correct old password to change to new one";
@@ -1476,22 +1739,21 @@ ppolicy_modify( Operation *op, SlapReply *rs )
                         * replace the delete value with the (possibly hashed)
                         * value which is currently in the password.
                         */
-                       for(i=0; delmod->sml_values[i].bv_val; i++) {
-                               free(delmod->sml_values[i].bv_val);
-                               delmod->sml_values[i].bv_len = 0;
+                       for ( i = 0; !BER_BVISNULL( &delmod->sml_values[i] ); i++ ) {
+                               free( delmod->sml_values[i].bv_val );
+                               BER_BVZERO( &delmod->sml_values[i] );
                        }
-                       free(delmod->sml_values);
+                       free( delmod->sml_values );
                        delmod->sml_values = ch_calloc( sizeof(struct berval), 2 );
-                       delmod->sml_values[1].bv_len = 0;
-                       delmod->sml_values[1].bv_val = NULL;
-                       ber_dupbv(&(delmod->sml_values[0]),  &(pa->a_nvals[0]));
+                       BER_BVZERO( &delmod->sml_values[1] );
+                       ber_dupbv( &(delmod->sml_values[0]),  &(pa->a_nvals[0]) );
                }
        }
 
-       bv = newpw.bv_val ? &newpw : addmod->sml_values;
+       bv = newpw.bv_val ? &newpw : &addmod->sml_values[0];
        if (pp.pwdCheckQuality > 0) {
 
-               rc = check_password_quality( bv, &pp, &pErr );
+               rc = check_password_quality( bv, &pp, &pErr, e );
                if (rc != LDAP_SUCCESS) {
                        rs->sr_err = rc;
                        rs->sr_text = "Password fails quality checking policy";
@@ -1499,99 +1761,118 @@ ppolicy_modify( Operation *op, SlapReply *rs )
                }
        }
 
-       /*
-        * Last check - the password history.
-        */
-       if (slap_passwd_check( op->o_conn, pa, bv, &txt ) == LDAP_SUCCESS) {
+       if (pa) {
                /*
-                * This is bad - it means that the user is attempting
-                * to set the password to the same as the old one.
+                * Last check - the password history.
                 */
-               rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
-               rs->sr_text = "Password is not being changed from existing value";
-               pErr = PP_passwordInHistory;
-               goto return_results;
-       }
-
-       if (pp.pwdInHistory < 1) goto do_modify;
-
-       /*
-        * Iterate through the password history, and fail on any
-        * password matches.
-        */
-       at = *pa;
-       at.a_vals = cr;
-       cr[1].bv_val = NULL;
-       for(p=tl; p; p=p->next) {
-               cr[0] = p->pw;
-               rc = slap_passwd_check( op->o_conn, &at, bv, &txt );
-               
-               if (rc != LDAP_SUCCESS) continue;
-               
-               rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
-               rs->sr_text = "Password is in history of old passwords";
-               pErr = PP_passwordInHistory;
-               goto return_results;
+               /* FIXME: no access checking? */
+               if (slap_passwd_check( op, NULL, pa, bv, &txt ) == LDAP_SUCCESS) {
+                       /*
+                        * This is bad - it means that the user is attempting
+                        * to set the password to the same as the old one.
+                        */
+                       rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
+                       rs->sr_text = "Password is not being changed from existing value";
+                       pErr = PP_passwordInHistory;
+                       goto return_results;
+               }
+       
+               if (pp.pwdInHistory < 1) goto do_modify;
+       
+               /*
+                * Iterate through the password history, and fail on any
+                * password matches.
+                */
+               at = *pa;
+               at.a_vals = cr;
+               cr[1].bv_val = NULL;
+               for(p=tl; p; p=p->next) {
+                       cr[0] = p->pw;
+                       /* FIXME: no access checking? */
+                       rc = slap_passwd_check( op, NULL, &at, bv, &txt );
+                       
+                       if (rc != LDAP_SUCCESS) continue;
+                       
+                       rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
+                       rs->sr_text = "Password is in history of old passwords";
+                       pErr = PP_passwordInHistory;
+                       goto return_results;
+               }
        }
 
 do_modify:
-       if ((pwmod) && (!repl_user)) {
+       if (pwmod) {
                struct berval timestamp;
                char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
-               struct tm *ltm;
                time_t now = slap_get_time();
-               Attribute *ga;
-               
+
+               /* If the conn is restricted, set a callback to clear it
+                * if the pwmod succeeds
+                */
+               if (!BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
+                       slap_callback *sc = op->o_tmpcalloc( 1, sizeof( slap_callback ),
+                               op->o_tmpmemctx );
+                       sc->sc_next = op->o_callback;
+                       /* Must use sc_response to insure we reset on success, before
+                        * the client sees the response. Must use sc_cleanup to insure
+                        * that it gets cleaned up if sc_response is not called.
+                        */
+                       sc->sc_response = ppolicy_mod_cb;
+                       sc->sc_cleanup = ppolicy_mod_cb;
+                       op->o_callback = sc;
+               }
+
                /*
                 * keep the necessary pwd.. operational attributes
                 * up to date.
                 */
 
-               ldap_pvt_thread_mutex_lock( &gmtime_mutex );
-               ltm = gmtime( &now );
-               lutil_gentime( timebuf, sizeof(timebuf), ltm );
-               ldap_pvt_thread_mutex_unlock( &gmtime_mutex );
-
                timestamp.bv_val = timebuf;
-               timestamp.bv_len = strlen(timebuf);
-               mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
-               mods->sml_type.bv_val = NULL;
+               timestamp.bv_len = sizeof(timebuf);
+               slap_timestamp( &now, &timestamp );
+
+               mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
                mods->sml_desc = ad_pwdChangedTime;
                if (pwmop != LDAP_MOD_DELETE) {
                        mods->sml_op = LDAP_MOD_REPLACE;
                        mods->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
                        ber_dupbv( &mods->sml_values[0], &timestamp );
-                       mods->sml_values[1].bv_len = 0;
-                       mods->sml_values[1].bv_val = NULL;
-                       assert( mods->sml_values[0].bv_val );
+                       BER_BVZERO( &mods->sml_values[1] );
+                       assert( !BER_BVISNULL( &mods->sml_values[0] ) );
+
                } else {
                        mods->sml_op = LDAP_MOD_DELETE;
-                       mods->sml_values = NULL;
                }
-               mods->sml_nvalues = NULL;
+               mods->sml_flags = SLAP_MOD_INTERNAL;
                mods->sml_next = NULL;
                modtail->sml_next = mods;
                modtail = mods;
 
                if (attr_find(e->e_attrs, ad_pwdGraceUseTime )) {
-                       mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
+                       mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
                        mods->sml_op = LDAP_MOD_DELETE;
-                       mods->sml_type.bv_val = NULL;
                        mods->sml_desc = ad_pwdGraceUseTime;
-                       mods->sml_values = NULL;
-                       mods->sml_nvalues = NULL;
+                       mods->sml_flags = SLAP_MOD_INTERNAL;
+                       mods->sml_next = NULL;
+                       modtail->sml_next = mods;
+                       modtail = mods;
+               }
+
+               if (attr_find(e->e_attrs, ad_pwdAccountLockedTime )) {
+                       mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
+                       mods->sml_op = LDAP_MOD_DELETE;
+                       mods->sml_desc = ad_pwdAccountLockedTime;
+                       mods->sml_flags = SLAP_MOD_INTERNAL;
                        mods->sml_next = NULL;
                        modtail->sml_next = mods;
                        modtail = mods;
                }
 
-               if (attr_find(e->e_attrs, ad_pwdExpirationWarned )) {
-                       mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
+               if (attr_find(e->e_attrs, ad_pwdFailureTime )) {
+                       mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
                        mods->sml_op = LDAP_MOD_DELETE;
-                       mods->sml_type.bv_val = NULL;
-                       mods->sml_desc = ad_pwdExpirationWarned;
-                       mods->sml_values = NULL;
-                       mods->sml_nvalues = NULL;
+                       mods->sml_desc = ad_pwdFailureTime;
+                       mods->sml_flags = SLAP_MOD_INTERNAL;
                        mods->sml_next = NULL;
                        modtail->sml_next = mods;
                        modtail = mods;
@@ -1599,12 +1880,10 @@ do_modify:
 
                /* Delete the pwdReset attribute, since it's being reset */
                if ((zapReset) && (attr_find(e->e_attrs, ad_pwdReset ))) {
-                       mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
+                       mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
                        mods->sml_op = LDAP_MOD_DELETE;
-                       mods->sml_type.bv_val = NULL;
                        mods->sml_desc = ad_pwdReset;
-                       mods->sml_values = NULL;
-                       mods->sml_nvalues = NULL;
+                       mods->sml_flags = SLAP_MOD_INTERNAL;
                        mods->sml_next = NULL;
                        modtail->sml_next = mods;
                        modtail = mods;
@@ -1628,18 +1907,15 @@ do_modify:
                                 * This is easily evaluated, since the linked list is
                                 * created in ascending time order.
                                 */
-                               mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
+                               mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
                                mods->sml_op = LDAP_MOD_DELETE;
-                               mods->sml_type.bv_val = NULL;
+                               mods->sml_flags = SLAP_MOD_INTERNAL;
                                mods->sml_desc = ad_pwdHistory;
-                               mods->sml_nvalues = NULL;
                                mods->sml_values = ch_calloc( sizeof( struct berval ),
-                                                                                          hsize - pp.pwdInHistory + 2 );
-                               mods->sml_values[ hsize - pp.pwdInHistory + 1 ].bv_val = NULL;
-                               mods->sml_values[ hsize - pp.pwdInHistory + 1 ].bv_len = 0;
+                                       hsize - pp.pwdInHistory + 2 );
+                               BER_BVZERO( &mods->sml_values[ hsize - pp.pwdInHistory + 1 ] );
                                for(i=0,p=tl; i < (hsize - pp.pwdInHistory + 1); i++, p=p->next) {
-                                       mods->sml_values[i].bv_val = NULL;
-                                       mods->sml_values[i].bv_len = 0;
+                                       BER_BVZERO( &mods->sml_values[i] );
                                        ber_dupbv( &(mods->sml_values[i]), &p->bv );
                                }
                                mods->sml_next = NULL;
@@ -1662,6 +1938,7 @@ do_modify:
                        if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL) {
                                mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
                                mods->sml_op = LDAP_MOD_ADD;
+                               mods->sml_flags = SLAP_MOD_INTERNAL;
                                mods->sml_type.bv_val = NULL;
                                mods->sml_desc = ad_pwdHistory;
                                mods->sml_nvalues = NULL;
@@ -1672,14 +1949,10 @@ do_modify:
                                mods->sml_next = NULL;
                                modtail->sml_next = mods;
                                modtail = mods;
+
                        } else {
-#ifdef NEW_LOGGING
-                               LDAP_LOG ( OPERATION, ERR, 
-                               "ppolicy_modify: password attr lookup failed\n", 0, 0, 0 );
-#else
                                Debug( LDAP_DEBUG_TRACE,
                                "ppolicy_modify: password attr lookup failed\n", 0, 0, 0 );
-#endif
                        }
                }
 
@@ -1700,8 +1973,9 @@ do_modify:
                 * leave it alone.
                 */
 
-               if ((addmod) && !newpw.bv_val && 
-                       (password_scheme( &(addmod->sml_values[0]), NULL ) != LDAP_SUCCESS)) {
+               if ((pi->hash_passwords) && (addmod) && !newpw.bv_val && 
+                       (password_scheme( &(addmod->sml_values[0]), NULL ) != LDAP_SUCCESS))
+               {
                        struct berval hpw, bv;
                        
                        slap_passwd_hash( &(addmod->sml_values[0]), &hpw, &txt );
@@ -1713,13 +1987,11 @@ do_modify:
                                rs->sr_text = txt;
                                goto return_results;
                        }
-                       bv.bv_val = addmod->sml_values[0].bv_val;
-                       bv.bv_len = addmod->sml_values[0].bv_len;
+                       bv = addmod->sml_values[0];
                                /* clear and discard the clear password */
                        memset(bv.bv_val, 0, bv.bv_len);
                        ber_memfree(bv.bv_val);
-                       addmod->sml_values[0].bv_val = hpw.bv_val;
-                       addmod->sml_values[0].bv_len = hpw.bv_len;
+                       addmod->sml_values[0] = hpw;
                }
        }
        op->o_bd->bd_info = (BackendInfo *)on->on_info;
@@ -1731,14 +2003,15 @@ return_results:
        op->o_bd->bd_info = (BackendInfo *)on->on_info;
        be_entry_release_r( op, e );
        if ( send_ctrl ) {
-               LDAPControl **ctrls = NULL;
+               LDAPControl *ctrl = NULL;
 
-               ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
-               ctrls[0] = create_passcontrol( -1, -1, pErr );
-               ctrls[1] = NULL;
-               rs->sr_ctrls = ctrls;
+               ctrl = create_passcontrol( -1, -1, pErr );
+               oldctrls = add_passcontrol( op, rs, ctrl );
        }
        send_ldap_result( op, rs );
+       if ( send_ctrl ) {
+               ctrls_cleanup( op, rs, oldctrls );
+       }
        return rs->sr_err;
 }
 
@@ -1752,14 +2025,51 @@ ppolicy_parseCtrl(
                rs->sr_text = "passwordPolicyRequest control value not empty";
                return LDAP_PROTOCOL_ERROR;
        }
-       if ( ctrl->ldctl_iscritical ) {
-               rs->sr_text = "passwordPolicyRequest control invalid criticality";
-               return LDAP_PROTOCOL_ERROR;
-       }
+       op->o_ctrlflag[ppolicy_cid] = ctrl->ldctl_iscritical
+               ? SLAP_CONTROL_CRITICAL
+               : SLAP_CONTROL_NONCRITICAL;
 
        return LDAP_SUCCESS;
 }
 
+static int
+attrPretty(
+       Syntax *syntax,
+       struct berval *val,
+       struct berval *out,
+       void *ctx )
+{
+       AttributeDescription *ad = NULL;
+       const char *err;
+       int code;
+
+       code = slap_bv2ad( val, &ad, &err );
+       if ( !code ) {
+               ber_dupbv_x( out, &ad->ad_type->sat_cname, ctx );
+       }
+       return code;
+}
+
+static int
+attrNormalize(
+       slap_mask_t use,
+       Syntax *syntax,
+       MatchingRule *mr,
+       struct berval *val,
+       struct berval *out,
+       void *ctx )
+{
+       AttributeDescription *ad = NULL;
+       const char *err;
+       int code;
+
+       code = slap_bv2ad( val, &ad, &err );
+       if ( !code ) {
+               ber_str2bv_x( ad->ad_type->sat_oid, 0, 1, out, ctx );
+       }
+       return code;
+}
+
 static int
 ppolicy_db_init(
        BackendDB *be
@@ -1767,6 +2077,34 @@ ppolicy_db_init(
 {
        slap_overinst *on = (slap_overinst *) be->bd_info;
 
+       /* Has User Schema been initialized yet? */
+       if ( !pwd_UsSchema[0].ad[0] ) {
+               const char *err;
+               int i, code;
+
+               for (i=0; pwd_UsSchema[i].def; i++) {
+                       code = slap_str2ad( pwd_UsSchema[i].def, pwd_UsSchema[i].ad, &err );
+                       if ( code ) {
+                               fprintf( stderr, "User Schema Load failed %d: %s\n", code, err );
+                               return code;
+                       }
+               }
+               {
+                       Syntax *syn;
+                       MatchingRule *mr;
+
+                       syn = ch_malloc( sizeof( Syntax ));
+                       *syn = *ad_pwdAttribute->ad_type->sat_syntax;
+                       syn->ssyn_pretty = attrPretty;
+                       ad_pwdAttribute->ad_type->sat_syntax = syn;
+
+                       mr = ch_malloc( sizeof( MatchingRule ));
+                       *mr = *ad_pwdAttribute->ad_type->sat_equality;
+                       mr->smr_normalize = attrNormalize;
+                       ad_pwdAttribute->ad_type->sat_equality = mr;
+               }
+       }
+
        on->on_bi.bi_private = ch_calloc( sizeof(pp_info), 1 );
 
        if ( dtblsize && !pwcons )
@@ -1775,6 +2113,14 @@ ppolicy_db_init(
        return 0;
 }
 
+static int
+ppolicy_db_open(
+    BackendDB *be
+)
+{
+       return overlay_register_control( be, LDAP_CONTROL_PASSWORDPOLICYREQUEST );
+}
+
 static int
 ppolicy_close(
        BackendDB *be
@@ -1790,44 +2136,6 @@ ppolicy_close(
        return 0;
 }
 
-static int
-ppolicy_config(
-    BackendDB  *be,
-    const char *fname,
-    int                lineno,
-    int                argc,
-    char       **argv
-)
-{
-       slap_overinst *on = (slap_overinst *) be->bd_info;
-       pp_info *pi = on->on_bi.bi_private;
-       struct berval dn;
-       
-
-       if ( strcasecmp( argv[0], "ppolicy_default" ) == 0 ) {
-               if ( argc != 2 ) {
-                       fprintf( stderr, "%s: line %d: invalid arguments in \"ppolicy_default"
-                               " <policyDN>\n", fname, lineno );
-                       return ( 1 );
-               }
-               ber_str2bv( argv[1], 0, 0, &dn );
-               if ( dnNormalize( 0, NULL, NULL, &dn, &pi->def_policy, NULL ) ) {
-                       fprintf( stderr, "%s: line %d: policyDN is invalid\n",
-                               fname, lineno );
-                       return 1;
-               }
-               return 0;
-       } else if ( strcasecmp( argv[0], "ppolicy_use_lockout" ) == 0 ) {
-               if ( argc != 1 ) {
-                       fprintf( stderr, "%s: line %d: ppolicy_use_lockout "
-                               "takes no arguments\n", fname, lineno );
-                       return ( 1 );
-               }
-               pi->use_lockout = 1;
-       }
-       return SLAP_CONF_UNKNOWN;
-}
-
 static char *extops[] = {
        LDAP_EXOP_MODIFY_PASSWD,
        NULL
@@ -1835,12 +2143,11 @@ static char *extops[] = {
 
 static slap_overinst ppolicy;
 
-int ppolicy_init()
+int ppolicy_initialize()
 {
        LDAPAttributeType *at;
-       int code;
        const char *err;
-       int i;
+       int i, code;
 
        for (i=0; pwd_OpSchema[i].def; i++) {
                at = ldap_str2attributetype( pwd_OpSchema[i].def, &code, &err,
@@ -1850,7 +2157,7 @@ int ppolicy_init()
                                ldap_scherr2str(code), err );
                        return code;
                }
-               code = at_add( at, &err );
+               code = at_add( at, 0, NULL, &err );
                if ( !code ) {
                        slap_str2ad( at->at_names[0], pwd_OpSchema[i].ad, &err );
                }
@@ -1860,19 +2167,16 @@ int ppolicy_init()
                                scherr2str(code), err );
                        return code;
                }
-       }
-
-       for (i=0; pwd_UsSchema[i].def; i++) {
-               code = slap_str2ad( pwd_UsSchema[i].def, pwd_UsSchema[i].ad, &err );
-               if ( code ) {
-                       fprintf( stderr, "User Schema Load failed %d: %s\n", code, err );
-                       return code;
+               /* Allow Manager to set these as needed */
+               if ( is_at_no_user_mod( (*pwd_OpSchema[i].ad)->ad_type )) {
+                       (*pwd_OpSchema[i].ad)->ad_type->sat_flags |=
+                               SLAP_AT_MANAGEABLE;
                }
        }
 
        code = register_supported_control( LDAP_CONTROL_PASSWORDPOLICYREQUEST,
-               SLAP_CTRL_ADD|SLAP_CTRL_BIND|SLAP_CTRL_MODIFY, extops,
-               ppolicy_parseCtrl );
+               SLAP_CTRL_ADD|SLAP_CTRL_BIND|SLAP_CTRL_MODIFY|SLAP_CTRL_HIDE, extops,
+               ppolicy_parseCtrl, &ppolicy_cid );
        if ( code != LDAP_SUCCESS ) {
                fprintf( stderr, "Failed to register control %d\n", code );
                return code;
@@ -1882,23 +2186,27 @@ int ppolicy_init()
 
        ppolicy.on_bi.bi_type = "ppolicy";
        ppolicy.on_bi.bi_db_init = ppolicy_db_init;
-       ppolicy.on_bi.bi_db_config = ppolicy_config;
+       ppolicy.on_bi.bi_db_open = ppolicy_db_open;
        ppolicy.on_bi.bi_db_close = ppolicy_close;
 
        ppolicy.on_bi.bi_op_add = ppolicy_add;
        ppolicy.on_bi.bi_op_bind = ppolicy_bind;
-       ppolicy.on_bi.bi_op_unbind = ppolicy_unbind;
        ppolicy.on_bi.bi_op_compare = ppolicy_restrict;
        ppolicy.on_bi.bi_op_delete = ppolicy_restrict;
        ppolicy.on_bi.bi_op_modify = ppolicy_modify;
        ppolicy.on_bi.bi_op_search = ppolicy_restrict;
+       ppolicy.on_bi.bi_connection_destroy = ppolicy_connection_destroy;
+
+       ppolicy.on_bi.bi_cf_ocs = ppolicyocs;
+       code = config_register_schema( ppolicycfg, ppolicyocs );
+       if ( code ) return code;
 
        return overlay_register( &ppolicy );
 }
 
 #if SLAPD_OVER_PPOLICY == SLAPD_MOD_DYNAMIC
 int init_module(int argc, char *argv[]) {
-       return ppolicy_init();
+       return ppolicy_initialize();
 }
 #endif