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