]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
Happy New Year
[openldap] / servers / slapd / sasl.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2018 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15
16 #include "portable.h"
17
18 #include <stdio.h>
19 #ifdef HAVE_LIMITS_H
20 #include <limits.h>
21 #endif
22
23 #include <ac/stdlib.h>
24 #include <ac/string.h>
25
26 #include <lber.h>
27 #include <ldap_log.h>
28
29 #include "slap.h"
30
31 #ifdef ENABLE_REWRITE
32 #include <rewrite.h>
33 #endif
34
35 #ifdef HAVE_CYRUS_SASL
36 # ifdef HAVE_SASL_SASL_H
37 #  include <sasl/sasl.h>
38 #  include <sasl/saslplug.h>
39 # else
40 #  include <sasl.h>
41 #  include <saslplug.h>
42 # endif
43
44 # define        SASL_CONST const
45
46 #define SASL_VERSION_FULL       ((SASL_VERSION_MAJOR << 16) |\
47         (SASL_VERSION_MINOR << 8) | SASL_VERSION_STEP)
48
49 #if SASL_VERSION_MINOR >= 0x020119 /* 2.1.25 */
50 typedef sasl_callback_ft slap_sasl_cb_ft;
51 #else
52 typedef int (*slap_sasl_cb_ft)();
53 #endif
54
55 static sasl_security_properties_t sasl_secprops;
56 #elif defined( SLAP_BUILTIN_SASL )
57 /*
58  * built-in SASL implementation
59  *      only supports EXTERNAL
60  */
61 typedef struct sasl_ctx {
62         slap_ssf_t sc_external_ssf;
63         struct berval sc_external_id;
64 } SASL_CTX;
65
66 #endif
67
68 #include <lutil.h>
69
70 static struct berval ext_bv = BER_BVC( "EXTERNAL" );
71
72 char *slap_sasl_auxprops;
73
74 #ifdef HAVE_CYRUS_SASL
75
76 /* Just use our internal auxprop by default */
77 static int
78 slap_sasl_getopt(
79         void *context,
80         const char *plugin_name,
81         const char *option,
82         const char **result,
83         unsigned *len)
84 {
85         if ( strcmp( option, "auxprop_plugin" )) {
86                 return SASL_FAIL;
87         }
88         if ( slap_sasl_auxprops )
89                 *result = slap_sasl_auxprops;
90         else
91                 *result = "slapd";
92         return SASL_OK;
93 }
94
95 int
96 slap_sasl_log(
97         void *context,
98         int priority,
99         const char *message) 
100 {
101         Connection *conn = context;
102         int level;
103         const char * label;
104
105         if ( message == NULL ) {
106                 return SASL_BADPARAM;
107         }
108
109         switch (priority) {
110         case SASL_LOG_NONE:
111                 level = LDAP_DEBUG_NONE;
112                 label = "None";
113                 break;
114         case SASL_LOG_ERR:
115                 level = LDAP_DEBUG_ANY;
116                 label = "Error";
117                 break;
118         case SASL_LOG_FAIL:
119                 level = LDAP_DEBUG_ANY;
120                 label = "Failure";
121                 break;
122         case SASL_LOG_WARN:
123                 level = LDAP_DEBUG_TRACE;
124                 label = "Warning";
125                 break;
126         case SASL_LOG_NOTE:
127                 level = LDAP_DEBUG_TRACE;
128                 label = "Notice";
129                 break;
130         case SASL_LOG_DEBUG:
131                 level = LDAP_DEBUG_TRACE;
132                 label = "Debug";
133                 break;
134         case SASL_LOG_TRACE:
135                 level = LDAP_DEBUG_TRACE;
136                 label = "Trace";
137                 break;
138         case SASL_LOG_PASS:
139                 level = LDAP_DEBUG_TRACE;
140                 label = "Password Trace";
141                 break;
142         default:
143                 return SASL_BADPARAM;
144         }
145
146         Debug( level, "SASL [conn=%ld] %s: %s\n",
147                 conn ? (long) conn->c_connid: -1L,
148                 label, message );
149
150
151         return SASL_OK;
152 }
153
154 static const char *slap_propnames[] = {
155         "*slapConn", "*slapAuthcDNlen", "*slapAuthcDN",
156         "*slapAuthzDNlen", "*slapAuthzDN", NULL };
157
158 #ifdef SLAP_AUXPROP_DONTUSECOPY
159 int slap_dontUseCopy_ignore;
160 BerVarray slap_dontUseCopy_propnames;
161 #endif /* SLAP_AUXPROP_DONTUSECOPY */
162
163 static Filter generic_filter = { LDAP_FILTER_PRESENT, { 0 }, NULL };
164 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
165
166 #define SLAP_SASL_PROP_CONN     0
167 #define SLAP_SASL_PROP_AUTHCLEN 1
168 #define SLAP_SASL_PROP_AUTHC    2
169 #define SLAP_SASL_PROP_AUTHZLEN 3
170 #define SLAP_SASL_PROP_AUTHZ    4
171 #define SLAP_SASL_PROP_COUNT    5       /* Number of properties we used */
172
173 typedef struct lookup_info {
174         int flags;
175         const struct propval *list;
176         sasl_server_params_t *sparams;
177 } lookup_info;
178
179 static slap_response sasl_ap_lookup;
180
181 static struct berval sc_cleartext = BER_BVC("{CLEARTEXT}");
182
183 static int
184 sasl_ap_lookup( Operation *op, SlapReply *rs )
185 {
186         BerVarray bv;
187         AttributeDescription *ad;
188         Attribute *a;
189         const char *text;
190         int rc, i;
191         lookup_info *sl = (lookup_info *)op->o_callback->sc_private;
192
193         /* return the actual error code,
194          * to allow caller to handle specific errors
195          */
196         if (rs->sr_type != REP_SEARCH) return rs->sr_err;
197
198         for( i = 0; sl->list[i].name; i++ ) {
199                 const char *name = sl->list[i].name;
200
201                 if ( name[0] == '*' ) {
202                         if ( sl->flags & SASL_AUXPROP_AUTHZID ) continue;
203                         /* Skip our private properties */
204                         if ( !strcmp( name, slap_propnames[0] )) {
205                                 i += SLAP_SASL_PROP_COUNT - 1;
206                                 continue;
207                         }
208                         name++;
209                 } else if ( !(sl->flags & SASL_AUXPROP_AUTHZID ) )
210                         continue;
211
212                 if ( sl->list[i].values ) {
213                         if ( !(sl->flags & SASL_AUXPROP_OVERRIDE) ) continue;
214                 }
215                 ad = NULL;
216                 rc = slap_str2ad( name, &ad, &text );
217                 if ( rc != LDAP_SUCCESS ) {
218                         Debug( LDAP_DEBUG_TRACE,
219                                 "slap_ap_lookup: str2ad(%s): %s\n", name, text, 0 );
220                         continue;
221                 }
222
223                 /* If it's the rootdn and a rootpw was present, we already set
224                  * it so don't override it here.
225                  */
226                 if ( ad == slap_schema.si_ad_userPassword && sl->list[i].values && 
227                         be_isroot_dn( op->o_bd, &op->o_req_ndn ))
228                         continue;
229
230                 a = attr_find( rs->sr_entry->e_attrs, ad );
231                 if ( !a ) continue;
232                 if ( ! access_allowed( op, rs->sr_entry, ad, NULL, ACL_AUTH, NULL ) ) {
233                         continue;
234                 }
235                 if ( sl->list[i].values && ( sl->flags & SASL_AUXPROP_OVERRIDE ) ) {
236                         sl->sparams->utils->prop_erase( sl->sparams->propctx,
237                         sl->list[i].name );
238                 }
239                 for ( bv = a->a_vals; bv->bv_val; bv++ ) {
240                         /* ITS#3846 don't give hashed passwords to SASL */
241                         if ( ad == slap_schema.si_ad_userPassword &&
242                                 bv->bv_val[0] == '{' /*}*/ )
243                         {
244                                 if ( lutil_passwd_scheme( bv->bv_val ) ) {
245                                         /* If it's not a recognized scheme, just assume it's
246                                          * a cleartext password that happened to include brackets.
247                                          *
248                                          * If it's a recognized scheme, skip this value, unless the
249                                          * scheme is {CLEARTEXT}. In that case, skip over the
250                                          * scheme name and use the remainder. If there is nothing
251                                          * past the scheme name, skip this value.
252                                          */
253 #ifdef SLAPD_CLEARTEXT
254                                         if ( !strncasecmp( bv->bv_val, sc_cleartext.bv_val,
255                                                 sc_cleartext.bv_len )) {
256                                                 struct berval cbv;
257                                                 cbv.bv_len = bv->bv_len - sc_cleartext.bv_len;
258                                                 if ( cbv.bv_len > 0 ) {
259                                                         cbv.bv_val = bv->bv_val + sc_cleartext.bv_len;
260                                                         sl->sparams->utils->prop_set( sl->sparams->propctx,
261                                                                 sl->list[i].name, cbv.bv_val, cbv.bv_len );
262                                                 }
263                                         }
264 #endif
265                                         continue;
266                                 }
267                         }
268                         sl->sparams->utils->prop_set( sl->sparams->propctx,
269                                 sl->list[i].name, bv->bv_val, bv->bv_len );
270                 }
271         }
272         return LDAP_SUCCESS;
273 }
274
275 #if SASL_VERSION_FULL >= 0x020118
276 static int
277 #else
278 static void
279 #endif
280 slap_auxprop_lookup(
281         void *glob_context,
282         sasl_server_params_t *sparams,
283         unsigned flags,
284         const char *user,
285         unsigned ulen)
286 {
287         OperationBuffer opbuf = {{ NULL }};
288         Operation *op = (Operation *)&opbuf;
289         int i, doit = 0;
290         Connection *conn = NULL;
291         lookup_info sl;
292         int rc = LDAP_SUCCESS;
293 #ifdef SLAP_AUXPROP_DONTUSECOPY
294         int dontUseCopy = 0;
295         BackendDB *dontUseCopy_bd = NULL;
296 #endif /* SLAP_AUXPROP_DONTUSECOPY */
297
298         sl.list = sparams->utils->prop_get( sparams->propctx );
299         sl.sparams = sparams;
300         sl.flags = flags;
301
302         /* Find our DN and conn first */
303         for( i = 0; sl.list[i].name; i++ ) {
304                 if ( sl.list[i].name[0] == '*' ) {
305                         if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_CONN] ) ) {
306                                 if ( sl.list[i].values && sl.list[i].values[0] )
307                                         AC_MEMCPY( &conn, sl.list[i].values[0], sizeof( conn ) );
308                                 continue;
309                         }
310                         if ( flags & SASL_AUXPROP_AUTHZID ) {
311                                 if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHZLEN] )) {
312                                         if ( sl.list[i].values && sl.list[i].values[0] )
313                                                 AC_MEMCPY( &op->o_req_ndn.bv_len, sl.list[i].values[0],
314                                                         sizeof( op->o_req_ndn.bv_len ) );
315                                 } else if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHZ] )) {
316                                         if ( sl.list[i].values )
317                                                 op->o_req_ndn.bv_val = (char *)sl.list[i].values[0];
318                                         break;
319                                 }
320                         }
321
322                         if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHCLEN] )) {
323                                 if ( sl.list[i].values && sl.list[i].values[0] )
324                                         AC_MEMCPY( &op->o_req_ndn.bv_len, sl.list[i].values[0],
325                                                 sizeof( op->o_req_ndn.bv_len ) );
326                         } else if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHC] ) ) {
327                                 if ( sl.list[i].values ) {
328                                         op->o_req_ndn.bv_val = (char *)sl.list[i].values[0];
329                                         if ( !(flags & SASL_AUXPROP_AUTHZID) )
330                                                 break;
331                                 }
332                         }
333 #ifdef SLAP_AUXPROP_DONTUSECOPY
334                         if ( slap_dontUseCopy_propnames != NULL ) {
335                                 int j;
336                                 struct berval bv;
337                                 ber_str2bv( &sl.list[i].name[1], 0, 1, &bv );
338                                 for ( j = 0; !BER_BVISNULL( &slap_dontUseCopy_propnames[ j ]); j++ ) {
339                                         if ( bvmatch( &bv, &slap_dontUseCopy_propnames[ j ] ) ) {
340                                                 dontUseCopy = 1;
341                                                 break;
342                                         }
343                                 }
344                         }
345 #endif /* SLAP_AUXPROP_DONTUSECOPY */
346                 }
347         }
348
349         /* we don't know anything about this, ignore it */
350         if ( !conn ) {
351                 rc == LDAP_SUCCESS;
352                 goto done;
353         }
354
355         /* Now see what else needs to be fetched */
356         for( i = 0; sl.list[i].name; i++ ) {
357                 const char *name = sl.list[i].name;
358
359                 if ( name[0] == '*' ) {
360                         if ( flags & SASL_AUXPROP_AUTHZID ) continue;
361                         /* Skip our private properties */
362                         if ( !strcmp( name, slap_propnames[0] )) {
363                                 i += SLAP_SASL_PROP_COUNT - 1;
364                                 continue;
365                         }
366                         name++;
367                 } else if ( !(flags & SASL_AUXPROP_AUTHZID ) )
368                         continue;
369
370                 if ( sl.list[i].values ) {
371                         if ( !(flags & SASL_AUXPROP_OVERRIDE) ) continue;
372                 }
373                 doit = 1;
374                 break;
375         }
376
377         if (doit) {
378                 slap_callback cb = { NULL, sasl_ap_lookup, NULL, NULL };
379
380                 cb.sc_private = &sl;
381
382                 op->o_bd = select_backend( &op->o_req_ndn, 1 );
383
384                 if ( op->o_bd ) {
385                         /* For rootdn, see if we can use the rootpw */
386                         if ( be_isroot_dn( op->o_bd, &op->o_req_ndn ) &&
387                                 !BER_BVISEMPTY( &op->o_bd->be_rootpw )) {
388                                 struct berval cbv = BER_BVNULL;
389
390                                 /* If there's a recognized scheme, see if it's CLEARTEXT */
391                                 if ( lutil_passwd_scheme( op->o_bd->be_rootpw.bv_val )) {
392                                         if ( !strncasecmp( op->o_bd->be_rootpw.bv_val,
393                                                 sc_cleartext.bv_val, sc_cleartext.bv_len )) {
394
395                                                 /* If it's CLEARTEXT, skip past scheme spec */
396                                                 cbv.bv_len = op->o_bd->be_rootpw.bv_len -
397                                                         sc_cleartext.bv_len;
398                                                 if ( cbv.bv_len ) {
399                                                         cbv.bv_val = op->o_bd->be_rootpw.bv_val +
400                                                                 sc_cleartext.bv_len;
401                                                 }
402                                         }
403                                 /* No scheme, use the whole value */
404                                 } else {
405                                         cbv = op->o_bd->be_rootpw;
406                                 }
407                                 if ( !BER_BVISEMPTY( &cbv )) {
408                                         for( i = 0; sl.list[i].name; i++ ) {
409                                                 const char *name = sl.list[i].name;
410
411                                                 if ( name[0] == '*' ) {
412                                                         if ( flags & SASL_AUXPROP_AUTHZID ) continue;
413                                                                 name++;
414                                                 } else if ( !(flags & SASL_AUXPROP_AUTHZID ) )
415                                                         continue;
416
417                                                 if ( !strcasecmp(name,"userPassword") ) {
418                                                         sl.sparams->utils->prop_set( sl.sparams->propctx,
419                                                                 sl.list[i].name, cbv.bv_val, cbv.bv_len );
420                                                         break;
421                                                 }
422                                         }
423                                 }
424                         }
425
426 #ifdef SLAP_AUXPROP_DONTUSECOPY
427                         if ( SLAP_SHADOW( op->o_bd ) && dontUseCopy ) {
428                                 dontUseCopy_bd = op->o_bd;
429                                 op->o_bd = frontendDB;
430                         }
431
432 retry_dontUseCopy:;
433 #endif /* SLAP_AUXPROP_DONTUSECOPY */
434
435                         if ( op->o_bd->be_search ) {
436                                 SlapReply rs = {REP_RESULT};
437 #ifdef SLAP_AUXPROP_DONTUSECOPY
438                                 LDAPControl **save_ctrls = NULL, c;
439                                 int save_dontUseCopy;
440 #endif /* SLAP_AUXPROP_DONTUSECOPY */
441
442                                 op->o_hdr = conn->c_sasl_bindop->o_hdr;
443                                 op->o_controls = opbuf.ob_controls;
444                                 op->o_tag = LDAP_REQ_SEARCH;
445                                 op->o_dn = conn->c_ndn;
446                                 op->o_ndn = conn->c_ndn;
447                                 op->o_callback = &cb;
448                                 slap_op_time( &op->o_time, &op->o_tincr );
449                                 op->o_do_not_cache = 1;
450                                 op->o_is_auth_check = 1;
451                                 op->o_req_dn = op->o_req_ndn;
452                                 op->ors_scope = LDAP_SCOPE_BASE;
453                                 op->ors_deref = LDAP_DEREF_NEVER;
454                                 op->ors_tlimit = SLAP_NO_LIMIT;
455                                 op->ors_slimit = 1;
456                                 op->ors_filter = &generic_filter;
457                                 op->ors_filterstr = generic_filterstr;
458                                 op->o_authz = conn->c_authz;
459                                 /* FIXME: we want all attributes, right? */
460                                 op->ors_attrs = NULL;
461
462 #ifdef SLAP_AUXPROP_DONTUSECOPY
463                                 if ( dontUseCopy ) {
464                                         save_dontUseCopy = op->o_dontUseCopy;
465                                         if ( !op->o_dontUseCopy ) {
466                                                 int cnt = 0;
467                                                 save_ctrls = op->o_ctrls;
468                                                 if ( op->o_ctrls ) {
469                                                         for ( ; op->o_ctrls[ cnt ]; cnt++ )
470                                                                 ;
471                                                 }
472                                                 op->o_ctrls = op->o_tmpcalloc( sizeof(LDAPControl *), cnt + 2, op->o_tmpmemctx );
473                                                 if ( cnt ) {
474                                                         for ( cnt = 0; save_ctrls[ cnt ]; cnt++ ) {
475                                                                 op->o_ctrls[ cnt ] = save_ctrls[ cnt ];
476                                                         }
477                                                 }
478                                                 c.ldctl_oid = LDAP_CONTROL_DONTUSECOPY;
479                                                 c.ldctl_iscritical = 1;
480                                                 BER_BVZERO( &c.ldctl_value );
481                                                 op->o_ctrls[ cnt ] = &c;
482                                         }
483                                         op->o_dontUseCopy = SLAP_CONTROL_CRITICAL;
484                                 }
485 #endif /* SLAP_AUXPROP_DONTUSECOPY */
486
487                                 rc = op->o_bd->be_search( op, &rs );
488
489 #ifdef SLAP_AUXPROP_DONTUSECOPY
490                                 if ( dontUseCopy ) {
491                                         if ( save_ctrls != op->o_ctrls ) {
492                                                 op->o_tmpfree( op->o_ctrls, op->o_tmpmemctx );
493                                                 op->o_ctrls = save_ctrls;
494                                                 op->o_dontUseCopy = save_dontUseCopy;
495                                         }
496
497                                         if ( rs.sr_err == LDAP_UNAVAILABLE && slap_dontUseCopy_ignore )
498                                         {
499                                                 op->o_bd = dontUseCopy_bd;
500                                                 dontUseCopy = 0;
501                                                 goto retry_dontUseCopy;
502                                         }
503                                 }
504 #endif /* SLAP_AUXPROP_DONTUSECOPY */
505                         }
506                 }
507         }
508 done:;
509 #if SASL_VERSION_FULL >= 0x020118
510         return rc != LDAP_SUCCESS ? SASL_FAIL : SASL_OK;
511 #endif
512 }
513
514 #if SASL_VERSION_FULL >= 0x020110
515 static int
516 slap_auxprop_store(
517         void *glob_context,
518         sasl_server_params_t *sparams,
519         struct propctx *prctx,
520         const char *user,
521         unsigned ulen)
522 {
523         Operation op = {0};
524         Opheader oph;
525         int rc, i;
526         unsigned j;
527         Connection *conn = NULL;
528         const struct propval *pr;
529         Modifications *modlist = NULL, **modtail = &modlist, *mod;
530         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
531         char textbuf[SLAP_TEXT_BUFLEN];
532         const char *text;
533         size_t textlen = sizeof(textbuf);
534 #ifdef SLAP_AUXPROP_DONTUSECOPY
535         int dontUseCopy = 0;
536         BackendDB *dontUseCopy_bd = NULL;
537 #endif /* SLAP_AUXPROP_DONTUSECOPY */
538
539         /* just checking if we are enabled */
540         if (!prctx) return SASL_OK;
541
542         if (!sparams || !user) return SASL_BADPARAM;
543
544         pr = sparams->utils->prop_get( sparams->propctx );
545
546         /* Find our DN and conn first */
547         for( i = 0; pr[i].name; i++ ) {
548                 if ( pr[i].name[0] == '*' ) {
549                         if ( !strcmp( pr[i].name, slap_propnames[SLAP_SASL_PROP_CONN] ) ) {
550                                 if ( pr[i].values && pr[i].values[0] )
551                                         AC_MEMCPY( &conn, pr[i].values[0], sizeof( conn ) );
552                                 continue;
553                         }
554                         if ( !strcmp( pr[i].name, slap_propnames[SLAP_SASL_PROP_AUTHCLEN] )) {
555                                 if ( pr[i].values && pr[i].values[0] )
556                                         AC_MEMCPY( &op.o_req_ndn.bv_len, pr[i].values[0],
557                                                 sizeof( op.o_req_ndn.bv_len ) );
558                         } else if ( !strcmp( pr[i].name, slap_propnames[SLAP_SASL_PROP_AUTHC] ) ) {
559                                 if ( pr[i].values )
560                                         op.o_req_ndn.bv_val = (char *)pr[i].values[0];
561                         }
562 #ifdef SLAP_AUXPROP_DONTUSECOPY
563                         if ( slap_dontUseCopy_propnames != NULL ) {
564                                 struct berval bv;
565                                 ber_str2bv( &pr[i].name[1], 0, 1, &bv );
566                                 for ( j = 0; !BER_BVISNULL( &slap_dontUseCopy_propnames[ j ] ); j++ ) {
567                                         if ( bvmatch( &bv, &slap_dontUseCopy_propnames[ j ] ) ) {
568                                                 dontUseCopy = 1;
569                                                 break;
570                                         }
571                                 }
572                         }
573 #endif /* SLAP_AUXPROP_DONTUSECOPY */
574                 }
575         }
576         if (!conn || !op.o_req_ndn.bv_val) return SASL_BADPARAM;
577
578         op.o_bd = select_backend( &op.o_req_ndn, 1 );
579
580         if ( !op.o_bd || !op.o_bd->be_modify ) return SASL_FAIL;
581
582 #ifdef SLAP_AUXPROP_DONTUSECOPY
583         if ( SLAP_SHADOW( op.o_bd ) && dontUseCopy ) {
584                 dontUseCopy_bd = op.o_bd;
585                 op.o_bd = frontendDB;
586                 op.o_dontUseCopy = SLAP_CONTROL_CRITICAL;
587         }
588 #endif /* SLAP_AUXPROP_DONTUSECOPY */
589
590         pr = sparams->utils->prop_get( prctx );
591         if (!pr) return SASL_BADPARAM;
592
593         for (i=0; pr[i].name; i++);
594         if (!i) return SASL_BADPARAM;
595
596         for (i=0; pr[i].name; i++) {
597                 mod = (Modifications *)ch_malloc( sizeof(Modifications) );
598                 mod->sml_op = LDAP_MOD_REPLACE;
599                 mod->sml_flags = 0;
600                 ber_str2bv( pr[i].name, 0, 0, &mod->sml_type );
601                 mod->sml_numvals = pr[i].nvalues;
602                 mod->sml_values = (struct berval *)ch_malloc( (pr[i].nvalues + 1) *
603                         sizeof(struct berval));
604                 for (j=0; j<pr[i].nvalues; j++) {
605                         ber_str2bv( pr[i].values[j], 0, 1, &mod->sml_values[j]);
606                 }
607                 BER_BVZERO( &mod->sml_values[j] );
608                 mod->sml_nvalues = NULL;
609                 mod->sml_desc = NULL;
610                 *modtail = mod;
611                 modtail = &mod->sml_next;
612         }
613         *modtail = NULL;
614
615         rc = slap_mods_check( &op, modlist, &text, textbuf, textlen, NULL );
616
617         if ( rc == LDAP_SUCCESS ) {
618                 rc = slap_mods_no_user_mod_check( &op, modlist,
619                         &text, textbuf, textlen );
620
621                 if ( rc == LDAP_SUCCESS ) {
622                         if ( conn->c_sasl_bindop ) {
623                                 op.o_hdr = conn->c_sasl_bindop->o_hdr;
624                         } else {
625                                 op.o_hdr = &oph;
626                                 memset( &oph, 0, sizeof(oph) );
627                                 operation_fake_init( conn, &op, ldap_pvt_thread_pool_context(), 0 );
628                         }
629                         op.o_tag = LDAP_REQ_MODIFY;
630                         op.o_ndn = op.o_req_ndn;
631                         op.o_callback = &cb;
632                         slap_op_time( &op.o_time, &op.o_tincr );
633                         op.o_do_not_cache = 1;
634                         op.o_is_auth_check = 1;
635                         op.o_req_dn = op.o_req_ndn;
636                         op.orm_modlist = modlist;
637
638                         for (;;) {
639                                 SlapReply rs = {REP_RESULT};
640                                 rc = op.o_bd->be_modify( &op, &rs );
641
642 #ifdef SLAP_AUXPROP_DONTUSECOPY
643                                 if ( dontUseCopy &&
644                                         rs.sr_err == LDAP_UNAVAILABLE &&
645                                         slap_dontUseCopy_ignore )
646                                 {
647                                         op.o_bd = dontUseCopy_bd;
648                                         op.o_dontUseCopy = SLAP_CONTROL_NONE;
649                                         dontUseCopy = 0;
650                                         continue;
651                                 }
652 #endif /* SLAP_AUXPROP_DONTUSECOPY */
653                                 break;
654                         }
655                 }
656         }
657         slap_mods_free( modlist, 1 );
658         return rc != LDAP_SUCCESS ? SASL_FAIL : SASL_OK;
659 }
660 #endif /* SASL_VERSION_FULL >= 2.1.16 */
661
662 static sasl_auxprop_plug_t slap_auxprop_plugin = {
663         0,      /* Features */
664         0,      /* spare */
665         NULL,   /* glob_context */
666         NULL,   /* auxprop_free */
667         slap_auxprop_lookup,
668         "slapd",        /* name */
669 #if SASL_VERSION_FULL >= 0x020110
670         slap_auxprop_store      /* the declaration of this member changed
671                                  * in cyrus SASL from 2.1.15 to 2.1.16 */
672 #else
673         NULL
674 #endif
675 };
676
677 static int
678 slap_auxprop_init(
679         const sasl_utils_t *utils,
680         int max_version,
681         int *out_version,
682         sasl_auxprop_plug_t **plug,
683         const char *plugname)
684 {
685         if ( !out_version || !plug ) return SASL_BADPARAM;
686
687         if ( max_version < SASL_AUXPROP_PLUG_VERSION ) return SASL_BADVERS;
688
689         *out_version = SASL_AUXPROP_PLUG_VERSION;
690         *plug = &slap_auxprop_plugin;
691         return SASL_OK;
692 }
693
694 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
695  * auxiliary property, so that we can refer to it in sasl_authorize
696  * without interfering with anything else. Also, the SASL username
697  * buffer is constrained to 256 characters, and our DNs could be
698  * much longer (SLAP_LDAPDN_MAXLEN, currently set to 8192)
699  */
700 static int
701 slap_sasl_canonicalize(
702         sasl_conn_t *sconn,
703         void *context,
704         const char *in,
705         unsigned inlen,
706         unsigned flags,
707         const char *user_realm,
708         char *out,
709         unsigned out_max,
710         unsigned *out_len)
711 {
712         Connection *conn = (Connection *)context;
713         struct propctx *props = sasl_auxprop_getctx( sconn );
714         struct propval auxvals[ SLAP_SASL_PROP_COUNT ] = { { 0 } };
715         struct berval dn;
716         int rc, which;
717         const char *names[2];
718         struct berval   bvin;
719
720         *out_len = 0;
721
722         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
723                 conn ? (long) conn->c_connid : -1L,
724                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
725                 in ? in : "<empty>");
726
727         /* If name is too big, just truncate. We don't care, we're
728          * using DNs, not the usernames.
729          */
730         if ( inlen > out_max )
731                 inlen = out_max-1;
732
733         /* This is a Simple Bind using SPASSWD. That means the in-directory
734          * userPassword of the Binding user already points at SASL, so it
735          * cannot be used to actually satisfy a password comparison. Just
736          * ignore it, some other mech will process it.
737          */
738         if ( !conn->c_sasl_bindop ||
739                 conn->c_sasl_bindop->orb_method != LDAP_AUTH_SASL ) goto done;
740
741         /* See if we need to add request, can only do it once */
742         prop_getnames( props, slap_propnames, auxvals );
743         if ( !auxvals[0].name )
744                 prop_request( props, slap_propnames );
745
746         if ( flags & SASL_CU_AUTHID )
747                 which = SLAP_SASL_PROP_AUTHCLEN;
748         else
749                 which = SLAP_SASL_PROP_AUTHZLEN;
750
751         /* Need to store the Connection for auxprop_lookup */
752         if ( !auxvals[SLAP_SASL_PROP_CONN].values ) {
753                 names[0] = slap_propnames[SLAP_SASL_PROP_CONN];
754                 names[1] = NULL;
755                 prop_set( props, names[0], (char *)&conn, sizeof( conn ) );
756         }
757                 
758         /* Already been here? */
759         if ( auxvals[which].values )
760                 goto done;
761
762         /* Normally we require an authzID to have a u: or dn: prefix.
763          * However, SASL frequently gives us an authzID that is just
764          * an exact copy of the authcID, without a prefix. We need to
765          * detect and allow this condition. If SASL calls canonicalize
766          * with SASL_CU_AUTHID|SASL_CU_AUTHZID this is a no-brainer.
767          * But if it's broken into two calls, we need to remember the
768          * authcID so that we can compare the authzID later. We store
769          * the authcID temporarily in conn->c_sasl_dn. We necessarily
770          * finish Canonicalizing before Authorizing, so there is no
771          * conflict with slap_sasl_authorize's use of this temp var.
772          *
773          * The SASL EXTERNAL mech is backwards from all the other mechs,
774          * it does authzID before the authcID. If we see that authzID
775          * has already been done, don't do anything special with authcID.
776          */
777         if ( flags == SASL_CU_AUTHID && !auxvals[SLAP_SASL_PROP_AUTHZ].values ) {
778                 conn->c_sasl_dn.bv_val = (char *) in;
779                 conn->c_sasl_dn.bv_len = 0;
780         } else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
781                 rc = strcmp( in, conn->c_sasl_dn.bv_val );
782                 conn->c_sasl_dn.bv_val = NULL;
783                 /* They were equal, no work needed */
784                 if ( !rc ) goto done;
785         }
786
787         bvin.bv_val = (char *)in;
788         bvin.bv_len = inlen;
789         rc = slap_sasl_getdn( conn, NULL, &bvin, (char *)user_realm, &dn,
790                 (flags & SASL_CU_AUTHID) ? SLAP_GETDN_AUTHCID : SLAP_GETDN_AUTHZID );
791         if ( rc != LDAP_SUCCESS ) {
792                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
793                 return SASL_NOAUTHZ;
794         }
795
796         names[0] = slap_propnames[which];
797         names[1] = NULL;
798         prop_set( props, names[0], (char *)&dn.bv_len, sizeof( dn.bv_len ) );
799
800         which++;
801         names[0] = slap_propnames[which];
802         prop_set( props, names[0], dn.bv_val, dn.bv_len );
803
804         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
805                 conn ? (long) conn->c_connid : -1L, names[0]+1,
806                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
807
808         /* Not needed any more, SASL has copied it */
809         if ( conn && conn->c_sasl_bindop )
810                 conn->c_sasl_bindop->o_tmpfree( dn.bv_val, conn->c_sasl_bindop->o_tmpmemctx );
811
812 done:
813         AC_MEMCPY( out, in, inlen );
814         out[inlen] = '\0';
815
816         *out_len = inlen;
817
818         return SASL_OK;
819 }
820
821 static int
822 slap_sasl_authorize(
823         sasl_conn_t *sconn,
824         void *context,
825         char *requested_user,
826         unsigned rlen,
827         char *auth_identity,
828         unsigned alen,
829         const char *def_realm,
830         unsigned urlen,
831         struct propctx *props)
832 {
833         Connection *conn = (Connection *)context;
834         /* actually:
835          *      (SLAP_SASL_PROP_COUNT - 1)      because we skip "conn",
836          *      + 1                             for NULL termination?
837          */
838         struct propval auxvals[ SLAP_SASL_PROP_COUNT ] = { { 0 } };
839         struct berval authcDN, authzDN = BER_BVNULL;
840         int rc;
841
842         /* Simple Binds don't support proxy authorization, ignore it */
843         if ( !conn->c_sasl_bindop ||
844                 conn->c_sasl_bindop->orb_method != LDAP_AUTH_SASL ) return SASL_OK;
845
846         Debug( LDAP_DEBUG_ARGS, "SASL proxy authorize [conn=%ld]: "
847                 "authcid=\"%s\" authzid=\"%s\"\n",
848                 conn ? (long) conn->c_connid : -1L, auth_identity, requested_user );
849         if ( conn->c_sasl_dn.bv_val ) {
850                 BER_BVZERO( &conn->c_sasl_dn );
851         }
852
853         /* Skip SLAP_SASL_PROP_CONN */
854         prop_getnames( props, slap_propnames+1, auxvals );
855         
856         /* Should not happen */
857         if ( !auxvals[0].values ) {
858                 sasl_seterror( sconn, 0, "invalid authcid" );
859                 return SASL_NOAUTHZ;
860         }
861
862         AC_MEMCPY( &authcDN.bv_len, auxvals[0].values[0], sizeof(authcDN.bv_len) );
863         authcDN.bv_val = auxvals[1].values ? (char *)auxvals[1].values[0] : NULL;
864         conn->c_sasl_dn = authcDN;
865
866         /* Nothing to do if no authzID was given */
867         if ( !auxvals[2].name || !auxvals[2].values ) {
868                 goto ok;
869         }
870         
871         AC_MEMCPY( &authzDN.bv_len, auxvals[2].values[0], sizeof(authzDN.bv_len) );
872         authzDN.bv_val = auxvals[3].values ? (char *)auxvals[3].values[0] : NULL;
873
874         rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
875         if ( rc != LDAP_SUCCESS ) {
876                 Debug( LDAP_DEBUG_TRACE, "SASL Proxy Authorize [conn=%ld]: "
877                         "proxy authorization disallowed (%d)\n",
878                         conn ? (long) conn->c_connid : -1L, rc, 0 );
879
880                 sasl_seterror( sconn, 0, "not authorized" );
881                 return SASL_NOAUTHZ;
882         }
883
884         /* FIXME: we need yet another dup because slap_sasl_getdn()
885          * is using the bind operation slab */
886         ber_dupbv( &conn->c_sasl_authz_dn, &authzDN );
887
888 ok:
889         if (conn->c_sasl_bindop) {
890                 Statslog( LDAP_DEBUG_STATS,
891                         "%s BIND authcid=\"%s\" authzid=\"%s\"\n",
892                         conn->c_sasl_bindop->o_log_prefix, 
893                         auth_identity, requested_user, 0, 0 );
894         }
895
896         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
897                 " proxy authorization allowed authzDN=\"%s\"\n",
898                 conn ? (long) conn->c_connid : -1L, 
899                 authzDN.bv_val ? authzDN.bv_val : "", 0 );
900         return SASL_OK;
901
902
903 static int
904 slap_sasl_err2ldap( int saslerr )
905 {
906         int rc;
907
908         /* map SASL errors to LDAP resultCode returned by:
909          *      sasl_server_new()
910          *              SASL_OK, SASL_NOMEM
911          *      sasl_server_step()
912          *              SASL_OK, SASL_CONTINUE, SASL_TRANS, SASL_BADPARAM, SASL_BADPROT,
913          *      ...
914          *      sasl_server_start()
915          *      + SASL_NOMECH
916          *      sasl_setprop()
917          *              SASL_OK, SASL_BADPARAM
918          */
919
920         switch (saslerr) {
921                 case SASL_OK:
922                         rc = LDAP_SUCCESS;
923                         break;
924                 case SASL_CONTINUE:
925                         rc = LDAP_SASL_BIND_IN_PROGRESS;
926                         break;
927                 case SASL_FAIL:
928                 case SASL_NOMEM:
929                         rc = LDAP_OTHER;
930                         break;
931                 case SASL_NOMECH:
932                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
933                         break;
934                 case SASL_BADAUTH:
935                 case SASL_NOUSER:
936                 case SASL_TRANS:
937                 case SASL_EXPIRED:
938                         rc = LDAP_INVALID_CREDENTIALS;
939                         break;
940                 case SASL_NOAUTHZ:
941                         rc = LDAP_INSUFFICIENT_ACCESS;
942                         break;
943                 case SASL_TOOWEAK:
944                 case SASL_ENCRYPT:
945                         rc = LDAP_INAPPROPRIATE_AUTH;
946                         break;
947                 case SASL_UNAVAIL:
948                 case SASL_TRYAGAIN:
949                         rc = LDAP_UNAVAILABLE;
950                         break;
951                 case SASL_DISABLED:
952                         rc = LDAP_UNWILLING_TO_PERFORM;
953                         break;
954                 default:
955                         rc = LDAP_OTHER;
956                         break;
957         }
958
959         return rc;
960 }
961
962 #ifdef SLAPD_SPASSWD
963
964 static struct berval sasl_pwscheme = BER_BVC("{SASL}");
965
966 static int chk_sasl(
967         const struct berval *sc,
968         const struct berval * passwd,
969         const struct berval * cred,
970         const char **text )
971 {
972         unsigned int i;
973         int rtn;
974         void *ctx, *sconn = NULL;
975
976         for( i=0; i<cred->bv_len; i++) {
977                 if(cred->bv_val[i] == '\0') {
978                         return LUTIL_PASSWD_ERR;        /* NUL character in password */
979                 }
980         }
981
982         if( cred->bv_val[i] != '\0' ) {
983                 return LUTIL_PASSWD_ERR;        /* cred must behave like a string */
984         }
985
986         for( i=0; i<passwd->bv_len; i++) {
987                 if(passwd->bv_val[i] == '\0') {
988                         return LUTIL_PASSWD_ERR;        /* NUL character in password */
989                 }
990         }
991
992         if( passwd->bv_val[i] != '\0' ) {
993                 return LUTIL_PASSWD_ERR;        /* passwd must behave like a string */
994         }
995
996         rtn = LUTIL_PASSWD_ERR;
997
998         ctx = ldap_pvt_thread_pool_context();
999         ldap_pvt_thread_pool_getkey( ctx, (void *)slap_sasl_bind, &sconn, NULL );
1000
1001         if( sconn != NULL ) {
1002                 int sc;
1003                 sc = sasl_checkpass( sconn,
1004                         passwd->bv_val, passwd->bv_len,
1005                         cred->bv_val, cred->bv_len );
1006                 rtn = ( sc != SASL_OK ) ? LUTIL_PASSWD_ERR : LUTIL_PASSWD_OK;
1007         }
1008
1009         return rtn;
1010 }
1011 #endif /* SLAPD_SPASSWD */
1012
1013 #endif /* HAVE_CYRUS_SASL */
1014
1015 #ifdef ENABLE_REWRITE
1016
1017 typedef struct slapd_map_data {
1018         struct berval base;
1019         struct berval filter;
1020         AttributeName attrs[2];
1021         int scope;
1022 } slapd_map_data;
1023
1024 static void *
1025 slapd_rw_config( const char *fname, int lineno, int argc, char **argv )
1026 {
1027         slapd_map_data *ret = NULL;
1028         LDAPURLDesc *lud = NULL;
1029         char *uri;
1030         AttributeDescription *ad = NULL;
1031         int rc, flen = 0;
1032         struct berval dn, ndn;
1033
1034         if ( argc != 1 ) {
1035                 Debug( LDAP_DEBUG_ANY,
1036                         "[%s:%d] slapd map needs URI\n",
1037                         fname, lineno, 0 );
1038         return NULL;
1039         }
1040
1041         uri = argv[0];
1042         if ( strncasecmp( uri, "uri=", STRLENOF( "uri=" ) ) == 0 ) {
1043                 uri += STRLENOF( "uri=" );
1044         }
1045
1046         if ( ldap_url_parse( uri, &lud ) != LDAP_URL_SUCCESS ) {
1047                 Debug( LDAP_DEBUG_ANY,
1048                         "[%s:%d] illegal URI '%s'\n",
1049                         fname, lineno, uri );
1050         return NULL;
1051         }
1052
1053         if ( strcasecmp( lud->lud_scheme, "ldap" )) {
1054                 Debug( LDAP_DEBUG_ANY,
1055                         "[%s:%d] illegal URI scheme '%s'\n",
1056                         fname, lineno, lud->lud_scheme );
1057                 goto done;
1058         }
1059
1060         if (( lud->lud_host && lud->lud_host[0] ) || lud->lud_exts
1061                 || !lud->lud_dn ) {
1062                 Debug( LDAP_DEBUG_ANY,
1063                         "[%s:%d] illegal URI '%s'\n",
1064                         fname, lineno, uri );
1065                 goto done;
1066         }
1067
1068         if ( lud->lud_attrs ) {
1069                 if ( lud->lud_attrs[1] ) {
1070                         Debug( LDAP_DEBUG_ANY,
1071                                 "[%s:%d] only one attribute allowed in URI\n",
1072                                 fname, lineno, 0 );
1073                         goto done;
1074                 }
1075                 if ( strcasecmp( lud->lud_attrs[0], "dn" ) &&
1076                         strcasecmp( lud->lud_attrs[0], "entryDN" )) {
1077                         const char *text;
1078                         rc = slap_str2ad( lud->lud_attrs[0], &ad, &text );
1079                         if ( rc )
1080                                 goto done;
1081                 }
1082         }
1083         ber_str2bv( lud->lud_dn, 0, 0, &dn );
1084         if ( dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL ))
1085                 goto done;
1086
1087         if ( lud->lud_filter ) {
1088                 flen = strlen( lud->lud_filter ) + 1;
1089         }
1090         ret = ch_malloc( sizeof( slapd_map_data ) + flen );
1091         ret->base = ndn;
1092         if ( flen ) {
1093                 ret->filter.bv_val = (char *)(ret+1);
1094                 ret->filter.bv_len = flen - 1;
1095                 strcpy( ret->filter.bv_val, lud->lud_filter );
1096         } else {
1097                 BER_BVZERO( &ret->filter );
1098         }
1099         ret->scope = lud->lud_scope;
1100         if ( ad ) {
1101                 ret->attrs[0].an_name = ad->ad_cname;
1102         } else {
1103                 BER_BVZERO( &ret->attrs[0].an_name );
1104         }
1105         ret->attrs[0].an_desc = ad;
1106         BER_BVZERO( &ret->attrs[1].an_name );
1107 done:
1108         ldap_free_urldesc( lud );
1109         return ret;
1110 }
1111
1112 struct slapd_rw_info {
1113         slapd_map_data *si_data;
1114         struct berval si_val;
1115 };
1116
1117 static int
1118 slapd_rw_cb( Operation *op, SlapReply *rs )
1119 {
1120         if ( rs->sr_type == REP_SEARCH ) {
1121                 struct slapd_rw_info *si = op->o_callback->sc_private;
1122
1123                 if ( si->si_data->attrs[0].an_desc ) {
1124                         Attribute *a;
1125
1126                         a = attr_find( rs->sr_entry->e_attrs,
1127                                 si->si_data->attrs[0].an_desc );
1128                         if ( a ) {
1129                                 ber_dupbv( &si->si_val, a->a_vals );
1130                         }
1131                 } else {
1132                         ber_dupbv( &si->si_val, &rs->sr_entry->e_name );
1133                 }
1134         }
1135         return LDAP_SUCCESS;
1136 }
1137
1138 static int
1139 slapd_rw_apply( void *private, const char *filter, struct berval *val )
1140 {
1141         slapd_map_data *sl = private;
1142         slap_callback cb = { NULL };
1143         Connection conn = {0};
1144         OperationBuffer opbuf;
1145         Operation *op;
1146         void *thrctx;
1147         SlapReply rs = {REP_RESULT};
1148         struct slapd_rw_info si;
1149         char *ptr;
1150         int rc;
1151
1152         thrctx = ldap_pvt_thread_pool_context();
1153         connection_fake_init2( &conn, &opbuf, thrctx, 0 );
1154         op = &opbuf.ob_op;
1155
1156         op->o_tag = LDAP_REQ_SEARCH;
1157         op->o_req_dn = op->o_req_ndn = sl->base;
1158         op->o_bd = select_backend( &op->o_req_ndn, 1 );
1159         if ( !op->o_bd ) {
1160                 return REWRITE_ERR;
1161         }
1162         si.si_data = sl;
1163         BER_BVZERO( &si.si_val );
1164         op->ors_scope = sl->scope;
1165         op->ors_deref = LDAP_DEREF_NEVER;
1166         op->ors_slimit = 1;
1167         op->ors_tlimit = SLAP_NO_LIMIT;
1168         if ( sl->attrs[0].an_desc ) {
1169                 op->ors_attrs = sl->attrs;
1170         } else {
1171                 op->ors_attrs = slap_anlist_no_attrs;
1172         }
1173         if ( filter ) {
1174                 rc = strlen( filter );
1175         } else {
1176                 rc = 0;
1177         }
1178         rc += sl->filter.bv_len;
1179         ptr = op->ors_filterstr.bv_val = op->o_tmpalloc( rc + 1, op->o_tmpmemctx );
1180         if ( sl->filter.bv_len ) {
1181                 ptr = lutil_strcopy( ptr, sl->filter.bv_val );
1182         } else {
1183                 *ptr = '\0';
1184         }
1185         if ( filter ) {
1186                 strcpy( ptr, filter );
1187         }
1188         op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
1189         if ( !op->ors_filter ) {
1190                 op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1191                 return REWRITE_ERR;
1192         }
1193
1194         op->ors_attrsonly = 0;
1195         op->o_dn = op->o_bd->be_rootdn;
1196         op->o_ndn = op->o_bd->be_rootndn;
1197         op->o_do_not_cache = 1;
1198
1199         cb.sc_response = slapd_rw_cb;
1200         cb.sc_private = &si;
1201         op->o_callback = &cb;
1202
1203         rc = op->o_bd->be_search( op, &rs );
1204         if ( rc == LDAP_SUCCESS && !BER_BVISNULL( &si.si_val )) {
1205                 *val = si.si_val;
1206                 rc = REWRITE_SUCCESS;
1207         } else {
1208                 if ( !BER_BVISNULL( &si.si_val )) {
1209                         ch_free( si.si_val.bv_val );
1210                 }
1211                 rc = REWRITE_ERR;
1212         }
1213         filter_free_x( op, op->ors_filter, 1 );
1214         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1215         return rc;
1216 }
1217
1218 static int
1219 slapd_rw_destroy( void *private )
1220 {
1221         slapd_map_data *md = private;
1222
1223         assert( private != NULL );
1224
1225         ch_free( md->base.bv_val );
1226         ch_free( md );
1227
1228         return 0;
1229 }
1230
1231 static const rewrite_mapper slapd_mapper = {
1232         "slapd",
1233         slapd_rw_config,
1234         slapd_rw_apply,
1235         slapd_rw_destroy
1236 };
1237 #endif
1238
1239 int slap_sasl_init( void )
1240 {
1241 #ifdef HAVE_CYRUS_SASL
1242         int rc;
1243         static sasl_callback_t server_callbacks[] = {
1244                 { SASL_CB_LOG, (slap_sasl_cb_ft)&slap_sasl_log, NULL },
1245                 { SASL_CB_GETOPT, (slap_sasl_cb_ft)&slap_sasl_getopt, NULL },
1246                 { SASL_CB_LIST_END, NULL, NULL }
1247         };
1248 #endif
1249
1250 #ifdef ENABLE_REWRITE
1251         rewrite_mapper_register( &slapd_mapper );
1252 #endif
1253
1254 #ifdef HAVE_CYRUS_SASL
1255 #ifdef HAVE_SASL_VERSION
1256         /* stringify the version number, sasl.h doesn't do it for us */
1257 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
1258 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
1259 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
1260                                 SASL_VERSION_STEP)
1261
1262         sasl_version( NULL, &rc );
1263         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1264                 (rc & 0xffff) < SASL_VERSION_STEP)
1265         {
1266                 char version[sizeof("xxx.xxx.xxxxx")];
1267                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
1268                         rc & 0xffff );
1269                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: SASL library version mismatch:"
1270                         " expected %s, got %s\n",
1271                         SASL_VERSION_STRING, version, 0 );
1272                 return -1;
1273         }
1274 #endif
1275
1276         sasl_set_mutex(
1277                 ldap_pvt_sasl_mutex_new,
1278                 ldap_pvt_sasl_mutex_lock,
1279                 ldap_pvt_sasl_mutex_unlock,
1280                 ldap_pvt_sasl_mutex_dispose );
1281
1282         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1283
1284         rc = sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1285         if( rc != SASL_OK ) {
1286                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: auxprop add plugin failed\n",
1287                         0, 0, 0 );
1288                 return -1;
1289         }
1290
1291         /* should provide callbacks for logging */
1292         /* server name should be configurable */
1293         rc = sasl_server_init( server_callbacks, "slapd" );
1294
1295         if( rc != SASL_OK ) {
1296                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: server init failed\n",
1297                         0, 0, 0 );
1298
1299                 return -1;
1300         }
1301
1302 #ifdef SLAPD_SPASSWD
1303         lutil_passwd_add( &sasl_pwscheme, chk_sasl, NULL );
1304 #endif
1305
1306         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1307                 0, 0, 0 );
1308
1309         /* default security properties */
1310         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1311         sasl_secprops.max_ssf = INT_MAX;
1312         sasl_secprops.maxbufsize = 65536;
1313         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1314 #endif
1315
1316         return 0;
1317 }
1318
1319 int slap_sasl_destroy( void )
1320 {
1321 #ifdef HAVE_CYRUS_SASL
1322         sasl_done();
1323
1324 #ifdef SLAP_AUXPROP_DONTUSECOPY
1325         if ( slap_dontUseCopy_propnames ) {
1326                 ber_bvarray_free( slap_dontUseCopy_propnames );
1327                 slap_dontUseCopy_propnames = NULL;
1328         }
1329 #endif /* SLAP_AUXPROP_DONTUSECOPY */
1330 #endif
1331         free( sasl_host );
1332         sasl_host = NULL;
1333
1334         return 0;
1335 }
1336
1337 static char *
1338 slap_sasl_peer2ipport( struct berval *peer )
1339 {
1340         int             isv6 = 0;
1341         char            *ipport, *p,
1342                         *addr = &peer->bv_val[ STRLENOF( "IP=" ) ];
1343         ber_len_t       plen = peer->bv_len - STRLENOF( "IP=" );
1344
1345         /* IPv6? */
1346         if ( addr[0] == '[' ) {
1347                 isv6 = 1;
1348                 plen--;
1349         }
1350         ipport = ch_strdup( &addr[isv6] );
1351
1352         /* Convert IPv6/IPv4 addresses to address;port syntax. */
1353         p = strrchr( ipport, ':' );
1354         if ( p != NULL ) {
1355                 *p = ';';
1356                 if ( isv6 ) {
1357                         assert( p[-1] == ']' );
1358                         AC_MEMCPY( &p[-1], p, plen - ( p - ipport ) + 1 );
1359                 }
1360
1361         } else if ( isv6 ) {
1362                 /* trim ']' */
1363                 plen--;
1364                 assert( addr[plen] == ']' );
1365                 addr[plen] = '\0';
1366         }
1367
1368         return ipport;
1369 }
1370
1371 int slap_sasl_open( Connection *conn, int reopen )
1372 {
1373         int sc = LDAP_SUCCESS;
1374 #ifdef HAVE_CYRUS_SASL
1375         int cb;
1376
1377         sasl_conn_t *ctx = NULL;
1378         sasl_callback_t *session_callbacks;
1379         char *ipremoteport = NULL, *iplocalport = NULL;
1380
1381         assert( conn->c_sasl_authctx == NULL );
1382
1383         if ( !reopen ) {
1384                 assert( conn->c_sasl_extra == NULL );
1385
1386                 session_callbacks =
1387                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1388                 if( session_callbacks == NULL ) {
1389                         Debug( LDAP_DEBUG_ANY, 
1390                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1391                         return -1;
1392                 }
1393                 conn->c_sasl_extra = session_callbacks;
1394
1395                 session_callbacks[cb=0].id = SASL_CB_LOG;
1396                 session_callbacks[cb].proc = (slap_sasl_cb_ft)&slap_sasl_log;
1397                 session_callbacks[cb++].context = conn;
1398
1399                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1400                 session_callbacks[cb].proc = (slap_sasl_cb_ft)&slap_sasl_authorize;
1401                 session_callbacks[cb++].context = conn;
1402
1403                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1404                 session_callbacks[cb].proc = (slap_sasl_cb_ft)&slap_sasl_canonicalize;
1405                 session_callbacks[cb++].context = conn;
1406
1407                 session_callbacks[cb].id = SASL_CB_LIST_END;
1408                 session_callbacks[cb].proc = NULL;
1409                 session_callbacks[cb++].context = NULL;
1410         } else {
1411                 session_callbacks = conn->c_sasl_extra;
1412         }
1413
1414         conn->c_sasl_layers = 0;
1415
1416         /* create new SASL context */
1417         if ( conn->c_sock_name.bv_len != 0 &&
1418                 strncmp( conn->c_sock_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1419         {
1420                 iplocalport = slap_sasl_peer2ipport( &conn->c_sock_name );
1421         }
1422
1423         if ( conn->c_peer_name.bv_len != 0 &&
1424                 strncmp( conn->c_peer_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1425         {
1426                 ipremoteport = slap_sasl_peer2ipport( &conn->c_peer_name );
1427         }
1428
1429         sc = sasl_server_new( "ldap", sasl_host, global_realm,
1430                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1431         if ( iplocalport != NULL ) {
1432                 ch_free( iplocalport );
1433         }
1434         if ( ipremoteport != NULL ) {
1435                 ch_free( ipremoteport );
1436         }
1437
1438         if( sc != SASL_OK ) {
1439                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1440                         sc, 0, 0 );
1441
1442                 return -1;
1443         }
1444
1445         conn->c_sasl_authctx = ctx;
1446
1447         if( sc == SASL_OK ) {
1448                 sc = sasl_setprop( ctx,
1449                         SASL_SEC_PROPS, &sasl_secprops );
1450
1451                 if( sc != SASL_OK ) {
1452                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1453                                 sc, 0, 0 );
1454
1455                         slap_sasl_close( conn );
1456                         return -1;
1457                 }
1458         }
1459
1460         sc = slap_sasl_err2ldap( sc );
1461
1462 #elif defined(SLAP_BUILTIN_SASL)
1463         /* built-in SASL implementation */
1464         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1465         if( ctx == NULL ) return -1;
1466
1467         ctx->sc_external_ssf = 0;
1468         BER_BVZERO( &ctx->sc_external_id );
1469
1470         conn->c_sasl_authctx = ctx;
1471 #endif
1472
1473         return sc;
1474 }
1475
1476 int slap_sasl_external(
1477         Connection *conn,
1478         slap_ssf_t ssf,
1479         struct berval *auth_id )
1480 {
1481 #ifdef HAVE_CYRUS_SASL
1482         int sc;
1483         sasl_conn_t *ctx = conn->c_sasl_authctx;
1484         sasl_ssf_t sasl_ssf = ssf;
1485
1486         if ( ctx == NULL ) {
1487                 return LDAP_UNAVAILABLE;
1488         }
1489
1490         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &sasl_ssf );
1491
1492         if ( sc != SASL_OK ) {
1493                 return LDAP_OTHER;
1494         }
1495
1496         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1497                 auth_id ? auth_id->bv_val : NULL );
1498
1499         if ( sc != SASL_OK ) {
1500                 return LDAP_OTHER;
1501         }
1502 #elif defined(SLAP_BUILTIN_SASL)
1503         /* built-in SASL implementation */
1504         SASL_CTX *ctx = conn->c_sasl_authctx;
1505         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1506
1507         ctx->sc_external_ssf = ssf;
1508         if( auth_id ) {
1509                 ctx->sc_external_id = *auth_id;
1510                 BER_BVZERO( auth_id );
1511         } else {
1512                 BER_BVZERO( &ctx->sc_external_id );
1513         }
1514 #endif
1515
1516         return LDAP_SUCCESS;
1517 }
1518
1519 int slap_sasl_cbinding( Connection *conn, struct berval *cbv )
1520 {
1521 #ifdef SASL_CHANNEL_BINDING
1522         sasl_channel_binding_t *cb = ch_malloc( sizeof(*cb) + cbv->bv_len );;
1523         cb->name = "ldap";
1524         cb->critical = 0;
1525         cb->data = (char *)(cb+1);
1526         cb->len = cbv->bv_len;
1527         memcpy( (void *)cb->data, cbv->bv_val, cbv->bv_len );
1528         sasl_setprop( conn->c_sasl_authctx, SASL_CHANNEL_BINDING, cb );
1529         conn->c_sasl_cbind = cb;
1530 #endif
1531         return LDAP_SUCCESS;
1532 }
1533
1534 int slap_sasl_reset( Connection *conn )
1535 {
1536         return LDAP_SUCCESS;
1537 }
1538
1539 char ** slap_sasl_mechs( Connection *conn )
1540 {
1541         char **mechs = NULL;
1542
1543 #ifdef HAVE_CYRUS_SASL
1544         sasl_conn_t *ctx = conn->c_sasl_authctx;
1545
1546         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1547
1548         if( ctx != NULL ) {
1549                 int sc;
1550                 SASL_CONST char *mechstr;
1551
1552                 sc = sasl_listmech( ctx,
1553                         NULL, NULL, ",", NULL,
1554                         &mechstr, NULL, NULL );
1555
1556                 if( sc != SASL_OK ) {
1557                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1558                                 sc, 0, 0 );
1559
1560                         return NULL;
1561                 }
1562
1563                 mechs = ldap_str2charray( mechstr, "," );
1564         }
1565 #elif defined(SLAP_BUILTIN_SASL)
1566         /* builtin SASL implementation */
1567         SASL_CTX *ctx = conn->c_sasl_authctx;
1568         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1569                 /* should check ssf */
1570                 mechs = ldap_str2charray( "EXTERNAL", "," );
1571         }
1572 #endif
1573
1574         return mechs;
1575 }
1576
1577 int slap_sasl_close( Connection *conn )
1578 {
1579 #ifdef HAVE_CYRUS_SASL
1580         sasl_conn_t *ctx = conn->c_sasl_authctx;
1581
1582         if( ctx != NULL ) {
1583                 sasl_dispose( &ctx );
1584         }
1585         if ( conn->c_sasl_sockctx &&
1586                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1587         {
1588                 ctx = conn->c_sasl_sockctx;
1589                 sasl_dispose( &ctx );
1590         }
1591
1592         conn->c_sasl_authctx = NULL;
1593         conn->c_sasl_sockctx = NULL;
1594         conn->c_sasl_done = 0;
1595
1596         free( conn->c_sasl_extra );
1597         conn->c_sasl_extra = NULL;
1598
1599         free( conn->c_sasl_cbind );
1600         conn->c_sasl_cbind = NULL;
1601
1602 #elif defined(SLAP_BUILTIN_SASL)
1603         SASL_CTX *ctx = conn->c_sasl_authctx;
1604         if( ctx ) {
1605                 if( ctx->sc_external_id.bv_val ) {
1606                         free( ctx->sc_external_id.bv_val );
1607                         BER_BVZERO( &ctx->sc_external_id );
1608                 }
1609                 free( ctx );
1610                 conn->c_sasl_authctx = NULL;
1611         }
1612 #endif
1613
1614         return LDAP_SUCCESS;
1615 }
1616
1617 int slap_sasl_bind( Operation *op, SlapReply *rs )
1618 {
1619 #ifdef HAVE_CYRUS_SASL
1620         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1621         struct berval response;
1622         unsigned reslen = 0;
1623         int sc;
1624
1625         Debug(LDAP_DEBUG_ARGS,
1626                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1627                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1628                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1629                 op->o_conn->c_sasl_bind_mech.bv_val,
1630                 op->orb_cred.bv_len );
1631
1632         if( ctx == NULL ) {
1633                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1634                         "SASL unavailable on this session" );
1635                 return rs->sr_err;
1636         }
1637
1638 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1639         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1640 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1641         sasl_server_step( ctx, cred, clen, resp, rlen )
1642
1643         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1644                 /* If we already authenticated once, must use a new context */
1645                 if ( op->o_conn->c_sasl_done ) {
1646                         sasl_ssf_t ssf = 0;
1647                         sasl_ssf_t *ssfp = NULL;
1648                         const char *authid = NULL;
1649
1650                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssfp );
1651                         if ( ssfp ) ssf = *ssfp;
1652
1653                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1654                         if ( authid ) authid = ch_strdup( authid );
1655
1656                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1657                                 sasl_dispose( &ctx );
1658                         }
1659                         op->o_conn->c_sasl_authctx = NULL;
1660                                 
1661                         slap_sasl_open( op->o_conn, 1 );
1662                         ctx = op->o_conn->c_sasl_authctx;
1663                         sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1664                         if ( authid ) {
1665                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1666                                 ch_free( (char *)authid );
1667                         }
1668                 }
1669                 sc = START( ctx,
1670                         op->o_conn->c_sasl_bind_mech.bv_val,
1671                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1672                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1673
1674         } else {
1675                 sc = STEP( ctx,
1676                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1677                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1678         }
1679
1680         response.bv_len = reslen;
1681
1682         if ( sc == SASL_OK ) {
1683                 sasl_ssf_t *ssf = NULL;
1684
1685                 ber_dupbv_x( &op->orb_edn, &op->o_conn->c_sasl_dn, op->o_tmpmemctx );
1686                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1687                 op->o_conn->c_sasl_done = 1;
1688
1689                 rs->sr_err = LDAP_SUCCESS;
1690
1691                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1692                 op->orb_ssf = ssf ? *ssf : 0;
1693
1694                 ctx = NULL;
1695                 if( op->orb_ssf ) {
1696                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1697                         op->o_conn->c_sasl_layers++;
1698
1699                         /* If there's an old layer, set sockctx to NULL to
1700                          * tell connection_read() to wait for us to finish.
1701                          * Otherwise there is a race condition: we have to
1702                          * send the Bind response using the old security
1703                          * context and then remove it before reading any
1704                          * new messages.
1705                          */
1706                         if ( op->o_conn->c_sasl_sockctx ) {
1707                                 ctx = op->o_conn->c_sasl_sockctx;
1708                                 op->o_conn->c_sasl_sockctx = NULL;
1709                         } else {
1710                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1711                         }
1712                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1713                 }
1714
1715                 /* Must send response using old security layer */
1716                 rs->sr_sasldata = (response.bv_len ? &response : NULL);
1717                 send_ldap_sasl( op, rs );
1718                 
1719                 /* Now dispose of the old security layer.
1720                  */
1721                 if ( ctx ) {
1722                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1723                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1724                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1725                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1726                         sasl_dispose( &ctx );
1727                 }
1728         } else if ( sc == SASL_CONTINUE ) {
1729                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1730                 rs->sr_text = sasl_errdetail( ctx );
1731                 rs->sr_sasldata = &response;
1732                 send_ldap_sasl( op, rs );
1733
1734         } else {
1735                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1736                 rs->sr_text = sasl_errdetail( ctx );
1737                 rs->sr_err = slap_sasl_err2ldap( sc ),
1738                 send_ldap_result( op, rs );
1739         }
1740
1741         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1742
1743 #elif defined(SLAP_BUILTIN_SASL)
1744         /* built-in SASL implementation */
1745         SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1746
1747         if ( ctx == NULL ) {
1748                 send_ldap_error( op, rs, LDAP_OTHER,
1749                         "Internal SASL Error" );
1750
1751         } else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1752                 /* EXTERNAL */
1753
1754                 if( op->orb_cred.bv_len ) {
1755                         rs->sr_text = "proxy authorization not supported";
1756                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1757                         send_ldap_result( op, rs );
1758
1759                 } else {
1760                         op->orb_edn = ctx->sc_external_id;
1761                         rs->sr_err = LDAP_SUCCESS;
1762                         rs->sr_sasldata = NULL;
1763                         send_ldap_sasl( op, rs );
1764                 }
1765
1766         } else {
1767                 send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1768                         "requested SASL mechanism not supported" );
1769         }
1770 #else
1771         send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1772                 "SASL not supported" );
1773 #endif
1774
1775         return rs->sr_err;
1776 }
1777
1778 char* slap_sasl_secprops( const char *in )
1779 {
1780 #ifdef HAVE_CYRUS_SASL
1781         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1782
1783         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1784 #else
1785         return "SASL not supported";
1786 #endif
1787 }
1788
1789 void slap_sasl_secprops_unparse( struct berval *bv )
1790 {
1791 #ifdef HAVE_CYRUS_SASL
1792         ldap_pvt_sasl_secprops_unparse( &sasl_secprops, bv );
1793 #endif
1794 }
1795
1796 #ifdef HAVE_CYRUS_SASL
1797 int
1798 slap_sasl_setpass( Operation *op, SlapReply *rs )
1799 {
1800         struct berval id = BER_BVNULL;  /* needs to come from connection */
1801         struct berval new = BER_BVNULL;
1802         struct berval old = BER_BVNULL;
1803
1804         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1805
1806         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1807                 (SASL_CONST void **)(char *)&id.bv_val );
1808
1809         if( rs->sr_err != SASL_OK ) {
1810                 rs->sr_text = "unable to retrieve SASL username";
1811                 rs->sr_err = LDAP_OTHER;
1812                 goto done;
1813         }
1814
1815         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1816                 id.bv_val ? id.bv_val : "", 0, 0 );
1817
1818         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1819                 NULL, &old, &new, &rs->sr_text );
1820
1821         if( rs->sr_err != LDAP_SUCCESS ) {
1822                 goto done;
1823         }
1824
1825         if( new.bv_len == 0 ) {
1826                 slap_passwd_generate(&new);
1827
1828                 if( new.bv_len == 0 ) {
1829                         rs->sr_text = "password generation failed.";
1830                         rs->sr_err = LDAP_OTHER;
1831                         goto done;
1832                 }
1833                 
1834                 rs->sr_rspdata = slap_passwd_return( &new );
1835         }
1836
1837         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1838                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1839         if( rs->sr_err != SASL_OK ) {
1840                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1841         }
1842         switch(rs->sr_err) {
1843                 case SASL_OK:
1844                         rs->sr_err = LDAP_SUCCESS;
1845                         break;
1846
1847                 case SASL_NOCHANGE:
1848                 case SASL_NOMECH:
1849                 case SASL_DISABLED:
1850                 case SASL_PWLOCK:
1851                 case SASL_FAIL:
1852                 case SASL_BADPARAM:
1853                 default:
1854                         rs->sr_err = LDAP_OTHER;
1855         }
1856
1857 done:
1858         return rs->sr_err;
1859 }
1860 #endif /* HAVE_CYRUS_SASL */
1861
1862 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1863  * string returned in *dn is in its own allocated memory, and must be free'd 
1864  * by the calling process.  -Mark Adamson, Carnegie Mellon
1865  *
1866  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1867  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1868  */
1869
1870 #define SET_NONE        0
1871 #define SET_DN          1
1872 #define SET_U           2
1873
1874 int slap_sasl_getdn( Connection *conn, Operation *op, struct berval *id,
1875         char *user_realm, struct berval *dn, int flags )
1876 {
1877         int rc, is_dn = SET_NONE, do_norm = 1;
1878         struct berval dn2, *mech;
1879
1880         assert( conn != NULL );
1881         assert( id != NULL );
1882
1883         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: conn %lu id=%s [len=%lu]\n", 
1884                 conn->c_connid,
1885                 BER_BVISNULL( id ) ? "NULL" : ( BER_BVISEMPTY( id ) ? "<empty>" : id->bv_val ),
1886                 BER_BVISNULL( id ) ? 0 : ( BER_BVISEMPTY( id ) ? 0 :
1887                                            (unsigned long) id->bv_len ) );
1888
1889         if ( !op ) {
1890                 op = conn->c_sasl_bindop;
1891         }
1892         assert( op != NULL );
1893
1894         BER_BVZERO( dn );
1895
1896         if ( !BER_BVISNULL( id ) ) {
1897                 /* Blatantly anonymous ID */
1898                 static struct berval bv_anonymous = BER_BVC( "anonymous" );
1899
1900                 if ( ber_bvstrcasecmp( id, &bv_anonymous ) == 0 ) {
1901                         return( LDAP_SUCCESS );
1902                 }
1903
1904         } else {
1905                 /* FIXME: if empty, should we stop? */
1906                 BER_BVSTR( id, "" );
1907         }
1908
1909         if ( !BER_BVISEMPTY( &conn->c_sasl_bind_mech ) ) {
1910                 mech = &conn->c_sasl_bind_mech;
1911         } else {
1912                 mech = &conn->c_authmech;
1913         }
1914
1915         /* An authcID needs to be converted to authzID form. Set the
1916          * values directly into *dn; they will be normalized later. (and
1917          * normalizing always makes a new copy.) An ID from a TLS certificate
1918          * is already normalized, so copy it and skip normalization.
1919          */
1920         if( flags & SLAP_GETDN_AUTHCID ) {
1921                 if( bvmatch( mech, &ext_bv )) {
1922                         /* EXTERNAL DNs are already normalized */
1923                         assert( !BER_BVISNULL( id ) );
1924
1925                         do_norm = 0;
1926                         is_dn = SET_DN;
1927                         ber_dupbv_x( dn, id, op->o_tmpmemctx );
1928
1929                 } else {
1930                         /* convert to u:<username> form */
1931                         is_dn = SET_U;
1932                         *dn = *id;
1933                 }
1934         }
1935
1936         if( is_dn == SET_NONE ) {
1937                 if( !strncasecmp( id->bv_val, "u:", STRLENOF( "u:" ) ) ) {
1938                         is_dn = SET_U;
1939                         dn->bv_val = id->bv_val + STRLENOF( "u:" );
1940                         dn->bv_len = id->bv_len - STRLENOF( "u:" );
1941
1942                 } else if ( !strncasecmp( id->bv_val, "dn:", STRLENOF( "dn:" ) ) ) {
1943                         is_dn = SET_DN;
1944                         dn->bv_val = id->bv_val + STRLENOF( "dn:" );
1945                         dn->bv_len = id->bv_len - STRLENOF( "dn:" );
1946                 }
1947         }
1948
1949         /* No other possibilities from here */
1950         if( is_dn == SET_NONE ) {
1951                 BER_BVZERO( dn );
1952                 return( LDAP_INAPPROPRIATE_AUTH );
1953         }
1954
1955         /* Username strings */
1956         if( is_dn == SET_U ) {
1957                 /* ITS#3419: values may need escape */
1958                 LDAPRDN         DN[ 5 ];
1959                 LDAPAVA         *RDNs[ 4 ][ 2 ];
1960                 LDAPAVA         AVAs[ 4 ];
1961                 int             irdn;
1962
1963                 irdn = 0;
1964                 DN[ irdn ] = RDNs[ irdn ];
1965                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1966                 AVAs[ irdn ].la_attr = slap_schema.si_ad_uid->ad_cname;
1967                 AVAs[ irdn ].la_value = *dn;
1968                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1969                 AVAs[ irdn ].la_private = NULL;
1970                 RDNs[ irdn ][ 1 ] = NULL;
1971
1972                 if ( user_realm && *user_realm ) {
1973                         irdn++;
1974                         DN[ irdn ] = RDNs[ irdn ];
1975                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1976                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1977                         ber_str2bv( user_realm, 0, 0, &AVAs[ irdn ].la_value );
1978                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1979                         AVAs[ irdn ].la_private = NULL;
1980                         RDNs[ irdn ][ 1 ] = NULL;
1981                 }
1982
1983                 if ( !BER_BVISNULL( mech ) ) {
1984                         irdn++;
1985                         DN[ irdn ] = RDNs[ irdn ];
1986                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1987                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1988                         AVAs[ irdn ].la_value = *mech;
1989                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1990                         AVAs[ irdn ].la_private = NULL;
1991                         RDNs[ irdn ][ 1 ] = NULL;
1992                 }
1993
1994                 irdn++;
1995                 DN[ irdn ] = RDNs[ irdn ];
1996                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1997                 AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1998                 BER_BVSTR( &AVAs[ irdn ].la_value, "auth" );
1999                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
2000                 AVAs[ irdn ].la_private = NULL;
2001                 RDNs[ irdn ][ 1 ] = NULL;
2002
2003                 irdn++;
2004                 DN[ irdn ] = NULL;
2005
2006                 rc = ldap_dn2bv_x( DN, dn, LDAP_DN_FORMAT_LDAPV3,
2007                                 op->o_tmpmemctx );
2008                 if ( rc != LDAP_SUCCESS ) {
2009                         BER_BVZERO( dn );
2010                         return rc;
2011                 }
2012
2013                 Debug( LDAP_DEBUG_TRACE,
2014                         "slap_sasl_getdn: u:id converted to %s\n",
2015                         dn->bv_val, 0, 0 );
2016
2017         } else {
2018                 
2019                 /* Dup the DN in any case, so we don't risk 
2020                  * leaks or dangling pointers later,
2021                  * and the DN value is '\0' terminated */
2022                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
2023                 dn->bv_val = dn2.bv_val;
2024         }
2025
2026         /* All strings are in DN form now. Normalize if needed. */
2027         if ( do_norm ) {
2028                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
2029
2030                 /* User DNs were constructed above and must be freed now */
2031                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
2032
2033                 if ( rc != LDAP_SUCCESS ) {
2034                         BER_BVZERO( dn );
2035                         return rc;
2036                 }
2037                 *dn = dn2;
2038         }
2039
2040         /* Run thru regexp */
2041         slap_sasl2dn( op, dn, &dn2, flags );
2042         if( !BER_BVISNULL( &dn2 ) ) {
2043                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
2044                 *dn = dn2;
2045                 Debug( LDAP_DEBUG_TRACE,
2046                         "slap_sasl_getdn: dn:id converted to %s\n",
2047                         dn->bv_val, 0, 0 );
2048         }
2049
2050         return( LDAP_SUCCESS );
2051 }