]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/ppolicy.c
ACIs almost entirely factored out of slapd
[openldap] / servers / slapd / overlays / ppolicy.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 2004-2005 The OpenLDAP Foundation.
5  * Portions Copyright 2004 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-08
27  */
28
29 #ifdef SLAPD_OVER_PPOLICY
30
31 #include <ldap.h>
32 #include "lutil.h"
33 #include "slap.h"
34 #if 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
43 #ifndef MODULE_NAME_SZ
44 #define MODULE_NAME_SZ 256
45 #endif
46
47 /* Per-instance configuration information */
48 typedef struct pp_info {
49         struct berval def_policy;       /* DN of default policy subentry */
50         int use_lockout;                /* send AccountLocked result? */
51         int hash_passwords;             /* transparently hash cleartext pwds */
52 } pp_info;
53
54 /* Our per-connection info - note, it is not per-instance, it is 
55  * used by all instances
56  */
57 typedef struct pw_conn {
58         int restricted;         /* TRUE if connection is restricted */
59 } pw_conn;
60
61 static pw_conn *pwcons;
62 static int ppolicy_cid;
63
64 typedef struct pass_policy {
65         AttributeDescription *ad; /* attribute to which the policy applies */
66         int pwdMinAge; /* minimum time (seconds) until passwd can change */
67         int pwdMaxAge; /* time in seconds until pwd will expire after change */
68         int pwdInHistory; /* number of previous passwords kept */
69         int pwdCheckQuality; /* 0 = don't check quality, 1 = check if possible,
70                                                    2 = check mandatory; fail if not possible */
71         int pwdMinLength; /* minimum number of chars in password */
72         int pwdExpireWarning; /* number of seconds that warning controls are
73                                                         sent before a password expires */
74         int pwdGraceAuthNLimit; /* number of times you can log in with an
75                                                         expired password */
76         int pwdLockout; /* 0 = do not lockout passwords, 1 = lock them out */
77         int pwdLockoutDuration; /* time in seconds a password is locked out for */
78         int pwdMaxFailure; /* number of failed binds allowed before lockout */
79         int pwdFailureCountInterval; /* number of seconds before failure
80                                                                         counts are zeroed */
81         int pwdMustChange; /* 0 = users can use admin set password
82                                                         1 = users must change password after admin set */
83         int pwdAllowUserChange; /* 0 = users cannot change their passwords
84                                                                 1 = users can change them */
85         int pwdSafeModify; /* 0 = old password doesn't need to come
86                                                                 with password change request
87                                                         1 = password change must supply existing pwd */
88         char pwdCheckModule[MODULE_NAME_SZ]; /* name of module to dynamically
89                                                                                     load to check password */
90 } PassPolicy;
91
92 typedef struct pw_hist {
93         time_t t;       /* timestamp of history entry */
94         struct berval pw;       /* old password hash */
95         struct berval bv;       /* text of entire entry */
96         struct pw_hist *next;
97 } pw_hist;
98
99 /* Operational attributes */
100 static AttributeDescription *ad_pwdChangedTime, *ad_pwdAccountLockedTime,
101         *ad_pwdFailureTime, *ad_pwdHistory, *ad_pwdGraceUseTime, *ad_pwdReset,
102         *ad_pwdPolicySubentry;
103
104 static struct schema_info {
105         char *def;
106         AttributeDescription **ad;
107 } pwd_OpSchema[] = {
108         {       "( 1.3.6.1.4.1.42.2.27.8.1.16 "
109                 "NAME ( 'pwdChangedTime' ) "
110                 "DESC 'The time the password was last changed' "
111                 "EQUALITY generalizedTimeMatch "
112                 "ORDERING generalizedTimeOrderingMatch "
113                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
114                 "SINGLE-VALUE USAGE directoryOperation NO-USER-MODIFICATION )",
115                 &ad_pwdChangedTime },
116         {       "( 1.3.6.1.4.1.42.2.27.8.1.17 "
117                 "NAME ( 'pwdAccountLockedTime' ) "
118                 "DESC 'The time an user account was locked' "
119                 "EQUALITY generalizedTimeMatch "
120                 "ORDERING generalizedTimeOrderingMatch "
121                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
122                 "SINGLE-VALUE USAGE directoryOperation )",
123                 &ad_pwdAccountLockedTime },
124         {       "( 1.3.6.1.4.1.42.2.27.8.1.19 "
125                 "NAME ( 'pwdFailureTime' ) "
126                 "DESC 'The timestamps of the last consecutive authentication failures' "
127                 "EQUALITY generalizedTimeMatch "
128                 "ORDERING generalizedTimeOrderingMatch "
129                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
130                 "USAGE directoryOperation )",
131                 &ad_pwdFailureTime },
132         {       "( 1.3.6.1.4.1.42.2.27.8.1.20 "
133                 "NAME ( 'pwdHistory' ) "
134                 "DESC 'The history of users passwords' "
135                 "EQUALITY octetStringMatch "
136                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.40 "
137                 "USAGE directoryOperation NO-USER-MODIFICATION )",
138                 &ad_pwdHistory },
139         {       "( 1.3.6.1.4.1.42.2.27.8.1.21 "
140                 "NAME ( 'pwdGraceUseTime' ) "
141                 "DESC 'The timestamps of the grace login once the password has expired' "
142                 "EQUALITY generalizedTimeMatch "
143                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.24 "
144                 "USAGE directoryOperation NO-USER-MODIFICATION )",
145                 &ad_pwdGraceUseTime }, 
146         {       "( 1.3.6.1.4.1.42.2.27.8.1.22 "
147                 "NAME ( 'pwdReset' ) "
148                 "DESC 'The indication that the password has been reset' "
149                 "EQUALITY booleanMatch "
150                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.7 "
151                 "SINGLE-VALUE USAGE directoryOperation )",
152                 &ad_pwdReset },
153         {       "( 1.3.6.1.4.1.42.2.27.8.1.23 "
154                 "NAME ( 'pwdPolicySubentry' ) "
155                 "DESC 'The pwdPolicy subentry in effect for this object' "
156                 "EQUALITY distinguishedNameMatch "
157                 "SYNTAX 1.3.6.1.4.1.1466.115.121.1.12 "
158                 "SINGLE-VALUE USAGE directoryOperation )",
159                 &ad_pwdPolicySubentry },
160         { NULL, NULL }
161 };
162
163 /* User attributes */
164 static AttributeDescription *ad_pwdMinAge, *ad_pwdMaxAge, *ad_pwdInHistory,
165         *ad_pwdCheckQuality, *ad_pwdMinLength, *ad_pwdMaxFailure, 
166         *ad_pwdGraceAuthNLimit, *ad_pwdExpireWarning, *ad_pwdLockoutDuration,
167         *ad_pwdFailureCountInterval, *ad_pwdCheckModule, *ad_pwdLockout,
168         *ad_pwdMustChange, *ad_pwdAllowUserChange, *ad_pwdSafeModify,
169         *ad_pwdAttribute;
170
171 #define TAB(name)       { #name, &ad_##name }
172
173 static struct schema_info pwd_UsSchema[] = {
174         TAB(pwdAttribute),
175         TAB(pwdMinAge),
176         TAB(pwdMaxAge),
177         TAB(pwdInHistory),
178         TAB(pwdCheckQuality),
179         TAB(pwdMinLength),
180         TAB(pwdMaxFailure),
181         TAB(pwdGraceAuthNLimit),
182         TAB(pwdExpireWarning),
183         TAB(pwdLockout),
184         TAB(pwdLockoutDuration),
185         TAB(pwdFailureCountInterval),
186         TAB(pwdCheckModule),
187         TAB(pwdMustChange),
188         TAB(pwdAllowUserChange),
189         TAB(pwdSafeModify),
190         { NULL, NULL }
191 };
192
193 static ldap_pvt_thread_mutex_t chk_syntax_mutex;
194
195 static time_t
196 parse_time( char *atm )
197 {
198         struct lutil_tm tm;
199         struct lutil_timet tt;
200         time_t ret = (time_t)-1;
201
202         if ( lutil_parsetime( atm, &tm ) == 0) {
203                 lutil_tm2time( &tm, &tt );
204                 ret = tt.tt_sec;
205         }
206         return ret;
207 }
208
209 static int
210 account_locked( Operation *op, Entry *e,
211                 PassPolicy *pp, Modifications **mod ) 
212 {
213         Attribute       *la;
214
215         assert(mod != NULL);
216
217         if ( (la = attr_find( e->e_attrs, ad_pwdAccountLockedTime )) != NULL ) {
218                 BerVarray vals = la->a_nvals;
219
220                 /*
221                  * there is a lockout stamp - we now need to know if it's
222                  * a valid one.
223                  */
224                 if (vals[0].bv_val != NULL) {
225                         time_t then, now;
226                         Modifications *m;
227
228                         if (!pp->pwdLockoutDuration)
229                                 return 1;
230
231                         if ((then = parse_time( vals[0].bv_val )) == (time_t)0)
232                                 return 1;
233
234                         now = slap_get_time();
235
236                         if (now < then + pp->pwdLockoutDuration)
237                                 return 1;
238
239                         m = ch_calloc( sizeof(Modifications), 1 );
240                         m->sml_op = LDAP_MOD_DELETE;
241                         m->sml_flags = 0;
242                         m->sml_type = ad_pwdAccountLockedTime->ad_cname;
243                         m->sml_desc = ad_pwdAccountLockedTime;
244                         m->sml_next = *mod;
245                         *mod = m;
246                 }
247         }
248
249         return 0;
250 }
251
252 #define PPOLICY_WARNING 0xa0L
253 #define PPOLICY_ERROR 0xa1L
254  
255 #define PPOLICY_EXPIRE 0xa0L
256 #define PPOLICY_GRACE  0xa1L
257
258 static LDAPControl *
259 create_passcontrol( int exptime, int grace, LDAPPasswordPolicyError err )
260 {
261         char berbuf[LBER_ELEMENT_SIZEOF], bb2[LBER_ELEMENT_SIZEOF];
262         BerElement *ber = (BerElement *)berbuf, *b2 = (BerElement *)bb2;
263         LDAPControl *c;
264         struct berval bv;
265
266         if ((c = ch_calloc( sizeof( LDAPControl ), 1 )) == NULL) return NULL;
267         c->ldctl_oid = LDAP_CONTROL_PASSWORDPOLICYRESPONSE;
268         c->ldctl_iscritical = 0;
269         c->ldctl_value.bv_val = NULL;
270         c->ldctl_value.bv_len = 0;
271
272         ber_init2( ber, NULL, LBER_USE_DER );
273         ber_printf(ber, "{" /*}*/ );
274
275         if (exptime >= 0) {
276                 ber_init2( b2, NULL, LBER_USE_DER );
277                 ber_printf( b2, "ti", PPOLICY_EXPIRE, exptime );
278                 ber_flatten2( b2, &bv, 1 );
279                 ber_printf( ber, "tO", PPOLICY_WARNING, &bv );
280                 ch_free( bv.bv_val );
281         } else if (grace > 0) {
282                 ber_init2( b2, NULL, LBER_USE_DER );
283                 ber_printf( b2, "ti", PPOLICY_GRACE, grace );
284                 ber_flatten2( b2, &bv, 1 );
285                 ber_printf( ber, "tO", PPOLICY_WARNING, &bv );
286                 ch_free( bv.bv_val );
287         }
288
289         if (err != PP_noError ) {
290                 ber_printf( ber, "te", PPOLICY_ERROR, err );
291         }
292         ber_printf( ber, /*{*/ "N}" );
293
294         if (ber_flatten2( ber, &(c->ldctl_value), 1 ) == LBER_DEFAULT) {
295                 ch_free(c);
296                 (void)ber_free_buf(ber);
297                 return NULL;
298         }
299         (void)ber_free_buf(ber);
300         return c;
301 }
302
303 static void
304 ppolicy_get( Operation *op, Entry *e, PassPolicy *pp )
305 {
306         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
307         pp_info *pi = on->on_bi.bi_private;
308         Attribute *a;
309         BerVarray vals;
310         int rc;
311         Entry *pe = NULL;
312 #if 0
313         const char *text;
314 #endif
315
316         memset( pp, 0, sizeof(PassPolicy) );
317
318         /* Users can change their own password by default */
319         pp->pwdAllowUserChange = 1;
320
321         if ((a = attr_find( e->e_attrs, ad_pwdPolicySubentry )) == NULL) {
322                 /*
323                  * entry has no password policy assigned - use default
324                  */
325                 vals = &pi->def_policy;
326                 if ( !vals->bv_val )
327                         goto defaultpol;
328         } else {
329                 vals = a->a_nvals;
330                 if (vals[0].bv_val == NULL) {
331                         Debug( LDAP_DEBUG_ANY,
332                                 "ppolicy_get: NULL value for policySubEntry\n", 0, 0, 0 );
333                         goto defaultpol;
334                 }
335         }
336
337         op->o_bd->bd_info = (BackendInfo *)on->on_info;
338         rc = be_entry_get_rw( op, vals, NULL, NULL, 0, &pe );
339         op->o_bd->bd_info = (BackendInfo *)on;
340
341         if ( rc ) goto defaultpol;
342
343 #if 0   /* Only worry about userPassword for now */
344         if ((a = attr_find( pe->e_attrs, ad_pwdAttribute )))
345                 slap_bv2ad( &a->a_vals[0], &pp->ad, &text );
346 #else
347         pp->ad = slap_schema.si_ad_userPassword;
348 #endif
349
350         if ((a = attr_find( pe->e_attrs, ad_pwdMinAge )))
351                 pp->pwdMinAge = atoi(a->a_vals[0].bv_val );
352         if ((a = attr_find( pe->e_attrs, ad_pwdMaxAge )))
353                 pp->pwdMaxAge = atoi(a->a_vals[0].bv_val );
354         if ((a = attr_find( pe->e_attrs, ad_pwdInHistory )))
355                 pp->pwdInHistory = atoi(a->a_vals[0].bv_val );
356         if ((a = attr_find( pe->e_attrs, ad_pwdCheckQuality )))
357                 pp->pwdCheckQuality = atoi(a->a_vals[0].bv_val );
358         if ((a = attr_find( pe->e_attrs, ad_pwdMinLength )))
359                 pp->pwdMinLength = atoi(a->a_vals[0].bv_val );
360         if ((a = attr_find( pe->e_attrs, ad_pwdMaxFailure )))
361                 pp->pwdMaxFailure = atoi(a->a_vals[0].bv_val );
362         if ((a = attr_find( pe->e_attrs, ad_pwdGraceAuthNLimit )))
363                 pp->pwdGraceAuthNLimit = atoi(a->a_vals[0].bv_val );
364         if ((a = attr_find( pe->e_attrs, ad_pwdExpireWarning )))
365                 pp->pwdExpireWarning = atoi(a->a_vals[0].bv_val );
366         if ((a = attr_find( pe->e_attrs, ad_pwdFailureCountInterval )))
367                 pp->pwdFailureCountInterval = atoi(a->a_vals[0].bv_val );
368         if ((a = attr_find( pe->e_attrs, ad_pwdLockoutDuration )))
369                 pp->pwdLockoutDuration = atoi(a->a_vals[0].bv_val );
370
371         if ((a = attr_find( pe->e_attrs, ad_pwdCheckModule ))) {
372                 strncpy(pp->pwdCheckModule, a->a_vals[0].bv_val,
373                         sizeof(pp->pwdCheckModule));
374                 pp->pwdCheckModule[sizeof(pp->pwdCheckModule)-1] = '\0';
375         }
376
377         if ((a = attr_find( pe->e_attrs, ad_pwdLockout )))
378         pp->pwdLockout = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
379         if ((a = attr_find( pe->e_attrs, ad_pwdMustChange )))
380         pp->pwdMustChange = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
381         if ((a = attr_find( pe->e_attrs, ad_pwdAllowUserChange )))
382         pp->pwdAllowUserChange = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
383         if ((a = attr_find( pe->e_attrs, ad_pwdSafeModify )))
384         pp->pwdSafeModify = !strcmp( a->a_nvals[0].bv_val, "TRUE" );
385     
386         op->o_bd->bd_info = (BackendInfo *)on->on_info;
387         be_entry_release_r( op, pe );
388         op->o_bd->bd_info = (BackendInfo *)on;
389
390         return;
391
392 defaultpol:
393         Debug( LDAP_DEBUG_ANY,
394                 "ppolicy_get: using default policy\n", 0, 0, 0 );
395         return;
396 }
397
398 static int
399 password_scheme( struct berval *cred, struct berval *sch )
400 {
401         int e;
402     
403         assert( cred != NULL );
404
405         if (sch) {
406                 sch->bv_val = NULL;
407                 sch->bv_len = 0;
408         }
409     
410         if ((cred->bv_len == 0) || (cred->bv_val == NULL) ||
411                 (cred->bv_val[0] != '{')) return LDAP_OTHER;
412
413         for(e = 1; cred->bv_val[e] && cred->bv_val[e] != '}'; e++);
414         if (cred->bv_val[e]) {
415                 int rc;
416                 rc = lutil_passwd_scheme( cred->bv_val );
417                 if (rc && sch) {
418                         sch->bv_val = cred->bv_val;
419                         sch->bv_len = e;
420                         return LDAP_SUCCESS;
421                 }
422         }
423         return LDAP_OTHER;
424 }
425
426 static int
427 check_password_quality( struct berval *cred, PassPolicy *pp, LDAPPasswordPolicyError *err, Entry *e )
428 {
429         int rc = LDAP_SUCCESS, ok = LDAP_SUCCESS;
430         char *ptr = cred->bv_val;
431         struct berval sch;
432
433         assert( cred != NULL );
434         assert( pp != NULL );
435
436         if ((cred->bv_len == 0) || (pp->pwdMinLength > cred->bv_len)) {
437                 rc = LDAP_CONSTRAINT_VIOLATION;
438                 if ( err ) *err = PP_passwordTooShort;
439                 return rc;
440         }
441
442         /*
443          * We need to know if the password is already hashed - if so
444          * what scheme is it. The reason being that the "hash" of
445          * {cleartext} still allows us to check the password.
446          */
447         rc = password_scheme( cred, &sch );
448         if (rc == LDAP_SUCCESS) {
449                 if ((sch.bv_val) && (strncasecmp( sch.bv_val, "{cleartext}",
450                         sch.bv_len ) == 0)) {
451                         /*
452                          * We can check the cleartext "hash"
453                          */
454                         ptr = cred->bv_val + sch.bv_len;
455                 } else {
456                         /* everything else, we can't check */
457                         if (pp->pwdCheckQuality == 2) {
458                                 rc = LDAP_CONSTRAINT_VIOLATION;
459                                 if (err) *err = PP_insufficientPasswordQuality;
460                                 return rc;
461                         }
462                         /*
463                          * We can't check the syntax of the password, but it's not
464                          * mandatory (according to the policy), so we return success.
465                          */
466                     
467                         return LDAP_SUCCESS;
468                 }
469         }
470
471         rc = LDAP_SUCCESS;
472
473         if (pp->pwdCheckModule[0]) {
474 #if SLAPD_MODULES
475                 lt_dlhandle mod;
476                 const char *err;
477                 
478                 if ((mod = lt_dlopen( pp->pwdCheckModule )) == NULL) {
479                         err = lt_dlerror();
480
481                         Debug(LDAP_DEBUG_ANY,
482                         "check_password_quality: lt_dlopen failed: (%s) %s.\n",
483                                 pp->pwdCheckModule, err, 0 );
484                         ok = LDAP_OTHER; /* internal error */
485                 } else {
486                         int (*prog)( char *passwd, char **text, Entry *ent );
487
488                         if ((prog = lt_dlsym( mod, "check_password" )) == NULL) {
489                                 err = lt_dlerror();
490                             
491                                 Debug(LDAP_DEBUG_ANY,
492                                         "check_password_quality: lt_dlsym failed: (%s) %s.\n",
493                                         pp->pwdCheckModule, err, 0 );
494                                 ok = LDAP_OTHER;
495                         } else {
496                                 char *txt = NULL;
497
498                                 ldap_pvt_thread_mutex_lock( &chk_syntax_mutex );
499                                 ok = prog( cred->bv_val, &txt, e );
500                                 ldap_pvt_thread_mutex_unlock( &chk_syntax_mutex );
501                                 if (txt) {
502                                         Debug(LDAP_DEBUG_ANY,
503                                                 "check_password_quality: module error: (%s) %s.[%d]\n",
504                                                 pp->pwdCheckModule, txt, ok );
505                                         free(txt);
506                                 } else
507                                         ok = LDAP_SUCCESS;
508                         }
509                             
510                         lt_dlclose( mod );
511                 }
512 #else
513         Debug(LDAP_DEBUG_ANY, "check_password_quality: external modules not "
514                 "supported. pwdCheckModule ignored.\n", 0, 0, 0);
515 #endif /* SLAPD_MODULES */
516         }
517                 
518                     
519         if (ok != LDAP_SUCCESS) {
520                 rc = LDAP_CONSTRAINT_VIOLATION;
521                 if (err) *err = PP_insufficientPasswordQuality;
522         }
523         
524         return rc;
525 }
526
527 static int
528 parse_pwdhistory( struct berval *bv, char **oid, time_t *oldtime, struct berval *oldpw )
529 {
530         char *ptr;
531         struct berval nv, npw;
532         int i, j;
533         
534         assert (bv && (bv->bv_len > 0) && (bv->bv_val) && oldtime && oldpw );
535
536         if ( oid ) *oid = 0;
537         *oldtime = (time_t)-1;
538         oldpw->bv_val = NULL;
539         oldpw->bv_len = 0;
540         
541         ber_dupbv( &nv, bv );
542
543         /* first get the time field */
544         for(i=0; (i < nv.bv_len) && (nv.bv_val[i] != '#'); i++);
545         if ( i == nv.bv_len) goto exit_failure; /* couldn't locate the '#' separator */
546         nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
547         ptr = nv.bv_val;
548         *oldtime = parse_time( ptr );
549         if (*oldtime == (time_t)-1) goto exit_failure;
550
551         /* get the OID field */
552         for(ptr = &(nv.bv_val[i]);(i < nv.bv_len) && (nv.bv_val[i] != '#'); i++);
553         if ( i == nv.bv_len) goto exit_failure; /* couldn't locate the '#' separator */
554         nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
555         if ( oid ) *oid = ber_strdup( ptr );
556         
557         /* get the length field */
558         for(ptr = &(nv.bv_val[i]);(i < nv.bv_len) && (nv.bv_val[i] != '#'); i++);
559         if ( i == nv.bv_len) goto exit_failure; /* couldn't locate the '#' separator */
560         nv.bv_val[i++] = '\0'; /* terminate the string & move to next field */
561         oldpw->bv_len = strtol( ptr, NULL, 10 );
562         if (errno == ERANGE) goto exit_failure;
563
564         /* lastly, get the octets of the string */
565         for(j=i, ptr = &(nv.bv_val[i]);i < nv.bv_len; i++);
566         if (i-j != oldpw->bv_len) goto exit_failure; /* length is wrong */
567
568         npw.bv_val = ptr;
569         npw.bv_len = oldpw->bv_len;
570         ber_dupbv( oldpw, &npw );
571         
572         return LDAP_SUCCESS;
573 exit_failure:
574         if (oid && *oid) { ber_memfree(*oid); *oid = NULL; }
575         if (oldpw->bv_val) {
576                 ber_memfree( oldpw->bv_val); oldpw->bv_val = NULL;
577                 oldpw->bv_len = 0;
578         }
579         ber_memfree(nv.bv_val);
580         return LDAP_OTHER;
581 }
582
583 static void
584 add_to_pwd_history( pw_hist **l, time_t t,
585                     struct berval *oldpw, struct berval *bv )
586 {
587         pw_hist *p, *p1, *p2;
588     
589         if (!l) return;
590
591         p = ch_malloc( sizeof( pw_hist ));
592         p->pw = *oldpw;
593         ber_dupbv( &p->bv, bv );
594         p->t = t;
595         p->next = NULL;
596         
597         if (*l == NULL) {
598                 /* degenerate case */
599                 *l = p;
600                 return;
601         }
602         /*
603          * advance p1 and p2 such that p1 is the node before the
604          * new one, and p2 is the node after it
605          */
606         for (p1 = NULL, p2 = *l; p2 && p2->t <= t; p1 = p2, p2=p2->next );
607         p->next = p2;
608         if (p1 == NULL) { *l = p; return; }
609         p1->next = p;
610 }
611
612 #ifndef MAX_PWD_HISTORY_SZ
613 #define MAX_PWD_HISTORY_SZ 1024
614 #endif /* MAX_PWD_HISTORY_SZ */
615
616 static void
617 make_pwd_history_value( char *timebuf, struct berval *bv, Attribute *pa )
618 {
619         char str[ MAX_PWD_HISTORY_SZ ];
620         int nlen;
621
622         snprintf( str, MAX_PWD_HISTORY_SZ,
623                   "%s#%s#%lu#", timebuf,
624                   pa->a_desc->ad_type->sat_syntax->ssyn_oid,
625                   (unsigned long) pa->a_nvals[0].bv_len );
626         str[MAX_PWD_HISTORY_SZ-1] = 0;
627         nlen = strlen(str);
628
629         /*
630          * We have to assume that the string is a string of octets,
631          * not readable characters. In reality, yes, it probably is
632          * a readable (ie, base64) string, but we can't count on that
633          * Hence, while the first 3 fields of the password history
634          * are definitely readable (a timestamp, an OID and an integer
635          * length), the remaining octets of the actual password
636          * are deemed to be binary data.
637          */
638         AC_MEMCPY( str + nlen, pa->a_nvals[0].bv_val, pa->a_nvals[0].bv_len );
639         nlen += pa->a_nvals[0].bv_len;
640         bv->bv_val = ch_malloc( nlen + 1 );
641         AC_MEMCPY( bv->bv_val, str, nlen );
642         bv->bv_val[nlen] = '\0';
643         bv->bv_len = nlen;
644 }
645
646 static void
647 free_pwd_history_list( pw_hist **l )
648 {
649         pw_hist *p;
650     
651         if (!l) return;
652         p = *l;
653         while (p) {
654                 pw_hist *pp = p->next;
655
656                 free(p->pw.bv_val);
657                 free(p->bv.bv_val);
658                 free(p);
659                 p = pp;
660         }
661         *l = NULL;
662 }
663
664 typedef struct ppbind {
665         slap_overinst *on;
666         int send_ctrl;
667         Modifications *mod;
668         LDAPPasswordPolicyError pErr;
669         PassPolicy pp;
670 } ppbind;
671
672 static int
673 ppolicy_bind_resp( Operation *op, SlapReply *rs )
674 {
675         ppbind *ppb = op->o_callback->sc_private;
676         slap_overinst *on = ppb->on;
677         Modifications *mod = ppb->mod, *m;
678         int pwExpired = 0;
679         int ngut = -1, warn = -1, age, rc;
680         Attribute *a;
681         time_t now, pwtime = (time_t)-1;
682         char nowstr[ LDAP_LUTIL_GENTIME_BUFSIZE ];
683         struct berval timestamp;
684         BackendInfo *bi = op->o_bd->bd_info;
685         Entry *e;
686
687         /* If we already know it's locked, just get on with it */
688         if ( ppb->pErr != PP_noError ) {
689                 goto locked;
690         }
691
692         op->o_bd->bd_info = (BackendInfo *)on->on_info;
693         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
694         op->o_bd->bd_info = bi;
695
696         if ( rc != LDAP_SUCCESS ) {
697                 return SLAP_CB_CONTINUE;
698         }
699
700         now = slap_get_time(); /* stored for later consideration */
701         timestamp.bv_val = nowstr;
702         timestamp.bv_len = sizeof(nowstr);
703         slap_timestamp( &now, &timestamp );
704
705         if ( rs->sr_err == LDAP_INVALID_CREDENTIALS ) {
706                 int i = 0, fc = 0;
707
708                 m = ch_calloc( sizeof(Modifications), 1 );
709                 m->sml_op = LDAP_MOD_ADD;
710                 m->sml_flags = 0;
711                 m->sml_type = ad_pwdFailureTime->ad_cname;
712                 m->sml_desc = ad_pwdFailureTime;
713                 m->sml_values = ch_calloc( sizeof(struct berval), 2 );
714
715                 ber_dupbv( &m->sml_values[0], &timestamp );
716                 m->sml_next = mod;
717                 mod = m;
718
719                 /*
720                  * Count the pwdFailureTimes - if it's
721                  * greater than the policy pwdMaxFailure,
722                  * then lock the account.
723                  */
724                 if ((a = attr_find( e->e_attrs, ad_pwdFailureTime )) != NULL) {
725                         for(i=0; a->a_nvals[i].bv_val; i++) {
726
727                                 /*
728                                  * If the interval is 0, then failures
729                                  * stay on the record until explicitly
730                                  * reset by successful authentication.
731                                  */
732                                 if (ppb->pp.pwdFailureCountInterval == 0) {
733                                         fc++;
734                                 } else if (now <=
735                                                         parse_time(a->a_nvals[i].bv_val) +
736                                                         ppb->pp.pwdFailureCountInterval) {
737
738                                         fc++;
739                                 }
740                                 /*
741                                  * We only count those failures
742                                  * which are not due to expire.
743                                  */
744                         }
745                 }
746                 
747                 if ((ppb->pp.pwdMaxFailure > 0) &&
748                         (fc >= ppb->pp.pwdMaxFailure - 1)) {
749
750                         /*
751                          * We subtract 1 from the failure max
752                          * because the new failure entry hasn't
753                          * made it to the entry yet.
754                          */
755                         m = ch_calloc( sizeof(Modifications), 1 );
756                         m->sml_op = LDAP_MOD_REPLACE;
757                         m->sml_flags = 0;
758                         m->sml_type = ad_pwdAccountLockedTime->ad_cname;
759                         m->sml_desc = ad_pwdAccountLockedTime;
760                         m->sml_values = ch_calloc( sizeof(struct berval), 2 );
761                         ber_dupbv( &m->sml_values[0], &timestamp );
762                         m->sml_next = mod;
763                         mod = m;
764                 }
765         } else if ( rs->sr_err == LDAP_SUCCESS ) {
766                 if ((a = attr_find( e->e_attrs, ad_pwdChangedTime )) != NULL)
767                         pwtime = parse_time( a->a_nvals[0].bv_val );
768
769                 /* delete all pwdFailureTimes */
770                 if ( attr_find( e->e_attrs, ad_pwdFailureTime )) {
771                         m = ch_calloc( sizeof(Modifications), 1 );
772                         m->sml_op = LDAP_MOD_DELETE;
773                         m->sml_flags = 0;
774                         m->sml_type = ad_pwdFailureTime->ad_cname;
775                         m->sml_desc = ad_pwdFailureTime;
776                         m->sml_next = mod;
777                         mod = m;
778                 }
779
780                 /*
781                  * check to see if the password must be changed
782                  */
783                 if ( ppb->pp.pwdMustChange &&
784                         (a = attr_find( e->e_attrs, ad_pwdReset )) &&
785                         !strcmp( a->a_nvals[0].bv_val, "TRUE" ) ) {
786                         /*
787                          * need to inject client controls here to give
788                          * more information. For the moment, we ensure
789                          * that we are disallowed from doing anything
790                          * other than change password.
791                          */
792                         pwcons[op->o_conn->c_conn_idx].restricted = 1;
793
794                         ppb->pErr = PP_changeAfterReset;
795
796                 } else {
797                         /*
798                          * the password does not need to be changed, so
799                          * we now check whether the password has expired.
800                          *
801                          * We can skip this bit if passwords don't age in
802                          * the policy.
803                          */
804                         if (ppb->pp.pwdMaxAge == 0) goto grace;
805
806                         if (pwtime == (time_t)-1) {
807                                 /*
808                                  * Hmm. No password changed time on the
809                                  * entry. This is odd - it should have
810                                  * been provided when the attribute was added.
811                                  *
812                                  * However, it's possible that it could be
813                                  * missing if the DIT was established via
814                                  * an import process.
815                                  */
816                                 Debug( LDAP_DEBUG_ANY,
817                                         "ppolicy_bind: Entry %s does not have valid pwdChangedTime attribute - assuming password expired\n",
818                                         e->e_name.bv_val, 0, 0);
819                                 
820                                 pwExpired = 1;
821                         } else {
822                                 /*
823                                  * Check: was the last change time of
824                                  * the password older than the maximum age
825                                  * allowed. (Ignore case 2 from I-D, it's just silly.)
826                                  */
827                                 if (now - pwtime > ppb->pp.pwdMaxAge ) pwExpired = 1;
828                         }
829                 }
830
831 grace:
832                 if (!pwExpired) goto check_expiring_password;
833                 
834                 if ((a = attr_find( e->e_attrs, ad_pwdGraceUseTime )) == NULL)
835                         ngut = ppb->pp.pwdGraceAuthNLimit;
836                 else {
837                         for(ngut=0; a->a_nvals[ngut].bv_val; ngut++);
838                         ngut = ppb->pp.pwdGraceAuthNLimit - ngut;
839                 }
840
841                 /*
842                  * ngut is the number of remaining grace logins
843                  */
844                 Debug( LDAP_DEBUG_ANY,
845                         "ppolicy_bind: Entry %s has an expired password: %d grace logins\n",
846                         e->e_name.bv_val, ngut, 0);
847                 
848                 if (ngut < 1) {
849                         ppb->pErr = PP_passwordExpired;
850                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
851                         goto done;
852                 }
853
854                 /*
855                  * Add a grace user time to the entry
856                  */
857                 m = ch_calloc( sizeof(Modifications), 1 );
858                 m->sml_op = LDAP_MOD_ADD;
859                 m->sml_flags = 0;
860                 m->sml_type = ad_pwdGraceUseTime->ad_cname;
861                 m->sml_desc = ad_pwdGraceUseTime;
862                 m->sml_values = ch_calloc( sizeof(struct berval), 2 );
863                 ber_dupbv( &m->sml_values[0], &timestamp );
864                 m->sml_next = mod;
865                 mod = m;
866
867 check_expiring_password:
868                 /*
869                  * Now we need to check to see
870                  * if it is about to expire, and if so, should the user
871                  * be warned about it in the password policy control.
872                  *
873                  * If the password has expired, and we're in the grace period, then
874                  * we don't need to do this bit. Similarly, if we don't have password
875                  * aging, then there's no need to do this bit either.
876                  */
877                 if ((ppb->pp.pwdMaxAge < 1) || (pwExpired) || (ppb->pp.pwdExpireWarning < 1))
878                         goto done;
879
880                 age = (int)(now - pwtime);
881                 
882                 /*
883                  * We know that there is a password Change Time attribute - if
884                  * there wasn't, then the pwdExpired value would be true, unless
885                  * there is no password aging - and if there is no password aging,
886                  * then this section isn't called anyway - you can't have an
887                  * expiring password if there's no limit to expire.
888                  */
889                 if (ppb->pp.pwdMaxAge - age < ppb->pp.pwdExpireWarning ) {
890                         /*
891                          * Set the warning value.
892                          */
893                         warn = ppb->pp.pwdMaxAge - age; /* seconds left until expiry */
894                         if (warn < 0) warn = 0; /* something weird here - why is pwExpired not set? */
895                         
896                         Debug( LDAP_DEBUG_ANY,
897                                 "ppolicy_bind: Setting warning for password expiry for %s = %d seconds\n",
898                                 op->o_req_dn.bv_val, warn, 0 );
899                 }
900         }
901
902 done:
903         op->o_bd->bd_info = (BackendInfo *)on->on_info;
904         be_entry_release_r( op, e );
905
906 locked:
907         if ( mod ) {
908                 Operation op2 = *op;
909                 SlapReply r2 = { REP_RESULT };
910                 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
911
912                 /* FIXME: Need to handle replication of some (but not all)
913                  * of the operational attributes...
914                  */
915                 op2.o_tag = LDAP_REQ_MODIFY;
916                 op2.o_callback = &cb;
917                 op2.orm_modlist = mod;
918                 op2.o_dn = op->o_bd->be_rootdn;
919                 op2.o_ndn = op->o_bd->be_rootndn;
920                 op2.o_bd->bd_info = (BackendInfo *)on->on_info;
921                 rc = op->o_bd->be_modify( &op2, &r2 );
922                 slap_mods_free( mod, 1 );
923         }
924
925         if ( ppb->send_ctrl ) {
926                 LDAPControl **ctrls = NULL;
927                 pp_info *pi = on->on_bi.bi_private;
928
929                 /* Do we really want to tell that the account is locked? */
930                 if ( ppb->pErr == PP_accountLocked && !pi->use_lockout ) {
931                         ppb->pErr = PP_noError;
932                 }
933                 ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
934                 ctrls[0] = create_passcontrol( warn, ngut, ppb->pErr );
935                 ctrls[1] = NULL;
936                 rs->sr_ctrls = ctrls;
937         }
938         op->o_bd->bd_info = bi;
939         return SLAP_CB_CONTINUE;
940 }
941
942 static int
943 ppolicy_bind( Operation *op, SlapReply *rs )
944 {
945         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
946
947         /* Root bypasses policy */
948         if ( !be_isroot_dn( op->o_bd, &op->o_req_ndn )) {
949                 Entry *e;
950                 int rc;
951                 ppbind *ppb;
952                 slap_callback *cb;
953
954                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
955                 rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
956
957                 if ( rc != LDAP_SUCCESS ) {
958                         return SLAP_CB_CONTINUE;
959                 }
960
961                 cb = op->o_tmpcalloc( sizeof(ppbind)+sizeof(slap_callback),
962                         1, op->o_tmpmemctx );
963                 ppb = (ppbind *)(cb+1);
964                 ppb->on = on;
965                 ppb->pErr = PP_noError;
966
967                 /* Setup a callback so we can munge the result */
968
969                 cb->sc_response = ppolicy_bind_resp;
970                 cb->sc_next = op->o_callback->sc_next;
971                 cb->sc_private = ppb;
972                 op->o_callback->sc_next = cb;
973
974                 /* Did we receive a password policy request control? */
975                 if ( op->o_ctrlflag[ppolicy_cid] ) {
976                         ppb->send_ctrl = 1;
977                 }
978
979                 op->o_bd->bd_info = (BackendInfo *)on;
980                 ppolicy_get( op, e, &ppb->pp );
981
982                 rc = account_locked( op, e, &ppb->pp, &ppb->mod );
983
984                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
985                 be_entry_release_r( op, e );
986
987                 if ( rc ) {
988                         /* This will be the Draft 8 response, Unwilling is bogus */
989                         ppb->pErr = PP_accountLocked;
990                         send_ldap_error( op, rs, LDAP_INVALID_CREDENTIALS, NULL );
991                         return rs->sr_err;
992                 }
993
994         }
995
996         return SLAP_CB_CONTINUE;
997 }
998
999 /* Reset the restricted flag for the next session on this connection */
1000 static int
1001 ppolicy_connection_destroy( BackendDB *bd, Connection *conn )
1002 {
1003         pwcons[conn->c_conn_idx].restricted = 0;
1004         return SLAP_CB_CONTINUE;
1005 }
1006
1007 /* Check if this connection is restricted */
1008 static int
1009 ppolicy_restrict(
1010         Operation *op,
1011         SlapReply *rs )
1012 {
1013         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1014         int send_ctrl = 0;
1015
1016         /* Did we receive a password policy request control? */
1017         if ( op->o_ctrlflag[ppolicy_cid] ) {
1018                 send_ctrl = 1;
1019         }
1020
1021         if ( op->o_conn && pwcons[op->o_conn->c_conn_idx].restricted ) {
1022                 Debug( LDAP_DEBUG_TRACE,
1023                         "connection restricted to password changing only\n", 0, 0, 0);
1024                 if ( send_ctrl ) {
1025                         LDAPControl **ctrls = NULL;
1026
1027                         ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
1028                         ctrls[0] = create_passcontrol( -1, -1, PP_changeAfterReset );
1029                         ctrls[1] = NULL;
1030                         rs->sr_ctrls = ctrls;
1031                 }
1032                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1033                 send_ldap_error( op, rs, LDAP_INSUFFICIENT_ACCESS, 
1034                         "Operations are restricted to bind/unbind/abandon/StartTLS/modify password" );
1035                 return rs->sr_err;
1036         }
1037
1038         return SLAP_CB_CONTINUE;
1039 }
1040
1041 static int
1042 ppolicy_add(
1043         Operation *op,
1044         SlapReply *rs )
1045 {
1046         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1047         pp_info *pi = on->on_bi.bi_private;
1048         PassPolicy pp;
1049         Attribute *pa;
1050         const char *txt;
1051
1052         if ( ppolicy_restrict( op, rs ) != SLAP_CB_CONTINUE )
1053                 return rs->sr_err;
1054
1055         /* Check for password in entry */
1056         if ((pa = attr_find( op->oq_add.rs_e->e_attrs,
1057                 slap_schema.si_ad_userPassword )))
1058         {
1059                 /*
1060                  * new entry contains a password - if we're not the root user
1061                  * then we need to check that the password fits in with the
1062                  * security policy for the new entry.
1063                  */
1064                 ppolicy_get( op, op->ora_e, &pp );
1065                 if (pp.pwdCheckQuality > 0 && !be_isroot( op )) {
1066                         struct berval *bv = &(pa->a_vals[0]);
1067                         int rc, send_ctrl = 0;
1068                         LDAPPasswordPolicyError pErr = PP_noError;
1069
1070                         /* Did we receive a password policy request control? */
1071                         if ( op->o_ctrlflag[ppolicy_cid] ) {
1072                                 send_ctrl = 1;
1073                         }
1074                         rc = check_password_quality( bv, &pp, &pErr, op->ora_e );
1075                         if (rc != LDAP_SUCCESS) {
1076                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1077                                 if ( send_ctrl ) {
1078                                         LDAPControl **ctrls = NULL;
1079
1080                                         ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
1081                                         ctrls[0] = create_passcontrol( -1, -1, pErr );
1082                                         ctrls[1] = NULL;
1083                                         rs->sr_ctrls = ctrls;
1084                                 }
1085                                 send_ldap_error( op, rs, rc, "Password fails quality checking policy" );
1086                                 return rs->sr_err;
1087                         }
1088                             /*
1089                              * A controversial bit. We hash cleartext
1090                              * passwords provided via add and modify operations
1091                              * You're not really supposed to do this, since
1092                              * the X.500 model says "store attributes" as they
1093                              * get provided. By default, this is what we do
1094                              *
1095                              * But if the hash_passwords flag is set, we hash
1096                              * any cleartext password attribute values via the
1097                              * default password hashing scheme.
1098                              */
1099                         if ((pi->hash_passwords) &&
1100                                 (password_scheme( &(pa->a_vals[0]), NULL ) != LDAP_SUCCESS)) {
1101                                 struct berval hpw;
1102
1103                                 slap_passwd_hash( &(pa->a_vals[0]), &hpw, &txt );
1104                                 if (hpw.bv_val == NULL) {
1105                                     /*
1106                                      * hashing didn't work. Emit an error.
1107                                      */
1108                                         rs->sr_err = LDAP_OTHER;
1109                                         rs->sr_text = txt;
1110                                         send_ldap_error( op, rs, LDAP_OTHER, "Password hashing failed" );
1111                                         return rs->sr_err;
1112                                 }
1113
1114                                 memset( pa->a_vals[0].bv_val, 0, pa->a_vals[0].bv_len);
1115                                 ber_memfree( pa->a_vals[0].bv_val );
1116                                 pa->a_vals[0].bv_val = hpw.bv_val;
1117                                 pa->a_vals[0].bv_len = hpw.bv_len;
1118                         }
1119                 }
1120                 /* If password aging is in effect, set the pwdChangedTime */
1121                 if (( pp.pwdMaxAge || pp.pwdMinAge ) && !be_shadow_update( op )) {
1122                         struct berval timestamp;
1123                         char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
1124                         time_t now = slap_get_time();
1125
1126                         timestamp.bv_val = timebuf;
1127                         timestamp.bv_len = sizeof(timebuf);
1128                         slap_timestamp( &now, &timestamp );
1129
1130                         attr_merge_one( op->ora_e, ad_pwdChangedTime, &timestamp, NULL );
1131                 }
1132         }
1133         return SLAP_CB_CONTINUE;
1134 }
1135
1136 static int
1137 ppolicy_modify( Operation *op, SlapReply *rs )
1138 {
1139         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1140         pp_info                 *pi = on->on_bi.bi_private;
1141         int                     i, rc, mod_pw_only, pwmod, pwmop, deladd,
1142                                 hsize = 0;
1143         PassPolicy              pp;
1144         Modifications           *mods = NULL, *modtail, *ml, *delmod, *addmod;
1145         Attribute               *pa, *ha, at;
1146         const char              *txt;
1147         pw_hist                 *tl = NULL, *p;
1148         int                     zapReset, send_ctrl = 0;
1149         Entry                   *e;
1150         struct berval           newpw = BER_BVNULL, oldpw = BER_BVNULL,
1151                                 *bv, cr[2];
1152         LDAPPasswordPolicyError pErr = PP_noError;
1153
1154         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1155         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1156         op->o_bd->bd_info = (BackendInfo *)on;
1157
1158         if ( rc != LDAP_SUCCESS ) return SLAP_CB_CONTINUE;
1159
1160         /* Did we receive a password policy request control? */
1161         if ( op->o_ctrlflag[ppolicy_cid] ) {
1162                 send_ctrl = 1;
1163         }
1164
1165         /* See if this is a pwdModify exop. If so, we can
1166          * access the plaintext passwords from that request.
1167          */
1168         {
1169                 slap_callback *sc;
1170
1171                 for ( sc = op->o_callback; sc; sc=sc->sc_next ) {
1172                         if ( sc->sc_response == slap_replog_cb &&
1173                                 sc->sc_private ) {
1174                                 req_pwdexop_s *qpw = sc->sc_private;
1175                                 newpw = qpw->rs_new;
1176                                 oldpw = qpw->rs_old;
1177                                 break;
1178                         }
1179                 }
1180         }
1181
1182         ppolicy_get( op, e, &pp );
1183
1184         for(ml = op->oq_modify.rs_modlist,
1185                         pwmod = 0, mod_pw_only = 1,
1186                         deladd = 0, delmod = NULL,
1187                         addmod = NULL,
1188                         zapReset = 1;
1189                 ml != NULL; modtail = ml, ml = ml->sml_next ) {
1190                 if ( ml->sml_desc == pp.ad ) {
1191                         pwmod = 1;
1192                         pwmop = ml->sml_op;
1193                         if ((deladd == 0) && (ml->sml_op == LDAP_MOD_DELETE) &&
1194                                 (ml->sml_values) && (ml->sml_values[0].bv_val != NULL)) {
1195                                 deladd = 1;
1196                                 delmod = ml;
1197                         }
1198
1199                         if ((deladd == 1) && ((ml->sml_op == LDAP_MOD_ADD) ||
1200                                                                   (ml->sml_op == LDAP_MOD_REPLACE)))
1201                                 deladd = 2;
1202
1203                         if ((ml->sml_op == LDAP_MOD_ADD) ||
1204                                 (ml->sml_op == LDAP_MOD_REPLACE))
1205                                 addmod = ml;
1206                 } else if (! is_at_operational( ml->sml_desc->ad_type )) {
1207                         mod_pw_only = 0;
1208                         /* modifying something other than password */
1209                 }
1210
1211                 /*
1212                  * If there is a request to explicitly add a pwdReset
1213                  * attribute, then we suppress the normal behaviour on
1214                  * password change, which is to remove the pwdReset
1215                  * attribute.
1216                  *
1217                  * This enables an administrator to assign a new password
1218                  * and place a "must reset" flag on the entry, which will
1219                  * stay until the user explicitly changes his/her password.
1220                  */
1221                 if (ml->sml_desc == ad_pwdReset ) {
1222                         if ((ml->sml_op == LDAP_MOD_ADD) ||
1223                                 (ml->sml_op == LDAP_MOD_REPLACE))
1224                                 zapReset = 0;
1225                 }
1226         }
1227         
1228         if (pwcons[op->o_conn->c_conn_idx].restricted && !mod_pw_only) {
1229                 Debug( LDAP_DEBUG_TRACE,
1230                         "connection restricted to password changing only\n", 0, 0, 0 );
1231                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS; 
1232                 rs->sr_text = "Operations are restricted to bind/unbind/abandon/StartTLS/modify password";
1233                 pErr = PP_changeAfterReset;
1234                 goto return_results;
1235         }
1236
1237         /*
1238          * if we have a "safe password modify policy", then we need to check if we're doing
1239          * a delete (with the old password), followed by an add (with the new password).
1240          *
1241          * If we don't have this, then we fail with an error. We also skip all the checks if
1242          * the root user is bound. Root can do anything, including avoid the policies.
1243          */
1244
1245         if (!pwmod) goto do_modify;
1246
1247         /*
1248          * Did we get a valid add mod?
1249          */
1250
1251         if (!addmod) {
1252                 rs->sr_err = LDAP_OTHER;
1253                 rs->sr_text = "Internal Error";
1254                 Debug( LDAP_DEBUG_TRACE,
1255                         "cannot locate modification supplying new password\n", 0, 0, 0 );
1256                 goto return_results;
1257         }
1258
1259         /*
1260          * Build the password history list in ascending time order
1261          * We need this, even if the user is root, in order to maintain
1262          * the pwdHistory operational attributes properly.
1263          */
1264         if (pp.pwdInHistory > 0 && (ha = attr_find( e->e_attrs, ad_pwdHistory ))) {
1265                 struct berval oldpw;
1266                 time_t oldtime;
1267
1268                 for(i=0; ha->a_nvals[i].bv_val; i++) {
1269                         rc = parse_pwdhistory( &(ha->a_nvals[i]), NULL,
1270                                 &oldtime, &oldpw );
1271
1272                         if (rc != LDAP_SUCCESS) continue; /* invalid history entry */
1273
1274                         if (oldpw.bv_val) {
1275                                 add_to_pwd_history( &tl, oldtime, &oldpw,
1276                                         &(ha->a_nvals[i]) );
1277                                 oldpw.bv_val = NULL;
1278                                 oldpw.bv_len = 0;
1279                         }
1280                 }
1281                 for(p=tl; p; p=p->next, hsize++); /* count history size */
1282         }
1283
1284         if (be_isroot( op )) goto do_modify;
1285
1286         /* This is a pwdModify exop that provided the old pw.
1287          * We need to create a Delete mod for this old pw and 
1288          * let the matching value get found later
1289          */
1290         if (pp.pwdSafeModify && oldpw.bv_val ) {
1291                 ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
1292                 ml->sml_op = LDAP_MOD_DELETE;
1293                 ml->sml_flags = SLAP_MOD_INTERNAL;
1294                 ml->sml_desc = pp.ad;
1295                 ml->sml_type = pp.ad->ad_cname;
1296                 ml->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
1297                 ber_dupbv( &ml->sml_values[0], &oldpw );
1298                 ml->sml_values[1].bv_len = 0;
1299                 ml->sml_values[1].bv_val = NULL;
1300                 ml->sml_nvalues = NULL;
1301                 ml->sml_next = op->orm_modlist;
1302                 op->orm_modlist = ml;
1303                 delmod = ml;
1304                 deladd = 2;
1305         }
1306
1307         if (pp.pwdSafeModify && deladd != 2) {
1308                 Debug( LDAP_DEBUG_TRACE,
1309                         "change password must use DELETE followed by ADD/REPLACE\n",
1310                         0, 0, 0 );
1311                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1312                 rs->sr_text = "Must supply old password to be changed as well as new one";
1313                 pErr = PP_mustSupplyOldPassword;
1314                 goto return_results;
1315         }
1316
1317         if (!pp.pwdAllowUserChange) {
1318                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1319                 rs->sr_text = "User alteration of password is not allowed";
1320                 pErr = PP_passwordModNotAllowed;
1321                 goto return_results;
1322         }
1323
1324         if (pp.pwdMinAge > 0) {
1325                 time_t pwtime = (time_t)-1, now;
1326                 int age;
1327
1328                 if ((pa = attr_find( e->e_attrs, ad_pwdChangedTime )) != NULL)
1329                         pwtime = parse_time( pa->a_nvals[0].bv_val );
1330                 now = slap_get_time();
1331                 age = (int)(now - pwtime);
1332                 if ((pwtime != (time_t)-1) && (age < pp.pwdMinAge)) {
1333                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1334                         rs->sr_text = "Password is too young to change";
1335                         pErr = PP_passwordTooYoung;
1336                         goto return_results;
1337                 }
1338         }
1339
1340         /* pa is used in password history check below, be sure it's set */
1341         if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL && delmod) {
1342                 /*
1343                  * we have a password to check
1344                  */
1345                 const char *txt;
1346                 
1347                 bv = oldpw.bv_val ? &oldpw : delmod->sml_values;
1348                 /* FIXME: no access checking? */
1349                 rc = slap_passwd_check( op, NULL, pa, bv, &txt );
1350                 if (rc != LDAP_SUCCESS) {
1351                         Debug( LDAP_DEBUG_TRACE,
1352                                 "old password check failed: %s\n", txt, 0, 0 );
1353                         
1354                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1355                         rs->sr_text = "Must supply correct old password to change to new one";
1356                         pErr = PP_mustSupplyOldPassword;
1357                         goto return_results;
1358
1359                 } else {
1360                         int i;
1361                         
1362                         /*
1363                          * replace the delete value with the (possibly hashed)
1364                          * value which is currently in the password.
1365                          */
1366                         for(i=0; delmod->sml_values[i].bv_val; i++) {
1367                                 free(delmod->sml_values[i].bv_val);
1368                                 delmod->sml_values[i].bv_len = 0;
1369                         }
1370                         free(delmod->sml_values);
1371                         delmod->sml_values = ch_calloc( sizeof(struct berval), 2 );
1372                         delmod->sml_values[1].bv_len = 0;
1373                         delmod->sml_values[1].bv_val = NULL;
1374                         ber_dupbv(&(delmod->sml_values[0]),  &(pa->a_nvals[0]));
1375                 }
1376         }
1377
1378         bv = newpw.bv_val ? &newpw : addmod->sml_values;
1379         if (pp.pwdCheckQuality > 0) {
1380
1381                 rc = check_password_quality( bv, &pp, &pErr, e );
1382                 if (rc != LDAP_SUCCESS) {
1383                         rs->sr_err = rc;
1384                         rs->sr_text = "Password fails quality checking policy";
1385                         goto return_results;
1386                 }
1387         }
1388
1389         if (pa) {
1390                 /*
1391                  * Last check - the password history.
1392                  */
1393                 /* FIXME: no access checking? */
1394                 if (slap_passwd_check( op, NULL, pa, bv, &txt ) == LDAP_SUCCESS) {
1395                         /*
1396                          * This is bad - it means that the user is attempting
1397                          * to set the password to the same as the old one.
1398                          */
1399                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1400                         rs->sr_text = "Password is not being changed from existing value";
1401                         pErr = PP_passwordInHistory;
1402                         goto return_results;
1403                 }
1404         
1405                 if (pp.pwdInHistory < 1) goto do_modify;
1406         
1407                 /*
1408                  * Iterate through the password history, and fail on any
1409                  * password matches.
1410                  */
1411                 at = *pa;
1412                 at.a_vals = cr;
1413                 cr[1].bv_val = NULL;
1414                 for(p=tl; p; p=p->next) {
1415                         cr[0] = p->pw;
1416                         /* FIXME: no access checking? */
1417                         rc = slap_passwd_check( op, NULL, &at, bv, &txt );
1418                         
1419                         if (rc != LDAP_SUCCESS) continue;
1420                         
1421                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1422                         rs->sr_text = "Password is in history of old passwords";
1423                         pErr = PP_passwordInHistory;
1424                         goto return_results;
1425                 }
1426         }
1427
1428 do_modify:
1429         if ((pwmod) && (!be_shadow_update( op ))) {
1430                 struct berval timestamp;
1431                 char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
1432                 time_t now = slap_get_time();
1433                 
1434                 /*
1435                  * keep the necessary pwd.. operational attributes
1436                  * up to date.
1437                  */
1438
1439                 timestamp.bv_val = timebuf;
1440                 timestamp.bv_len = sizeof(timebuf);
1441                 slap_timestamp( &now, &timestamp );
1442
1443                 mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
1444                 mods->sml_type.bv_val = NULL;
1445                 mods->sml_desc = ad_pwdChangedTime;
1446                 if (pwmop != LDAP_MOD_DELETE) {
1447                         mods->sml_op = LDAP_MOD_REPLACE;
1448                         mods->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
1449                         ber_dupbv( &mods->sml_values[0], &timestamp );
1450                         mods->sml_values[1].bv_len = 0;
1451                         mods->sml_values[1].bv_val = NULL;
1452                         assert( mods->sml_values[0].bv_val != NULL );
1453                 } else {
1454                         mods->sml_op = LDAP_MOD_DELETE;
1455                         mods->sml_values = NULL;
1456                 }
1457                 mods->sml_flags = SLAP_MOD_INTERNAL;
1458                 mods->sml_nvalues = NULL;
1459                 mods->sml_next = NULL;
1460                 modtail->sml_next = mods;
1461                 modtail = mods;
1462
1463                 if (attr_find(e->e_attrs, ad_pwdGraceUseTime )) {
1464                         mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
1465                         mods->sml_op = LDAP_MOD_DELETE;
1466                         mods->sml_flags = SLAP_MOD_INTERNAL;
1467                         mods->sml_type.bv_val = NULL;
1468                         mods->sml_desc = ad_pwdGraceUseTime;
1469                         mods->sml_values = NULL;
1470                         mods->sml_nvalues = NULL;
1471                         mods->sml_next = NULL;
1472                         modtail->sml_next = mods;
1473                         modtail = mods;
1474                 }
1475
1476                 /* Delete the pwdReset attribute, since it's being reset */
1477                 if ((zapReset) && (attr_find(e->e_attrs, ad_pwdReset ))) {
1478                         mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
1479                         mods->sml_op = LDAP_MOD_DELETE;
1480                         mods->sml_flags = SLAP_MOD_INTERNAL;
1481                         mods->sml_type.bv_val = NULL;
1482                         mods->sml_desc = ad_pwdReset;
1483                         mods->sml_values = NULL;
1484                         mods->sml_nvalues = NULL;
1485                         mods->sml_next = NULL;
1486                         modtail->sml_next = mods;
1487                         modtail = mods;
1488                 }
1489
1490                 if (pp.pwdInHistory > 0) {
1491                         if (hsize >= pp.pwdInHistory) {
1492                                 /*
1493                                  * We use the >= operator, since we are going to add
1494                                  * the existing password attribute value into the
1495                                  * history - thus the cardinality of history values is
1496                                  * about to rise by one.
1497                                  *
1498                                  * If this would push it over the limit of history
1499                                  * values (remembering - the password policy could have
1500                                  * changed since the password was last altered), we must
1501                                  * delete at least 1 value from the pwdHistory list.
1502                                  *
1503                                  * In fact, we delete '(#pwdHistory attrs - max pwd
1504                                  * history length) + 1' values, starting with the oldest.
1505                                  * This is easily evaluated, since the linked list is
1506                                  * created in ascending time order.
1507                                  */
1508                                 mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
1509                                 mods->sml_op = LDAP_MOD_DELETE;
1510                                 mods->sml_flags = SLAP_MOD_INTERNAL;
1511                                 mods->sml_type.bv_val = NULL;
1512                                 mods->sml_desc = ad_pwdHistory;
1513                                 mods->sml_nvalues = NULL;
1514                                 mods->sml_values = ch_calloc( sizeof( struct berval ),
1515                                                                                            hsize - pp.pwdInHistory + 2 );
1516                                 mods->sml_values[ hsize - pp.pwdInHistory + 1 ].bv_val = NULL;
1517                                 mods->sml_values[ hsize - pp.pwdInHistory + 1 ].bv_len = 0;
1518                                 for(i=0,p=tl; i < (hsize - pp.pwdInHistory + 1); i++, p=p->next) {
1519                                         mods->sml_values[i].bv_val = NULL;
1520                                         mods->sml_values[i].bv_len = 0;
1521                                         ber_dupbv( &(mods->sml_values[i]), &p->bv );
1522                                 }
1523                                 mods->sml_next = NULL;
1524                                 modtail->sml_next = mods;
1525                                 modtail = mods;
1526                         }
1527                         free_pwd_history_list( &tl );
1528
1529                         /*
1530                          * Now add the existing password into the history list.
1531                          * This will be executed even if the operation is to delete
1532                          * the password entirely.
1533                          *
1534                          * This isn't in the spec explicitly, but it seems to make
1535                          * sense that the password history list is the list of all
1536                          * previous passwords - even if they were deleted. Thus, if
1537                          * someone tries to add a historical password at some future
1538                          * point, it will fail.
1539                          */
1540                         if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL) {
1541                                 mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
1542                                 mods->sml_op = LDAP_MOD_ADD;
1543                                 mods->sml_flags = SLAP_MOD_INTERNAL;
1544                                 mods->sml_type.bv_val = NULL;
1545                                 mods->sml_desc = ad_pwdHistory;
1546                                 mods->sml_nvalues = NULL;
1547                                 mods->sml_values = ch_calloc( sizeof( struct berval ), 2 );
1548                                 mods->sml_values[ 1 ].bv_val = NULL;
1549                                 mods->sml_values[ 1 ].bv_len = 0;
1550                                 make_pwd_history_value( timebuf, &mods->sml_values[0], pa );
1551                                 mods->sml_next = NULL;
1552                                 modtail->sml_next = mods;
1553                                 modtail = mods;
1554                         } else {
1555                                 Debug( LDAP_DEBUG_TRACE,
1556                                 "ppolicy_modify: password attr lookup failed\n", 0, 0, 0 );
1557                         }
1558                 }
1559
1560                 /*
1561                  * Controversial bit here. If the new password isn't hashed
1562                  * (ie, is cleartext), we probably should hash it according
1563                  * to the default hash. The reason for this is that we want
1564                  * to use the policy if possible, but if we hash the password
1565                  * before, then we're going to run into trouble when it
1566                  * comes time to check the password.
1567                  *
1568                  * Now, the right thing to do is to use the extended password
1569                  * modify operation, but not all software can do this,
1570                  * therefore it makes sense to hash the new password, now
1571                  * we know it passes the policy requirements.
1572                  *
1573                  * Of course, if the password is already hashed, then we
1574                  * leave it alone.
1575                  */
1576
1577                 if ((pi->hash_passwords) && (addmod) && !newpw.bv_val && 
1578                         (password_scheme( &(addmod->sml_values[0]), NULL ) != LDAP_SUCCESS)) {
1579                         struct berval hpw, bv;
1580                         
1581                         slap_passwd_hash( &(addmod->sml_values[0]), &hpw, &txt );
1582                         if (hpw.bv_val == NULL) {
1583                                         /*
1584                                          * hashing didn't work. Emit an error.
1585                                          */
1586                                 rs->sr_err = LDAP_OTHER;
1587                                 rs->sr_text = txt;
1588                                 goto return_results;
1589                         }
1590                         bv.bv_val = addmod->sml_values[0].bv_val;
1591                         bv.bv_len = addmod->sml_values[0].bv_len;
1592                                 /* clear and discard the clear password */
1593                         memset(bv.bv_val, 0, bv.bv_len);
1594                         ber_memfree(bv.bv_val);
1595                         addmod->sml_values[0].bv_val = hpw.bv_val;
1596                         addmod->sml_values[0].bv_len = hpw.bv_len;
1597                 }
1598         }
1599         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1600         be_entry_release_r( op, e );
1601         return SLAP_CB_CONTINUE;
1602
1603 return_results:
1604         free_pwd_history_list( &tl );
1605         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1606         be_entry_release_r( op, e );
1607         if ( send_ctrl ) {
1608                 LDAPControl **ctrls = NULL;
1609
1610                 ctrls = ch_calloc( sizeof( LDAPControl *) , 2 );
1611                 ctrls[0] = create_passcontrol( -1, -1, pErr );
1612                 ctrls[1] = NULL;
1613                 rs->sr_ctrls = ctrls;
1614         }
1615         send_ldap_result( op, rs );
1616         return rs->sr_err;
1617 }
1618
1619 static int
1620 ppolicy_parseCtrl(
1621         Operation *op,
1622         SlapReply *rs,
1623         LDAPControl *ctrl )
1624 {
1625         if ( ctrl->ldctl_value.bv_len ) {
1626                 rs->sr_text = "passwordPolicyRequest control value not empty";
1627                 return LDAP_PROTOCOL_ERROR;
1628         }
1629         if ( ctrl->ldctl_iscritical ) {
1630                 rs->sr_text = "passwordPolicyRequest control invalid criticality";
1631                 return LDAP_PROTOCOL_ERROR;
1632         }
1633         op->o_ctrlflag[ppolicy_cid] = SLAP_CONTROL_NONCRITICAL;
1634
1635         return LDAP_SUCCESS;
1636 }
1637
1638 static int
1639 ppolicy_db_init(
1640         BackendDB *be
1641 )
1642 {
1643         slap_overinst *on = (slap_overinst *) be->bd_info;
1644
1645         /* Has User Schema been initialized yet? */
1646         if ( !pwd_UsSchema[0].ad[0] ) {
1647                 const char *err;
1648                 int i, code;
1649
1650                 for (i=0; pwd_UsSchema[i].def; i++) {
1651                         code = slap_str2ad( pwd_UsSchema[i].def, pwd_UsSchema[i].ad, &err );
1652                         if ( code ) {
1653                                 fprintf( stderr, "User Schema Load failed %d: %s\n", code, err );
1654                                 return code;
1655                         }
1656                 }
1657         }
1658
1659         on->on_bi.bi_private = ch_calloc( sizeof(pp_info), 1 );
1660
1661         if ( dtblsize && !pwcons )
1662                 pwcons = ch_calloc(sizeof(pw_conn), dtblsize );
1663
1664         return 0;
1665 }
1666
1667 static int
1668 ppolicy_db_open(
1669     BackendDB *be
1670 )
1671 {
1672         return overlay_register_control( be, LDAP_CONTROL_PASSWORDPOLICYREQUEST );
1673 }
1674
1675 static int
1676 ppolicy_close(
1677         BackendDB *be
1678 )
1679 {
1680         slap_overinst *on = (slap_overinst *) be->bd_info;
1681         pp_info *pi = on->on_bi.bi_private;
1682         
1683         free( pwcons );
1684         free( pi->def_policy.bv_val );
1685         free( pi );
1686
1687         return 0;
1688 }
1689
1690 static int
1691 ppolicy_config(
1692     BackendDB   *be,
1693     const char  *fname,
1694     int         lineno,
1695     int         argc,
1696     char        **argv
1697 )
1698 {
1699         slap_overinst *on = (slap_overinst *) be->bd_info;
1700         pp_info *pi = on->on_bi.bi_private;
1701         struct berval dn;
1702         
1703
1704         if ( strcasecmp( argv[0], "ppolicy_default" ) == 0 ) {
1705                 if ( argc != 2 ) {
1706                         fprintf( stderr, "%s: line %d: invalid arguments in \"ppolicy_default"
1707                                 " <policyDN>\n", fname, lineno );
1708                         return ( 1 );
1709                 }
1710                 ber_str2bv( argv[1], 0, 0, &dn );
1711                 if ( dnNormalize( 0, NULL, NULL, &dn, &pi->def_policy, NULL ) ) {
1712                         fprintf( stderr, "%s: line %d: policyDN is invalid\n",
1713                                 fname, lineno );
1714                         return 1;
1715                 }
1716                 return 0;
1717
1718         } else if ( strcasecmp( argv[0], "ppolicy_use_lockout" ) == 0 ) {
1719                 if ( argc != 1 ) {
1720                         fprintf( stderr, "%s: line %d: ppolicy_use_lockout "
1721                                 "takes no arguments\n", fname, lineno );
1722                         return ( 1 );
1723                 }
1724                 pi->use_lockout = 1;
1725                 return 0;
1726         } else if ( strcasecmp( argv[0], "ppolicy_hash_cleartext" ) == 0 ) {
1727                 if ( argc != 1 ) {
1728                         fprintf( stderr, "%s: line %d: ppolicy_hash_cleartext "
1729                                 "takes no arguments\n", fname, lineno );
1730                         return ( 1 );
1731                 }
1732                 pi->hash_passwords = 1;
1733         }
1734         return SLAP_CONF_UNKNOWN;
1735 }
1736
1737 static char *extops[] = {
1738         LDAP_EXOP_MODIFY_PASSWD,
1739         NULL
1740 };
1741
1742 static slap_overinst ppolicy;
1743
1744 int ppolicy_init()
1745 {
1746         LDAPAttributeType *at;
1747         const char *err;
1748         int i, code;
1749
1750         for (i=0; pwd_OpSchema[i].def; i++) {
1751                 at = ldap_str2attributetype( pwd_OpSchema[i].def, &code, &err,
1752                         LDAP_SCHEMA_ALLOW_ALL );
1753                 if ( !at ) {
1754                         fprintf( stderr, "AttributeType Load failed %s %s\n",
1755                                 ldap_scherr2str(code), err );
1756                         return code;
1757                 }
1758                 code = at_add( at, 0, NULL, &err );
1759                 if ( !code ) {
1760                         slap_str2ad( at->at_names[0], pwd_OpSchema[i].ad, &err );
1761                 }
1762                 ldap_memfree( at );
1763                 if ( code ) {
1764                         fprintf( stderr, "AttributeType Load failed %s %s\n",
1765                                 scherr2str(code), err );
1766                         return code;
1767                 }
1768         }
1769
1770         code = register_supported_control( LDAP_CONTROL_PASSWORDPOLICYREQUEST,
1771                 SLAP_CTRL_ADD|SLAP_CTRL_BIND|SLAP_CTRL_MODIFY|SLAP_CTRL_HIDE, extops,
1772                 ppolicy_parseCtrl, &ppolicy_cid );
1773         if ( code != LDAP_SUCCESS ) {
1774                 fprintf( stderr, "Failed to register control %d\n", code );
1775                 return code;
1776         }
1777
1778         ldap_pvt_thread_mutex_init( &chk_syntax_mutex );
1779
1780         ppolicy.on_bi.bi_type = "ppolicy";
1781         ppolicy.on_bi.bi_db_init = ppolicy_db_init;
1782         ppolicy.on_bi.bi_db_open = ppolicy_db_open;
1783         ppolicy.on_bi.bi_db_config = ppolicy_config;
1784         ppolicy.on_bi.bi_db_close = ppolicy_close;
1785
1786         ppolicy.on_bi.bi_op_add = ppolicy_add;
1787         ppolicy.on_bi.bi_op_bind = ppolicy_bind;
1788         ppolicy.on_bi.bi_op_compare = ppolicy_restrict;
1789         ppolicy.on_bi.bi_op_delete = ppolicy_restrict;
1790         ppolicy.on_bi.bi_op_modify = ppolicy_modify;
1791         ppolicy.on_bi.bi_op_search = ppolicy_restrict;
1792         ppolicy.on_bi.bi_connection_destroy = ppolicy_connection_destroy;
1793
1794         return overlay_register( &ppolicy );
1795 }
1796
1797 #if SLAPD_OVER_PPOLICY == SLAPD_MOD_DYNAMIC
1798 int init_module(int argc, char *argv[]) {
1799         return ppolicy_init();
1800 }
1801 #endif
1802
1803 #endif  /* defined(SLAPD_OVER_PPOLICY) */