]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
typo in error message
[openldap] / servers / slapd / sasl.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2010 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15
16 #include "portable.h"
17
18 #include <stdio.h>
19 #ifdef HAVE_LIMITS_H
20 #include <limits.h>
21 #endif
22
23 #include <ac/stdlib.h>
24 #include <ac/string.h>
25
26 #include <lber.h>
27 #include <ldap_log.h>
28
29 #include "slap.h"
30
31 #ifdef ENABLE_REWRITE
32 #include <rewrite.h>
33 #endif
34
35 #ifdef HAVE_CYRUS_SASL
36 # ifdef HAVE_SASL_SASL_H
37 #  include <sasl/sasl.h>
38 #  include <sasl/saslplug.h>
39 # else
40 #  include <sasl.h>
41 #  include <saslplug.h>
42 # endif
43
44 # define        SASL_CONST const
45
46 #define SASL_VERSION_FULL       ((SASL_VERSION_MAJOR << 16) |\
47         (SASL_VERSION_MINOR << 8) | SASL_VERSION_STEP)
48
49 static sasl_security_properties_t sasl_secprops;
50 #elif defined( SLAP_BUILTIN_SASL )
51 /*
52  * built-in SASL implementation
53  *      only supports EXTERNAL
54  */
55 typedef struct sasl_ctx {
56         slap_ssf_t sc_external_ssf;
57         struct berval sc_external_id;
58 } SASL_CTX;
59
60 #endif
61
62 #include <lutil.h>
63
64 static struct berval ext_bv = BER_BVC( "EXTERNAL" );
65
66 char *slap_sasl_auxprops;
67
68 #ifdef HAVE_CYRUS_SASL
69
70 /* Just use our internal auxprop by default */
71 static int
72 slap_sasl_getopt(
73         void *context,
74         const char *plugin_name,
75         const char *option,
76         const char **result,
77         unsigned *len)
78 {
79         if ( strcmp( option, "auxprop_plugin" )) {
80                 return SASL_FAIL;
81         }
82         if ( slap_sasl_auxprops )
83                 *result = slap_sasl_auxprops;
84         else
85                 *result = "slapd";
86         return SASL_OK;
87 }
88
89 int
90 slap_sasl_log(
91         void *context,
92         int priority,
93         const char *message) 
94 {
95         Connection *conn = context;
96         int level;
97         const char * label;
98
99         if ( message == NULL ) {
100                 return SASL_BADPARAM;
101         }
102
103         switch (priority) {
104         case SASL_LOG_NONE:
105                 level = LDAP_DEBUG_NONE;
106                 label = "None";
107                 break;
108         case SASL_LOG_ERR:
109                 level = LDAP_DEBUG_ANY;
110                 label = "Error";
111                 break;
112         case SASL_LOG_FAIL:
113                 level = LDAP_DEBUG_ANY;
114                 label = "Failure";
115                 break;
116         case SASL_LOG_WARN:
117                 level = LDAP_DEBUG_TRACE;
118                 label = "Warning";
119                 break;
120         case SASL_LOG_NOTE:
121                 level = LDAP_DEBUG_TRACE;
122                 label = "Notice";
123                 break;
124         case SASL_LOG_DEBUG:
125                 level = LDAP_DEBUG_TRACE;
126                 label = "Debug";
127                 break;
128         case SASL_LOG_TRACE:
129                 level = LDAP_DEBUG_TRACE;
130                 label = "Trace";
131                 break;
132         case SASL_LOG_PASS:
133                 level = LDAP_DEBUG_TRACE;
134                 label = "Password Trace";
135                 break;
136         default:
137                 return SASL_BADPARAM;
138         }
139
140         Debug( level, "SASL [conn=%ld] %s: %s\n",
141                 conn ? (long) conn->c_connid: -1L,
142                 label, message );
143
144
145         return SASL_OK;
146 }
147
148 static const char *slap_propnames[] = {
149         "*slapConn", "*slapAuthcDNlen", "*slapAuthcDN",
150         "*slapAuthzDNlen", "*slapAuthzDN", NULL };
151
152 static Filter generic_filter = { LDAP_FILTER_PRESENT, { 0 }, NULL };
153 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
154
155 #define SLAP_SASL_PROP_CONN     0
156 #define SLAP_SASL_PROP_AUTHCLEN 1
157 #define SLAP_SASL_PROP_AUTHC    2
158 #define SLAP_SASL_PROP_AUTHZLEN 3
159 #define SLAP_SASL_PROP_AUTHZ    4
160 #define SLAP_SASL_PROP_COUNT    5       /* Number of properties we used */
161
162 typedef struct lookup_info {
163         int flags;
164         const struct propval *list;
165         sasl_server_params_t *sparams;
166 } lookup_info;
167
168 static slap_response sasl_ap_lookup;
169
170 static struct berval sc_cleartext = BER_BVC("{CLEARTEXT}");
171
172 static int
173 sasl_ap_lookup( Operation *op, SlapReply *rs )
174 {
175         BerVarray bv;
176         AttributeDescription *ad;
177         Attribute *a;
178         const char *text;
179         int rc, i;
180         lookup_info *sl = (lookup_info *)op->o_callback->sc_private;
181
182         if (rs->sr_type != REP_SEARCH) return 0;
183
184         for( i = 0; sl->list[i].name; i++ ) {
185                 const char *name = sl->list[i].name;
186
187                 if ( name[0] == '*' ) {
188                         if ( sl->flags & SASL_AUXPROP_AUTHZID ) continue;
189                         /* Skip our private properties */
190                         if ( !strcmp( name, slap_propnames[0] )) {
191                                 i += SLAP_SASL_PROP_COUNT - 1;
192                                 continue;
193                         }
194                         name++;
195                 } else if ( !(sl->flags & SASL_AUXPROP_AUTHZID ) )
196                         continue;
197
198                 if ( sl->list[i].values ) {
199                         if ( !(sl->flags & SASL_AUXPROP_OVERRIDE) ) continue;
200                 }
201                 ad = NULL;
202                 rc = slap_str2ad( name, &ad, &text );
203                 if ( rc != LDAP_SUCCESS ) {
204                         Debug( LDAP_DEBUG_TRACE,
205                                 "slap_ap_lookup: str2ad(%s): %s\n", name, text, 0 );
206                         continue;
207                 }
208
209                 /* If it's the rootdn and a rootpw was present, we already set
210                  * it so don't override it here.
211                  */
212                 if ( ad == slap_schema.si_ad_userPassword && sl->list[i].values && 
213                         be_isroot_dn( op->o_bd, &op->o_req_ndn ))
214                         continue;
215
216                 a = attr_find( rs->sr_entry->e_attrs, ad );
217                 if ( !a ) continue;
218                 if ( ! access_allowed( op, rs->sr_entry, ad, NULL, ACL_AUTH, NULL ) ) {
219                         continue;
220                 }
221                 if ( sl->list[i].values && ( sl->flags & SASL_AUXPROP_OVERRIDE ) ) {
222                         sl->sparams->utils->prop_erase( sl->sparams->propctx,
223                         sl->list[i].name );
224                 }
225                 for ( bv = a->a_vals; bv->bv_val; bv++ ) {
226                         /* ITS#3846 don't give hashed passwords to SASL */
227                         if ( ad == slap_schema.si_ad_userPassword &&
228                                 bv->bv_val[0] == '{' /*}*/ )
229                         {
230                                 if ( lutil_passwd_scheme( bv->bv_val ) ) {
231                                         /* If it's not a recognized scheme, just assume it's
232                                          * a cleartext password that happened to include brackets.
233                                          *
234                                          * If it's a recognized scheme, skip this value, unless the
235                                          * scheme is {CLEARTEXT}. In that case, skip over the
236                                          * scheme name and use the remainder. If there is nothing
237                                          * past the scheme name, skip this value.
238                                          */
239 #ifdef SLAPD_CLEARTEXT
240                                         if ( !strncasecmp( bv->bv_val, sc_cleartext.bv_val,
241                                                 sc_cleartext.bv_len )) {
242                                                 struct berval cbv;
243                                                 cbv.bv_len = bv->bv_len - sc_cleartext.bv_len;
244                                                 if ( cbv.bv_len > 0 ) {
245                                                         cbv.bv_val = bv->bv_val + sc_cleartext.bv_len;
246                                                         sl->sparams->utils->prop_set( sl->sparams->propctx,
247                                                                 sl->list[i].name, cbv.bv_val, cbv.bv_len );
248                                                 }
249                                         }
250 #endif
251                                         continue;
252                                 }
253                         }
254                         sl->sparams->utils->prop_set( sl->sparams->propctx,
255                                 sl->list[i].name, bv->bv_val, bv->bv_len );
256                 }
257         }
258         return LDAP_SUCCESS;
259 }
260
261 #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->filter.bv_val );
1094         ch_free( md );
1095
1096         return 0;
1097 }
1098
1099 static const rewrite_mapper slapd_mapper = {
1100         "slapd",
1101         slapd_rw_config,
1102         slapd_rw_apply,
1103         slapd_rw_destroy
1104 };
1105 #endif
1106
1107 int slap_sasl_init( void )
1108 {
1109 #ifdef HAVE_CYRUS_SASL
1110         int rc;
1111         static sasl_callback_t server_callbacks[] = {
1112                 { SASL_CB_LOG, &slap_sasl_log, NULL },
1113                 { SASL_CB_GETOPT, &slap_sasl_getopt, NULL },
1114                 { SASL_CB_LIST_END, NULL, NULL }
1115         };
1116 #endif
1117
1118 #ifdef ENABLE_REWRITE
1119         rewrite_mapper_register( &slapd_mapper );
1120 #endif
1121
1122 #ifdef HAVE_CYRUS_SASL
1123 #ifdef HAVE_SASL_VERSION
1124         /* stringify the version number, sasl.h doesn't do it for us */
1125 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
1126 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
1127 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
1128                                 SASL_VERSION_STEP)
1129
1130         sasl_version( NULL, &rc );
1131         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1132                 (rc & 0xffff) < SASL_VERSION_STEP)
1133         {
1134                 char version[sizeof("xxx.xxx.xxxxx")];
1135                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
1136                         rc & 0xffff );
1137                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: SASL library version mismatch:"
1138                         " expected %s, got %s\n",
1139                         SASL_VERSION_STRING, version, 0 );
1140                 return -1;
1141         }
1142 #endif
1143
1144         sasl_set_mutex(
1145                 ldap_pvt_sasl_mutex_new,
1146                 ldap_pvt_sasl_mutex_lock,
1147                 ldap_pvt_sasl_mutex_unlock,
1148                 ldap_pvt_sasl_mutex_dispose );
1149
1150         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1151
1152         rc = sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1153         if( rc != SASL_OK ) {
1154                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: auxprop add plugin failed\n",
1155                         0, 0, 0 );
1156                 return -1;
1157         }
1158
1159         /* should provide callbacks for logging */
1160         /* server name should be configurable */
1161         rc = sasl_server_init( server_callbacks, "slapd" );
1162
1163         if( rc != SASL_OK ) {
1164                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: server init failed\n",
1165                         0, 0, 0 );
1166
1167                 return -1;
1168         }
1169
1170 #ifdef SLAPD_SPASSWD
1171         lutil_passwd_add( &sasl_pwscheme, chk_sasl, NULL );
1172 #endif
1173
1174         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1175                 0, 0, 0 );
1176
1177         /* default security properties */
1178         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1179         sasl_secprops.max_ssf = INT_MAX;
1180         sasl_secprops.maxbufsize = 65536;
1181         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1182 #endif
1183
1184         return 0;
1185 }
1186
1187 int slap_sasl_destroy( void )
1188 {
1189 #ifdef HAVE_CYRUS_SASL
1190         sasl_done();
1191 #endif
1192         free( sasl_host );
1193         sasl_host = NULL;
1194
1195         return 0;
1196 }
1197
1198 static char *
1199 slap_sasl_peer2ipport( struct berval *peer )
1200 {
1201         int             isv6 = 0;
1202         char            *ipport, *p,
1203                         *addr = &peer->bv_val[ STRLENOF( "IP=" ) ];
1204         ber_len_t       plen = peer->bv_len - STRLENOF( "IP=" );
1205
1206         /* IPv6? */
1207         if ( addr[0] == '[' ) {
1208                 isv6 = 1;
1209                 plen--;
1210         }
1211         ipport = ch_strdup( &addr[isv6] );
1212
1213         /* Convert IPv6/IPv4 addresses to address;port syntax. */
1214         p = strrchr( ipport, ':' );
1215         if ( p != NULL ) {
1216                 *p = ';';
1217                 if ( isv6 ) {
1218                         assert( p[-1] == ']' );
1219                         AC_MEMCPY( &p[-1], p, plen - ( p - ipport ) + 1 );
1220                 }
1221
1222         } else if ( isv6 ) {
1223                 /* trim ']' */
1224                 plen--;
1225                 assert( addr[plen] == ']' );
1226                 addr[plen] = '\0';
1227         }
1228
1229         return ipport;
1230 }
1231
1232 int slap_sasl_open( Connection *conn, int reopen )
1233 {
1234         int sc = LDAP_SUCCESS;
1235 #ifdef HAVE_CYRUS_SASL
1236         int cb;
1237
1238         sasl_conn_t *ctx = NULL;
1239         sasl_callback_t *session_callbacks;
1240         char *ipremoteport = NULL, *iplocalport = NULL;
1241
1242         assert( conn->c_sasl_authctx == NULL );
1243
1244         if ( !reopen ) {
1245                 assert( conn->c_sasl_extra == NULL );
1246
1247                 session_callbacks =
1248                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1249                 if( session_callbacks == NULL ) {
1250                         Debug( LDAP_DEBUG_ANY, 
1251                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1252                         return -1;
1253                 }
1254                 conn->c_sasl_extra = session_callbacks;
1255
1256                 session_callbacks[cb=0].id = SASL_CB_LOG;
1257                 session_callbacks[cb].proc = &slap_sasl_log;
1258                 session_callbacks[cb++].context = conn;
1259
1260                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1261                 session_callbacks[cb].proc = &slap_sasl_authorize;
1262                 session_callbacks[cb++].context = conn;
1263
1264                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1265                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1266                 session_callbacks[cb++].context = conn;
1267
1268                 session_callbacks[cb].id = SASL_CB_LIST_END;
1269                 session_callbacks[cb].proc = NULL;
1270                 session_callbacks[cb++].context = NULL;
1271         } else {
1272                 session_callbacks = conn->c_sasl_extra;
1273         }
1274
1275         conn->c_sasl_layers = 0;
1276
1277         /* create new SASL context */
1278         if ( conn->c_sock_name.bv_len != 0 &&
1279                 strncmp( conn->c_sock_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1280         {
1281                 iplocalport = slap_sasl_peer2ipport( &conn->c_sock_name );
1282         }
1283
1284         if ( conn->c_peer_name.bv_len != 0 &&
1285                 strncmp( conn->c_peer_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1286         {
1287                 ipremoteport = slap_sasl_peer2ipport( &conn->c_peer_name );
1288         }
1289
1290         sc = sasl_server_new( "ldap", sasl_host, global_realm,
1291                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1292         if ( iplocalport != NULL ) {
1293                 ch_free( iplocalport );
1294         }
1295         if ( ipremoteport != NULL ) {
1296                 ch_free( ipremoteport );
1297         }
1298
1299         if( sc != SASL_OK ) {
1300                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1301                         sc, 0, 0 );
1302
1303                 return -1;
1304         }
1305
1306         conn->c_sasl_authctx = ctx;
1307
1308         if( sc == SASL_OK ) {
1309                 sc = sasl_setprop( ctx,
1310                         SASL_SEC_PROPS, &sasl_secprops );
1311
1312                 if( sc != SASL_OK ) {
1313                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1314                                 sc, 0, 0 );
1315
1316                         slap_sasl_close( conn );
1317                         return -1;
1318                 }
1319         }
1320
1321         sc = slap_sasl_err2ldap( sc );
1322
1323 #elif defined(SLAP_BUILTIN_SASL)
1324         /* built-in SASL implementation */
1325         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1326         if( ctx == NULL ) return -1;
1327
1328         ctx->sc_external_ssf = 0;
1329         BER_BVZERO( &ctx->sc_external_id );
1330
1331         conn->c_sasl_authctx = ctx;
1332 #endif
1333
1334         return sc;
1335 }
1336
1337 int slap_sasl_external(
1338         Connection *conn,
1339         slap_ssf_t ssf,
1340         struct berval *auth_id )
1341 {
1342 #ifdef HAVE_CYRUS_SASL
1343         int sc;
1344         sasl_conn_t *ctx = conn->c_sasl_authctx;
1345         sasl_ssf_t sasl_ssf = ssf;
1346
1347         if ( ctx == NULL ) {
1348                 return LDAP_UNAVAILABLE;
1349         }
1350
1351         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &sasl_ssf );
1352
1353         if ( sc != SASL_OK ) {
1354                 return LDAP_OTHER;
1355         }
1356
1357         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1358                 auth_id ? auth_id->bv_val : NULL );
1359
1360         if ( sc != SASL_OK ) {
1361                 return LDAP_OTHER;
1362         }
1363 #elif defined(SLAP_BUILTIN_SASL)
1364         /* built-in SASL implementation */
1365         SASL_CTX *ctx = conn->c_sasl_authctx;
1366         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1367
1368         ctx->sc_external_ssf = ssf;
1369         if( auth_id ) {
1370                 ctx->sc_external_id = *auth_id;
1371                 BER_BVZERO( auth_id );
1372         } else {
1373                 BER_BVZERO( &ctx->sc_external_id );
1374         }
1375 #endif
1376
1377         return LDAP_SUCCESS;
1378 }
1379
1380 int slap_sasl_reset( Connection *conn )
1381 {
1382         return LDAP_SUCCESS;
1383 }
1384
1385 char ** slap_sasl_mechs( Connection *conn )
1386 {
1387         char **mechs = NULL;
1388
1389 #ifdef HAVE_CYRUS_SASL
1390         sasl_conn_t *ctx = conn->c_sasl_authctx;
1391
1392         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1393
1394         if( ctx != NULL ) {
1395                 int sc;
1396                 SASL_CONST char *mechstr;
1397
1398                 sc = sasl_listmech( ctx,
1399                         NULL, NULL, ",", NULL,
1400                         &mechstr, NULL, NULL );
1401
1402                 if( sc != SASL_OK ) {
1403                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1404                                 sc, 0, 0 );
1405
1406                         return NULL;
1407                 }
1408
1409                 mechs = ldap_str2charray( mechstr, "," );
1410         }
1411 #elif defined(SLAP_BUILTIN_SASL)
1412         /* builtin SASL implementation */
1413         SASL_CTX *ctx = conn->c_sasl_authctx;
1414         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1415                 /* should check ssf */
1416                 mechs = ldap_str2charray( "EXTERNAL", "," );
1417         }
1418 #endif
1419
1420         return mechs;
1421 }
1422
1423 int slap_sasl_close( Connection *conn )
1424 {
1425 #ifdef HAVE_CYRUS_SASL
1426         sasl_conn_t *ctx = conn->c_sasl_authctx;
1427
1428         if( ctx != NULL ) {
1429                 sasl_dispose( &ctx );
1430         }
1431         if ( conn->c_sasl_sockctx &&
1432                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1433         {
1434                 ctx = conn->c_sasl_sockctx;
1435                 sasl_dispose( &ctx );
1436         }
1437
1438         conn->c_sasl_authctx = NULL;
1439         conn->c_sasl_sockctx = NULL;
1440         conn->c_sasl_done = 0;
1441
1442         free( conn->c_sasl_extra );
1443         conn->c_sasl_extra = NULL;
1444
1445 #elif defined(SLAP_BUILTIN_SASL)
1446         SASL_CTX *ctx = conn->c_sasl_authctx;
1447         if( ctx ) {
1448                 if( ctx->sc_external_id.bv_val ) {
1449                         free( ctx->sc_external_id.bv_val );
1450                         BER_BVZERO( &ctx->sc_external_id );
1451                 }
1452                 free( ctx );
1453                 conn->c_sasl_authctx = NULL;
1454         }
1455 #endif
1456
1457         return LDAP_SUCCESS;
1458 }
1459
1460 int slap_sasl_bind( Operation *op, SlapReply *rs )
1461 {
1462 #ifdef HAVE_CYRUS_SASL
1463         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1464         struct berval response;
1465         unsigned reslen = 0;
1466         int sc;
1467
1468         Debug(LDAP_DEBUG_ARGS,
1469                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1470                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1471                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1472                 op->o_conn->c_sasl_bind_mech.bv_val,
1473                 op->orb_cred.bv_len );
1474
1475         if( ctx == NULL ) {
1476                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1477                         "SASL unavailable on this session" );
1478                 return rs->sr_err;
1479         }
1480
1481 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1482         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1483 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1484         sasl_server_step( ctx, cred, clen, resp, rlen )
1485
1486         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1487                 /* If we already authenticated once, must use a new context */
1488                 if ( op->o_conn->c_sasl_done ) {
1489                         sasl_ssf_t ssf = 0;
1490                         const char *authid = NULL;
1491                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1492                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1493                         if ( authid ) authid = ch_strdup( authid );
1494                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1495                                 sasl_dispose( &ctx );
1496                         }
1497                         op->o_conn->c_sasl_authctx = NULL;
1498                                 
1499                         slap_sasl_open( op->o_conn, 1 );
1500                         ctx = op->o_conn->c_sasl_authctx;
1501                         if ( authid ) {
1502                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1503                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1504                                 ch_free( (char *)authid );
1505                         }
1506                 }
1507                 sc = START( ctx,
1508                         op->o_conn->c_sasl_bind_mech.bv_val,
1509                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1510                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1511
1512         } else {
1513                 sc = STEP( ctx,
1514                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1515                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1516         }
1517
1518         response.bv_len = reslen;
1519
1520         if ( sc == SASL_OK ) {
1521                 sasl_ssf_t *ssf = NULL;
1522
1523                 ber_dupbv_x( &op->orb_edn, &op->o_conn->c_sasl_dn, op->o_tmpmemctx );
1524                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1525                 op->o_conn->c_sasl_done = 1;
1526
1527                 rs->sr_err = LDAP_SUCCESS;
1528
1529                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1530                 op->orb_ssf = ssf ? *ssf : 0;
1531
1532                 ctx = NULL;
1533                 if( op->orb_ssf ) {
1534                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1535                         op->o_conn->c_sasl_layers++;
1536
1537                         /* If there's an old layer, set sockctx to NULL to
1538                          * tell connection_read() to wait for us to finish.
1539                          * Otherwise there is a race condition: we have to
1540                          * send the Bind response using the old security
1541                          * context and then remove it before reading any
1542                          * new messages.
1543                          */
1544                         if ( op->o_conn->c_sasl_sockctx ) {
1545                                 ctx = op->o_conn->c_sasl_sockctx;
1546                                 op->o_conn->c_sasl_sockctx = NULL;
1547                         } else {
1548                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1549                         }
1550                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1551                 }
1552
1553                 /* Must send response using old security layer */
1554                 rs->sr_sasldata = (response.bv_len ? &response : NULL);
1555                 send_ldap_sasl( op, rs );
1556                 
1557                 /* Now dispose of the old security layer.
1558                  */
1559                 if ( ctx ) {
1560                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1561                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1562                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1563                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1564                         sasl_dispose( &ctx );
1565                 }
1566         } else if ( sc == SASL_CONTINUE ) {
1567                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1568                 rs->sr_text = sasl_errdetail( ctx );
1569                 rs->sr_sasldata = &response;
1570                 send_ldap_sasl( op, rs );
1571
1572         } else {
1573                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1574                 rs->sr_text = sasl_errdetail( ctx );
1575                 rs->sr_err = slap_sasl_err2ldap( sc ),
1576                 send_ldap_result( op, rs );
1577         }
1578
1579         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1580
1581 #elif defined(SLAP_BUILTIN_SASL)
1582         /* built-in SASL implementation */
1583         SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1584
1585         if ( ctx == NULL ) {
1586                 send_ldap_error( op, rs, LDAP_OTHER,
1587                         "Internal SASL Error" );
1588
1589         } else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1590                 /* EXTERNAL */
1591
1592                 if( op->orb_cred.bv_len ) {
1593                         rs->sr_text = "proxy authorization not supported";
1594                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1595                         send_ldap_result( op, rs );
1596
1597                 } else {
1598                         op->orb_edn = ctx->sc_external_id;
1599                         rs->sr_err = LDAP_SUCCESS;
1600                         rs->sr_sasldata = NULL;
1601                         send_ldap_sasl( op, rs );
1602                 }
1603
1604         } else {
1605                 send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1606                         "requested SASL mechanism not supported" );
1607         }
1608 #else
1609         send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1610                 "SASL not supported" );
1611 #endif
1612
1613         return rs->sr_err;
1614 }
1615
1616 char* slap_sasl_secprops( const char *in )
1617 {
1618 #ifdef HAVE_CYRUS_SASL
1619         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1620
1621         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1622 #else
1623         return "SASL not supported";
1624 #endif
1625 }
1626
1627 void slap_sasl_secprops_unparse( struct berval *bv )
1628 {
1629 #ifdef HAVE_CYRUS_SASL
1630         ldap_pvt_sasl_secprops_unparse( &sasl_secprops, bv );
1631 #endif
1632 }
1633
1634 #ifdef HAVE_CYRUS_SASL
1635 int
1636 slap_sasl_setpass( Operation *op, SlapReply *rs )
1637 {
1638         struct berval id = BER_BVNULL;  /* needs to come from connection */
1639         struct berval new = BER_BVNULL;
1640         struct berval old = BER_BVNULL;
1641
1642         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1643
1644         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1645                 (SASL_CONST void **)(char *)&id.bv_val );
1646
1647         if( rs->sr_err != SASL_OK ) {
1648                 rs->sr_text = "unable to retrieve SASL username";
1649                 rs->sr_err = LDAP_OTHER;
1650                 goto done;
1651         }
1652
1653         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1654                 id.bv_val ? id.bv_val : "", 0, 0 );
1655
1656         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1657                 NULL, &old, &new, &rs->sr_text );
1658
1659         if( rs->sr_err != LDAP_SUCCESS ) {
1660                 goto done;
1661         }
1662
1663         if( new.bv_len == 0 ) {
1664                 slap_passwd_generate(&new);
1665
1666                 if( new.bv_len == 0 ) {
1667                         rs->sr_text = "password generation failed.";
1668                         rs->sr_err = LDAP_OTHER;
1669                         goto done;
1670                 }
1671                 
1672                 rs->sr_rspdata = slap_passwd_return( &new );
1673         }
1674
1675         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1676                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1677         if( rs->sr_err != SASL_OK ) {
1678                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1679         }
1680         switch(rs->sr_err) {
1681                 case SASL_OK:
1682                         rs->sr_err = LDAP_SUCCESS;
1683                         break;
1684
1685                 case SASL_NOCHANGE:
1686                 case SASL_NOMECH:
1687                 case SASL_DISABLED:
1688                 case SASL_PWLOCK:
1689                 case SASL_FAIL:
1690                 case SASL_BADPARAM:
1691                 default:
1692                         rs->sr_err = LDAP_OTHER;
1693         }
1694
1695 done:
1696         return rs->sr_err;
1697 }
1698 #endif /* HAVE_CYRUS_SASL */
1699
1700 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1701  * string returned in *dn is in its own allocated memory, and must be free'd 
1702  * by the calling process.  -Mark Adamson, Carnegie Mellon
1703  *
1704  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1705  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1706  */
1707
1708 #define SET_NONE        0
1709 #define SET_DN          1
1710 #define SET_U           2
1711
1712 int slap_sasl_getdn( Connection *conn, Operation *op, struct berval *id,
1713         char *user_realm, struct berval *dn, int flags )
1714 {
1715         int rc, is_dn = SET_NONE, do_norm = 1;
1716         struct berval dn2, *mech;
1717
1718         assert( conn != NULL );
1719         assert( id != NULL );
1720
1721         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: conn %lu id=%s [len=%lu]\n", 
1722                 conn->c_connid,
1723                 BER_BVISNULL( id ) ? "NULL" : ( BER_BVISEMPTY( id ) ? "<empty>" : id->bv_val ),
1724                 BER_BVISNULL( id ) ? 0 : ( BER_BVISEMPTY( id ) ? 0 :
1725                                            (unsigned long) id->bv_len ) );
1726
1727         if ( !op ) {
1728                 op = conn->c_sasl_bindop;
1729         }
1730         assert( op != NULL );
1731
1732         BER_BVZERO( dn );
1733
1734         if ( !BER_BVISNULL( id ) ) {
1735                 /* Blatantly anonymous ID */
1736                 static struct berval bv_anonymous = BER_BVC( "anonymous" );
1737
1738                 if ( ber_bvstrcasecmp( id, &bv_anonymous ) == 0 ) {
1739                         return( LDAP_SUCCESS );
1740                 }
1741
1742         } else {
1743                 /* FIXME: if empty, should we stop? */
1744                 BER_BVSTR( id, "" );
1745         }
1746
1747         if ( !BER_BVISEMPTY( &conn->c_sasl_bind_mech ) ) {
1748                 mech = &conn->c_sasl_bind_mech;
1749         } else {
1750                 mech = &conn->c_authmech;
1751         }
1752
1753         /* An authcID needs to be converted to authzID form. Set the
1754          * values directly into *dn; they will be normalized later. (and
1755          * normalizing always makes a new copy.) An ID from a TLS certificate
1756          * is already normalized, so copy it and skip normalization.
1757          */
1758         if( flags & SLAP_GETDN_AUTHCID ) {
1759                 if( bvmatch( mech, &ext_bv )) {
1760                         /* EXTERNAL DNs are already normalized */
1761                         assert( !BER_BVISNULL( id ) );
1762
1763                         do_norm = 0;
1764                         is_dn = SET_DN;
1765                         ber_dupbv_x( dn, id, op->o_tmpmemctx );
1766
1767                 } else {
1768                         /* convert to u:<username> form */
1769                         is_dn = SET_U;
1770                         *dn = *id;
1771                 }
1772         }
1773
1774         if( is_dn == SET_NONE ) {
1775                 if( !strncasecmp( id->bv_val, "u:", STRLENOF( "u:" ) ) ) {
1776                         is_dn = SET_U;
1777                         dn->bv_val = id->bv_val + STRLENOF( "u:" );
1778                         dn->bv_len = id->bv_len - STRLENOF( "u:" );
1779
1780                 } else if ( !strncasecmp( id->bv_val, "dn:", STRLENOF( "dn:" ) ) ) {
1781                         is_dn = SET_DN;
1782                         dn->bv_val = id->bv_val + STRLENOF( "dn:" );
1783                         dn->bv_len = id->bv_len - STRLENOF( "dn:" );
1784                 }
1785         }
1786
1787         /* No other possibilities from here */
1788         if( is_dn == SET_NONE ) {
1789                 BER_BVZERO( dn );
1790                 return( LDAP_INAPPROPRIATE_AUTH );
1791         }
1792
1793         /* Username strings */
1794         if( is_dn == SET_U ) {
1795                 /* ITS#3419: values may need escape */
1796                 LDAPRDN         DN[ 5 ];
1797                 LDAPAVA         *RDNs[ 4 ][ 2 ];
1798                 LDAPAVA         AVAs[ 4 ];
1799                 int             irdn;
1800
1801                 irdn = 0;
1802                 DN[ irdn ] = RDNs[ irdn ];
1803                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1804                 AVAs[ irdn ].la_attr = slap_schema.si_ad_uid->ad_cname;
1805                 AVAs[ irdn ].la_value = *dn;
1806                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1807                 AVAs[ irdn ].la_private = NULL;
1808                 RDNs[ irdn ][ 1 ] = NULL;
1809
1810                 if ( user_realm && *user_realm ) {
1811                         irdn++;
1812                         DN[ irdn ] = RDNs[ irdn ];
1813                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1814                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1815                         ber_str2bv( user_realm, 0, 0, &AVAs[ irdn ].la_value );
1816                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1817                         AVAs[ irdn ].la_private = NULL;
1818                         RDNs[ irdn ][ 1 ] = NULL;
1819                 }
1820
1821                 if ( !BER_BVISNULL( mech ) ) {
1822                         irdn++;
1823                         DN[ irdn ] = RDNs[ irdn ];
1824                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1825                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1826                         AVAs[ irdn ].la_value = *mech;
1827                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1828                         AVAs[ irdn ].la_private = NULL;
1829                         RDNs[ irdn ][ 1 ] = NULL;
1830                 }
1831
1832                 irdn++;
1833                 DN[ irdn ] = RDNs[ irdn ];
1834                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1835                 AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1836                 BER_BVSTR( &AVAs[ irdn ].la_value, "auth" );
1837                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1838                 AVAs[ irdn ].la_private = NULL;
1839                 RDNs[ irdn ][ 1 ] = NULL;
1840
1841                 irdn++;
1842                 DN[ irdn ] = NULL;
1843
1844                 rc = ldap_dn2bv_x( DN, dn, LDAP_DN_FORMAT_LDAPV3,
1845                                 op->o_tmpmemctx );
1846                 if ( rc != LDAP_SUCCESS ) {
1847                         BER_BVZERO( dn );
1848                         return rc;
1849                 }
1850
1851                 Debug( LDAP_DEBUG_TRACE,
1852                         "slap_sasl_getdn: u:id converted to %s\n",
1853                         dn->bv_val, 0, 0 );
1854
1855         } else {
1856                 
1857                 /* Dup the DN in any case, so we don't risk 
1858                  * leaks or dangling pointers later,
1859                  * and the DN value is '\0' terminated */
1860                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1861                 dn->bv_val = dn2.bv_val;
1862         }
1863
1864         /* All strings are in DN form now. Normalize if needed. */
1865         if ( do_norm ) {
1866                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1867
1868                 /* User DNs were constructed above and must be freed now */
1869                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1870
1871                 if ( rc != LDAP_SUCCESS ) {
1872                         BER_BVZERO( dn );
1873                         return rc;
1874                 }
1875                 *dn = dn2;
1876         }
1877
1878         /* Run thru regexp */
1879         slap_sasl2dn( op, dn, &dn2, flags );
1880         if( !BER_BVISNULL( &dn2 ) ) {
1881                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1882                 *dn = dn2;
1883                 Debug( LDAP_DEBUG_TRACE,
1884                         "slap_sasl_getdn: dn:id converted to %s\n",
1885                         dn->bv_val, 0, 0 );
1886         }
1887
1888         return( LDAP_SUCCESS );
1889 }