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