]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/ppolicy.c
check for NULL backend (ITS#6490)
[openldap] / servers / slapd / overlays / ppolicy.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2004-2009 The OpenLDAP Foundation.
5  * Portions Copyright 2004-2005 Howard Chu, Symas Corporation.
6  * Portions Copyright 2004 Hewlett-Packard Company.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted only as authorized by the OpenLDAP
11  * Public License.
12  *
13  * A copy of this license is available in the file LICENSE in the
14  * top-level directory of the distribution or, alternatively, at
15  * <http://www.OpenLDAP.org/license.html>.
16  */
17 /* ACKNOWLEDGEMENTS:
18  * This work was developed by Howard Chu for inclusion in
19  * OpenLDAP Software, based on prior work by Neil Dunbar (HP).
20  * This work was sponsored by the Hewlett-Packard Company.
21  */
22
23 #include "portable.h"
24
25 /* This file implements "Password Policy for LDAP Directories",
26  * based on draft behera-ldap-password-policy-09
27  */
28
29 #ifdef SLAPD_OVER_PPOLICY
30
31 #include <ldap.h>
32 #include "lutil.h"
33 #include "slap.h"
34 #ifdef SLAPD_MODULES
35 #define LIBLTDL_DLL_IMPORT      /* Win32: don't re-export libltdl's symbols */
36 #include <ltdl.h>
37 #endif
38 #include <ac/errno.h>
39 #include <ac/time.h>
40 #include <ac/string.h>
41 #include <ac/ctype.h>
42 #include "config.h"
43
44 #ifndef MODULE_NAME_SZ
45 #define MODULE_NAME_SZ 256
46 #endif
47
48 /* Per-instance configuration information */
49 typedef struct pp_info {
50         struct berval def_policy;       /* DN of default policy subentry */
51         int use_lockout;                /* send AccountLocked result? */
52         int hash_passwords;             /* transparently hash cleartext pwds */
53         int forward_updates;    /* use frontend for policy state updates */
54 } pp_info;
55
56 /* Our per-connection info - note, it is not per-instance, it is 
57  * used by all instances
58  */
59 typedef struct pw_conn {
60         struct berval dn;       /* DN of restricted user */
61 } pw_conn;
62
63 static pw_conn *pwcons;
64 static int ppolicy_cid;
65 static int ov_count;
66
67 typedef struct pass_policy {
68         AttributeDescription *ad; /* attribute to which the policy applies */
69         int pwdMinAge; /* minimum time (seconds) until passwd can change */
70         int pwdMaxAge; /* time in seconds until pwd will expire after change */
71         int pwdInHistory; /* number of previous passwords kept */
72         int pwdCheckQuality; /* 0 = don't check quality, 1 = check if possible,
73                                                    2 = check mandatory; fail if not possible */
74         int pwdMinLength; /* minimum number of chars in password */
75         int pwdExpireWarning; /* number of seconds that warning controls are
76                                                         sent before a password expires */
77         int pwdGraceAuthNLimit; /* number of times you can log in with an
78                                                         expired password */
79         int pwdLockout; /* 0 = do not lockout passwords, 1 = lock them out */
80         int pwdLockoutDuration; /* time in seconds a password is locked out for */
81         int pwdMaxFailure; /* number of failed binds allowed before lockout */
82         int pwdFailureCountInterval; /* number of seconds before failure
83                                                                         counts are zeroed */
84         int pwdMustChange; /* 0 = users can use admin set password
85                                                         1 = users must change password after admin set */
86         int pwdAllowUserChange; /* 0 = users cannot change their passwords
87                                                                 1 = users can change them */
88         int pwdSafeModify; /* 0 = old password doesn't need to come
89                                                                 with password change request
90                                                         1 = password change must supply existing pwd */
91         char pwdCheckModule[MODULE_NAME_SZ]; /* name of module to dynamically
92                                                                                     load to check password */
93 } PassPolicy;
94
95 typedef struct pw_hist {
96         time_t t;       /* timestamp of history entry */
97         struct berval pw;       /* old password hash */
98         struct berval bv;       /* text of entire entry */
99         struct pw_hist *next;
100 } pw_hist;
101
102 /* Operational attributes */
103 static AttributeDescription *ad_pwdChangedTime, *ad_pwdAccountLockedTime,
104         *ad_pwdFailureTime, *ad_pwdHistory, *ad_pwdGraceUseTime, *ad_pwdReset,
105         *ad_pwdPolicySubentry;
106
107 static struct schema_info {
108         char *def;
109         AttributeDescription **ad;
110 } pwd_OpSchema[] = {
111         {       "( 1.3.6.1.4.1.42.2.27.8.1.16 "
112                 "NAME ( 'pwdChangedTime' ) "
113                 "DESC 'The time the password was last changed' "
114                 "EQUALITY generalizedTimeMatch "
115                 "ORDERING generalizedTimeOrderingMatch "
116                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
117                 "SINGLE-VALUE NO-USER-MODIFICATION USAGE directoryOperation )",
118                 &ad_pwdChangedTime },
119         {       "( 1.3.6.1.4.1.42.2.27.8.1.17 "
120                 "NAME ( 'pwdAccountLockedTime' ) "
121                 "DESC 'The time an user account was locked' "
122                 "EQUALITY generalizedTimeMatch "
123                 "ORDERING generalizedTimeOrderingMatch "
124                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
125                 "SINGLE-VALUE "
126 #if 0
127                 /* Not until Relax control is released */
128                 "NO-USER-MODIFICATION "
129 #endif
130                 "USAGE directoryOperation )",
131                 &ad_pwdAccountLockedTime },
132         {       "( 1.3.6.1.4.1.42.2.27.8.1.19 "
133                 "NAME ( 'pwdFailureTime' ) "
134                 "DESC 'The timestamps of the last consecutive authentication failures' "
135                 "EQUALITY generalizedTimeMatch "
136                 "ORDERING generalizedTimeOrderingMatch "
137                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
138                 "NO-USER-MODIFICATION USAGE directoryOperation )",
139                 &ad_pwdFailureTime },
140         {       "( 1.3.6.1.4.1.42.2.27.8.1.20 "
141                 "NAME ( 'pwdHistory' ) "
142                 "DESC 'The history of users passwords' "
143                 "EQUALITY octetStringMatch "
144                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 "
145                 "NO-USER-MODIFICATION USAGE directoryOperation )",
146                 &ad_pwdHistory },
147         {       "( 1.3.6.1.4.1.42.2.27.8.1.21 "
148                 "NAME ( 'pwdGraceUseTime' ) "
149                 "DESC 'The timestamps of the grace login once the password has expired' "
150                 "EQUALITY generalizedTimeMatch "
151                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
152                 "NO-USER-MODIFICATION USAGE directoryOperation )",
153                 &ad_pwdGraceUseTime }, 
154         {       "( 1.3.6.1.4.1.42.2.27.8.1.22 "
155                 "NAME ( 'pwdReset' ) "
156                 "DESC 'The indication that the password has been reset' "
157                 "EQUALITY booleanMatch "
158                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 "
159                 "SINGLE-VALUE USAGE directoryOperation )",
160                 &ad_pwdReset },
161         {       "( 1.3.6.1.4.1.42.2.27.8.1.23 "
162                 "NAME ( 'pwdPolicySubentry' ) "
163                 "DESC 'The pwdPolicy subentry in effect for this object' "
164                 "EQUALITY distinguishedNameMatch "
165                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 "
166                 "SINGLE-VALUE "
167 #if 0
168                 /* Not until Relax control is released */
169                 "NO-USER-MODIFICATION "
170 #endif
171                 "USAGE directoryOperation )",
172                 &ad_pwdPolicySubentry },
173         { NULL, NULL }
174 };
175
176 /* User attributes */
177 static AttributeDescription *ad_pwdMinAge, *ad_pwdMaxAge, *ad_pwdInHistory,
178         *ad_pwdCheckQuality, *ad_pwdMinLength, *ad_pwdMaxFailure, 
179         *ad_pwdGraceAuthNLimit, *ad_pwdExpireWarning, *ad_pwdLockoutDuration,
180         *ad_pwdFailureCountInterval, *ad_pwdCheckModule, *ad_pwdLockout,
181         *ad_pwdMustChange, *ad_pwdAllowUserChange, *ad_pwdSafeModify,
182         *ad_pwdAttribute;
183
184 #define TAB(name)       { #name, &ad_##name }
185
186 static struct schema_info pwd_UsSchema[] = {
187         TAB(pwdAttribute),
188         TAB(pwdMinAge),
189         TAB(pwdMaxAge),
190         TAB(pwdInHistory),
191         TAB(pwdCheckQuality),
192         TAB(pwdMinLength),
193         TAB(pwdMaxFailure),
194         TAB(pwdGraceAuthNLimit),
195         TAB(pwdExpireWarning),
196         TAB(pwdLockout),
197         TAB(pwdLockoutDuration),
198         TAB(pwdFailureCountInterval),
199         TAB(pwdCheckModule),
200         TAB(pwdMustChange),
201         TAB(pwdAllowUserChange),
202         TAB(pwdSafeModify),
203         { NULL, NULL }
204 };
205
206 static ldap_pvt_thread_mutex_t chk_syntax_mutex;
207
208 enum {
209         PPOLICY_DEFAULT = 1,
210         PPOLICY_HASH_CLEARTEXT,
211         PPOLICY_USE_LOCKOUT
212 };
213
214 static ConfigDriver ppolicy_cf_default;
215
216 static ConfigTable ppolicycfg[] = {
217         { "ppolicy_default", "policyDN", 2, 2, 0,
218           ARG_DN|ARG_QUOTE|ARG_MAGIC|PPOLICY_DEFAULT, ppolicy_cf_default,
219           "( OLcfgOvAt:12.1 NAME 'olcPPolicyDefault' "
220           "DESC 'DN of a pwdPolicy object for uncustomized objects' "
221           "SYNTAX OMsDN SINGLE-VALUE )", NULL, NULL },
222         { "ppolicy_hash_cleartext", "on|off", 1, 2, 0,
223           ARG_ON_OFF|ARG_OFFSET|PPOLICY_HASH_CLEARTEXT,
224           (void *)offsetof(pp_info,hash_passwords),
225           "( OLcfgOvAt:12.2 NAME 'olcPPolicyHashCleartext' "
226           "DESC 'Hash passwords on add or modify' "
227           "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
228         { "ppolicy_forward_updates", "on|off", 1, 2, 0,
229           ARG_ON_OFF|ARG_OFFSET,
230           (void *)offsetof(pp_info,forward_updates),
231           "( OLcfgOvAt:12.4 NAME 'olcPPolicyForwardUpdates' "
232           "DESC 'Allow policy state updates to be forwarded via updateref' "
233           "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
234         { "ppolicy_use_lockout", "on|off", 1, 2, 0,
235           ARG_ON_OFF|ARG_OFFSET|PPOLICY_USE_LOCKOUT,
236           (void *)offsetof(pp_info,use_lockout),
237           "( OLcfgOvAt:12.3 NAME 'olcPPolicyUseLockout' "
238           "DESC 'Warn clients with AccountLocked' "
239           "SYNTAX OMsBoolean SINGLE-VALUE )", NULL, NULL },
240         { NULL, NULL, 0, 0, 0, ARG_IGNORED }
241 };
242
243 static ConfigOCs ppolicyocs[] = {
244         { "( OLcfgOvOc:12.1 "
245           "NAME 'olcPPolicyConfig' "
246           "DESC 'Password Policy configuration' "
247           "SUP olcOverlayConfig "
248           "MAY ( olcPPolicyDefault $ olcPPolicyHashCleartext $ "
249           "olcPPolicyUseLockout $ olcPPolicyForwardUpdates ) )",
250           Cft_Overlay, ppolicycfg },
251         { NULL, 0, NULL }
252 };
253
254 static int
255 ppolicy_cf_default( ConfigArgs *c )
256 {
257         slap_overinst *on = (slap_overinst *)c->bi;
258         pp_info *pi = (pp_info *)on->on_bi.bi_private;
259         int rc = ARG_BAD_CONF;
260
261         assert ( c->type == PPOLICY_DEFAULT );
262         Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default\n", 0, 0, 0);
263
264         switch ( c->op ) {
265         case SLAP_CONFIG_EMIT:
266                 Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default emit\n", 0, 0, 0);
267                 rc = 0;
268                 if ( !BER_BVISEMPTY( &pi->def_policy )) {
269                         rc = value_add_one( &c->rvalue_vals,
270                                             &pi->def_policy );
271                         if ( rc ) return rc;
272                         rc = value_add_one( &c->rvalue_nvals,
273                                             &pi->def_policy );
274                 }
275                 break;
276         case LDAP_MOD_DELETE:
277                 Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default delete\n", 0, 0, 0);
278                 if ( pi->def_policy.bv_val ) {
279                         ber_memfree ( pi->def_policy.bv_val );
280                         pi->def_policy.bv_val = NULL;
281                 }
282                 pi->def_policy.bv_len = 0;
283                 rc = 0;
284                 break;
285         case SLAP_CONFIG_ADD:
286                 /* fallthrough to LDAP_MOD_ADD */
287         case LDAP_MOD_ADD:
288                 Debug(LDAP_DEBUG_TRACE, "==> ppolicy_cf_default add\n", 0, 0, 0);
289                 if ( pi->def_policy.bv_val ) {
290                         ber_memfree ( pi->def_policy.bv_val );
291                 }
292                 pi->def_policy = c->value_ndn;
293                 ber_memfree( c->value_dn.bv_val );
294                 BER_BVZERO( &c->value_dn );
295                 BER_BVZERO( &c->value_ndn );
296                 rc = 0;
297                 break;
298         default:
299                 abort ();
300         }
301
302         return rc;
303 }
304
305 static time_t
306 parse_time( char *atm )
307 {
308         struct lutil_tm tm;
309         struct lutil_timet tt;
310         time_t ret = (time_t)-1;
311
312         if ( lutil_parsetime( atm, &tm ) == 0) {
313                 lutil_tm2time( &tm, &tt );
314                 ret = tt.tt_sec;
315         }
316         return ret;
317 }
318
319 static int
320 account_locked( Operation *op, Entry *e,
321                 PassPolicy *pp, Modifications **mod ) 
322 {
323         Attribute       *la;
324
325         assert(mod != NULL);
326
327         if ( !pp->pwdLockout )
328                 return 0;
329
330         if ( (la = attr_find( e->e_attrs, ad_pwdAccountLockedTime )) != NULL ) {
331                 BerVarray vals = la->a_nvals;
332
333                 /*
334                  * there is a lockout stamp - we now need to know if it's
335                  * a valid one.
336                  */
337                 if (vals[0].bv_val != NULL) {
338                         time_t then, now;
339                         Modifications *m;
340
341                         if ((then = parse_time( vals[0].bv_val )) == (time_t)0)
342                                 return 1;
343
344                         now = slap_get_time();
345
346                         /* Still in the future? not yet in effect */
347                         if (now < then)
348                                 return 0;
349
350                         if (!pp->pwdLockoutDuration)
351                                 return 1;
352
353                         if (now < then + pp->pwdLockoutDuration)
354                                 return 1;
355
356                         m = ch_calloc( sizeof(Modifications), 1 );
357                         m->sml_op = LDAP_MOD_DELETE;
358                         m->sml_flags = 0;
359                         m->sml_type = ad_pwdAccountLockedTime->ad_cname;
360                         m->sml_desc = ad_pwdAccountLockedTime;
361                         m->sml_next = *mod;
362                         *mod = m;
363                 }
364         }
365
366         return 0;
367 }
368
369 /* IMPLICIT TAGS, all context-specific */
370 #define PPOLICY_WARNING 0xa0L   /* constructed + 0 */
371 #define PPOLICY_ERROR 0x81L             /* primitive + 1 */
372  
373 #define PPOLICY_EXPIRE 0x80L    /* primitive + 0 */
374 #define PPOLICY_GRACE  0x81L    /* primitive + 1 */
375
376 static const char ppolicy_ctrl_oid[] = LDAP_CONTROL_PASSWORDPOLICYRESPONSE;
377
378 static LDAPControl *
379 create_passcontrol( Operation *op, int exptime, int grace, LDAPPasswordPolicyError err )
380 {
381         BerElementBuffer berbuf, bb2;
382         BerElement *ber = (BerElement *) &berbuf, *b2 = (BerElement *) &bb2;
383         LDAPControl c = { 0 }, *cp;
384         struct berval bv;
385
386         BER_BVZERO( &c.ldctl_value );
387
388         ber_init2( ber, NULL, LBER_USE_DER );
389         ber_printf( ber, "{" /*}*/ );
390
391         if ( exptime >= 0 ) {
392                 ber_init2( b2, NULL, LBER_USE_DER );
393                 ber_printf( b2, "ti", PPOLICY_EXPIRE, exptime );
394                 ber_flatten2( b2, &bv, 1 );
395                 (void)ber_free_buf(b2);
396                 ber_printf( ber, "tO", PPOLICY_WARNING, &bv );
397                 ch_free( bv.bv_val );
398         } else if ( grace > 0 ) {
399                 ber_init2( b2, NULL, LBER_USE_DER );
400                 ber_printf( b2, "ti", PPOLICY_GRACE, grace );
401                 ber_flatten2( b2, &bv, 1 );
402                 (void)ber_free_buf(b2);
403                 ber_printf( ber, "tO", PPOLICY_WARNING, &bv );
404                 ch_free( bv.bv_val );
405         }
406
407         if (err != PP_noError ) {
408                 ber_printf( ber, "te", PPOLICY_ERROR, err );
409         }
410         ber_printf( ber, /*{*/ "N}" );
411
412         if (ber_flatten2( ber, &c.ldctl_value, 0 ) == -1) {
413                 return NULL;
414         }
415         cp = op->o_tmpalloc( sizeof( LDAPControl ) + c.ldctl_value.bv_len, op->o_tmpmemctx );
416         cp->ldctl_oid = (char *)ppolicy_ctrl_oid;
417         cp->ldctl_iscritical = 0;
418         cp->ldctl_value.bv_val = (char *)&cp[1];
419         cp->ldctl_value.bv_len = c.ldctl_value.bv_len;
420         AC_MEMCPY( cp->ldctl_value.bv_val, c.ldctl_value.bv_val, c.ldctl_value.bv_len );
421         (void)ber_free_buf(ber);
422         
423         return cp;
424 }
425
426 static LDAPControl **
427 add_passcontrol( Operation *op, SlapReply *rs, LDAPControl *ctrl )
428 {
429         LDAPControl **ctrls, **oldctrls = rs->sr_ctrls;
430         int n;
431
432         n = 0;
433         if ( oldctrls ) {
434                 for ( ; oldctrls[n]; n++ )
435                         ;
436         }
437         n += 2;
438
439         ctrls = op->o_tmpcalloc( sizeof( LDAPControl * ), n, op->o_tmpmemctx );
440
441         n = 0;
442         if ( oldctrls ) {
443                 for ( ; oldctrls[n]; n++ ) {
444                         ctrls[n] = oldctrls[n];
445                 }
446         }
447         ctrls[n] = ctrl;
448         ctrls[n+1] = NULL;
449
450         rs->sr_ctrls = ctrls;
451
452         return oldctrls;
453 }
454
455 static void
456 ppolicy_get( Operation *op, Entry *e, PassPolicy *pp )
457 {
458         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
459         pp_info *pi = on->on_bi.bi_private;
460         Attribute *a;
461         BerVarray vals;
462         int rc;
463         Entry *pe = NULL;
464 #if 0
465         const char *text;
466 #endif
467
468         memset( pp, 0, sizeof(PassPolicy) );
469
470         pp->ad = slap_schema.si_ad_userPassword;
471
472         /* Users can change their own password by default */
473         pp->pwdAllowUserChange = 1;
474
475         if ((a = attr_find( e->e_attrs, ad_pwdPolicySubentry )) == NULL) {
476                 /*
477                  * entry has no password policy assigned - use default
478                  */
479                 vals = &pi->def_policy;
480                 if ( !vals->bv_val )
481                         goto defaultpol;
482         } else {
483                 vals = a->a_nvals;
484                 if (vals[0].bv_val == NULL) {
485                         Debug( LDAP_DEBUG_ANY,
486                                 "ppolicy_get: NULL value for policySubEntry\n", 0, 0, 0 );
487                         goto defaultpol;
488                 }
489         }
490
491         op->o_bd->bd_info = (BackendInfo *)on->on_info;
492         rc = be_entry_get_rw( op, vals, NULL, NULL, 0, &pe );
493         op->o_bd->bd_info = (BackendInfo *)on;
494
495         if ( rc ) goto defaultpol;
496
497 #if 0   /* Only worry about userPassword for now */
498         if ((a = attr_find( pe->e_attrs, ad_pwdAttribute )))
499                 slap_bv2ad( &a->a_vals[0], &pp->ad, &text );
500 #endif
501
502         if ( ( a = attr_find( pe->e_attrs, ad_pwdMinAge ) )
503                         && lutil_atoi( &pp->pwdMinAge, a->a_vals[0].bv_val ) != 0 )
504                 goto defaultpol;
505         if ( ( a = attr_find( pe->e_attrs, ad_pwdMaxAge ) )
506                         && lutil_atoi( &pp->pwdMaxAge, a->a_vals[0].bv_val ) != 0 )
507                 goto defaultpol;
508         if ( ( a = attr_find( pe->e_attrs, ad_pwdInHistory ) )
509                         && lutil_atoi( &pp->pwdInHistory, a->a_vals[0].bv_val ) != 0 )
510                 goto defaultpol;
511         if ( ( a = attr_find( pe->e_attrs, ad_pwdCheckQuality ) )
512                         && lutil_atoi( &pp->pwdCheckQuality, a->a_vals[0].bv_val ) != 0 )
513                 goto defaultpol;
514         if ( ( a = attr_find( pe->e_attrs, ad_pwdMinLength ) )
515                         && lutil_atoi( &pp->pwdMinLength, a->a_vals[0].bv_val ) != 0 )
516                 goto defaultpol;
517         if ( ( a = attr_find( pe->e_attrs, ad_pwdMaxFailure ) )
518                         && lutil_atoi( &pp->pwdMaxFailure, a->a_vals[0].bv_val ) != 0 )
519                 goto defaultpol;
520         if ( ( a = attr_find( pe->e_attrs, ad_pwdGraceAuthNLimit ) )
521                         && lutil_atoi( &pp->pwdGraceAuthNLimit, a->a_vals[0].bv_val ) != 0 )
522                 goto defaultpol;
523         if ( ( a = attr_find( pe->e_attrs, ad_pwdExpireWarning ) )
524                         && lutil_atoi( &pp->pwdExpireWarning, a->a_vals[0].bv_val ) != 0 )
525                 goto defaultpol;
526         if ( ( a = attr_find( pe->e_attrs, ad_pwdFailureCountInterval ) )
527                         && lutil_atoi( &pp->pwdFailureCountInterval, a->a_vals[0].bv_val ) != 0 )
528                 goto defaultpol;
529         if ( ( a = attr_find( pe->e_attrs, ad_pwdLockoutDuration ) )
530                         && lutil_atoi( &pp->pwdLockoutDuration, a->a_vals[0].bv_val ) != 0 )
531                 goto defaultpol;
532
533         if ( ( a = attr_find( pe->e_attrs, ad_pwdCheckModule ) ) ) {
534                 strncpy( pp->pwdCheckModule, a->a_vals[0].bv_val,
535                         sizeof(pp->pwdCheckModule) );
536                 pp->pwdCheckModule[sizeof(pp->pwdCheckModule)-1] = '\0';
537         }
538
539         if ((a = attr_find( pe->e_attrs, ad_pwdLockout )))
540                 pp->pwdLockout = bvmatch( &a->a_nvals[0], &slap_true_bv );
541         if ((a = attr_find( pe->e_attrs, ad_pwdMustChange )))
542                 pp->pwdMustChange = bvmatch( &a->a_nvals[0], &slap_true_bv );
543         if ((a = attr_find( pe->e_attrs, ad_pwdAllowUserChange )))
544                 pp->pwdAllowUserChange = bvmatch( &a->a_nvals[0], &slap_true_bv );
545         if ((a = attr_find( pe->e_attrs, ad_pwdSafeModify )))
546                 pp->pwdSafeModify = bvmatch( &a->a_nvals[0], &slap_true_bv );
547     
548         op->o_bd->bd_info = (BackendInfo *)on->on_info;
549         be_entry_release_r( op, pe );
550         op->o_bd->bd_info = (BackendInfo *)on;
551
552         return;
553
554 defaultpol:
555         Debug( LDAP_DEBUG_TRACE,
556                 "ppolicy_get: using default policy\n", 0, 0, 0 );
557         return;
558 }
559
560 static int
561 password_scheme( struct berval *cred, struct berval *sch )
562 {
563         int e;
564     
565         assert( cred != NULL );
566
567         if (sch) {
568                 sch->bv_val = NULL;
569                 sch->bv_len = 0;
570         }
571     
572         if ((cred->bv_len == 0) || (cred->bv_val == NULL) ||
573                 (cred->bv_val[0] != '{')) return LDAP_OTHER;
574
575         for(e = 1; cred->bv_val[e] && cred->bv_val[e] != '}'; e++);
576         if (cred->bv_val[e]) {
577                 int rc;
578                 rc = lutil_passwd_scheme( cred->bv_val );
579                 if (rc) {
580                         if (sch) {
581                                 sch->bv_val = cred->bv_val;
582                                 sch->bv_len = e;
583                         }
584                         return LDAP_SUCCESS;
585                 }
586         }
587         return LDAP_OTHER;
588 }
589
590 static int
591 check_password_quality( struct berval *cred, PassPolicy *pp, LDAPPasswordPolicyError *err, Entry *e, char **txt )
592 {
593         int rc = LDAP_SUCCESS, ok = LDAP_SUCCESS;
594         char *ptr = cred->bv_val;
595         struct berval sch;
596
597         assert( cred != NULL );
598         assert( pp != NULL );
599         assert( txt != NULL );
600
601         *txt = NULL;
602
603         if ((cred->bv_len == 0) || (pp->pwdMinLength > cred->bv_len)) {
604                 rc = LDAP_CONSTRAINT_VIOLATION;
605                 if ( err ) *err = PP_passwordTooShort;
606                 return rc;
607         }
608
609         /*
610          * We need to know if the password is already hashed - if so
611          * what scheme is it. The reason being that the "hash" of
612          * {cleartext} still allows us to check the password.
613          */
614         rc = password_scheme( cred, &sch );
615         if (rc == LDAP_SUCCESS) {
616                 if ((sch.bv_val) && (strncasecmp( sch.bv_val, "{cleartext}",
617                         sch.bv_len ) == 0)) {
618                         /*
619                          * We can check the cleartext "hash"
620                          */
621                         ptr = cred->bv_val + sch.bv_len;
622                 } else {
623                         /* everything else, we can't check */
624                         if (pp->pwdCheckQuality == 2) {
625                                 rc = LDAP_CONSTRAINT_VIOLATION;
626                                 if (err) *err = PP_insufficientPasswordQuality;
627                                 return rc;
628                         }
629                         /*
630                          * We can't check the syntax of the password, but it's not
631                          * mandatory (according to the policy), so we return success.
632                          */
633                     
634                         return LDAP_SUCCESS;
635                 }
636         }
637
638         rc = LDAP_SUCCESS;
639
640         if (pp->pwdCheckModule[0]) {
641 #ifdef SLAPD_MODULES
642                 lt_dlhandle mod;
643                 const char *err;
644                 
645                 if ((mod = lt_dlopen( pp->pwdCheckModule )) == NULL) {
646                         err = lt_dlerror();
647
648                         Debug(LDAP_DEBUG_ANY,
649                         "check_password_quality: lt_dlopen failed: (%s) %s.\n",
650                                 pp->pwdCheckModule, err, 0 );
651                         ok = LDAP_OTHER; /* internal error */
652                 } else {
653                         /* FIXME: the error message ought to be passed thru a
654                          * struct berval, with preallocated buffer and size
655                          * passed in. Module can still allocate a buffer for
656                          * it if the provided one is too small.
657                          */
658                         int (*prog)( char *passwd, char **text, Entry *ent );
659
660                         if ((prog = lt_dlsym( mod, "check_password" )) == NULL) {
661                                 err = lt_dlerror();
662                             
663                                 Debug(LDAP_DEBUG_ANY,
664                                         "check_password_quality: lt_dlsym failed: (%s) %s.\n",
665                                         pp->pwdCheckModule, err, 0 );
666                                 ok = LDAP_OTHER;
667                         } else {
668                                 ldap_pvt_thread_mutex_lock( &chk_syntax_mutex );
669                                 ok = prog( ptr, txt, e );
670                                 ldap_pvt_thread_mutex_unlock( &chk_syntax_mutex );
671                                 if (ok != LDAP_SUCCESS) {
672                                         Debug(LDAP_DEBUG_ANY,
673                                                 "check_password_quality: module error: (%s) %s.[%d]\n",
674                                                 pp->pwdCheckModule, *txt ? *txt : "", ok );
675                                 }
676                         }
677                             
678                         lt_dlclose( mod );
679                 }
680 #else
681         Debug(LDAP_DEBUG_ANY, "check_password_quality: external modules not "
682                 "supported. pwdCheckModule ignored.\n", 0, 0, 0);
683 #endif /* SLAPD_MODULES */
684         }
685                 
686                     
687         if (ok != LDAP_SUCCESS) {
688                 rc = LDAP_CONSTRAINT_VIOLATION;
689                 if (err) *err = PP_insufficientPasswordQuality;
690         }
691         
692         return rc;
693 }
694
695 static int
696 parse_pwdhistory( struct berval *bv, char **oid, time_t *oldtime, struct berval *oldpw )
697 {
698         char *ptr;
699         struct berval nv, npw;
700         ber_len_t i, j;
701         
702         assert (bv && (bv->bv_len > 0) && (bv->bv_val) && oldtime && oldpw );
703
704         if ( oid ) {
705                 *oid = 0;
706         }
707         *oldtime = (time_t)-1;
708         BER_BVZERO( oldpw );
709         
710         ber_dupbv( &nv, bv );
711
712         /* first get the time field */
713         for ( i = 0; (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++ )
714                 ;
715         if ( i == nv.bv_len ) {
716                 goto exit_failure; /* couldn't locate the '#' separator */
717         }
718         nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
719         ptr = nv.bv_val;
720         *oldtime = parse_time( ptr );
721         if (*oldtime == (time_t)-1) {
722                 goto exit_failure;
723         }
724
725         /* get the OID field */
726         for (ptr = &(nv.bv_val[i]); (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++ )
727                 ;
728         if ( i == nv.bv_len ) {
729                 goto exit_failure; /* couldn't locate the '#' separator */
730         }
731         nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
732         if ( oid ) {
733                 *oid = ber_strdup( ptr );
734         }
735         
736         /* get the length field */
737         for ( ptr = &(nv.bv_val[i]); (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++ )
738                 ;
739         if ( i == nv.bv_len ) {
740                 goto exit_failure; /* couldn't locate the '#' separator */
741         }
742         nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
743         oldpw->bv_len = strtol( ptr, NULL, 10 );
744         if (errno == ERANGE) {
745                 goto exit_failure;
746         }
747
748         /* lastly, get the octets of the string */
749         for ( j = i, ptr = &(nv.bv_val[i]); i < nv.bv_len; i++ )
750                 ;
751         if ( i - j != oldpw->bv_len) {
752                 goto exit_failure; /* length is wrong */
753         }
754
755         npw.bv_val = ptr;
756         npw.bv_len = oldpw->bv_len;
757         ber_dupbv( oldpw, &npw );
758         ber_memfree( nv.bv_val );
759         
760         return LDAP_SUCCESS;
761
762 exit_failure:;
763         if ( oid && *oid ) {
764                 ber_memfree(*oid);
765                 *oid = NULL;
766         }
767         if ( oldpw->bv_val ) {
768                 ber_memfree( oldpw->bv_val);
769                 BER_BVZERO( oldpw );
770         }
771         ber_memfree( nv.bv_val );
772
773         return LDAP_OTHER;
774 }
775
776 static void
777 add_to_pwd_history( pw_hist **l, time_t t,
778                     struct berval *oldpw, struct berval *bv )
779 {
780         pw_hist *p, *p1, *p2;
781     
782         if (!l) return;
783
784         p = ch_malloc( sizeof( pw_hist ));
785         p->pw = *oldpw;
786         ber_dupbv( &p->bv, bv );
787         p->t = t;
788         p->next = NULL;
789         
790         if (*l == NULL) {
791                 /* degenerate case */
792                 *l = p;
793                 return;
794         }
795         /*
796          * advance p1 and p2 such that p1 is the node before the
797          * new one, and p2 is the node after it
798          */
799         for (p1 = NULL, p2 = *l; p2 && p2->t <= t; p1 = p2, p2=p2->next );
800         p->next = p2;
801         if (p1 == NULL) { *l = p; return; }
802         p1->next = p;
803 }
804
805 #ifndef MAX_PWD_HISTORY_SZ
806 #define MAX_PWD_HISTORY_SZ 1024
807 #endif /* MAX_PWD_HISTORY_SZ */
808
809 static void
810 make_pwd_history_value( char *timebuf, struct berval *bv, Attribute *pa )
811 {
812         char str[ MAX_PWD_HISTORY_SZ ];
813         int nlen;
814
815         snprintf( str, MAX_PWD_HISTORY_SZ,
816                   "%s#%s#%lu#", timebuf,
817                   pa->a_desc->ad_type->sat_syntax->ssyn_oid,
818                   (unsigned long) pa->a_nvals[0].bv_len );
819         str[MAX_PWD_HISTORY_SZ-1] = 0;
820         nlen = strlen(str);
821
822         /*
823          * We have to assume that the string is a string of octets,
824          * not readable characters. In reality, yes, it probably is
825          * a readable (ie, base64) string, but we can't count on that
826          * Hence, while the first 3 fields of the password history
827          * are definitely readable (a timestamp, an OID and an integer
828          * length), the remaining octets of the actual password
829          * are deemed to be binary data.
830          */
831         AC_MEMCPY( str + nlen, pa->a_nvals[0].bv_val, pa->a_nvals[0].bv_len );
832         nlen += pa->a_nvals[0].bv_len;
833         bv->bv_val = ch_malloc( nlen + 1 );
834         AC_MEMCPY( bv->bv_val, str, nlen );
835         bv->bv_val[nlen] = '\0';
836         bv->bv_len = nlen;
837 }
838
839 static void
840 free_pwd_history_list( pw_hist **l )
841 {
842         pw_hist *p;
843     
844         if (!l) return;
845         p = *l;
846         while (p) {
847                 pw_hist *pp = p->next;
848
849                 free(p->pw.bv_val);
850                 free(p->bv.bv_val);
851                 free(p);
852                 p = pp;
853         }
854         *l = NULL;
855 }
856
857 typedef struct ppbind {
858         slap_overinst *on;
859         int send_ctrl;
860         int set_restrict;
861         LDAPControl **oldctrls;
862         Modifications *mod;
863         LDAPPasswordPolicyError pErr;
864         PassPolicy pp;
865 } ppbind;
866
867 static void
868 ctrls_cleanup( Operation *op, SlapReply *rs, LDAPControl **oldctrls )
869 {
870         int n;
871
872         assert( rs->sr_ctrls != NULL );
873         assert( rs->sr_ctrls[0] != NULL );
874
875         for ( n = 0; rs->sr_ctrls[n]; n++ ) {
876                 if ( rs->sr_ctrls[n]->ldctl_oid == ppolicy_ctrl_oid ) {
877                         op->o_tmpfree( rs->sr_ctrls[n], op->o_tmpmemctx );
878                         rs->sr_ctrls[n] = (LDAPControl *)(-1);
879                         break;
880                 }
881         }
882
883         if ( rs->sr_ctrls[n] == NULL ) {
884                 /* missed? */
885         }
886
887         op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
888
889         rs->sr_ctrls = oldctrls;
890 }
891
892 static int
893 ppolicy_ctrls_cleanup( Operation *op, SlapReply *rs )
894 {
895         ppbind *ppb = op->o_callback->sc_private;
896         if ( ppb->send_ctrl ) {
897                 ctrls_cleanup( op, rs, ppb->oldctrls );
898         }
899         return SLAP_CB_CONTINUE;
900 }
901
902 static int
903 ppolicy_bind_response( Operation *op, SlapReply *rs )
904 {
905         ppbind *ppb = op->o_callback->sc_private;
906         slap_overinst *on = ppb->on;
907         Modifications *mod = ppb->mod, *m;
908         int pwExpired = 0;
909         int ngut = -1, warn = -1, age, rc;
910         Attribute *a;
911         time_t now, pwtime = (time_t)-1;
912         char nowstr[ LDAP_LUTIL_GENTIME_BUFSIZE ];
913         struct berval timestamp;
914         BackendInfo *bi = op->o_bd->bd_info;
915         Entry *e;
916
917         /* If we already know it's locked, just get on with it */
918         if ( ppb->pErr != PP_noError ) {
919                 goto locked;
920         }
921
922         op->o_bd->bd_info = (BackendInfo *)on->on_info;
923         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
924         op->o_bd->bd_info = bi;
925
926         if ( rc != LDAP_SUCCESS ) {
927                 return SLAP_CB_CONTINUE;
928         }
929
930         now = slap_get_time(); /* stored for later consideration */
931         timestamp.bv_val = nowstr;
932         timestamp.bv_len = sizeof(nowstr);
933         slap_timestamp( &now, &timestamp );
934
935         if ( rs->sr_err == LDAP_INVALID_CREDENTIALS ) {
936                 int i = 0, fc = 0;
937
938                 m = ch_calloc( sizeof(Modifications), 1 );
939                 m->sml_op = LDAP_MOD_ADD;
940                 m->sml_flags = 0;
941                 m->sml_type = ad_pwdFailureTime->ad_cname;
942                 m->sml_desc = ad_pwdFailureTime;
943                 m->sml_numvals = 1;
944                 m->sml_values = ch_calloc( sizeof(struct berval), 2 );
945                 m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
946
947                 ber_dupbv( &m->sml_values[0], &timestamp );
948                 ber_dupbv( &m->sml_nvalues[0], &timestamp );
949                 m->sml_next = mod;
950                 mod = m;
951
952                 /*
953                  * Count the pwdFailureTimes - if it's
954                  * greater than the policy pwdMaxFailure,
955                  * then lock the account.
956                  */
957                 if ((a = attr_find( e->e_attrs, ad_pwdFailureTime )) != NULL) {
958                         for(i=0; a->a_nvals[i].bv_val; i++) {
959
960                                 /*
961                                  * If the interval is 0, then failures
962                                  * stay on the record until explicitly
963                                  * reset by successful authentication.
964                                  */
965                                 if (ppb->pp.pwdFailureCountInterval == 0) {
966                                         fc++;
967                                 } else if (now <=
968                                                         parse_time(a->a_nvals[i].bv_val) +
969                                                         ppb->pp.pwdFailureCountInterval) {
970
971                                         fc++;
972                                 }
973                                 /*
974                                  * We only count those failures
975                                  * which are not due to expire.
976                                  */
977                         }
978                 }
979                 
980                 if ((ppb->pp.pwdMaxFailure > 0) &&
981                         (fc >= ppb->pp.pwdMaxFailure - 1)) {
982
983                         /*
984                          * We subtract 1 from the failure max
985                          * because the new failure entry hasn't
986                          * made it to the entry yet.
987                          */
988                         m = ch_calloc( sizeof(Modifications), 1 );
989                         m->sml_op = LDAP_MOD_REPLACE;
990                         m->sml_flags = 0;
991                         m->sml_type = ad_pwdAccountLockedTime->ad_cname;
992                         m->sml_desc = ad_pwdAccountLockedTime;
993                         m->sml_numvals = 1;
994                         m->sml_values = ch_calloc( sizeof(struct berval), 2 );
995                         m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
996                         ber_dupbv( &m->sml_values[0], &timestamp );
997                         ber_dupbv( &m->sml_nvalues[0], &timestamp );
998                         m->sml_next = mod;
999                         mod = m;
1000                 }
1001         } else if ( rs->sr_err == LDAP_SUCCESS ) {
1002                 if ((a = attr_find( e->e_attrs, ad_pwdChangedTime )) != NULL)
1003                         pwtime = parse_time( a->a_nvals[0].bv_val );
1004
1005                 /* delete all pwdFailureTimes */
1006                 if ( attr_find( e->e_attrs, ad_pwdFailureTime )) {
1007                         m = ch_calloc( sizeof(Modifications), 1 );
1008                         m->sml_op = LDAP_MOD_DELETE;
1009                         m->sml_flags = 0;
1010                         m->sml_type = ad_pwdFailureTime->ad_cname;
1011                         m->sml_desc = ad_pwdFailureTime;
1012                         m->sml_next = mod;
1013                         mod = m;
1014                 }
1015
1016                 /*
1017                  * check to see if the password must be changed
1018                  */
1019                 if ( ppb->pp.pwdMustChange &&
1020                         (a = attr_find( e->e_attrs, ad_pwdReset )) &&
1021                         bvmatch( &a->a_nvals[0], &slap_true_bv ) )
1022                 {
1023                         /*
1024                          * need to inject client controls here to give
1025                          * more information. For the moment, we ensure
1026                          * that we are disallowed from doing anything
1027                          * other than change password.
1028                          */
1029                         if ( ppb->set_restrict ) {
1030                                 ber_dupbv( &pwcons[op->o_conn->c_conn_idx].dn,
1031                                         &op->o_conn->c_ndn );
1032                         }
1033
1034                         ppb->pErr = PP_changeAfterReset;
1035
1036                 } else {
1037                         /*
1038                          * the password does not need to be changed, so
1039                          * we now check whether the password has expired.
1040                          *
1041                          * We can skip this bit if passwords don't age in
1042                          * the policy. Also, if there was no pwdChangedTime
1043                          * attribute in the entry, the password never expires.
1044                          */
1045                         if (ppb->pp.pwdMaxAge == 0) goto grace;
1046
1047                         if (pwtime != (time_t)-1) {
1048                                 /*
1049                                  * Check: was the last change time of
1050                                  * the password older than the maximum age
1051                                  * allowed. (Ignore case 2 from I-D, it's just silly.)
1052                                  */
1053                                 if (now - pwtime > ppb->pp.pwdMaxAge ) pwExpired = 1;
1054                         }
1055                 }
1056
1057 grace:
1058                 if (!pwExpired) goto check_expiring_password;
1059                 
1060                 if ((a = attr_find( e->e_attrs, ad_pwdGraceUseTime )) == NULL)
1061                         ngut = ppb->pp.pwdGraceAuthNLimit;
1062                 else {
1063                         for(ngut=0; a->a_nvals[ngut].bv_val; ngut++);
1064                         ngut = ppb->pp.pwdGraceAuthNLimit - ngut;
1065                 }
1066
1067                 /*
1068                  * ngut is the number of remaining grace logins
1069                  */
1070                 Debug( LDAP_DEBUG_ANY,
1071                         "ppolicy_bind: Entry %s has an expired password: %d grace logins\n",
1072                         e->e_name.bv_val, ngut, 0);
1073                 
1074                 if (ngut < 1) {
1075                         ppb->pErr = PP_passwordExpired;
1076                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
1077                         goto done;
1078                 }
1079
1080                 /*
1081                  * Add a grace user time to the entry
1082                  */
1083                 m = ch_calloc( sizeof(Modifications), 1 );
1084                 m->sml_op = LDAP_MOD_ADD;
1085                 m->sml_flags = 0;
1086                 m->sml_type = ad_pwdGraceUseTime->ad_cname;
1087                 m->sml_desc = ad_pwdGraceUseTime;
1088                 m->sml_numvals = 1;
1089                 m->sml_values = ch_calloc( sizeof(struct berval), 2 );
1090                 m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
1091                 ber_dupbv( &m->sml_values[0], &timestamp );
1092                 ber_dupbv( &m->sml_nvalues[0], &timestamp );
1093                 m->sml_next = mod;
1094                 mod = m;
1095
1096 check_expiring_password:
1097                 /*
1098                  * Now we need to check to see
1099                  * if it is about to expire, and if so, should the user
1100                  * be warned about it in the password policy control.
1101                  *
1102                  * If the password has expired, and we're in the grace period, then
1103                  * we don't need to do this bit. Similarly, if we don't have password
1104                  * aging, then there's no need to do this bit either.
1105                  */
1106                 if ((ppb->pp.pwdMaxAge < 1) || (pwExpired) || (ppb->pp.pwdExpireWarning < 1))
1107                         goto done;
1108
1109                 age = (int)(now - pwtime);
1110                 
1111                 /*
1112                  * We know that there is a password Change Time attribute - if
1113                  * there wasn't, then the pwdExpired value would be true, unless
1114                  * there is no password aging - and if there is no password aging,
1115                  * then this section isn't called anyway - you can't have an
1116                  * expiring password if there's no limit to expire.
1117                  */
1118                 if (ppb->pp.pwdMaxAge - age < ppb->pp.pwdExpireWarning ) {
1119                         /*
1120                          * Set the warning value.
1121                          */
1122                         warn = ppb->pp.pwdMaxAge - age; /* seconds left until expiry */
1123                         if (warn < 0) warn = 0; /* something weird here - why is pwExpired not set? */
1124                         
1125                         Debug( LDAP_DEBUG_ANY,
1126                                 "ppolicy_bind: Setting warning for password expiry for %s = %d seconds\n",
1127                                 op->o_req_dn.bv_val, warn, 0 );
1128                 }
1129         }
1130
1131 done:
1132         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1133         be_entry_release_r( op, e );
1134
1135 locked:
1136         if ( mod ) {
1137                 Operation op2 = *op;
1138                 SlapReply r2 = { REP_RESULT };
1139                 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
1140                 pp_info *pi = on->on_bi.bi_private;
1141                 LDAPControl c, *ca[2];
1142
1143                 op2.o_tag = LDAP_REQ_MODIFY;
1144                 op2.o_callback = &cb;
1145                 op2.orm_modlist = mod;
1146                 op2.orm_no_opattrs = 0;
1147                 op2.o_dn = op->o_bd->be_rootdn;
1148                 op2.o_ndn = op->o_bd->be_rootndn;
1149
1150                 /* If this server is a shadow and forward_updates is true,
1151                  * use the frontend to perform this modify. That will trigger
1152                  * the update referral, which can then be forwarded by the
1153                  * chain overlay. Obviously the updateref and chain overlay
1154                  * must be configured appropriately for this to be useful.
1155                  */
1156                 if ( SLAP_SHADOW( op->o_bd ) && pi->forward_updates ) {
1157                         op2.o_bd = frontendDB;
1158
1159                         /* Must use Relax control since these are no-user-mod */
1160                         op2.o_relax = SLAP_CONTROL_CRITICAL;
1161                         op2.o_ctrls = ca;
1162                         ca[0] = &c;
1163                         ca[1] = NULL;
1164                         BER_BVZERO( &c.ldctl_value );
1165                         c.ldctl_iscritical = 1;
1166                         c.ldctl_oid = LDAP_CONTROL_RELAX;
1167                 } else {
1168                         op2.o_bd->bd_info = (BackendInfo *)on->on_info;
1169                 }
1170                 rc = op2.o_bd->be_modify( &op2, &r2 );
1171                 slap_mods_free( mod, 1 );
1172         }
1173
1174         if ( ppb->send_ctrl ) {
1175                 LDAPControl *ctrl = NULL;
1176                 pp_info *pi = on->on_bi.bi_private;
1177
1178                 /* Do we really want to tell that the account is locked? */
1179                 if ( ppb->pErr == PP_accountLocked && !pi->use_lockout ) {
1180                         ppb->pErr = PP_noError;
1181                 }
1182                 ctrl = create_passcontrol( op, warn, ngut, ppb->pErr );
1183                 ppb->oldctrls = add_passcontrol( op, rs, ctrl );
1184                 op->o_callback->sc_cleanup = ppolicy_ctrls_cleanup;
1185         }
1186         op->o_bd->bd_info = bi;
1187         return SLAP_CB_CONTINUE;
1188 }
1189
1190 static int
1191 ppolicy_bind( Operation *op, SlapReply *rs )
1192 {
1193         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1194
1195         /* Reset lockout status on all Bind requests */
1196         if ( !BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
1197                 ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1198                 BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1199         }
1200
1201         /* Root bypasses policy */
1202         if ( !be_isroot_dn( op->o_bd, &op->o_req_ndn )) {
1203                 Entry *e;
1204                 int rc;
1205                 ppbind *ppb;
1206                 slap_callback *cb;
1207
1208                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1209                 rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1210
1211                 if ( rc != LDAP_SUCCESS ) {
1212                         return SLAP_CB_CONTINUE;
1213                 }
1214
1215                 cb = op->o_tmpcalloc( sizeof(ppbind)+sizeof(slap_callback),
1216                         1, op->o_tmpmemctx );
1217                 ppb = (ppbind *)(cb+1);
1218                 ppb->on = on;
1219                 ppb->pErr = PP_noError;
1220                 ppb->set_restrict = 1;
1221
1222                 /* Setup a callback so we can munge the result */
1223
1224                 cb->sc_response = ppolicy_bind_response;
1225                 cb->sc_next = op->o_callback->sc_next;
1226                 cb->sc_private = ppb;
1227                 op->o_callback->sc_next = cb;
1228
1229                 /* Did we receive a password policy request control? */
1230                 if ( op->o_ctrlflag[ppolicy_cid] ) {
1231                         ppb->send_ctrl = 1;
1232                 }
1233
1234                 op->o_bd->bd_info = (BackendInfo *)on;
1235                 ppolicy_get( op, e, &ppb->pp );
1236
1237                 rc = account_locked( op, e, &ppb->pp, &ppb->mod );
1238
1239                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1240                 be_entry_release_r( op, e );
1241
1242                 if ( rc ) {
1243                         ppb->pErr = PP_accountLocked;
1244                         send_ldap_error( op, rs, LDAP_INVALID_CREDENTIALS, NULL );
1245                         return rs->sr_err;
1246                 }
1247
1248         }
1249
1250         return SLAP_CB_CONTINUE;
1251 }
1252
1253 /* Reset the restricted info for the next session on this connection */
1254 static int
1255 ppolicy_connection_destroy( BackendDB *bd, Connection *conn )
1256 {
1257         if ( !BER_BVISEMPTY( &pwcons[conn->c_conn_idx].dn )) {
1258                 ch_free( pwcons[conn->c_conn_idx].dn.bv_val );
1259                 BER_BVZERO( &pwcons[conn->c_conn_idx].dn );
1260         }
1261         return SLAP_CB_CONTINUE;
1262 }
1263
1264 /* Check if this connection is restricted */
1265 static int
1266 ppolicy_restrict(
1267         Operation *op,
1268         SlapReply *rs )
1269 {
1270         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1271         int send_ctrl = 0;
1272
1273         /* Did we receive a password policy request control? */
1274         if ( op->o_ctrlflag[ppolicy_cid] ) {
1275                 send_ctrl = 1;
1276         }
1277
1278         if ( op->o_conn && !BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
1279                 LDAPControl **oldctrls;
1280                 /* if the current authcDN doesn't match the one we recorded,
1281                  * then an intervening Bind has succeeded and the restriction
1282                  * no longer applies. (ITS#4516)
1283                  */
1284                 if ( !dn_match( &op->o_conn->c_ndn,
1285                                 &pwcons[op->o_conn->c_conn_idx].dn )) {
1286                         ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1287                         BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1288                         return SLAP_CB_CONTINUE;
1289                 }
1290
1291                 Debug( LDAP_DEBUG_TRACE,
1292                         "connection restricted to password changing only\n", 0, 0, 0);
1293                 if ( send_ctrl ) {
1294                         LDAPControl *ctrl = NULL;
1295                         ctrl = create_passcontrol( op, -1, -1, PP_changeAfterReset );
1296                         oldctrls = add_passcontrol( op, rs, ctrl );
1297                 }
1298                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1299                 send_ldap_error( op, rs, LDAP_INSUFFICIENT_ACCESS, 
1300                         "Operations are restricted to bind/unbind/abandon/StartTLS/modify password" );
1301                 if ( send_ctrl ) {
1302                         ctrls_cleanup( op, rs, oldctrls );
1303                 }
1304                 return rs->sr_err;
1305         }
1306
1307         return SLAP_CB_CONTINUE;
1308 }
1309
1310 static int
1311 ppolicy_compare_response(
1312         Operation *op,
1313         SlapReply *rs )
1314 {
1315         /* map compare responses to bind responses */
1316         if ( rs->sr_err == LDAP_COMPARE_TRUE )
1317                 rs->sr_err = LDAP_SUCCESS;
1318         else if ( rs->sr_err == LDAP_COMPARE_FALSE )
1319                 rs->sr_err = LDAP_INVALID_CREDENTIALS;
1320
1321         ppolicy_bind_response( op, rs );
1322
1323         /* map back to compare */
1324         if ( rs->sr_err == LDAP_SUCCESS )
1325                 rs->sr_err = LDAP_COMPARE_TRUE;
1326         else if ( rs->sr_err == LDAP_INVALID_CREDENTIALS )
1327                 rs->sr_err = LDAP_COMPARE_FALSE;
1328
1329         return SLAP_CB_CONTINUE;
1330 }
1331
1332 static int
1333 ppolicy_compare(
1334         Operation *op,
1335         SlapReply *rs )
1336 {
1337         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1338
1339         if ( ppolicy_restrict( op, rs ) != SLAP_CB_CONTINUE )
1340                 return rs->sr_err;
1341
1342         /* Did we receive a password policy request control?
1343          * Are we testing the userPassword?
1344          */
1345         if ( op->o_ctrlflag[ppolicy_cid] && 
1346                 op->orc_ava->aa_desc == slap_schema.si_ad_userPassword ) {
1347                 Entry *e;
1348                 int rc;
1349                 ppbind *ppb;
1350                 slap_callback *cb;
1351
1352                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1353                 rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1354
1355                 if ( rc != LDAP_SUCCESS ) {
1356                         return SLAP_CB_CONTINUE;
1357                 }
1358
1359                 cb = op->o_tmpcalloc( sizeof(ppbind)+sizeof(slap_callback),
1360                         1, op->o_tmpmemctx );
1361                 ppb = (ppbind *)(cb+1);
1362                 ppb->on = on;
1363                 ppb->pErr = PP_noError;
1364                 ppb->send_ctrl = 1;
1365                 /* failures here don't lockout the connection */
1366                 ppb->set_restrict = 0;
1367
1368                 /* Setup a callback so we can munge the result */
1369
1370                 cb->sc_response = ppolicy_compare_response;
1371                 cb->sc_next = op->o_callback->sc_next;
1372                 cb->sc_private = ppb;
1373                 op->o_callback->sc_next = cb;
1374
1375                 op->o_bd->bd_info = (BackendInfo *)on;
1376                 ppolicy_get( op, e, &ppb->pp );
1377
1378                 rc = account_locked( op, e, &ppb->pp, &ppb->mod );
1379
1380                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1381                 be_entry_release_r( op, e );
1382
1383                 if ( rc ) {
1384                         ppb->pErr = PP_accountLocked;
1385                         send_ldap_error( op, rs, LDAP_COMPARE_FALSE, NULL );
1386                         return rs->sr_err;
1387                 }
1388         }
1389         return SLAP_CB_CONTINUE;
1390 }
1391
1392 static int
1393 ppolicy_add(
1394         Operation *op,
1395         SlapReply *rs )
1396 {
1397         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1398         pp_info *pi = on->on_bi.bi_private;
1399         PassPolicy pp;
1400         Attribute *pa;
1401         const char *txt;
1402
1403         if ( ppolicy_restrict( op, rs ) != SLAP_CB_CONTINUE )
1404                 return rs->sr_err;
1405
1406         /* If this is a replica, assume the master checked everything */
1407         if ( be_shadow_update( op ))
1408                 return SLAP_CB_CONTINUE;
1409
1410         /* Check for password in entry */
1411         if ((pa = attr_find( op->oq_add.rs_e->e_attrs,
1412                 slap_schema.si_ad_userPassword )))
1413         {
1414                 assert( pa->a_vals != NULL );
1415                 assert( !BER_BVISNULL( &pa->a_vals[ 0 ] ) );
1416
1417                 if ( !BER_BVISNULL( &pa->a_vals[ 1 ] ) ) {
1418                         send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION, "Password policy only allows one password value" );
1419                         return rs->sr_err;
1420                 }
1421
1422                 /*
1423                  * new entry contains a password - if we're not the root user
1424                  * then we need to check that the password fits in with the
1425                  * security policy for the new entry.
1426                  */
1427                 ppolicy_get( op, op->ora_e, &pp );
1428                 if (pp.pwdCheckQuality > 0 && !be_isroot( op )) {
1429                         struct berval *bv = &(pa->a_vals[0]);
1430                         int rc, send_ctrl = 0;
1431                         LDAPPasswordPolicyError pErr = PP_noError;
1432                         char *txt;
1433
1434                         /* Did we receive a password policy request control? */
1435                         if ( op->o_ctrlflag[ppolicy_cid] ) {
1436                                 send_ctrl = 1;
1437                         }
1438                         rc = check_password_quality( bv, &pp, &pErr, op->ora_e, &txt );
1439                         if (rc != LDAP_SUCCESS) {
1440                                 LDAPControl **oldctrls = NULL;
1441                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1442                                 if ( send_ctrl ) {
1443                                         LDAPControl *ctrl = NULL;
1444                                         ctrl = create_passcontrol( op, -1, -1, pErr );
1445                                         oldctrls = add_passcontrol( op, rs, ctrl );
1446                                 }
1447                                 send_ldap_error( op, rs, rc, txt ? txt : "Password fails quality checking policy" );
1448                                 if ( txt ) {
1449                                         free( txt );
1450                                 }
1451                                 if ( send_ctrl ) {
1452                                         ctrls_cleanup( op, rs, oldctrls );
1453                                 }
1454                                 return rs->sr_err;
1455                         }
1456                 }
1457                         /*
1458                          * A controversial bit. We hash cleartext
1459                          * passwords provided via add and modify operations
1460                          * You're not really supposed to do this, since
1461                          * the X.500 model says "store attributes" as they
1462                          * get provided. By default, this is what we do
1463                          *
1464                          * But if the hash_passwords flag is set, we hash
1465                          * any cleartext password attribute values via the
1466                          * default password hashing scheme.
1467                          */
1468                 if ((pi->hash_passwords) &&
1469                         (password_scheme( &(pa->a_vals[0]), NULL ) != LDAP_SUCCESS)) {
1470                         struct berval hpw;
1471
1472                         slap_passwd_hash( &(pa->a_vals[0]), &hpw, &txt );
1473                         if (hpw.bv_val == NULL) {
1474                                 /*
1475                                  * hashing didn't work. Emit an error.
1476                                  */
1477                                 rs->sr_err = LDAP_OTHER;
1478                                 rs->sr_text = txt;
1479                                 send_ldap_error( op, rs, LDAP_OTHER, "Password hashing failed" );
1480                                 return rs->sr_err;
1481                         }
1482
1483                         memset( pa->a_vals[0].bv_val, 0, pa->a_vals[0].bv_len);
1484                         ber_memfree( pa->a_vals[0].bv_val );
1485                         pa->a_vals[0].bv_val = hpw.bv_val;
1486                         pa->a_vals[0].bv_len = hpw.bv_len;
1487                 }
1488
1489                 /* If password aging is in effect, set the pwdChangedTime */
1490                 if ( pp.pwdMaxAge || pp.pwdMinAge ) {
1491                         struct berval timestamp;
1492                         char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
1493                         time_t now = slap_get_time();
1494
1495                         timestamp.bv_val = timebuf;
1496                         timestamp.bv_len = sizeof(timebuf);
1497                         slap_timestamp( &now, &timestamp );
1498
1499                         attr_merge_one( op->ora_e, ad_pwdChangedTime, &timestamp, &timestamp );
1500                 }
1501         }
1502         return SLAP_CB_CONTINUE;
1503 }
1504
1505 static int
1506 ppolicy_mod_cb( Operation *op, SlapReply *rs )
1507 {
1508         slap_callback *sc = op->o_callback;
1509         op->o_callback = sc->sc_next;
1510         if ( rs->sr_err == LDAP_SUCCESS ) {
1511                 ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1512                 BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1513         }
1514         op->o_tmpfree( sc, op->o_tmpmemctx );
1515         return SLAP_CB_CONTINUE;
1516 }
1517
1518 static int
1519 ppolicy_modify( Operation *op, SlapReply *rs )
1520 {
1521         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1522         pp_info                 *pi = on->on_bi.bi_private;
1523         int                     i, rc, mod_pw_only, pwmod, pwmop = -1, deladd,
1524                                 hsize = 0;
1525         PassPolicy              pp;
1526         Modifications           *mods = NULL, *modtail = NULL,
1527                                 *ml, *delmod, *addmod;
1528         Attribute               *pa, *ha, at;
1529         const char              *txt;
1530         pw_hist                 *tl = NULL, *p;
1531         int                     zapReset, send_ctrl = 0, free_txt = 0;
1532         Entry                   *e;
1533         struct berval           newpw = BER_BVNULL, oldpw = BER_BVNULL,
1534                                 *bv, cr[2];
1535         LDAPPasswordPolicyError pErr = PP_noError;
1536         LDAPControl             *ctrl = NULL;
1537         LDAPControl             **oldctrls = NULL;
1538         int                     is_pwdexop = 0;
1539
1540         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1541         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1542         op->o_bd->bd_info = (BackendInfo *)on;
1543
1544         if ( rc != LDAP_SUCCESS ) return SLAP_CB_CONTINUE;
1545
1546         /* If this is a replica, we may need to tweak some of the
1547          * master's modifications. Otherwise, just pass it through.
1548          */
1549         if ( be_shadow_update( op )) {
1550                 Modifications **prev;
1551                 int got_del_grace = 0, got_del_lock = 0, got_pw = 0, got_del_fail = 0;
1552                 Attribute *a_grace, *a_lock, *a_fail;
1553
1554                 a_grace = attr_find( e->e_attrs, ad_pwdGraceUseTime );
1555                 a_lock = attr_find( e->e_attrs, ad_pwdAccountLockedTime );
1556                 a_fail = attr_find( e->e_attrs, ad_pwdFailureTime );
1557
1558                 for( prev = &op->orm_modlist, ml = *prev; ml; ml = *prev ) {
1559
1560                         if ( ml->sml_desc == slap_schema.si_ad_userPassword )
1561                                 got_pw = 1;
1562
1563                         /* If we're deleting an attr that didn't exist,
1564                          * drop this delete op
1565                          */
1566                         if ( ml->sml_op == LDAP_MOD_DELETE ) {
1567                                 int drop = 0;
1568
1569                                 if ( ml->sml_desc == ad_pwdGraceUseTime ) {
1570                                         got_del_grace = 1;
1571                                         if ( !a_grace )
1572                                                 drop = 1;
1573                                 } else
1574                                 if ( ml->sml_desc == ad_pwdAccountLockedTime ) {
1575                                         got_del_lock = 1;
1576                                         if ( !a_lock )
1577                                                 drop = 1;
1578                                 } else
1579                                 if ( ml->sml_desc == ad_pwdFailureTime ) {
1580                                         got_del_fail = 1;
1581                                         if ( !a_fail )
1582                                                 drop = 1;
1583                                 }
1584                                 if ( drop ) {
1585                                         *prev = ml->sml_next;
1586                                         ml->sml_next = NULL;
1587                                         slap_mods_free( ml, 1 );
1588                                         continue;
1589                                 }
1590                         }
1591                         prev = &ml->sml_next;
1592                 }
1593
1594                 /* If we're resetting the password, make sure grace, accountlock,
1595                  * and failure also get removed.
1596                  */
1597                 if ( got_pw ) {
1598                         if ( a_grace && !got_del_grace ) {
1599                                 ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
1600                                 ml->sml_op = LDAP_MOD_DELETE;
1601                                 ml->sml_flags = SLAP_MOD_INTERNAL;
1602                                 ml->sml_type.bv_val = NULL;
1603                                 ml->sml_desc = ad_pwdGraceUseTime;
1604                                 ml->sml_numvals = 0;
1605                                 ml->sml_values = NULL;
1606                                 ml->sml_nvalues = NULL;
1607                                 ml->sml_next = NULL;
1608                                 *prev = ml;
1609                                 prev = &ml->sml_next;
1610                         }
1611                         if ( a_lock && !got_del_lock ) {
1612                                 ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
1613                                 ml->sml_op = LDAP_MOD_DELETE;
1614                                 ml->sml_flags = SLAP_MOD_INTERNAL;
1615                                 ml->sml_type.bv_val = NULL;
1616                                 ml->sml_desc = ad_pwdAccountLockedTime;
1617                                 ml->sml_numvals = 0;
1618                                 ml->sml_values = NULL;
1619                                 ml->sml_nvalues = NULL;
1620                                 ml->sml_next = NULL;
1621                                 *prev = ml;
1622                         }
1623                         if ( a_fail && !got_del_fail ) {
1624                                 ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
1625                                 ml->sml_op = LDAP_MOD_DELETE;
1626                                 ml->sml_flags = SLAP_MOD_INTERNAL;
1627                                 ml->sml_type.bv_val = NULL;
1628                                 ml->sml_desc = ad_pwdFailureTime;
1629                                 ml->sml_numvals = 0;
1630                                 ml->sml_values = NULL;
1631                                 ml->sml_nvalues = NULL;
1632                                 ml->sml_next = NULL;
1633                                 *prev = ml;
1634                         }
1635                 }
1636                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1637                 be_entry_release_r( op, e );
1638                 return SLAP_CB_CONTINUE;
1639         }
1640
1641         /* Did we receive a password policy request control? */
1642         if ( op->o_ctrlflag[ppolicy_cid] ) {
1643                 send_ctrl = 1;
1644         }
1645
1646         /* See if this is a pwdModify exop. If so, we can
1647          * access the plaintext passwords from that request.
1648          */
1649         {
1650                 slap_callback *sc;
1651
1652                 for ( sc = op->o_callback; sc; sc=sc->sc_next ) {
1653                         if ( sc->sc_response == slap_null_cb &&
1654                                 sc->sc_private ) {
1655                                 req_pwdexop_s *qpw = sc->sc_private;
1656                                 newpw = qpw->rs_new;
1657                                 oldpw = qpw->rs_old;
1658                                 is_pwdexop = 1;
1659                                 break;
1660                         }
1661                 }
1662         }
1663
1664         ppolicy_get( op, e, &pp );
1665
1666         for ( ml = op->orm_modlist,
1667                         pwmod = 0, mod_pw_only = 1,
1668                         deladd = 0, delmod = NULL,
1669                         addmod = NULL,
1670                         zapReset = 1;
1671                 ml != NULL; modtail = ml, ml = ml->sml_next )
1672         {
1673                 if ( ml->sml_desc == pp.ad ) {
1674                         pwmod = 1;
1675                         pwmop = ml->sml_op;
1676                         if ((deladd == 0) && (ml->sml_op == LDAP_MOD_DELETE) &&
1677                                 (ml->sml_values) && !BER_BVISNULL( &ml->sml_values[0] ))
1678                         {
1679                                 deladd = 1;
1680                                 delmod = ml;
1681                         }
1682
1683                         if ((ml->sml_op == LDAP_MOD_ADD) ||
1684                                 (ml->sml_op == LDAP_MOD_REPLACE))
1685                         {
1686                                 if ( ml->sml_values && !BER_BVISNULL( &ml->sml_values[0] )) {
1687                                         if ( deladd == 1 )
1688                                                 deladd = 2;
1689
1690                                         /* FIXME: there's no easy way to ensure
1691                                          * that add does not cause multiple
1692                                          * userPassword values; one way (that 
1693                                          * would be consistent with the single
1694                                          * password constraint) would be to turn
1695                                          * add into replace); another would be
1696                                          * to disallow add.
1697                                          *
1698                                          * Let's check at least that a single value
1699                                          * is being added
1700                                          */
1701                                         if ( addmod || !BER_BVISNULL( &ml->sml_values[ 1 ] ) ) {
1702                                                 rs->sr_err = LDAP_CONSTRAINT_VIOLATION; 
1703                                                 rs->sr_text = "Password policy only allows one password value";
1704                                                 goto return_results;
1705                                         }
1706
1707                                         addmod = ml;
1708                                 } else {
1709                                         /* replace can have no values, add cannot */
1710                                         assert( ml->sml_op == LDAP_MOD_REPLACE );
1711                                 }
1712                         }
1713
1714                 } else if ( !(ml->sml_flags & SLAP_MOD_INTERNAL) && !is_at_operational( ml->sml_desc->ad_type ) ) {
1715                         mod_pw_only = 0;
1716                         /* modifying something other than password */
1717                 }
1718
1719                 /*
1720                  * If there is a request to explicitly add a pwdReset
1721                  * attribute, then we suppress the normal behaviour on
1722                  * password change, which is to remove the pwdReset
1723                  * attribute.
1724                  *
1725                  * This enables an administrator to assign a new password
1726                  * and place a "must reset" flag on the entry, which will
1727                  * stay until the user explicitly changes his/her password.
1728                  */
1729                 if (ml->sml_desc == ad_pwdReset ) {
1730                         if ((ml->sml_op == LDAP_MOD_ADD) ||
1731                                 (ml->sml_op == LDAP_MOD_REPLACE))
1732                                 zapReset = 0;
1733                 }
1734         }
1735         
1736         if (!BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn ) && !mod_pw_only ) {
1737                 if ( dn_match( &op->o_conn->c_ndn,
1738                                 &pwcons[op->o_conn->c_conn_idx].dn )) {
1739                         Debug( LDAP_DEBUG_TRACE,
1740                                 "connection restricted to password changing only\n", 0, 0, 0 );
1741                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS; 
1742                         rs->sr_text = "Operations are restricted to bind/unbind/abandon/StartTLS/modify password";
1743                         pErr = PP_changeAfterReset;
1744                         goto return_results;
1745                 } else {
1746                         ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1747                         BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1748                 }
1749         }
1750
1751         /*
1752          * if we have a "safe password modify policy", then we need to check if we're doing
1753          * a delete (with the old password), followed by an add (with the new password).
1754          *
1755          * If we got just a delete with nothing else, just let it go. We also skip all the checks if
1756          * the root user is bound. Root can do anything, including avoid the policies.
1757          */
1758
1759         if (!pwmod) goto do_modify;
1760
1761         /*
1762          * Build the password history list in ascending time order
1763          * We need this, even if the user is root, in order to maintain
1764          * the pwdHistory operational attributes properly.
1765          */
1766         if (addmod && pp.pwdInHistory > 0 && (ha = attr_find( e->e_attrs, ad_pwdHistory ))) {
1767                 struct berval oldpw;
1768                 time_t oldtime;
1769
1770                 for(i=0; ha->a_nvals[i].bv_val; i++) {
1771                         rc = parse_pwdhistory( &(ha->a_nvals[i]), NULL,
1772                                 &oldtime, &oldpw );
1773
1774                         if (rc != LDAP_SUCCESS) continue; /* invalid history entry */
1775
1776                         if (oldpw.bv_val) {
1777                                 add_to_pwd_history( &tl, oldtime, &oldpw,
1778                                         &(ha->a_nvals[i]) );
1779                                 oldpw.bv_val = NULL;
1780                                 oldpw.bv_len = 0;
1781                         }
1782                 }
1783                 for(p=tl; p; p=p->next, hsize++); /* count history size */
1784         }
1785
1786         if (be_isroot( op )) goto do_modify;
1787
1788         if (!pp.pwdAllowUserChange) {
1789                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1790                 rs->sr_text = "User alteration of password is not allowed";
1791                 pErr = PP_passwordModNotAllowed;
1792                 goto return_results;
1793         }
1794
1795         /* Just deleting? */
1796         if (!addmod) {
1797                 /* skip everything else */
1798                 pwmod = 0;
1799                 goto do_modify;
1800         }
1801
1802         /* This is a pwdModify exop that provided the old pw.
1803          * We need to create a Delete mod for this old pw and 
1804          * let the matching value get found later
1805          */
1806         if (pp.pwdSafeModify && oldpw.bv_val ) {
1807                 ml = (Modifications *)ch_calloc( sizeof( Modifications ), 1 );
1808                 ml->sml_op = LDAP_MOD_DELETE;
1809                 ml->sml_flags = SLAP_MOD_INTERNAL;
1810                 ml->sml_desc = pp.ad;
1811                 ml->sml_type = pp.ad->ad_cname;
1812                 ml->sml_numvals = 1;
1813                 ml->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
1814                 ber_dupbv( &ml->sml_values[0], &oldpw );
1815                 BER_BVZERO( &ml->sml_values[1] );
1816                 ml->sml_next = op->orm_modlist;
1817                 op->orm_modlist = ml;
1818                 delmod = ml;
1819                 deladd = 2;
1820         }
1821
1822         if (pp.pwdSafeModify && deladd != 2) {
1823                 Debug( LDAP_DEBUG_TRACE,
1824                         "change password must use DELETE followed by ADD/REPLACE\n",
1825                         0, 0, 0 );
1826                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1827                 rs->sr_text = "Must supply old password to be changed as well as new one";
1828                 pErr = PP_mustSupplyOldPassword;
1829                 goto return_results;
1830         }
1831
1832         /* Check age, but only if pwdReset is not TRUE */
1833         pa = attr_find( e->e_attrs, ad_pwdReset );
1834         if ((!pa || !bvmatch( &pa->a_nvals[0], &slap_true_bv )) &&
1835                 pp.pwdMinAge > 0) {
1836                 time_t pwtime = (time_t)-1, now;
1837                 int age;
1838
1839                 if ((pa = attr_find( e->e_attrs, ad_pwdChangedTime )) != NULL)
1840                         pwtime = parse_time( pa->a_nvals[0].bv_val );
1841                 now = slap_get_time();
1842                 age = (int)(now - pwtime);
1843                 if ((pwtime != (time_t)-1) && (age < pp.pwdMinAge)) {
1844                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1845                         rs->sr_text = "Password is too young to change";
1846                         pErr = PP_passwordTooYoung;
1847                         goto return_results;
1848                 }
1849         }
1850
1851         /* pa is used in password history check below, be sure it's set */
1852         if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL && delmod) {
1853                 /*
1854                  * we have a password to check
1855                  */
1856                 bv = oldpw.bv_val ? &oldpw : delmod->sml_values;
1857                 /* FIXME: no access checking? */
1858                 rc = slap_passwd_check( op, NULL, pa, bv, &txt );
1859                 if (rc != LDAP_SUCCESS) {
1860                         Debug( LDAP_DEBUG_TRACE,
1861                                 "old password check failed: %s\n", txt, 0, 0 );
1862                         
1863                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1864                         rs->sr_text = "Must supply correct old password to change to new one";
1865                         pErr = PP_mustSupplyOldPassword;
1866                         goto return_results;
1867
1868                 } else {
1869                         int i;
1870                         
1871                         /*
1872                          * replace the delete value with the (possibly hashed)
1873                          * value which is currently in the password.
1874                          */
1875                         for ( i = 0; !BER_BVISNULL( &delmod->sml_values[i] ); i++ ) {
1876                                 free( delmod->sml_values[i].bv_val );
1877                                 BER_BVZERO( &delmod->sml_values[i] );
1878                         }
1879                         free( delmod->sml_values );
1880                         delmod->sml_values = ch_calloc( sizeof(struct berval), 2 );
1881                         BER_BVZERO( &delmod->sml_values[1] );
1882                         ber_dupbv( &(delmod->sml_values[0]),  &(pa->a_nvals[0]) );
1883                 }
1884         }
1885
1886         bv = newpw.bv_val ? &newpw : &addmod->sml_values[0];
1887         if (pp.pwdCheckQuality > 0) {
1888
1889                 rc = check_password_quality( bv, &pp, &pErr, e, (char **)&txt );
1890                 if (rc != LDAP_SUCCESS) {
1891                         rs->sr_err = rc;
1892                         if ( txt ) {
1893                                 rs->sr_text = txt;
1894                                 free_txt = 1;
1895                         } else {
1896                                 rs->sr_text = "Password fails quality checking policy";
1897                         }
1898                         goto return_results;
1899                 }
1900         }
1901
1902         /* If pwdInHistory is zero, passwords may be reused */
1903         if (pa && pp.pwdInHistory > 0) {
1904                 /*
1905                  * Last check - the password history.
1906                  */
1907                 /* FIXME: no access checking? */
1908                 if (slap_passwd_check( op, NULL, pa, bv, &txt ) == LDAP_SUCCESS) {
1909                         /*
1910                          * This is bad - it means that the user is attempting
1911                          * to set the password to the same as the old one.
1912                          */
1913                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1914                         rs->sr_text = "Password is not being changed from existing value";
1915                         pErr = PP_passwordInHistory;
1916                         goto return_results;
1917                 }
1918         
1919                 /*
1920                  * Iterate through the password history, and fail on any
1921                  * password matches.
1922                  */
1923                 at = *pa;
1924                 at.a_vals = cr;
1925                 cr[1].bv_val = NULL;
1926                 for(p=tl; p; p=p->next) {
1927                         cr[0] = p->pw;
1928                         /* FIXME: no access checking? */
1929                         rc = slap_passwd_check( op, NULL, &at, bv, &txt );
1930                         
1931                         if (rc != LDAP_SUCCESS) continue;
1932                         
1933                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1934                         rs->sr_text = "Password is in history of old passwords";
1935                         pErr = PP_passwordInHistory;
1936                         goto return_results;
1937                 }
1938         }
1939
1940 do_modify:
1941         if (pwmod) {
1942                 struct berval timestamp;
1943                 char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
1944                 time_t now = slap_get_time();
1945
1946                 /* If the conn is restricted, set a callback to clear it
1947                  * if the pwmod succeeds
1948                  */
1949                 if (!BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
1950                         slap_callback *sc = op->o_tmpcalloc( 1, sizeof( slap_callback ),
1951                                 op->o_tmpmemctx );
1952                         sc->sc_next = op->o_callback;
1953                         /* Must use sc_response to insure we reset on success, before
1954                          * the client sees the response. Must use sc_cleanup to insure
1955                          * that it gets cleaned up if sc_response is not called.
1956                          */
1957                         sc->sc_response = ppolicy_mod_cb;
1958                         sc->sc_cleanup = ppolicy_mod_cb;
1959                         op->o_callback = sc;
1960                 }
1961
1962                 /*
1963                  * keep the necessary pwd.. operational attributes
1964                  * up to date.
1965                  */
1966
1967                 timestamp.bv_val = timebuf;
1968                 timestamp.bv_len = sizeof(timebuf);
1969                 slap_timestamp( &now, &timestamp );
1970
1971                 mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1972                 mods->sml_desc = ad_pwdChangedTime;
1973                 if (pwmop != LDAP_MOD_DELETE) {
1974                         mods->sml_op = LDAP_MOD_REPLACE;
1975                         mods->sml_numvals = 1;
1976                         mods->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
1977                         ber_dupbv( &mods->sml_values[0], &timestamp );
1978                         BER_BVZERO( &mods->sml_values[1] );
1979                         assert( !BER_BVISNULL( &mods->sml_values[0] ) );
1980
1981                 } else {
1982                         mods->sml_op = LDAP_MOD_DELETE;
1983                 }
1984                 mods->sml_flags = SLAP_MOD_INTERNAL;
1985                 mods->sml_next = NULL;
1986                 modtail->sml_next = mods;
1987                 modtail = mods;
1988
1989                 if (attr_find(e->e_attrs, ad_pwdGraceUseTime )) {
1990                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1991                         mods->sml_op = LDAP_MOD_DELETE;
1992                         mods->sml_desc = ad_pwdGraceUseTime;
1993                         mods->sml_flags = SLAP_MOD_INTERNAL;
1994                         mods->sml_next = NULL;
1995                         modtail->sml_next = mods;
1996                         modtail = mods;
1997                 }
1998
1999                 if (attr_find(e->e_attrs, ad_pwdAccountLockedTime )) {
2000                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
2001                         mods->sml_op = LDAP_MOD_DELETE;
2002                         mods->sml_desc = ad_pwdAccountLockedTime;
2003                         mods->sml_flags = SLAP_MOD_INTERNAL;
2004                         mods->sml_next = NULL;
2005                         modtail->sml_next = mods;
2006                         modtail = mods;
2007                 }
2008
2009                 if (attr_find(e->e_attrs, ad_pwdFailureTime )) {
2010                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
2011                         mods->sml_op = LDAP_MOD_DELETE;
2012                         mods->sml_desc = ad_pwdFailureTime;
2013                         mods->sml_flags = SLAP_MOD_INTERNAL;
2014                         mods->sml_next = NULL;
2015                         modtail->sml_next = mods;
2016                         modtail = mods;
2017                 }
2018
2019                 /* Delete the pwdReset attribute, since it's being reset */
2020                 if ((zapReset) && (attr_find(e->e_attrs, ad_pwdReset ))) {
2021                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
2022                         mods->sml_op = LDAP_MOD_DELETE;
2023                         mods->sml_desc = ad_pwdReset;
2024                         mods->sml_flags = SLAP_MOD_INTERNAL;
2025                         mods->sml_next = NULL;
2026                         modtail->sml_next = mods;
2027                         modtail = mods;
2028                 }
2029
2030                 if (pp.pwdInHistory > 0) {
2031                         if (hsize >= pp.pwdInHistory) {
2032                                 /*
2033                                  * We use the >= operator, since we are going to add
2034                                  * the existing password attribute value into the
2035                                  * history - thus the cardinality of history values is
2036                                  * about to rise by one.
2037                                  *
2038                                  * If this would push it over the limit of history
2039                                  * values (remembering - the password policy could have
2040                                  * changed since the password was last altered), we must
2041                                  * delete at least 1 value from the pwdHistory list.
2042                                  *
2043                                  * In fact, we delete '(#pwdHistory attrs - max pwd
2044                                  * history length) + 1' values, starting with the oldest.
2045                                  * This is easily evaluated, since the linked list is
2046                                  * created in ascending time order.
2047                                  */
2048                                 mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
2049                                 mods->sml_op = LDAP_MOD_DELETE;
2050                                 mods->sml_flags = SLAP_MOD_INTERNAL;
2051                                 mods->sml_desc = ad_pwdHistory;
2052                                 mods->sml_numvals = hsize - pp.pwdInHistory + 1;
2053                                 mods->sml_values = ch_calloc( sizeof( struct berval ),
2054                                         hsize - pp.pwdInHistory + 2 );
2055                                 BER_BVZERO( &mods->sml_values[ hsize - pp.pwdInHistory + 1 ] );
2056                                 for(i=0,p=tl; i < (hsize - pp.pwdInHistory + 1); i++, p=p->next) {
2057                                         BER_BVZERO( &mods->sml_values[i] );
2058                                         ber_dupbv( &(mods->sml_values[i]), &p->bv );
2059                                 }
2060                                 mods->sml_next = NULL;
2061                                 modtail->sml_next = mods;
2062                                 modtail = mods;
2063                         }
2064                         free_pwd_history_list( &tl );
2065
2066                         /*
2067                          * Now add the existing password into the history list.
2068                          * This will be executed even if the operation is to delete
2069                          * the password entirely.
2070                          *
2071                          * This isn't in the spec explicitly, but it seems to make
2072                          * sense that the password history list is the list of all
2073                          * previous passwords - even if they were deleted. Thus, if
2074                          * someone tries to add a historical password at some future
2075                          * point, it will fail.
2076                          */
2077                         if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL) {
2078                                 mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
2079                                 mods->sml_op = LDAP_MOD_ADD;
2080                                 mods->sml_flags = SLAP_MOD_INTERNAL;
2081                                 mods->sml_type.bv_val = NULL;
2082                                 mods->sml_desc = ad_pwdHistory;
2083                                 mods->sml_nvalues = NULL;
2084                                 mods->sml_numvals = 1;
2085                                 mods->sml_values = ch_calloc( sizeof( struct berval ), 2 );
2086                                 mods->sml_values[ 1 ].bv_val = NULL;
2087                                 mods->sml_values[ 1 ].bv_len = 0;
2088                                 make_pwd_history_value( timebuf, &mods->sml_values[0], pa );
2089                                 mods->sml_next = NULL;
2090                                 modtail->sml_next = mods;
2091                                 modtail = mods;
2092
2093                         } else {
2094                                 Debug( LDAP_DEBUG_TRACE,
2095                                 "ppolicy_modify: password attr lookup failed\n", 0, 0, 0 );
2096                         }
2097                 }
2098
2099                 /*
2100                  * Controversial bit here. If the new password isn't hashed
2101                  * (ie, is cleartext), we probably should hash it according
2102                  * to the default hash. The reason for this is that we want
2103                  * to use the policy if possible, but if we hash the password
2104                  * before, then we're going to run into trouble when it
2105                  * comes time to check the password.
2106                  *
2107                  * Now, the right thing to do is to use the extended password
2108                  * modify operation, but not all software can do this,
2109                  * therefore it makes sense to hash the new password, now
2110                  * we know it passes the policy requirements.
2111                  *
2112                  * Of course, if the password is already hashed, then we
2113                  * leave it alone.
2114                  */
2115
2116                 if ((pi->hash_passwords) && (addmod) && !newpw.bv_val && 
2117                         (password_scheme( &(addmod->sml_values[0]), NULL ) != LDAP_SUCCESS))
2118                 {
2119                         struct berval hpw, bv;
2120                         
2121                         slap_passwd_hash( &(addmod->sml_values[0]), &hpw, &txt );
2122                         if (hpw.bv_val == NULL) {
2123                                         /*
2124                                          * hashing didn't work. Emit an error.
2125                                          */
2126                                 rs->sr_err = LDAP_OTHER;
2127                                 rs->sr_text = txt;
2128                                 goto return_results;
2129                         }
2130                         bv = addmod->sml_values[0];
2131                                 /* clear and discard the clear password */
2132                         memset(bv.bv_val, 0, bv.bv_len);
2133                         ber_memfree(bv.bv_val);
2134                         addmod->sml_values[0] = hpw;
2135                 }
2136         }
2137         op->o_bd->bd_info = (BackendInfo *)on->on_info;
2138         be_entry_release_r( op, e );
2139         return SLAP_CB_CONTINUE;
2140
2141 return_results:
2142         free_pwd_history_list( &tl );
2143         op->o_bd->bd_info = (BackendInfo *)on->on_info;
2144         be_entry_release_r( op, e );
2145         if ( send_ctrl ) {
2146                 ctrl = create_passcontrol( op, -1, -1, pErr );
2147                 oldctrls = add_passcontrol( op, rs, ctrl );
2148         }
2149         send_ldap_result( op, rs );
2150         if ( free_txt ) {
2151                 free( (char *)txt );
2152                 rs->sr_text = NULL;
2153         }
2154         if ( send_ctrl ) {
2155                 if ( is_pwdexop ) {
2156                         if ( rs->sr_flags & REP_CTRLS_MUSTBEFREED ) {
2157                                 op->o_tmpfree( oldctrls, op->o_tmpmemctx );
2158                         }
2159                         oldctrls = NULL;
2160                         rs->sr_flags |= REP_CTRLS_MUSTBEFREED;
2161
2162                 } else {
2163                         ctrls_cleanup( op, rs, oldctrls );
2164                 }
2165         }
2166         return rs->sr_err;
2167 }
2168
2169 static int
2170 ppolicy_parseCtrl(
2171         Operation *op,
2172         SlapReply *rs,
2173         LDAPControl *ctrl )
2174 {
2175         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
2176                 rs->sr_text = "passwordPolicyRequest control value not absent";
2177                 return LDAP_PROTOCOL_ERROR;
2178         }
2179         op->o_ctrlflag[ppolicy_cid] = ctrl->ldctl_iscritical
2180                 ? SLAP_CONTROL_CRITICAL
2181                 : SLAP_CONTROL_NONCRITICAL;
2182
2183         return LDAP_SUCCESS;
2184 }
2185
2186 static int
2187 attrPretty(
2188         Syntax *syntax,
2189         struct berval *val,
2190         struct berval *out,
2191         void *ctx )
2192 {
2193         AttributeDescription *ad = NULL;
2194         const char *err;
2195         int code;
2196
2197         code = slap_bv2ad( val, &ad, &err );
2198         if ( !code ) {
2199                 ber_dupbv_x( out, &ad->ad_type->sat_cname, ctx );
2200         }
2201         return code;
2202 }
2203
2204 static int
2205 attrNormalize(
2206         slap_mask_t use,
2207         Syntax *syntax,
2208         MatchingRule *mr,
2209         struct berval *val,
2210         struct berval *out,
2211         void *ctx )
2212 {
2213         AttributeDescription *ad = NULL;
2214         const char *err;
2215         int code;
2216
2217         code = slap_bv2ad( val, &ad, &err );
2218         if ( !code ) {
2219                 ber_str2bv_x( ad->ad_type->sat_oid, 0, 1, out, ctx );
2220         }
2221         return code;
2222 }
2223
2224 static int
2225 ppolicy_db_init(
2226         BackendDB *be,
2227         ConfigReply *cr
2228 )
2229 {
2230         slap_overinst *on = (slap_overinst *) be->bd_info;
2231
2232         if ( SLAP_ISGLOBALOVERLAY( be ) ) {
2233                 /* do not allow slapo-ppolicy to be global by now (ITS#5858) */
2234                 if ( cr ){
2235                         snprintf( cr->msg, sizeof(cr->msg), 
2236                                 "slapo-ppolicy cannot be global" );
2237                         fprintf( stderr, "%s\n", cr->msg );
2238                 }
2239                 return 1;
2240         }
2241
2242         /* Has User Schema been initialized yet? */
2243         if ( !pwd_UsSchema[0].ad[0] ) {
2244                 const char *err;
2245                 int i, code;
2246
2247                 for (i=0; pwd_UsSchema[i].def; i++) {
2248                         code = slap_str2ad( pwd_UsSchema[i].def, pwd_UsSchema[i].ad, &err );
2249                         if ( code ) {
2250                                 if ( cr ){
2251                                         snprintf( cr->msg, sizeof(cr->msg), 
2252                                                 "User Schema load failed for attribute \"%s\". Error code %d: %s",
2253                                                 pwd_UsSchema[i].def, code, err );
2254                                         fprintf( stderr, "%s\n", cr->msg );
2255                                 }
2256                                 return code;
2257                         }
2258                 }
2259                 {
2260                         Syntax *syn;
2261                         MatchingRule *mr;
2262
2263                         syn = ch_malloc( sizeof( Syntax ));
2264                         *syn = *ad_pwdAttribute->ad_type->sat_syntax;
2265                         syn->ssyn_pretty = attrPretty;
2266                         ad_pwdAttribute->ad_type->sat_syntax = syn;
2267
2268                         mr = ch_malloc( sizeof( MatchingRule ));
2269                         *mr = *ad_pwdAttribute->ad_type->sat_equality;
2270                         mr->smr_normalize = attrNormalize;
2271                         ad_pwdAttribute->ad_type->sat_equality = mr;
2272                 }
2273         }
2274
2275         on->on_bi.bi_private = ch_calloc( sizeof(pp_info), 1 );
2276
2277         if ( dtblsize && !pwcons ) {
2278                 /* accommodate for c_conn_idx == -1 */
2279                 pwcons = ch_calloc( sizeof(pw_conn), dtblsize + 1 );
2280                 pwcons++;
2281         }
2282
2283         return 0;
2284 }
2285
2286 static int
2287 ppolicy_db_open(
2288         BackendDB *be,
2289         ConfigReply *cr
2290 )
2291 {
2292         ov_count++;
2293         return overlay_register_control( be, LDAP_CONTROL_PASSWORDPOLICYREQUEST );
2294 }
2295
2296 static int
2297 ppolicy_close(
2298         BackendDB *be,
2299         ConfigReply *cr
2300 )
2301 {
2302         slap_overinst *on = (slap_overinst *) be->bd_info;
2303         pp_info *pi = on->on_bi.bi_private;
2304
2305         /* Perhaps backover should provide bi_destroy hooks... */
2306         ov_count--;
2307         if ( ov_count <=0 && pwcons ) {
2308                 pwcons--;
2309                 free( pwcons );
2310                 pwcons = NULL;
2311         }
2312         free( pi->def_policy.bv_val );
2313         free( pi );
2314
2315         return 0;
2316 }
2317
2318 static char *extops[] = {
2319         LDAP_EXOP_MODIFY_PASSWD,
2320         NULL
2321 };
2322
2323 static slap_overinst ppolicy;
2324
2325 int ppolicy_initialize()
2326 {
2327         int i, code;
2328
2329         for (i=0; pwd_OpSchema[i].def; i++) {
2330                 code = register_at( pwd_OpSchema[i].def, pwd_OpSchema[i].ad, 0 );
2331                 if ( code ) {
2332                         Debug( LDAP_DEBUG_ANY,
2333                                 "ppolicy_initialize: register_at failed\n", 0, 0, 0 );
2334                         return code;
2335                 }
2336                 /* Allow Manager to set these as needed */
2337                 if ( is_at_no_user_mod( (*pwd_OpSchema[i].ad)->ad_type )) {
2338                         (*pwd_OpSchema[i].ad)->ad_type->sat_flags |=
2339                                 SLAP_AT_MANAGEABLE;
2340                 }
2341         }
2342
2343         code = register_supported_control( LDAP_CONTROL_PASSWORDPOLICYREQUEST,
2344                 SLAP_CTRL_ADD|SLAP_CTRL_BIND|SLAP_CTRL_MODIFY|SLAP_CTRL_HIDE, extops,
2345                 ppolicy_parseCtrl, &ppolicy_cid );
2346         if ( code != LDAP_SUCCESS ) {
2347                 fprintf( stderr, "Failed to register control %d\n", code );
2348                 return code;
2349         }
2350
2351         ldap_pvt_thread_mutex_init( &chk_syntax_mutex );
2352
2353         ppolicy.on_bi.bi_type = "ppolicy";
2354         ppolicy.on_bi.bi_db_init = ppolicy_db_init;
2355         ppolicy.on_bi.bi_db_open = ppolicy_db_open;
2356         ppolicy.on_bi.bi_db_close = ppolicy_close;
2357
2358         ppolicy.on_bi.bi_op_add = ppolicy_add;
2359         ppolicy.on_bi.bi_op_bind = ppolicy_bind;
2360         ppolicy.on_bi.bi_op_compare = ppolicy_compare;
2361         ppolicy.on_bi.bi_op_delete = ppolicy_restrict;
2362         ppolicy.on_bi.bi_op_modify = ppolicy_modify;
2363         ppolicy.on_bi.bi_op_search = ppolicy_restrict;
2364         ppolicy.on_bi.bi_connection_destroy = ppolicy_connection_destroy;
2365
2366         ppolicy.on_bi.bi_cf_ocs = ppolicyocs;
2367         code = config_register_schema( ppolicycfg, ppolicyocs );
2368         if ( code ) return code;
2369
2370         return overlay_register( &ppolicy );
2371 }
2372
2373 #if SLAPD_OVER_PPOLICY == SLAPD_MOD_DYNAMIC
2374 int init_module(int argc, char *argv[]) {
2375         return ppolicy_initialize();
2376 }
2377 #endif
2378
2379 #endif  /* defined(SLAPD_OVER_PPOLICY) */