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