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