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