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