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