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