]> git.sur5r.net Git - openldap/blob - servers/slapd/overlays/ppolicy.c
ITS#6152 add olcProxyCacheOffline for manually toggling cache expiration,
[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         LDAPControl **oldctrls;
861         Modifications *mod;
862         LDAPPasswordPolicyError pErr;
863         PassPolicy pp;
864 } ppbind;
865
866 static void
867 ctrls_cleanup( Operation *op, SlapReply *rs, LDAPControl **oldctrls )
868 {
869         int n;
870
871         assert( rs->sr_ctrls != NULL );
872         assert( rs->sr_ctrls[0] != NULL );
873
874         for ( n = 0; rs->sr_ctrls[n]; n++ ) {
875                 if ( rs->sr_ctrls[n]->ldctl_oid == ppolicy_ctrl_oid ) {
876                         op->o_tmpfree( rs->sr_ctrls[n], op->o_tmpmemctx );
877                         rs->sr_ctrls[n] = (LDAPControl *)(-1);
878                         break;
879                 }
880         }
881
882         if ( rs->sr_ctrls[n] == NULL ) {
883                 /* missed? */
884         }
885
886         op->o_tmpfree( rs->sr_ctrls, op->o_tmpmemctx );
887
888         rs->sr_ctrls = oldctrls;
889 }
890
891 static int
892 ppolicy_ctrls_cleanup( Operation *op, SlapReply *rs )
893 {
894         ppbind *ppb = op->o_callback->sc_private;
895         if ( ppb->send_ctrl ) {
896                 ctrls_cleanup( op, rs, ppb->oldctrls );
897         }
898         return SLAP_CB_CONTINUE;
899 }
900
901 static int
902 ppolicy_bind_response( Operation *op, SlapReply *rs )
903 {
904         ppbind *ppb = op->o_callback->sc_private;
905         slap_overinst *on = ppb->on;
906         Modifications *mod = ppb->mod, *m;
907         int pwExpired = 0;
908         int ngut = -1, warn = -1, age, rc;
909         Attribute *a;
910         time_t now, pwtime = (time_t)-1;
911         char nowstr[ LDAP_LUTIL_GENTIME_BUFSIZE ];
912         struct berval timestamp;
913         BackendInfo *bi = op->o_bd->bd_info;
914         Entry *e;
915
916         /* If we already know it's locked, just get on with it */
917         if ( ppb->pErr != PP_noError ) {
918                 goto locked;
919         }
920
921         op->o_bd->bd_info = (BackendInfo *)on->on_info;
922         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
923         op->o_bd->bd_info = bi;
924
925         if ( rc != LDAP_SUCCESS ) {
926                 return SLAP_CB_CONTINUE;
927         }
928
929         now = slap_get_time(); /* stored for later consideration */
930         timestamp.bv_val = nowstr;
931         timestamp.bv_len = sizeof(nowstr);
932         slap_timestamp( &now, &timestamp );
933
934         if ( rs->sr_err == LDAP_INVALID_CREDENTIALS ) {
935                 int i = 0, fc = 0;
936
937                 m = ch_calloc( sizeof(Modifications), 1 );
938                 m->sml_op = LDAP_MOD_ADD;
939                 m->sml_flags = 0;
940                 m->sml_type = ad_pwdFailureTime->ad_cname;
941                 m->sml_desc = ad_pwdFailureTime;
942                 m->sml_numvals = 1;
943                 m->sml_values = ch_calloc( sizeof(struct berval), 2 );
944                 m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
945
946                 ber_dupbv( &m->sml_values[0], &timestamp );
947                 ber_dupbv( &m->sml_nvalues[0], &timestamp );
948                 m->sml_next = mod;
949                 mod = m;
950
951                 /*
952                  * Count the pwdFailureTimes - if it's
953                  * greater than the policy pwdMaxFailure,
954                  * then lock the account.
955                  */
956                 if ((a = attr_find( e->e_attrs, ad_pwdFailureTime )) != NULL) {
957                         for(i=0; a->a_nvals[i].bv_val; i++) {
958
959                                 /*
960                                  * If the interval is 0, then failures
961                                  * stay on the record until explicitly
962                                  * reset by successful authentication.
963                                  */
964                                 if (ppb->pp.pwdFailureCountInterval == 0) {
965                                         fc++;
966                                 } else if (now <=
967                                                         parse_time(a->a_nvals[i].bv_val) +
968                                                         ppb->pp.pwdFailureCountInterval) {
969
970                                         fc++;
971                                 }
972                                 /*
973                                  * We only count those failures
974                                  * which are not due to expire.
975                                  */
976                         }
977                 }
978                 
979                 if ((ppb->pp.pwdMaxFailure > 0) &&
980                         (fc >= ppb->pp.pwdMaxFailure - 1)) {
981
982                         /*
983                          * We subtract 1 from the failure max
984                          * because the new failure entry hasn't
985                          * made it to the entry yet.
986                          */
987                         m = ch_calloc( sizeof(Modifications), 1 );
988                         m->sml_op = LDAP_MOD_REPLACE;
989                         m->sml_flags = 0;
990                         m->sml_type = ad_pwdAccountLockedTime->ad_cname;
991                         m->sml_desc = ad_pwdAccountLockedTime;
992                         m->sml_numvals = 1;
993                         m->sml_values = ch_calloc( sizeof(struct berval), 2 );
994                         m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
995                         ber_dupbv( &m->sml_values[0], &timestamp );
996                         ber_dupbv( &m->sml_nvalues[0], &timestamp );
997                         m->sml_next = mod;
998                         mod = m;
999                 }
1000         } else if ( rs->sr_err == LDAP_SUCCESS ) {
1001                 if ((a = attr_find( e->e_attrs, ad_pwdChangedTime )) != NULL)
1002                         pwtime = parse_time( a->a_nvals[0].bv_val );
1003
1004                 /* delete all pwdFailureTimes */
1005                 if ( attr_find( e->e_attrs, ad_pwdFailureTime )) {
1006                         m = ch_calloc( sizeof(Modifications), 1 );
1007                         m->sml_op = LDAP_MOD_DELETE;
1008                         m->sml_flags = 0;
1009                         m->sml_type = ad_pwdFailureTime->ad_cname;
1010                         m->sml_desc = ad_pwdFailureTime;
1011                         m->sml_next = mod;
1012                         mod = m;
1013                 }
1014
1015                 /*
1016                  * check to see if the password must be changed
1017                  */
1018                 if ( ppb->pp.pwdMustChange &&
1019                         (a = attr_find( e->e_attrs, ad_pwdReset )) &&
1020                         bvmatch( &a->a_nvals[0], &slap_true_bv ) )
1021                 {
1022                         /*
1023                          * need to inject client controls here to give
1024                          * more information. For the moment, we ensure
1025                          * that we are disallowed from doing anything
1026                          * other than change password.
1027                          */
1028                         ber_dupbv( &pwcons[op->o_conn->c_conn_idx].dn,
1029                                 &op->o_conn->c_ndn );
1030
1031                         ppb->pErr = PP_changeAfterReset;
1032
1033                 } else {
1034                         /*
1035                          * the password does not need to be changed, so
1036                          * we now check whether the password has expired.
1037                          *
1038                          * We can skip this bit if passwords don't age in
1039                          * the policy. Also, if there was no pwdChangedTime
1040                          * attribute in the entry, the password never expires.
1041                          */
1042                         if (ppb->pp.pwdMaxAge == 0) goto grace;
1043
1044                         if (pwtime != (time_t)-1) {
1045                                 /*
1046                                  * Check: was the last change time of
1047                                  * the password older than the maximum age
1048                                  * allowed. (Ignore case 2 from I-D, it's just silly.)
1049                                  */
1050                                 if (now - pwtime > ppb->pp.pwdMaxAge ) pwExpired = 1;
1051                         }
1052                 }
1053
1054 grace:
1055                 if (!pwExpired) goto check_expiring_password;
1056                 
1057                 if ((a = attr_find( e->e_attrs, ad_pwdGraceUseTime )) == NULL)
1058                         ngut = ppb->pp.pwdGraceAuthNLimit;
1059                 else {
1060                         for(ngut=0; a->a_nvals[ngut].bv_val; ngut++);
1061                         ngut = ppb->pp.pwdGraceAuthNLimit - ngut;
1062                 }
1063
1064                 /*
1065                  * ngut is the number of remaining grace logins
1066                  */
1067                 Debug( LDAP_DEBUG_ANY,
1068                         "ppolicy_bind: Entry %s has an expired password: %d grace logins\n",
1069                         e->e_name.bv_val, ngut, 0);
1070                 
1071                 if (ngut < 1) {
1072                         ppb->pErr = PP_passwordExpired;
1073                         rs->sr_err = LDAP_INVALID_CREDENTIALS;
1074                         goto done;
1075                 }
1076
1077                 /*
1078                  * Add a grace user time to the entry
1079                  */
1080                 m = ch_calloc( sizeof(Modifications), 1 );
1081                 m->sml_op = LDAP_MOD_ADD;
1082                 m->sml_flags = 0;
1083                 m->sml_type = ad_pwdGraceUseTime->ad_cname;
1084                 m->sml_desc = ad_pwdGraceUseTime;
1085                 m->sml_numvals = 1;
1086                 m->sml_values = ch_calloc( sizeof(struct berval), 2 );
1087                 m->sml_nvalues = ch_calloc( sizeof(struct berval), 2 );
1088                 ber_dupbv( &m->sml_values[0], &timestamp );
1089                 ber_dupbv( &m->sml_nvalues[0], &timestamp );
1090                 m->sml_next = mod;
1091                 mod = m;
1092
1093 check_expiring_password:
1094                 /*
1095                  * Now we need to check to see
1096                  * if it is about to expire, and if so, should the user
1097                  * be warned about it in the password policy control.
1098                  *
1099                  * If the password has expired, and we're in the grace period, then
1100                  * we don't need to do this bit. Similarly, if we don't have password
1101                  * aging, then there's no need to do this bit either.
1102                  */
1103                 if ((ppb->pp.pwdMaxAge < 1) || (pwExpired) || (ppb->pp.pwdExpireWarning < 1))
1104                         goto done;
1105
1106                 age = (int)(now - pwtime);
1107                 
1108                 /*
1109                  * We know that there is a password Change Time attribute - if
1110                  * there wasn't, then the pwdExpired value would be true, unless
1111                  * there is no password aging - and if there is no password aging,
1112                  * then this section isn't called anyway - you can't have an
1113                  * expiring password if there's no limit to expire.
1114                  */
1115                 if (ppb->pp.pwdMaxAge - age < ppb->pp.pwdExpireWarning ) {
1116                         /*
1117                          * Set the warning value.
1118                          */
1119                         warn = ppb->pp.pwdMaxAge - age; /* seconds left until expiry */
1120                         if (warn < 0) warn = 0; /* something weird here - why is pwExpired not set? */
1121                         
1122                         Debug( LDAP_DEBUG_ANY,
1123                                 "ppolicy_bind: Setting warning for password expiry for %s = %d seconds\n",
1124                                 op->o_req_dn.bv_val, warn, 0 );
1125                 }
1126         }
1127
1128 done:
1129         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1130         be_entry_release_r( op, e );
1131
1132 locked:
1133         if ( mod ) {
1134                 Operation op2 = *op;
1135                 SlapReply r2 = { REP_RESULT };
1136                 slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
1137                 pp_info *pi = on->on_bi.bi_private;
1138                 LDAPControl c, *ca[2];
1139
1140                 op2.o_tag = LDAP_REQ_MODIFY;
1141                 op2.o_callback = &cb;
1142                 op2.orm_modlist = mod;
1143                 op2.o_dn = op->o_bd->be_rootdn;
1144                 op2.o_ndn = op->o_bd->be_rootndn;
1145
1146                 /* If this server is a shadow and forward_updates is true,
1147                  * use the frontend to perform this modify. That will trigger
1148                  * the update referral, which can then be forwarded by the
1149                  * chain overlay. Obviously the updateref and chain overlay
1150                  * must be configured appropriately for this to be useful.
1151                  */
1152                 if ( SLAP_SHADOW( op->o_bd ) && pi->forward_updates ) {
1153                         op2.o_bd = frontendDB;
1154
1155                         /* Must use Relax control since these are no-user-mod */
1156                         op2.o_relax = SLAP_CONTROL_CRITICAL;
1157                         op2.o_ctrls = ca;
1158                         ca[0] = &c;
1159                         ca[1] = NULL;
1160                         BER_BVZERO( &c.ldctl_value );
1161                         c.ldctl_iscritical = 1;
1162                         c.ldctl_oid = LDAP_CONTROL_RELAX;
1163                 } else {
1164                         op2.o_bd->bd_info = (BackendInfo *)on->on_info;
1165                 }
1166                 rc = op2.o_bd->be_modify( &op2, &r2 );
1167                 slap_mods_free( mod, 1 );
1168         }
1169
1170         if ( ppb->send_ctrl ) {
1171                 LDAPControl *ctrl = NULL;
1172                 pp_info *pi = on->on_bi.bi_private;
1173
1174                 /* Do we really want to tell that the account is locked? */
1175                 if ( ppb->pErr == PP_accountLocked && !pi->use_lockout ) {
1176                         ppb->pErr = PP_noError;
1177                 }
1178                 ctrl = create_passcontrol( op, warn, ngut, ppb->pErr );
1179                 ppb->oldctrls = add_passcontrol( op, rs, ctrl );
1180                 op->o_callback->sc_cleanup = ppolicy_ctrls_cleanup;
1181         }
1182         op->o_bd->bd_info = bi;
1183         return SLAP_CB_CONTINUE;
1184 }
1185
1186 static int
1187 ppolicy_bind( Operation *op, SlapReply *rs )
1188 {
1189         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1190
1191         /* Reset lockout status on all Bind requests */
1192         if ( !BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
1193                 ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1194                 BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1195         }
1196
1197         /* Root bypasses policy */
1198         if ( !be_isroot_dn( op->o_bd, &op->o_req_ndn )) {
1199                 Entry *e;
1200                 int rc;
1201                 ppbind *ppb;
1202                 slap_callback *cb;
1203
1204                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1205                 rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1206
1207                 if ( rc != LDAP_SUCCESS ) {
1208                         return SLAP_CB_CONTINUE;
1209                 }
1210
1211                 cb = op->o_tmpcalloc( sizeof(ppbind)+sizeof(slap_callback),
1212                         1, op->o_tmpmemctx );
1213                 ppb = (ppbind *)(cb+1);
1214                 ppb->on = on;
1215                 ppb->pErr = PP_noError;
1216
1217                 /* Setup a callback so we can munge the result */
1218
1219                 cb->sc_response = ppolicy_bind_response;
1220                 cb->sc_next = op->o_callback->sc_next;
1221                 cb->sc_private = ppb;
1222                 op->o_callback->sc_next = cb;
1223
1224                 /* Did we receive a password policy request control? */
1225                 if ( op->o_ctrlflag[ppolicy_cid] ) {
1226                         ppb->send_ctrl = 1;
1227                 }
1228
1229                 op->o_bd->bd_info = (BackendInfo *)on;
1230                 ppolicy_get( op, e, &ppb->pp );
1231
1232                 rc = account_locked( op, e, &ppb->pp, &ppb->mod );
1233
1234                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1235                 be_entry_release_r( op, e );
1236
1237                 if ( rc ) {
1238                         /* This will be the Draft 8 response, Unwilling is bogus */
1239                         ppb->pErr = PP_accountLocked;
1240                         send_ldap_error( op, rs, LDAP_INVALID_CREDENTIALS, NULL );
1241                         return rs->sr_err;
1242                 }
1243
1244         }
1245
1246         return SLAP_CB_CONTINUE;
1247 }
1248
1249 /* Reset the restricted info for the next session on this connection */
1250 static int
1251 ppolicy_connection_destroy( BackendDB *bd, Connection *conn )
1252 {
1253         if ( !BER_BVISEMPTY( &pwcons[conn->c_conn_idx].dn )) {
1254                 ch_free( pwcons[conn->c_conn_idx].dn.bv_val );
1255                 BER_BVZERO( &pwcons[conn->c_conn_idx].dn );
1256         }
1257         return SLAP_CB_CONTINUE;
1258 }
1259
1260 /* Check if this connection is restricted */
1261 static int
1262 ppolicy_restrict(
1263         Operation *op,
1264         SlapReply *rs )
1265 {
1266         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1267         int send_ctrl = 0;
1268
1269         /* Did we receive a password policy request control? */
1270         if ( op->o_ctrlflag[ppolicy_cid] ) {
1271                 send_ctrl = 1;
1272         }
1273
1274         if ( op->o_conn && !BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
1275                 LDAPControl **oldctrls;
1276                 /* if the current authcDN doesn't match the one we recorded,
1277                  * then an intervening Bind has succeeded and the restriction
1278                  * no longer applies. (ITS#4516)
1279                  */
1280                 if ( !dn_match( &op->o_conn->c_ndn,
1281                                 &pwcons[op->o_conn->c_conn_idx].dn )) {
1282                         ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1283                         BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1284                         return SLAP_CB_CONTINUE;
1285                 }
1286
1287                 Debug( LDAP_DEBUG_TRACE,
1288                         "connection restricted to password changing only\n", 0, 0, 0);
1289                 if ( send_ctrl ) {
1290                         LDAPControl *ctrl = NULL;
1291                         ctrl = create_passcontrol( op, -1, -1, PP_changeAfterReset );
1292                         oldctrls = add_passcontrol( op, rs, ctrl );
1293                 }
1294                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1295                 send_ldap_error( op, rs, LDAP_INSUFFICIENT_ACCESS, 
1296                         "Operations are restricted to bind/unbind/abandon/StartTLS/modify password" );
1297                 if ( send_ctrl ) {
1298                         ctrls_cleanup( op, rs, oldctrls );
1299                 }
1300                 return rs->sr_err;
1301         }
1302
1303         return SLAP_CB_CONTINUE;
1304 }
1305
1306 static int
1307 ppolicy_add(
1308         Operation *op,
1309         SlapReply *rs )
1310 {
1311         slap_overinst *on = (slap_overinst *)op->o_bd->bd_info;
1312         pp_info *pi = on->on_bi.bi_private;
1313         PassPolicy pp;
1314         Attribute *pa;
1315         const char *txt;
1316
1317         if ( ppolicy_restrict( op, rs ) != SLAP_CB_CONTINUE )
1318                 return rs->sr_err;
1319
1320         /* If this is a replica, assume the master checked everything */
1321         if ( be_shadow_update( op ))
1322                 return SLAP_CB_CONTINUE;
1323
1324         /* Check for password in entry */
1325         if ((pa = attr_find( op->oq_add.rs_e->e_attrs,
1326                 slap_schema.si_ad_userPassword )))
1327         {
1328                 assert( pa->a_vals != NULL );
1329                 assert( !BER_BVISNULL( &pa->a_vals[ 0 ] ) );
1330
1331                 if ( !BER_BVISNULL( &pa->a_vals[ 1 ] ) ) {
1332                         send_ldap_error( op, rs, LDAP_CONSTRAINT_VIOLATION, "Password policy only allows one password value" );
1333                         return rs->sr_err;
1334                 }
1335
1336                 /*
1337                  * new entry contains a password - if we're not the root user
1338                  * then we need to check that the password fits in with the
1339                  * security policy for the new entry.
1340                  */
1341                 ppolicy_get( op, op->ora_e, &pp );
1342                 if (pp.pwdCheckQuality > 0 && !be_isroot( op )) {
1343                         struct berval *bv = &(pa->a_vals[0]);
1344                         int rc, send_ctrl = 0;
1345                         LDAPPasswordPolicyError pErr = PP_noError;
1346                         char *txt;
1347
1348                         /* Did we receive a password policy request control? */
1349                         if ( op->o_ctrlflag[ppolicy_cid] ) {
1350                                 send_ctrl = 1;
1351                         }
1352                         rc = check_password_quality( bv, &pp, &pErr, op->ora_e, &txt );
1353                         if (rc != LDAP_SUCCESS) {
1354                                 LDAPControl **oldctrls = NULL;
1355                                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1356                                 if ( send_ctrl ) {
1357                                         LDAPControl *ctrl = NULL;
1358                                         ctrl = create_passcontrol( op, -1, -1, pErr );
1359                                         oldctrls = add_passcontrol( op, rs, ctrl );
1360                                 }
1361                                 send_ldap_error( op, rs, rc, txt ? txt : "Password fails quality checking policy" );
1362                                 if ( txt ) {
1363                                         free( txt );
1364                                 }
1365                                 if ( send_ctrl ) {
1366                                         ctrls_cleanup( op, rs, oldctrls );
1367                                 }
1368                                 return rs->sr_err;
1369                         }
1370                 }
1371                         /*
1372                          * A controversial bit. We hash cleartext
1373                          * passwords provided via add and modify operations
1374                          * You're not really supposed to do this, since
1375                          * the X.500 model says "store attributes" as they
1376                          * get provided. By default, this is what we do
1377                          *
1378                          * But if the hash_passwords flag is set, we hash
1379                          * any cleartext password attribute values via the
1380                          * default password hashing scheme.
1381                          */
1382                 if ((pi->hash_passwords) &&
1383                         (password_scheme( &(pa->a_vals[0]), NULL ) != LDAP_SUCCESS)) {
1384                         struct berval hpw;
1385
1386                         slap_passwd_hash( &(pa->a_vals[0]), &hpw, &txt );
1387                         if (hpw.bv_val == NULL) {
1388                                 /*
1389                                  * hashing didn't work. Emit an error.
1390                                  */
1391                                 rs->sr_err = LDAP_OTHER;
1392                                 rs->sr_text = txt;
1393                                 send_ldap_error( op, rs, LDAP_OTHER, "Password hashing failed" );
1394                                 return rs->sr_err;
1395                         }
1396
1397                         memset( pa->a_vals[0].bv_val, 0, pa->a_vals[0].bv_len);
1398                         ber_memfree( pa->a_vals[0].bv_val );
1399                         pa->a_vals[0].bv_val = hpw.bv_val;
1400                         pa->a_vals[0].bv_len = hpw.bv_len;
1401                 }
1402
1403                 /* If password aging is in effect, set the pwdChangedTime */
1404                 if ( pp.pwdMaxAge || pp.pwdMinAge ) {
1405                         struct berval timestamp;
1406                         char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
1407                         time_t now = slap_get_time();
1408
1409                         timestamp.bv_val = timebuf;
1410                         timestamp.bv_len = sizeof(timebuf);
1411                         slap_timestamp( &now, &timestamp );
1412
1413                         attr_merge_one( op->ora_e, ad_pwdChangedTime, &timestamp, &timestamp );
1414                 }
1415         }
1416         return SLAP_CB_CONTINUE;
1417 }
1418
1419 static int
1420 ppolicy_mod_cb( Operation *op, SlapReply *rs )
1421 {
1422         slap_callback *sc = op->o_callback;
1423         op->o_callback = sc->sc_next;
1424         if ( rs->sr_err == LDAP_SUCCESS ) {
1425                 ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1426                 BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1427         }
1428         op->o_tmpfree( sc, op->o_tmpmemctx );
1429         return SLAP_CB_CONTINUE;
1430 }
1431
1432 static int
1433 ppolicy_modify( Operation *op, SlapReply *rs )
1434 {
1435         slap_overinst           *on = (slap_overinst *)op->o_bd->bd_info;
1436         pp_info                 *pi = on->on_bi.bi_private;
1437         int                     i, rc, mod_pw_only, pwmod, pwmop = -1, deladd,
1438                                 hsize = 0;
1439         PassPolicy              pp;
1440         Modifications           *mods = NULL, *modtail = NULL,
1441                                 *ml, *delmod, *addmod;
1442         Attribute               *pa, *ha, at;
1443         const char              *txt;
1444         pw_hist                 *tl = NULL, *p;
1445         int                     zapReset, send_ctrl = 0, free_txt = 0;
1446         Entry                   *e;
1447         struct berval           newpw = BER_BVNULL, oldpw = BER_BVNULL,
1448                                 *bv, cr[2];
1449         LDAPPasswordPolicyError pErr = PP_noError;
1450         LDAPControl             *ctrl = NULL;
1451         LDAPControl             **oldctrls = NULL;
1452         int                     is_pwdexop = 0;
1453
1454         op->o_bd->bd_info = (BackendInfo *)on->on_info;
1455         rc = be_entry_get_rw( op, &op->o_req_ndn, NULL, NULL, 0, &e );
1456         op->o_bd->bd_info = (BackendInfo *)on;
1457
1458         if ( rc != LDAP_SUCCESS ) return SLAP_CB_CONTINUE;
1459
1460         /* If this is a replica, we may need to tweak some of the
1461          * master's modifications. Otherwise, just pass it through.
1462          */
1463         if ( be_shadow_update( op )) {
1464                 Modifications **prev;
1465                 int got_del_grace = 0, got_del_lock = 0, got_pw = 0, got_del_fail = 0;
1466                 Attribute *a_grace, *a_lock, *a_fail;
1467
1468                 a_grace = attr_find( e->e_attrs, ad_pwdGraceUseTime );
1469                 a_lock = attr_find( e->e_attrs, ad_pwdAccountLockedTime );
1470                 a_fail = attr_find( e->e_attrs, ad_pwdFailureTime );
1471
1472                 for( prev = &op->orm_modlist, ml = *prev; ml; ml = *prev ) {
1473
1474                         if ( ml->sml_desc == slap_schema.si_ad_userPassword )
1475                                 got_pw = 1;
1476
1477                         /* If we're deleting an attr that didn't exist,
1478                          * drop this delete op
1479                          */
1480                         if ( ml->sml_op == LDAP_MOD_DELETE ) {
1481                                 int drop = 0;
1482
1483                                 if ( ml->sml_desc == ad_pwdGraceUseTime ) {
1484                                         got_del_grace = 1;
1485                                         if ( !a_grace )
1486                                                 drop = 1;
1487                                 } else
1488                                 if ( ml->sml_desc == ad_pwdAccountLockedTime ) {
1489                                         got_del_lock = 1;
1490                                         if ( !a_lock )
1491                                                 drop = 1;
1492                                 } else
1493                                 if ( ml->sml_desc == ad_pwdFailureTime ) {
1494                                         got_del_fail = 1;
1495                                         if ( !a_fail )
1496                                                 drop = 1;
1497                                 }
1498                                 if ( drop ) {
1499                                         *prev = ml->sml_next;
1500                                         ml->sml_next = NULL;
1501                                         slap_mods_free( ml, 1 );
1502                                         continue;
1503                                 }
1504                         }
1505                         prev = &ml->sml_next;
1506                 }
1507
1508                 /* If we're resetting the password, make sure grace, accountlock,
1509                  * and failure also get removed.
1510                  */
1511                 if ( got_pw ) {
1512                         if ( a_grace && !got_del_grace ) {
1513                                 ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
1514                                 ml->sml_op = LDAP_MOD_DELETE;
1515                                 ml->sml_flags = SLAP_MOD_INTERNAL;
1516                                 ml->sml_type.bv_val = NULL;
1517                                 ml->sml_desc = ad_pwdGraceUseTime;
1518                                 ml->sml_numvals = 0;
1519                                 ml->sml_values = NULL;
1520                                 ml->sml_nvalues = NULL;
1521                                 ml->sml_next = NULL;
1522                                 *prev = ml;
1523                                 prev = &ml->sml_next;
1524                         }
1525                         if ( a_lock && !got_del_lock ) {
1526                                 ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
1527                                 ml->sml_op = LDAP_MOD_DELETE;
1528                                 ml->sml_flags = SLAP_MOD_INTERNAL;
1529                                 ml->sml_type.bv_val = NULL;
1530                                 ml->sml_desc = ad_pwdAccountLockedTime;
1531                                 ml->sml_numvals = 0;
1532                                 ml->sml_values = NULL;
1533                                 ml->sml_nvalues = NULL;
1534                                 ml->sml_next = NULL;
1535                                 *prev = ml;
1536                         }
1537                         if ( a_fail && !got_del_fail ) {
1538                                 ml = (Modifications *) ch_malloc( sizeof( Modifications ) );
1539                                 ml->sml_op = LDAP_MOD_DELETE;
1540                                 ml->sml_flags = SLAP_MOD_INTERNAL;
1541                                 ml->sml_type.bv_val = NULL;
1542                                 ml->sml_desc = ad_pwdFailureTime;
1543                                 ml->sml_numvals = 0;
1544                                 ml->sml_values = NULL;
1545                                 ml->sml_nvalues = NULL;
1546                                 ml->sml_next = NULL;
1547                                 *prev = ml;
1548                         }
1549                 }
1550                 op->o_bd->bd_info = (BackendInfo *)on->on_info;
1551                 be_entry_release_r( op, e );
1552                 return SLAP_CB_CONTINUE;
1553         }
1554
1555         /* Did we receive a password policy request control? */
1556         if ( op->o_ctrlflag[ppolicy_cid] ) {
1557                 send_ctrl = 1;
1558         }
1559
1560         /* See if this is a pwdModify exop. If so, we can
1561          * access the plaintext passwords from that request.
1562          */
1563         {
1564                 slap_callback *sc;
1565
1566                 for ( sc = op->o_callback; sc; sc=sc->sc_next ) {
1567                         if ( sc->sc_response == slap_null_cb &&
1568                                 sc->sc_private ) {
1569                                 req_pwdexop_s *qpw = sc->sc_private;
1570                                 newpw = qpw->rs_new;
1571                                 oldpw = qpw->rs_old;
1572                                 is_pwdexop = 1;
1573                                 break;
1574                         }
1575                 }
1576         }
1577
1578         ppolicy_get( op, e, &pp );
1579
1580         for ( ml = op->orm_modlist,
1581                         pwmod = 0, mod_pw_only = 1,
1582                         deladd = 0, delmod = NULL,
1583                         addmod = NULL,
1584                         zapReset = 1;
1585                 ml != NULL; modtail = ml, ml = ml->sml_next )
1586         {
1587                 if ( ml->sml_desc == pp.ad ) {
1588                         pwmod = 1;
1589                         pwmop = ml->sml_op;
1590                         if ((deladd == 0) && (ml->sml_op == LDAP_MOD_DELETE) &&
1591                                 (ml->sml_values) && !BER_BVISNULL( &ml->sml_values[0] ))
1592                         {
1593                                 deladd = 1;
1594                                 delmod = ml;
1595                         }
1596
1597                         if ((ml->sml_op == LDAP_MOD_ADD) ||
1598                                 (ml->sml_op == LDAP_MOD_REPLACE))
1599                         {
1600                                 if ( ml->sml_values && !BER_BVISNULL( &ml->sml_values[0] )) {
1601                                         if ( deladd == 1 )
1602                                                 deladd = 2;
1603
1604                                         /* FIXME: there's no easy way to ensure
1605                                          * that add does not cause multiple
1606                                          * userPassword values; one way (that 
1607                                          * would be consistent with the single
1608                                          * password constraint) would be to turn
1609                                          * add into replace); another would be
1610                                          * to disallow add.
1611                                          *
1612                                          * Let's check at least that a single value
1613                                          * is being added
1614                                          */
1615                                         if ( addmod || !BER_BVISNULL( &ml->sml_values[ 1 ] ) ) {
1616                                                 rs->sr_err = LDAP_CONSTRAINT_VIOLATION; 
1617                                                 rs->sr_text = "Password policy only allows one password value";
1618                                                 goto return_results;
1619                                         }
1620
1621                                         addmod = ml;
1622                                 } else {
1623                                         /* replace can have no values, add cannot */
1624                                         assert( ml->sml_op == LDAP_MOD_REPLACE );
1625                                 }
1626                         }
1627
1628                 } else if ( !(ml->sml_flags & SLAP_MOD_INTERNAL) && !is_at_operational( ml->sml_desc->ad_type ) ) {
1629                         mod_pw_only = 0;
1630                         /* modifying something other than password */
1631                 }
1632
1633                 /*
1634                  * If there is a request to explicitly add a pwdReset
1635                  * attribute, then we suppress the normal behaviour on
1636                  * password change, which is to remove the pwdReset
1637                  * attribute.
1638                  *
1639                  * This enables an administrator to assign a new password
1640                  * and place a "must reset" flag on the entry, which will
1641                  * stay until the user explicitly changes his/her password.
1642                  */
1643                 if (ml->sml_desc == ad_pwdReset ) {
1644                         if ((ml->sml_op == LDAP_MOD_ADD) ||
1645                                 (ml->sml_op == LDAP_MOD_REPLACE))
1646                                 zapReset = 0;
1647                 }
1648         }
1649         
1650         if (!BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn ) && !mod_pw_only ) {
1651                 if ( dn_match( &op->o_conn->c_ndn,
1652                                 &pwcons[op->o_conn->c_conn_idx].dn )) {
1653                         Debug( LDAP_DEBUG_TRACE,
1654                                 "connection restricted to password changing only\n", 0, 0, 0 );
1655                         rs->sr_err = LDAP_INSUFFICIENT_ACCESS; 
1656                         rs->sr_text = "Operations are restricted to bind/unbind/abandon/StartTLS/modify password";
1657                         pErr = PP_changeAfterReset;
1658                         goto return_results;
1659                 } else {
1660                         ch_free( pwcons[op->o_conn->c_conn_idx].dn.bv_val );
1661                         BER_BVZERO( &pwcons[op->o_conn->c_conn_idx].dn );
1662                 }
1663         }
1664
1665         /*
1666          * if we have a "safe password modify policy", then we need to check if we're doing
1667          * a delete (with the old password), followed by an add (with the new password).
1668          *
1669          * If we got just a delete with nothing else, just let it go. We also skip all the checks if
1670          * the root user is bound. Root can do anything, including avoid the policies.
1671          */
1672
1673         if (!pwmod) goto do_modify;
1674
1675         /*
1676          * Build the password history list in ascending time order
1677          * We need this, even if the user is root, in order to maintain
1678          * the pwdHistory operational attributes properly.
1679          */
1680         if (addmod && pp.pwdInHistory > 0 && (ha = attr_find( e->e_attrs, ad_pwdHistory ))) {
1681                 struct berval oldpw;
1682                 time_t oldtime;
1683
1684                 for(i=0; ha->a_nvals[i].bv_val; i++) {
1685                         rc = parse_pwdhistory( &(ha->a_nvals[i]), NULL,
1686                                 &oldtime, &oldpw );
1687
1688                         if (rc != LDAP_SUCCESS) continue; /* invalid history entry */
1689
1690                         if (oldpw.bv_val) {
1691                                 add_to_pwd_history( &tl, oldtime, &oldpw,
1692                                         &(ha->a_nvals[i]) );
1693                                 oldpw.bv_val = NULL;
1694                                 oldpw.bv_len = 0;
1695                         }
1696                 }
1697                 for(p=tl; p; p=p->next, hsize++); /* count history size */
1698         }
1699
1700         if (be_isroot( op )) goto do_modify;
1701
1702         if (!pp.pwdAllowUserChange) {
1703                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1704                 rs->sr_text = "User alteration of password is not allowed";
1705                 pErr = PP_passwordModNotAllowed;
1706                 goto return_results;
1707         }
1708
1709         /* Just deleting? */
1710         if (!addmod) {
1711                 /* skip everything else */
1712                 pwmod = 0;
1713                 goto do_modify;
1714         }
1715
1716         /* This is a pwdModify exop that provided the old pw.
1717          * We need to create a Delete mod for this old pw and 
1718          * let the matching value get found later
1719          */
1720         if (pp.pwdSafeModify && oldpw.bv_val ) {
1721                 ml = (Modifications *)ch_calloc( sizeof( Modifications ), 1 );
1722                 ml->sml_op = LDAP_MOD_DELETE;
1723                 ml->sml_flags = SLAP_MOD_INTERNAL;
1724                 ml->sml_desc = pp.ad;
1725                 ml->sml_type = pp.ad->ad_cname;
1726                 ml->sml_numvals = 1;
1727                 ml->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
1728                 ber_dupbv( &ml->sml_values[0], &oldpw );
1729                 BER_BVZERO( &ml->sml_values[1] );
1730                 ml->sml_next = op->orm_modlist;
1731                 op->orm_modlist = ml;
1732                 delmod = ml;
1733                 deladd = 2;
1734         }
1735
1736         if (pp.pwdSafeModify && deladd != 2) {
1737                 Debug( LDAP_DEBUG_TRACE,
1738                         "change password must use DELETE followed by ADD/REPLACE\n",
1739                         0, 0, 0 );
1740                 rs->sr_err = LDAP_INSUFFICIENT_ACCESS;
1741                 rs->sr_text = "Must supply old password to be changed as well as new one";
1742                 pErr = PP_mustSupplyOldPassword;
1743                 goto return_results;
1744         }
1745
1746         /* Check age, but only if pwdReset is not TRUE */
1747         pa = attr_find( e->e_attrs, ad_pwdReset );
1748         if ((!pa || !bvmatch( &pa->a_nvals[0], &slap_true_bv )) &&
1749                 pp.pwdMinAge > 0) {
1750                 time_t pwtime = (time_t)-1, now;
1751                 int age;
1752
1753                 if ((pa = attr_find( e->e_attrs, ad_pwdChangedTime )) != NULL)
1754                         pwtime = parse_time( pa->a_nvals[0].bv_val );
1755                 now = slap_get_time();
1756                 age = (int)(now - pwtime);
1757                 if ((pwtime != (time_t)-1) && (age < pp.pwdMinAge)) {
1758                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1759                         rs->sr_text = "Password is too young to change";
1760                         pErr = PP_passwordTooYoung;
1761                         goto return_results;
1762                 }
1763         }
1764
1765         /* pa is used in password history check below, be sure it's set */
1766         if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL && delmod) {
1767                 /*
1768                  * we have a password to check
1769                  */
1770                 bv = oldpw.bv_val ? &oldpw : delmod->sml_values;
1771                 /* FIXME: no access checking? */
1772                 rc = slap_passwd_check( op, NULL, pa, bv, &txt );
1773                 if (rc != LDAP_SUCCESS) {
1774                         Debug( LDAP_DEBUG_TRACE,
1775                                 "old password check failed: %s\n", txt, 0, 0 );
1776                         
1777                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1778                         rs->sr_text = "Must supply correct old password to change to new one";
1779                         pErr = PP_mustSupplyOldPassword;
1780                         goto return_results;
1781
1782                 } else {
1783                         int i;
1784                         
1785                         /*
1786                          * replace the delete value with the (possibly hashed)
1787                          * value which is currently in the password.
1788                          */
1789                         for ( i = 0; !BER_BVISNULL( &delmod->sml_values[i] ); i++ ) {
1790                                 free( delmod->sml_values[i].bv_val );
1791                                 BER_BVZERO( &delmod->sml_values[i] );
1792                         }
1793                         free( delmod->sml_values );
1794                         delmod->sml_values = ch_calloc( sizeof(struct berval), 2 );
1795                         BER_BVZERO( &delmod->sml_values[1] );
1796                         ber_dupbv( &(delmod->sml_values[0]),  &(pa->a_nvals[0]) );
1797                 }
1798         }
1799
1800         bv = newpw.bv_val ? &newpw : &addmod->sml_values[0];
1801         if (pp.pwdCheckQuality > 0) {
1802
1803                 rc = check_password_quality( bv, &pp, &pErr, e, (char **)&txt );
1804                 if (rc != LDAP_SUCCESS) {
1805                         rs->sr_err = rc;
1806                         if ( txt ) {
1807                                 rs->sr_text = txt;
1808                                 free_txt = 1;
1809                         } else {
1810                                 rs->sr_text = "Password fails quality checking policy";
1811                         }
1812                         goto return_results;
1813                 }
1814         }
1815
1816         /* If pwdInHistory is zero, passwords may be reused */
1817         if (pa && pp.pwdInHistory > 0) {
1818                 /*
1819                  * Last check - the password history.
1820                  */
1821                 /* FIXME: no access checking? */
1822                 if (slap_passwd_check( op, NULL, pa, bv, &txt ) == LDAP_SUCCESS) {
1823                         /*
1824                          * This is bad - it means that the user is attempting
1825                          * to set the password to the same as the old one.
1826                          */
1827                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1828                         rs->sr_text = "Password is not being changed from existing value";
1829                         pErr = PP_passwordInHistory;
1830                         goto return_results;
1831                 }
1832         
1833                 /*
1834                  * Iterate through the password history, and fail on any
1835                  * password matches.
1836                  */
1837                 at = *pa;
1838                 at.a_vals = cr;
1839                 cr[1].bv_val = NULL;
1840                 for(p=tl; p; p=p->next) {
1841                         cr[0] = p->pw;
1842                         /* FIXME: no access checking? */
1843                         rc = slap_passwd_check( op, NULL, &at, bv, &txt );
1844                         
1845                         if (rc != LDAP_SUCCESS) continue;
1846                         
1847                         rs->sr_err = LDAP_CONSTRAINT_VIOLATION;
1848                         rs->sr_text = "Password is in history of old passwords";
1849                         pErr = PP_passwordInHistory;
1850                         goto return_results;
1851                 }
1852         }
1853
1854 do_modify:
1855         if (pwmod) {
1856                 struct berval timestamp;
1857                 char timebuf[ LDAP_LUTIL_GENTIME_BUFSIZE ];
1858                 time_t now = slap_get_time();
1859
1860                 /* If the conn is restricted, set a callback to clear it
1861                  * if the pwmod succeeds
1862                  */
1863                 if (!BER_BVISEMPTY( &pwcons[op->o_conn->c_conn_idx].dn )) {
1864                         slap_callback *sc = op->o_tmpcalloc( 1, sizeof( slap_callback ),
1865                                 op->o_tmpmemctx );
1866                         sc->sc_next = op->o_callback;
1867                         /* Must use sc_response to insure we reset on success, before
1868                          * the client sees the response. Must use sc_cleanup to insure
1869                          * that it gets cleaned up if sc_response is not called.
1870                          */
1871                         sc->sc_response = ppolicy_mod_cb;
1872                         sc->sc_cleanup = ppolicy_mod_cb;
1873                         op->o_callback = sc;
1874                 }
1875
1876                 /*
1877                  * keep the necessary pwd.. operational attributes
1878                  * up to date.
1879                  */
1880
1881                 timestamp.bv_val = timebuf;
1882                 timestamp.bv_len = sizeof(timebuf);
1883                 slap_timestamp( &now, &timestamp );
1884
1885                 mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1886                 mods->sml_desc = ad_pwdChangedTime;
1887                 if (pwmop != LDAP_MOD_DELETE) {
1888                         mods->sml_op = LDAP_MOD_REPLACE;
1889                         mods->sml_numvals = 1;
1890                         mods->sml_values = (BerVarray) ch_malloc( 2 * sizeof( struct berval ) );
1891                         ber_dupbv( &mods->sml_values[0], &timestamp );
1892                         BER_BVZERO( &mods->sml_values[1] );
1893                         assert( !BER_BVISNULL( &mods->sml_values[0] ) );
1894
1895                 } else {
1896                         mods->sml_op = LDAP_MOD_DELETE;
1897                 }
1898                 mods->sml_flags = SLAP_MOD_INTERNAL;
1899                 mods->sml_next = NULL;
1900                 modtail->sml_next = mods;
1901                 modtail = mods;
1902
1903                 if (attr_find(e->e_attrs, ad_pwdGraceUseTime )) {
1904                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1905                         mods->sml_op = LDAP_MOD_DELETE;
1906                         mods->sml_desc = ad_pwdGraceUseTime;
1907                         mods->sml_flags = SLAP_MOD_INTERNAL;
1908                         mods->sml_next = NULL;
1909                         modtail->sml_next = mods;
1910                         modtail = mods;
1911                 }
1912
1913                 if (attr_find(e->e_attrs, ad_pwdAccountLockedTime )) {
1914                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1915                         mods->sml_op = LDAP_MOD_DELETE;
1916                         mods->sml_desc = ad_pwdAccountLockedTime;
1917                         mods->sml_flags = SLAP_MOD_INTERNAL;
1918                         mods->sml_next = NULL;
1919                         modtail->sml_next = mods;
1920                         modtail = mods;
1921                 }
1922
1923                 if (attr_find(e->e_attrs, ad_pwdFailureTime )) {
1924                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1925                         mods->sml_op = LDAP_MOD_DELETE;
1926                         mods->sml_desc = ad_pwdFailureTime;
1927                         mods->sml_flags = SLAP_MOD_INTERNAL;
1928                         mods->sml_next = NULL;
1929                         modtail->sml_next = mods;
1930                         modtail = mods;
1931                 }
1932
1933                 /* Delete the pwdReset attribute, since it's being reset */
1934                 if ((zapReset) && (attr_find(e->e_attrs, ad_pwdReset ))) {
1935                         mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1936                         mods->sml_op = LDAP_MOD_DELETE;
1937                         mods->sml_desc = ad_pwdReset;
1938                         mods->sml_flags = SLAP_MOD_INTERNAL;
1939                         mods->sml_next = NULL;
1940                         modtail->sml_next = mods;
1941                         modtail = mods;
1942                 }
1943
1944                 if (pp.pwdInHistory > 0) {
1945                         if (hsize >= pp.pwdInHistory) {
1946                                 /*
1947                                  * We use the >= operator, since we are going to add
1948                                  * the existing password attribute value into the
1949                                  * history - thus the cardinality of history values is
1950                                  * about to rise by one.
1951                                  *
1952                                  * If this would push it over the limit of history
1953                                  * values (remembering - the password policy could have
1954                                  * changed since the password was last altered), we must
1955                                  * delete at least 1 value from the pwdHistory list.
1956                                  *
1957                                  * In fact, we delete '(#pwdHistory attrs - max pwd
1958                                  * history length) + 1' values, starting with the oldest.
1959                                  * This is easily evaluated, since the linked list is
1960                                  * created in ascending time order.
1961                                  */
1962                                 mods = (Modifications *) ch_calloc( sizeof( Modifications ), 1 );
1963                                 mods->sml_op = LDAP_MOD_DELETE;
1964                                 mods->sml_flags = SLAP_MOD_INTERNAL;
1965                                 mods->sml_desc = ad_pwdHistory;
1966                                 mods->sml_numvals = hsize - pp.pwdInHistory + 1;
1967                                 mods->sml_values = ch_calloc( sizeof( struct berval ),
1968                                         hsize - pp.pwdInHistory + 2 );
1969                                 BER_BVZERO( &mods->sml_values[ hsize - pp.pwdInHistory + 1 ] );
1970                                 for(i=0,p=tl; i < (hsize - pp.pwdInHistory + 1); i++, p=p->next) {
1971                                         BER_BVZERO( &mods->sml_values[i] );
1972                                         ber_dupbv( &(mods->sml_values[i]), &p->bv );
1973                                 }
1974                                 mods->sml_next = NULL;
1975                                 modtail->sml_next = mods;
1976                                 modtail = mods;
1977                         }
1978                         free_pwd_history_list( &tl );
1979
1980                         /*
1981                          * Now add the existing password into the history list.
1982                          * This will be executed even if the operation is to delete
1983                          * the password entirely.
1984                          *
1985                          * This isn't in the spec explicitly, but it seems to make
1986                          * sense that the password history list is the list of all
1987                          * previous passwords - even if they were deleted. Thus, if
1988                          * someone tries to add a historical password at some future
1989                          * point, it will fail.
1990                          */
1991                         if ((pa = attr_find( e->e_attrs, pp.ad )) != NULL) {
1992                                 mods = (Modifications *) ch_malloc( sizeof( Modifications ) );
1993                                 mods->sml_op = LDAP_MOD_ADD;
1994                                 mods->sml_flags = SLAP_MOD_INTERNAL;
1995                                 mods->sml_type.bv_val = NULL;
1996                                 mods->sml_desc = ad_pwdHistory;
1997                                 mods->sml_nvalues = NULL;
1998                                 mods->sml_numvals = 1;
1999                                 mods->sml_values = ch_calloc( sizeof( struct berval ), 2 );
2000                                 mods->sml_values[ 1 ].bv_val = NULL;
2001                                 mods->sml_values[ 1 ].bv_len = 0;
2002                                 make_pwd_history_value( timebuf, &mods->sml_values[0], pa );
2003                                 mods->sml_next = NULL;
2004                                 modtail->sml_next = mods;
2005                                 modtail = mods;
2006
2007                         } else {
2008                                 Debug( LDAP_DEBUG_TRACE,
2009                                 "ppolicy_modify: password attr lookup failed\n", 0, 0, 0 );
2010                         }
2011                 }
2012
2013                 /*
2014                  * Controversial bit here. If the new password isn't hashed
2015                  * (ie, is cleartext), we probably should hash it according
2016                  * to the default hash. The reason for this is that we want
2017                  * to use the policy if possible, but if we hash the password
2018                  * before, then we're going to run into trouble when it
2019                  * comes time to check the password.
2020                  *
2021                  * Now, the right thing to do is to use the extended password
2022                  * modify operation, but not all software can do this,
2023                  * therefore it makes sense to hash the new password, now
2024                  * we know it passes the policy requirements.
2025                  *
2026                  * Of course, if the password is already hashed, then we
2027                  * leave it alone.
2028                  */
2029
2030                 if ((pi->hash_passwords) && (addmod) && !newpw.bv_val && 
2031                         (password_scheme( &(addmod->sml_values[0]), NULL ) != LDAP_SUCCESS))
2032                 {
2033                         struct berval hpw, bv;
2034                         
2035                         slap_passwd_hash( &(addmod->sml_values[0]), &hpw, &txt );
2036                         if (hpw.bv_val == NULL) {
2037                                         /*
2038                                          * hashing didn't work. Emit an error.
2039                                          */
2040                                 rs->sr_err = LDAP_OTHER;
2041                                 rs->sr_text = txt;
2042                                 goto return_results;
2043                         }
2044                         bv = addmod->sml_values[0];
2045                                 /* clear and discard the clear password */
2046                         memset(bv.bv_val, 0, bv.bv_len);
2047                         ber_memfree(bv.bv_val);
2048                         addmod->sml_values[0] = hpw;
2049                 }
2050         }
2051         op->o_bd->bd_info = (BackendInfo *)on->on_info;
2052         be_entry_release_r( op, e );
2053         return SLAP_CB_CONTINUE;
2054
2055 return_results:
2056         free_pwd_history_list( &tl );
2057         op->o_bd->bd_info = (BackendInfo *)on->on_info;
2058         be_entry_release_r( op, e );
2059         if ( send_ctrl ) {
2060                 ctrl = create_passcontrol( op, -1, -1, pErr );
2061                 oldctrls = add_passcontrol( op, rs, ctrl );
2062         }
2063         send_ldap_result( op, rs );
2064         if ( free_txt ) {
2065                 free( (char *)txt );
2066                 rs->sr_text = NULL;
2067         }
2068         if ( send_ctrl ) {
2069                 if ( is_pwdexop ) {
2070                         if ( rs->sr_flags & REP_CTRLS_MUSTBEFREED ) {
2071                                 op->o_tmpfree( oldctrls, op->o_tmpmemctx );
2072                         }
2073                         oldctrls = NULL;
2074                         rs->sr_flags |= REP_CTRLS_MUSTBEFREED;
2075
2076                 } else {
2077                         ctrls_cleanup( op, rs, oldctrls );
2078                 }
2079         }
2080         return rs->sr_err;
2081 }
2082
2083 static int
2084 ppolicy_parseCtrl(
2085         Operation *op,
2086         SlapReply *rs,
2087         LDAPControl *ctrl )
2088 {
2089         if ( !BER_BVISNULL( &ctrl->ldctl_value ) ) {
2090                 rs->sr_text = "passwordPolicyRequest control value not absent";
2091                 return LDAP_PROTOCOL_ERROR;
2092         }
2093         op->o_ctrlflag[ppolicy_cid] = ctrl->ldctl_iscritical
2094                 ? SLAP_CONTROL_CRITICAL
2095                 : SLAP_CONTROL_NONCRITICAL;
2096
2097         return LDAP_SUCCESS;
2098 }
2099
2100 static int
2101 attrPretty(
2102         Syntax *syntax,
2103         struct berval *val,
2104         struct berval *out,
2105         void *ctx )
2106 {
2107         AttributeDescription *ad = NULL;
2108         const char *err;
2109         int code;
2110
2111         code = slap_bv2ad( val, &ad, &err );
2112         if ( !code ) {
2113                 ber_dupbv_x( out, &ad->ad_type->sat_cname, ctx );
2114         }
2115         return code;
2116 }
2117
2118 static int
2119 attrNormalize(
2120         slap_mask_t use,
2121         Syntax *syntax,
2122         MatchingRule *mr,
2123         struct berval *val,
2124         struct berval *out,
2125         void *ctx )
2126 {
2127         AttributeDescription *ad = NULL;
2128         const char *err;
2129         int code;
2130
2131         code = slap_bv2ad( val, &ad, &err );
2132         if ( !code ) {
2133                 ber_str2bv_x( ad->ad_type->sat_oid, 0, 1, out, ctx );
2134         }
2135         return code;
2136 }
2137
2138 static int
2139 ppolicy_db_init(
2140         BackendDB *be,
2141         ConfigReply *cr
2142 )
2143 {
2144         slap_overinst *on = (slap_overinst *) be->bd_info;
2145
2146         if ( SLAP_ISGLOBALOVERLAY( be ) ) {
2147                 /* do not allow slapo-ppolicy to be global by now (ITS#5858) */
2148                 if ( cr ){
2149                         snprintf( cr->msg, sizeof(cr->msg), 
2150                                 "slapo-ppolicy cannot be global" );
2151                         fprintf( stderr, "%s\n", cr->msg );
2152                 }
2153                 return 1;
2154         }
2155
2156         /* Has User Schema been initialized yet? */
2157         if ( !pwd_UsSchema[0].ad[0] ) {
2158                 const char *err;
2159                 int i, code;
2160
2161                 for (i=0; pwd_UsSchema[i].def; i++) {
2162                         code = slap_str2ad( pwd_UsSchema[i].def, pwd_UsSchema[i].ad, &err );
2163                         if ( code ) {
2164                                 if ( cr ){
2165                                         snprintf( cr->msg, sizeof(cr->msg), 
2166                                                 "User Schema load failed for attribute \"%s\". Error code %d: %s",
2167                                                 pwd_UsSchema[i].def, code, err );
2168                                         fprintf( stderr, "%s\n", cr->msg );
2169                                 }
2170                                 return code;
2171                         }
2172                 }
2173                 {
2174                         Syntax *syn;
2175                         MatchingRule *mr;
2176
2177                         syn = ch_malloc( sizeof( Syntax ));
2178                         *syn = *ad_pwdAttribute->ad_type->sat_syntax;
2179                         syn->ssyn_pretty = attrPretty;
2180                         ad_pwdAttribute->ad_type->sat_syntax = syn;
2181
2182                         mr = ch_malloc( sizeof( MatchingRule ));
2183                         *mr = *ad_pwdAttribute->ad_type->sat_equality;
2184                         mr->smr_normalize = attrNormalize;
2185                         ad_pwdAttribute->ad_type->sat_equality = mr;
2186                 }
2187         }
2188
2189         on->on_bi.bi_private = ch_calloc( sizeof(pp_info), 1 );
2190
2191         if ( dtblsize && !pwcons ) {
2192                 /* accommodate for c_conn_idx == -1 */
2193                 pwcons = ch_calloc( sizeof(pw_conn), dtblsize + 1 );
2194                 pwcons++;
2195         }
2196
2197         return 0;
2198 }
2199
2200 static int
2201 ppolicy_db_open(
2202         BackendDB *be,
2203         ConfigReply *cr
2204 )
2205 {
2206         ov_count++;
2207         return overlay_register_control( be, LDAP_CONTROL_PASSWORDPOLICYREQUEST );
2208 }
2209
2210 static int
2211 ppolicy_close(
2212         BackendDB *be,
2213         ConfigReply *cr
2214 )
2215 {
2216         slap_overinst *on = (slap_overinst *) be->bd_info;
2217         pp_info *pi = on->on_bi.bi_private;
2218
2219         /* Perhaps backover should provide bi_destroy hooks... */
2220         ov_count--;
2221         if ( ov_count <=0 && pwcons ) {
2222                 pwcons--;
2223                 free( pwcons );
2224                 pwcons = NULL;
2225         }
2226         free( pi->def_policy.bv_val );
2227         free( pi );
2228
2229         return 0;
2230 }
2231
2232 static char *extops[] = {
2233         LDAP_EXOP_MODIFY_PASSWD,
2234         NULL
2235 };
2236
2237 static slap_overinst ppolicy;
2238
2239 int ppolicy_initialize()
2240 {
2241         int i, code;
2242
2243         for (i=0; pwd_OpSchema[i].def; i++) {
2244                 code = register_at( pwd_OpSchema[i].def, pwd_OpSchema[i].ad, 0 );
2245                 if ( code ) {
2246                         Debug( LDAP_DEBUG_ANY,
2247                                 "ppolicy_initialize: register_at failed\n", 0, 0, 0 );
2248                         return code;
2249                 }
2250                 /* Allow Manager to set these as needed */
2251                 if ( is_at_no_user_mod( (*pwd_OpSchema[i].ad)->ad_type )) {
2252                         (*pwd_OpSchema[i].ad)->ad_type->sat_flags |=
2253                                 SLAP_AT_MANAGEABLE;
2254                 }
2255         }
2256
2257         code = register_supported_control( LDAP_CONTROL_PASSWORDPOLICYREQUEST,
2258                 SLAP_CTRL_ADD|SLAP_CTRL_BIND|SLAP_CTRL_MODIFY|SLAP_CTRL_HIDE, extops,
2259                 ppolicy_parseCtrl, &ppolicy_cid );
2260         if ( code != LDAP_SUCCESS ) {
2261                 fprintf( stderr, "Failed to register control %d\n", code );
2262                 return code;
2263         }
2264
2265         ldap_pvt_thread_mutex_init( &chk_syntax_mutex );
2266
2267         ppolicy.on_bi.bi_type = "ppolicy";
2268         ppolicy.on_bi.bi_db_init = ppolicy_db_init;
2269         ppolicy.on_bi.bi_db_open = ppolicy_db_open;
2270         ppolicy.on_bi.bi_db_close = ppolicy_close;
2271
2272         ppolicy.on_bi.bi_op_add = ppolicy_add;
2273         ppolicy.on_bi.bi_op_bind = ppolicy_bind;
2274         ppolicy.on_bi.bi_op_compare = ppolicy_restrict;
2275         ppolicy.on_bi.bi_op_delete = ppolicy_restrict;
2276         ppolicy.on_bi.bi_op_modify = ppolicy_modify;
2277         ppolicy.on_bi.bi_op_search = ppolicy_restrict;
2278         ppolicy.on_bi.bi_connection_destroy = ppolicy_connection_destroy;
2279
2280         ppolicy.on_bi.bi_cf_ocs = ppolicyocs;
2281         code = config_register_schema( ppolicycfg, ppolicyocs );
2282         if ( code ) return code;
2283
2284         return overlay_register( &ppolicy );
2285 }
2286
2287 #if SLAPD_OVER_PPOLICY == SLAPD_MOD_DYNAMIC
2288 int init_module(int argc, char *argv[]) {
2289         return ppolicy_initialize();
2290 }
2291 #endif
2292
2293 #endif  /* defined(SLAPD_OVER_PPOLICY) */