]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
s/bvalues/values
[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                 mod->sml_values[j].bv_val = NULL;
559                 mod->sml_values[j].bv_len = 0;
560                 mod->sml_nvalues = NULL;
561                 mod->sml_desc = NULL;
562                 *modtail = mod;
563                 modtail = &mod->sml_next;
564         }
565         *modtail = NULL;
566
567         rc = slap_mods_check( modlist, 0, &text, textbuf, textlen, NULL );
568
569         if ( rc == LDAP_SUCCESS ) {
570                 rc = slap_mods_opattrs( &op, modlist, modtail, &text, textbuf,
571                         textlen );
572         }
573
574         if ( rc == LDAP_SUCCESS ) {
575                 op.o_tag = LDAP_REQ_MODIFY;
576                 op.o_protocol = LDAP_VERSION3;
577                 op.o_ndn = op.o_req_ndn;
578                 op.o_callback = &cb;
579                 op.o_time = slap_get_time();
580                 op.o_do_not_cache = 1;
581                 op.o_is_auth_check = 1;
582                 op.o_threadctx = conn->c_sasl_bindop->o_threadctx;
583                 op.o_tmpmemctx = conn->c_sasl_bindop->o_tmpmemctx;
584                 op.o_tmpmfuncs = conn->c_sasl_bindop->o_tmpmfuncs;
585                 op.o_conn = conn;
586                 op.o_connid = conn->c_connid;
587                 op.o_req_dn = op.o_req_ndn;
588                 op.orm_modlist = modlist;
589
590                 rc = op.o_bd->be_modify( &op, &rs );
591         }
592         slap_mods_free( modlist );
593         return rc ? SASL_FAIL : SASL_OK;
594 }
595 #endif /* SASL_VERSION_FULL >= 2.1.16 */
596
597 static sasl_auxprop_plug_t slap_auxprop_plugin = {
598         0,      /* Features */
599         0,      /* spare */
600         NULL,   /* glob_context */
601         NULL,   /* auxprop_free */
602         slap_auxprop_lookup,
603         "slapd",        /* name */
604 #if SASL_VERSION_FULL >= 0x020110
605         slap_auxprop_store      /* the declaration of this member changed
606                                  * in cyrus SASL from 2.1.15 to 2.1.16 */
607 #else
608         NULL
609 #endif
610 };
611
612 static int
613 slap_auxprop_init(
614         const sasl_utils_t *utils,
615         int max_version,
616         int *out_version,
617         sasl_auxprop_plug_t **plug,
618         const char *plugname)
619 {
620         if ( !out_version || !plug ) return SASL_BADPARAM;
621
622         if ( max_version < SASL_AUXPROP_PLUG_VERSION ) return SASL_BADVERS;
623
624         *out_version = SASL_AUXPROP_PLUG_VERSION;
625         *plug = &slap_auxprop_plugin;
626         return SASL_OK;
627 }
628
629 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
630  * auxiliary property, so that we can refer to it in sasl_authorize
631  * without interfering with anything else. Also, the SASL username
632  * buffer is constrained to 256 characters, and our DNs could be
633  * much longer (SLAP_LDAPDN_MAXLEN, currently set to 8192)
634  */
635 static int
636 slap_sasl_canonicalize(
637         sasl_conn_t *sconn,
638         void *context,
639         const char *in,
640         unsigned inlen,
641         unsigned flags,
642         const char *user_realm,
643         char *out,
644         unsigned out_max,
645         unsigned *out_len)
646 {
647         Connection *conn = (Connection *)context;
648         struct propctx *props = sasl_auxprop_getctx( sconn );
649         struct propval auxvals[3];
650         struct berval dn;
651         int rc, which;
652         const char *names[2];
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         rc = slap_sasl_getdn( conn, NULL, (char *)in, inlen, (char *)user_realm, &dn,
729                 (flags & SASL_CU_AUTHID) ? SLAP_GETDN_AUTHCID : SLAP_GETDN_AUTHZID );
730         if ( rc != LDAP_SUCCESS ) {
731                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
732                 return SASL_NOAUTHZ;
733         }               
734
735         names[0] = slap_propnames[which];
736         names[1] = NULL;
737
738         prop_set( props, names[0], (char *)&dn, sizeof( dn ) );
739                 
740 #ifdef NEW_LOGGING
741         LDAP_LOG( TRANSPORT, ENTRY, 
742                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
743                 conn ? conn->c_connid : -1, names[0]+1,
744                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
745 #else
746         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
747                 conn ? conn->c_connid : -1, names[0]+1,
748                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
749 #endif
750
751 done:
752         AC_MEMCPY( out, in, inlen );
753         out[inlen] = '\0';
754
755         *out_len = inlen;
756
757         return SASL_OK;
758 }
759
760 static int
761 slap_sasl_authorize(
762         sasl_conn_t *sconn,
763         void *context,
764         char *requested_user,
765         unsigned rlen,
766         char *auth_identity,
767         unsigned alen,
768         const char *def_realm,
769         unsigned urlen,
770         struct propctx *props)
771 {
772         Connection *conn = (Connection *)context;
773         struct propval auxvals[3];
774         struct berval authcDN, authzDN;
775         int rc;
776
777         /* Simple Binds don't support proxy authorization, ignore it */
778         if ( !conn->c_sasl_bindop ||
779                 conn->c_sasl_bindop->orb_method != LDAP_AUTH_SASL ) return SASL_OK;
780
781 #ifdef NEW_LOGGING
782         LDAP_LOG( TRANSPORT, ENTRY, 
783                 "slap_sasl_authorize: conn %d authcid=\"%s\" authzid=\"%s\"\n",
784                 conn ? conn->c_connid : -1, auth_identity, requested_user);
785 #else
786         Debug( LDAP_DEBUG_ARGS, "SASL proxy authorize [conn=%ld]: "
787                 "authcid=\"%s\" authzid=\"%s\"\n",
788                 conn ? conn->c_connid : -1, auth_identity, requested_user );
789 #endif
790         if ( conn->c_sasl_dn.bv_val ) {
791                 ch_free( conn->c_sasl_dn.bv_val );
792                 conn->c_sasl_dn.bv_val = NULL;
793                 conn->c_sasl_dn.bv_len = 0;
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
868         *user = NULL;
869         if ( conn->c_sasl_dn.bv_val ) {
870                 ch_free( conn->c_sasl_dn.bv_val );
871                 conn->c_sasl_dn.bv_val = NULL;
872                 conn->c_sasl_dn.bv_len = 0;
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         rc = slap_sasl_getdn( conn, NULL, (char *)authcid, 0, realm,
905                 &authcDN, SLAP_GETDN_AUTHCID );
906         if( rc != LDAP_SUCCESS ) {
907                 *errstr = ldap_err2string( rc );
908                 return SASL_NOAUTHZ;
909         }
910         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
911 #ifdef NEW_LOGGING
912                 LDAP_LOG( TRANSPORT, ENTRY, 
913                         "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
914                         conn ? conn->c_connid : -1, authcDN.bv_val, 0 );
915 #else
916                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
917                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
918 #endif
919
920                 conn->c_sasl_dn = authcDN;
921                 goto ok;
922         }
923         rc = slap_sasl_getdn( conn, NULL, (char *)authzid, 0, realm,
924                 &authzDN, SLAP_GETDN_AUTHZID );
925         if( rc != LDAP_SUCCESS ) {
926                 ch_free( authcDN.bv_val );
927                 *errstr = ldap_err2string( rc );
928                 return SASL_NOAUTHZ;
929         }
930
931         rc = slap_sasl_authorized(conn->c_sasl_bindop, &authcDN, &authzDN );
932         ch_free( authcDN.bv_val );
933         if( rc ) {
934 #ifdef NEW_LOGGING
935                 LDAP_LOG( TRANSPORT, INFO, 
936                         "slap_sasl_authorize: conn %ld "
937                         "proxy authorization disallowed (%d)\n",
938                         (long)(conn ? conn->c_connid : -1), rc, 0 );
939 #else
940                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
941                         "proxy authorization disallowed (%d)\n",
942                         (long) (conn ? conn->c_connid : -1), rc, 0 );
943 #endif
944
945                 *errstr = "not authorized";
946                 ch_free( authzDN.bv_val );
947                 return SASL_NOAUTHZ;
948         }
949         conn->c_sasl_dn = authzDN;
950
951 ok:
952 #ifdef NEW_LOGGING
953         LDAP_LOG( TRANSPORT, RESULTS, 
954                 "slap_sasl_authorize: conn %d proxy authorization allowed\n",
955            (long)(conn ? conn->c_connid : -1 ), 0, 0 );
956 #else
957         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
958                 " authorization allowed\n",
959                 (long) (conn ? conn->c_connid : -1), 0, 0 );
960 #endif
961
962         if (conn->c_sasl_bindop) {
963                 Statslog( LDAP_DEBUG_STATS,
964                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
965                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
966                         authcid, 0, 0);
967         }
968
969         *errstr = NULL;
970         return SASL_OK;
971 }
972 #endif /* SASL_VERSION_MAJOR >= 2 */
973
974 static int
975 slap_sasl_err2ldap( int saslerr )
976 {
977         int rc;
978
979         switch (saslerr) {
980                 case SASL_OK:
981                         rc = LDAP_SUCCESS;
982                         break;
983                 case SASL_CONTINUE:
984                         rc = LDAP_SASL_BIND_IN_PROGRESS;
985                         break;
986                 case SASL_FAIL:
987                         rc = LDAP_OTHER;
988                         break;
989                 case SASL_NOMEM:
990                         rc = LDAP_OTHER;
991                         break;
992                 case SASL_NOMECH:
993                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
994                         break;
995                 case SASL_BADAUTH:
996                         rc = LDAP_INVALID_CREDENTIALS;
997                         break;
998                 case SASL_NOAUTHZ:
999                         rc = LDAP_INSUFFICIENT_ACCESS;
1000                         break;
1001                 case SASL_TOOWEAK:
1002                 case SASL_ENCRYPT:
1003                         rc = LDAP_INAPPROPRIATE_AUTH;
1004                         break;
1005                 default:
1006                         rc = LDAP_OTHER;
1007                         break;
1008         }
1009
1010         return rc;
1011 }
1012 #endif
1013
1014 int slap_sasl_init( void )
1015 {
1016 #ifdef HAVE_CYRUS_SASL
1017         int rc;
1018         static sasl_callback_t server_callbacks[] = {
1019                 { SASL_CB_LOG, &slap_sasl_log, NULL },
1020                 { SASL_CB_LIST_END, NULL, NULL }
1021         };
1022
1023 #ifdef HAVE_SASL_VERSION
1024         /* stringify the version number, sasl.h doesn't do it for us */
1025 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
1026 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
1027 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
1028                                 SASL_VERSION_STEP)
1029
1030         sasl_version( NULL, &rc );
1031         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1032                 (rc & 0xffff) < SASL_VERSION_STEP)
1033         {
1034                 char version[sizeof("xxx.xxx.xxxxx")];
1035                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
1036                         rc & 0xffff );
1037 #ifdef NEW_LOGGING
1038                 LDAP_LOG( TRANSPORT, INFO,
1039                 "slap_sasl_init: SASL library version mismatch:"
1040                 " expected " SASL_VERSION_STRING ","
1041                 " got %s\n", version, 0, 0 );
1042 #else
1043                 Debug( LDAP_DEBUG_ANY,
1044                 "slap_sasl_init: SASL library version mismatch:"
1045                 " expected " SASL_VERSION_STRING ","
1046                 " got %s\n", version, 0, 0 );
1047 #endif
1048                 return -1;
1049         }
1050 #endif
1051
1052         /* SASL 2 does its own memory management internally */
1053 #if SASL_VERSION_MAJOR < 2
1054         sasl_set_alloc(
1055                 ber_memalloc,
1056                 ber_memcalloc,
1057                 ber_memrealloc,
1058                 ber_memfree ); 
1059 #endif
1060
1061         sasl_set_mutex(
1062                 ldap_pvt_sasl_mutex_new,
1063                 ldap_pvt_sasl_mutex_lock,
1064                 ldap_pvt_sasl_mutex_unlock,
1065                 ldap_pvt_sasl_mutex_dispose );
1066
1067 #if SASL_VERSION_MAJOR >= 2
1068         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1069
1070         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1071 #endif
1072         /* should provide callbacks for logging */
1073         /* server name should be configurable */
1074         rc = sasl_server_init( server_callbacks, "slapd" );
1075
1076         if( rc != SASL_OK ) {
1077 #ifdef NEW_LOGGING
1078                 LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: init failed.\n", 0, 0, 0 );
1079 #else
1080                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
1081                         0, 0, 0 );
1082 #endif
1083 #if SASL_VERSION_MAJOR < 2
1084                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1085                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1086 #endif
1087
1088                 return -1;
1089         }
1090
1091 #ifdef NEW_LOGGING
1092         LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: initialized!\n", 0, 0, 0 );
1093 #else
1094         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1095                 0, 0, 0 );
1096 #endif
1097
1098         /* default security properties */
1099         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1100         sasl_secprops.max_ssf = INT_MAX;
1101         sasl_secprops.maxbufsize = 65536;
1102         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1103 #endif
1104
1105         return 0;
1106 }
1107
1108 int slap_sasl_destroy( void )
1109 {
1110 #ifdef HAVE_CYRUS_SASL
1111         sasl_done();
1112 #endif
1113         free( global_host );
1114         global_host = NULL;
1115
1116         return 0;
1117 }
1118
1119 int slap_sasl_open( Connection *conn, int reopen )
1120 {
1121         int sc = LDAP_SUCCESS;
1122 #ifdef HAVE_CYRUS_SASL
1123         int cb;
1124
1125         sasl_conn_t *ctx = NULL;
1126         sasl_callback_t *session_callbacks;
1127
1128 #if SASL_VERSION_MAJOR >= 2
1129         char *ipremoteport = NULL, *iplocalport = NULL;
1130 #endif
1131
1132         assert( conn->c_sasl_authctx == NULL );
1133
1134         if ( !reopen ) {
1135                 assert( conn->c_sasl_extra == NULL );
1136
1137                 session_callbacks =
1138 #if SASL_VERSION_MAJOR >= 2
1139                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1140 #else
1141                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1142 #endif
1143                 if( session_callbacks == NULL ) {
1144 #ifdef NEW_LOGGING
1145                         LDAP_LOG( TRANSPORT, ERR, 
1146                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1147 #else
1148                         Debug( LDAP_DEBUG_ANY, 
1149                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1150 #endif
1151                         return -1;
1152                 }
1153                 conn->c_sasl_extra = session_callbacks;
1154
1155                 session_callbacks[cb=0].id = SASL_CB_LOG;
1156                 session_callbacks[cb].proc = &slap_sasl_log;
1157                 session_callbacks[cb++].context = conn;
1158
1159                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1160                 session_callbacks[cb].proc = &slap_sasl_authorize;
1161                 session_callbacks[cb++].context = conn;
1162
1163 #if SASL_VERSION_MAJOR >= 2
1164                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1165                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1166                 session_callbacks[cb++].context = conn;
1167 #endif
1168
1169                 session_callbacks[cb].id = SASL_CB_LIST_END;
1170                 session_callbacks[cb].proc = NULL;
1171                 session_callbacks[cb++].context = NULL;
1172         } else {
1173                 session_callbacks = conn->c_sasl_extra;
1174         }
1175
1176         conn->c_sasl_layers = 0;
1177
1178         if( global_host == NULL ) {
1179                 global_host = ldap_pvt_get_fqdn( NULL );
1180         }
1181
1182         /* create new SASL context */
1183 #if SASL_VERSION_MAJOR >= 2
1184         if ( conn->c_sock_name.bv_len != 0 &&
1185              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1186                 char *p;
1187
1188                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1189                 /* Convert IPv6 addresses to address;port syntax. */
1190                 p = strrchr( iplocalport, ' ' );
1191                 /* Convert IPv4 addresses to address;port syntax. */
1192                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1193                 if ( p != NULL ) {
1194                         *p = ';';
1195                 }
1196         }
1197         if ( conn->c_peer_name.bv_len != 0 &&
1198              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1199                 char *p;
1200
1201                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1202                 /* Convert IPv6 addresses to address;port syntax. */
1203                 p = strrchr( ipremoteport, ' ' );
1204                 /* Convert IPv4 addresses to address;port syntax. */
1205                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1206                 if ( p != NULL ) {
1207                         *p = ';';
1208                 }
1209         }
1210         sc = sasl_server_new( "ldap", global_host, global_realm,
1211                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1212         if ( iplocalport != NULL ) {
1213                 ch_free( iplocalport );
1214         }
1215         if ( ipremoteport != NULL ) {
1216                 ch_free( ipremoteport );
1217         }
1218 #else
1219         sc = sasl_server_new( "ldap", global_host, global_realm,
1220                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1221 #endif
1222
1223         if( sc != SASL_OK ) {
1224 #ifdef NEW_LOGGING
1225                 LDAP_LOG( TRANSPORT, ERR, 
1226                         "slap_sasl_open: sasl_server_new failed: %d\n", sc, 0, 0 );
1227 #else
1228                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1229                         sc, 0, 0 );
1230 #endif
1231
1232                 return -1;
1233         }
1234
1235         conn->c_sasl_authctx = ctx;
1236
1237         if( sc == SASL_OK ) {
1238                 sc = sasl_setprop( ctx,
1239                         SASL_SEC_PROPS, &sasl_secprops );
1240
1241                 if( sc != SASL_OK ) {
1242 #ifdef NEW_LOGGING
1243                         LDAP_LOG( TRANSPORT, ERR, 
1244                                 "slap_sasl_open: sasl_setprop failed: %d \n", sc, 0, 0 );
1245 #else
1246                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1247                                 sc, 0, 0 );
1248 #endif
1249
1250                         slap_sasl_close( conn );
1251                         return -1;
1252                 }
1253         }
1254
1255         sc = slap_sasl_err2ldap( sc );
1256
1257 #elif defined(SLAP_BUILTIN_SASL)
1258         /* built-in SASL implementation */
1259         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1260         if( ctx == NULL ) return -1;
1261
1262         ctx->sc_external_ssf = 0;
1263         ctx->sc_external_id.bv_len = 0;
1264         ctx->sc_external_id.bv_val = NULL;
1265
1266         conn->c_sasl_authctx = ctx;
1267 #endif
1268
1269         return sc;
1270 }
1271
1272 int slap_sasl_external(
1273         Connection *conn,
1274         slap_ssf_t ssf,
1275         struct berval *auth_id )
1276 {
1277 #if SASL_VERSION_MAJOR >= 2
1278         int sc;
1279         sasl_conn_t *ctx = conn->c_sasl_authctx;
1280
1281         if ( ctx == NULL ) {
1282                 return LDAP_UNAVAILABLE;
1283         }
1284
1285         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1286
1287         if ( sc != SASL_OK ) {
1288                 return LDAP_OTHER;
1289         }
1290
1291         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1292                 auth_id ? auth_id->bv_val : NULL );
1293
1294         if ( sc != SASL_OK ) {
1295                 return LDAP_OTHER;
1296         }
1297
1298 #elif defined(HAVE_CYRUS_SASL)
1299         int sc;
1300         sasl_conn_t *ctx = conn->c_sasl_authctx;
1301         sasl_external_properties_t extprops;
1302
1303         if ( ctx == NULL ) {
1304                 return LDAP_UNAVAILABLE;
1305         }
1306
1307         memset( &extprops, '\0', sizeof(extprops) );
1308         extprops.ssf = ssf;
1309         extprops.auth_id = auth_id ? auth_id->bv_val : NULL;
1310
1311         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1312                 (void *) &extprops );
1313
1314         if ( sc != SASL_OK ) {
1315                 return LDAP_OTHER;
1316         }
1317 #elif defined(SLAP_BUILTIN_SASL)
1318         /* built-in SASL implementation */
1319         SASL_CTX *ctx = conn->c_sasl_authctx;
1320         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1321
1322         ctx->sc_external_ssf = ssf;
1323         if( auth_id ) {
1324                 ctx->sc_external_id = *auth_id;
1325                 auth_id->bv_len = 0;
1326                 auth_id->bv_val = NULL;
1327         } else {
1328                 ctx->sc_external_id.bv_len = 0;
1329                 ctx->sc_external_id.bv_val = NULL;
1330         }
1331 #endif
1332
1333         return LDAP_SUCCESS;
1334 }
1335
1336 int slap_sasl_reset( Connection *conn )
1337 {
1338         return LDAP_SUCCESS;
1339 }
1340
1341 char ** slap_sasl_mechs( Connection *conn )
1342 {
1343         char **mechs = NULL;
1344
1345 #ifdef HAVE_CYRUS_SASL
1346         sasl_conn_t *ctx = conn->c_sasl_authctx;
1347
1348         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1349
1350         if( ctx != NULL ) {
1351                 int sc;
1352                 SASL_CONST char *mechstr;
1353
1354                 sc = sasl_listmech( ctx,
1355                         NULL, NULL, ",", NULL,
1356                         &mechstr, NULL, NULL );
1357
1358                 if( sc != SASL_OK ) {
1359 #ifdef NEW_LOGGING
1360                         LDAP_LOG( TRANSPORT, ERR, 
1361                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc, 0, 0 );
1362 #else
1363                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1364                                 sc, 0, 0 );
1365 #endif
1366
1367                         return NULL;
1368                 }
1369
1370                 mechs = ldap_str2charray( mechstr, "," );
1371
1372 #if SASL_VERSION_MAJOR < 2
1373                 ch_free( mechstr );
1374 #endif
1375         }
1376 #elif defined(SLAP_BUILTIN_SASL)
1377         /* builtin SASL implementation */
1378         SASL_CTX *ctx = conn->c_sasl_authctx;
1379         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1380                 /* should check ssf */
1381                 mechs = ldap_str2charray( "EXTERNAL", "," );
1382         }
1383 #endif
1384
1385         return mechs;
1386 }
1387
1388 int slap_sasl_close( Connection *conn )
1389 {
1390 #ifdef HAVE_CYRUS_SASL
1391         sasl_conn_t *ctx = conn->c_sasl_authctx;
1392
1393         if( ctx != NULL ) {
1394                 sasl_dispose( &ctx );
1395         }
1396         if ( conn->c_sasl_sockctx &&
1397                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1398         {
1399                 ctx = conn->c_sasl_sockctx;
1400                 sasl_dispose( &ctx );
1401         }
1402
1403         conn->c_sasl_authctx = NULL;
1404         conn->c_sasl_sockctx = NULL;
1405         conn->c_sasl_done = 0;
1406
1407         free( conn->c_sasl_extra );
1408         conn->c_sasl_extra = NULL;
1409
1410 #elif defined(SLAP_BUILTIN_SASL)
1411         SASL_CTX *ctx = conn->c_sasl_authctx;
1412         if( ctx ) {
1413                 if( ctx->sc_external_id.bv_val ) {
1414                         free( ctx->sc_external_id.bv_val );
1415                         ctx->sc_external_id.bv_val = NULL;
1416                 }
1417                 free( ctx );
1418                 conn->c_sasl_authctx = NULL;
1419         }
1420 #endif
1421
1422         return LDAP_SUCCESS;
1423 }
1424
1425 int slap_sasl_bind( Operation *op, SlapReply *rs )
1426 {
1427 #ifdef HAVE_CYRUS_SASL
1428         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1429         struct berval response;
1430         unsigned reslen = 0;
1431         int sc;
1432
1433 #ifdef NEW_LOGGING
1434         LDAP_LOG( TRANSPORT, ENTRY, 
1435                 "sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1436                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1437                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1438                 op->o_conn->c_sasl_bind_mech.bv_val,
1439                 op->orb_cred.bv_len );
1440 #else
1441         Debug(LDAP_DEBUG_ARGS,
1442                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1443                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1444                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1445                 op->o_conn->c_sasl_bind_mech.bv_val,
1446                 op->orb_cred.bv_len );
1447 #endif
1448
1449         if( ctx == NULL ) {
1450                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1451                         "SASL unavailable on this session" );
1452                 return rs->sr_err;
1453         }
1454
1455 #if SASL_VERSION_MAJOR >= 2
1456 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1457         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1458 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1459         sasl_server_step( ctx, cred, clen, resp, rlen )
1460 #else
1461 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1462         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1463 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1464         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1465 #endif
1466
1467         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1468                 /* If we already authenticated once, must use a new context */
1469                 if ( op->o_conn->c_sasl_done ) {
1470                         slap_ssf_t ssf = 0;
1471                         const char *authid = NULL;
1472 #if SASL_VERSION_MAJOR >= 2
1473                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1474                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1475                         if ( authid ) authid = ch_strdup( authid );
1476 #endif
1477                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1478                                 sasl_dispose( &ctx );
1479                         }
1480                         op->o_conn->c_sasl_authctx = NULL;
1481                                 
1482                         slap_sasl_open( op->o_conn, 1 );
1483                         ctx = op->o_conn->c_sasl_authctx;
1484 #if SASL_VERSION_MAJOR >= 2
1485                         if ( authid ) {
1486                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1487                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1488                                 ch_free( (char *)authid );
1489                         }
1490 #endif
1491                 }
1492                 sc = START( ctx,
1493                         op->o_conn->c_sasl_bind_mech.bv_val,
1494                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1495                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1496
1497         } else {
1498                 sc = STEP( ctx,
1499                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1500                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1501         }
1502
1503         response.bv_len = reslen;
1504
1505         if ( sc == SASL_OK ) {
1506                 sasl_ssf_t *ssf = NULL;
1507
1508                 op->orb_edn = op->o_conn->c_sasl_dn;
1509                 op->o_conn->c_sasl_dn.bv_val = NULL;
1510                 op->o_conn->c_sasl_dn.bv_len = 0;
1511                 op->o_conn->c_sasl_done = 1;
1512
1513                 rs->sr_err = LDAP_SUCCESS;
1514
1515                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1516                 op->orb_ssf = ssf ? *ssf : 0;
1517
1518                 ctx = NULL;
1519                 if( op->orb_ssf ) {
1520                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1521                         op->o_conn->c_sasl_layers++;
1522
1523                         /* If there's an old layer, set sockctx to NULL to
1524                          * tell connection_read() to wait for us to finish.
1525                          * Otherwise there is a race condition: we have to
1526                          * send the Bind response using the old security
1527                          * context and then remove it before reading any
1528                          * new messages.
1529                          */
1530                         if ( op->o_conn->c_sasl_sockctx ) {
1531                                 ctx = op->o_conn->c_sasl_sockctx;
1532                                 op->o_conn->c_sasl_sockctx = NULL;
1533                         } else {
1534                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1535                         }
1536                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1537                 }
1538
1539                 /* Must send response using old security layer */
1540                 if (response.bv_len) rs->sr_sasldata = &response;
1541                 send_ldap_sasl( op, rs );
1542                 
1543                 /* Now dispose of the old security layer.
1544                  */
1545                 if ( ctx ) {
1546                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1547                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1548                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1549                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1550                         sasl_dispose( &ctx );
1551                 }
1552         } else if ( sc == SASL_CONTINUE ) {
1553                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1554                 rs->sr_sasldata = &response;
1555                 send_ldap_sasl( op, rs );
1556
1557         } else {
1558 #if SASL_VERSION_MAJOR >= 2
1559                 rs->sr_text = sasl_errdetail( ctx );
1560 #endif
1561                 rs->sr_err = slap_sasl_err2ldap( sc ),
1562                 send_ldap_result( op, rs );
1563         }
1564
1565 #if SASL_VERSION_MAJOR < 2
1566         if( response.bv_len ) {
1567                 ch_free( response.bv_val );
1568         }
1569 #endif
1570
1571 #ifdef NEW_LOGGING
1572         LDAP_LOG( TRANSPORT, RESULTS, "slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0 );
1573 #else
1574         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1575 #endif
1576
1577 #elif defined(SLAP_BUILTIN_SASL)
1578         /* built-in SASL implementation */
1579         SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1580
1581         if ( ctx == NULL ) {
1582                 send_ldap_error( op, rs, LDAP_OTHER,
1583                         "Internal SASL Error" );
1584
1585         } else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1586                 /* EXTERNAL */
1587
1588                 if( op->orb_cred.bv_len ) {
1589                         rs->sr_text = "proxy authorization not support";
1590                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1591                         send_ldap_result( op, rs );
1592
1593                 } else {
1594                         op->orb_edn = ctx->sc_external_id;
1595                         rs->sr_err = LDAP_SUCCESS;
1596                         rs->sr_sasldata = NULL;
1597                         send_ldap_sasl( op, rs );
1598                 }
1599
1600         } else {
1601                 send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1602                         "requested SASL mechanism not supported" );
1603         }
1604 #else
1605         send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1606                 "SASL not supported" );
1607 #endif
1608
1609         return rs->sr_err;
1610 }
1611
1612 char* slap_sasl_secprops( const char *in )
1613 {
1614 #ifdef HAVE_CYRUS_SASL
1615         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1616
1617         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1618 #else
1619         return "SASL not supported";
1620 #endif
1621 }
1622
1623 #ifdef HAVE_CYRUS_SASL
1624 int
1625 slap_sasl_setpass( Operation *op, SlapReply *rs )
1626 {
1627         struct berval id = BER_BVNULL;  /* needs to come from connection */
1628         struct berval new = BER_BVNULL;
1629         struct berval old = BER_BVNULL;
1630
1631         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1632
1633         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1634                 (SASL_CONST void **)&id.bv_val );
1635
1636         if( rs->sr_err != SASL_OK ) {
1637                 rs->sr_text = "unable to retrieve SASL username";
1638                 rs->sr_err = LDAP_OTHER;
1639                 goto done;
1640         }
1641
1642 #ifdef NEW_LOGGING
1643         LDAP_LOG( BACKEND, ENTRY,
1644                 "slap_sasl_setpass: \"%s\"\n",
1645                 id.bv_val ? id.bv_val : "", 0, 0);
1646 #else
1647         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1648                 id.bv_val ? id.bv_val : "", 0, 0 );
1649 #endif
1650
1651         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1652                 NULL, &old, &new, &rs->sr_text );
1653
1654         if( rs->sr_err != LDAP_SUCCESS ) {
1655                 goto done;
1656         }
1657
1658         if( new.bv_len == 0 ) {
1659                 slap_passwd_generate(&new);
1660
1661                 if( new.bv_len == 0 ) {
1662                         rs->sr_text = "password generation failed.";
1663                         rs->sr_err = LDAP_OTHER;
1664                         goto done;
1665                 }
1666                 
1667                 rs->sr_rspdata = slap_passwd_return( &new );
1668         }
1669
1670 #if SASL_VERSION_MAJOR < 2
1671         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx,
1672                 id.bv_val, new.bv_val, new.bv_len, 0, &rs->sr_text );
1673 #else
1674         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1675                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1676         if( rs->sr_err != SASL_OK ) {
1677                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1678         }
1679 #endif
1680         switch(rs->sr_err) {
1681                 case SASL_OK:
1682                         rs->sr_err = LDAP_SUCCESS;
1683                         break;
1684
1685                 case SASL_NOCHANGE:
1686                 case SASL_NOMECH:
1687                 case SASL_DISABLED:
1688                 case SASL_PWLOCK:
1689                 case SASL_FAIL:
1690                 case SASL_BADPARAM:
1691                 default:
1692                         rs->sr_err = LDAP_OTHER;
1693         }
1694
1695 done:
1696         return rs->sr_err;
1697 }
1698 #endif /* HAVE_CYRUS_SASL */
1699
1700 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1701  * string returned in *dn is in its own allocated memory, and must be free'd 
1702  * by the calling process.  -Mark Adamson, Carnegie Mellon
1703  *
1704  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1705  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1706  */
1707
1708 #define SET_NONE        0
1709 #define SET_DN          1
1710 #define SET_U           2
1711
1712 int slap_sasl_getdn( Connection *conn, Operation *op, char *id, int len,
1713         char *user_realm, struct berval *dn, int flags )
1714 {
1715         int rc, is_dn = SET_NONE, do_norm = 1;
1716         struct berval dn2, *mech;
1717
1718         assert( conn );
1719
1720 #ifdef NEW_LOGGING
1721         LDAP_LOG( TRANSPORT, ENTRY, 
1722                 "slap_sasl_getdn: conn %d id=%s [len=%d]\n",
1723                 conn->c_connid, id ? (*id ? id : "<empty>") : "NULL", len );
1724 #else
1725         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: id=%s [len=%d]\n", 
1726                 id ? ( *id ? id : "<empty>" ) : "NULL", len, 0 );
1727 #endif
1728
1729         if ( !op ) {
1730                 op = conn->c_sasl_bindop;
1731         }
1732
1733         dn->bv_val = NULL;
1734         dn->bv_len = 0;
1735
1736         if ( id ) {
1737                 if ( len == 0 ) len = strlen( id );
1738
1739                 /* Blatantly anonymous ID */
1740                 if ( len == sizeof("anonymous") - 1 &&
1741                         !strcasecmp( id, "anonymous" ) ) {
1742                         return( LDAP_SUCCESS );
1743                 }
1744         } else {
1745                 len = 0;
1746         }
1747
1748         if ( conn->c_sasl_bind_mech.bv_len ) {
1749                 mech = &conn->c_sasl_bind_mech;
1750         } else {
1751                 mech = &conn->c_authmech;
1752         }
1753
1754         /* An authcID needs to be converted to authzID form. Set the
1755          * values directly into *dn; they will be normalized later. (and
1756          * normalizing always makes a new copy.) An ID from a TLS certificate
1757          * is already normalized, so copy it and skip normalization.
1758          */
1759         if( flags & SLAP_GETDN_AUTHCID ) {
1760                 if( bvmatch( mech, &ext_bv )) {
1761                         /* EXTERNAL DNs are already normalized */
1762                         do_norm = 0;
1763                         is_dn = SET_DN;
1764                         ber_str2bv_x( id, len, 1, dn, op->o_tmpmemctx );
1765
1766                 } else {
1767                         /* convert to u:<username> form */
1768                         is_dn = SET_U;
1769                         dn->bv_val = id;
1770                         dn->bv_len = len;
1771                 }
1772         }
1773         if( is_dn == SET_NONE ) {
1774                 if( !strncasecmp( id, "u:", sizeof("u:")-1 )) {
1775                         is_dn = SET_U;
1776                         dn->bv_val = id+2;
1777                         dn->bv_len = len-2;
1778                 } else if ( !strncasecmp( id, "dn:", sizeof("dn:")-1) ) {
1779                         is_dn = SET_DN;
1780                         dn->bv_val = id+3;
1781                         dn->bv_len = len-3;
1782                 }
1783         }
1784
1785         /* No other possibilities from here */
1786         if( is_dn == SET_NONE ) {
1787                 dn->bv_val = NULL;
1788                 dn->bv_len = 0;
1789                 return( LDAP_INAPPROPRIATE_AUTH );
1790         }
1791
1792         /* Username strings */
1793         if( is_dn == SET_U ) {
1794                 char            *p;
1795                 struct berval   realm = BER_BVNULL, c1 = *dn;
1796
1797                 len = dn->bv_len + sizeof("uid=")-1 + sizeof(",cn=auth")-1;
1798
1799                 if( user_realm && *user_realm ) {
1800                         realm.bv_val = user_realm;
1801                         realm.bv_len = strlen( user_realm );
1802                         len += realm.bv_len + sizeof(",cn=") - 1;
1803                 }
1804
1805                 if( mech->bv_len ) {
1806                         len += mech->bv_len + sizeof(",cn=")-1;
1807                 }
1808
1809                 /* Build the new dn */
1810                 dn->bv_val = sl_malloc( len+1, op->o_tmpmemctx );
1811                 if( dn->bv_val == NULL ) {
1812 #ifdef NEW_LOGGING
1813                         LDAP_LOG( TRANSPORT, ERR, 
1814                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1815 #else
1816                         Debug( LDAP_DEBUG_ANY, 
1817                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1818 #endif
1819                         return LDAP_OTHER;
1820                 }
1821                 p = lutil_strcopy( dn->bv_val, "uid=" );
1822                 p = lutil_strncopy( p, c1.bv_val, c1.bv_len );
1823
1824                 if( realm.bv_len ) {
1825                         p = lutil_strcopy( p, ",cn=" );
1826                         p = lutil_strncopy( p, realm.bv_val, realm.bv_len );
1827                 }
1828
1829                 if( mech->bv_len ) {
1830                         p = lutil_strcopy( p, ",cn=" );
1831                         p = lutil_strcopy( p, mech->bv_val );
1832                 }
1833                 p = lutil_strcopy( p, ",cn=auth" );
1834                 dn->bv_len = p - dn->bv_val;
1835
1836 #ifdef NEW_LOGGING
1837                 LDAP_LOG( TRANSPORT, ENTRY, 
1838                         "slap_sasl_getdn: u:id converted to %s.\n", dn->bv_val, 0, 0 );
1839 #else
1840                 Debug( LDAP_DEBUG_TRACE, "slap_sasl_getdn: u:id converted to %s\n", dn->bv_val,0,0 );
1841 #endif
1842         } else {
1843                 
1844                 /* Dup the DN in any case, so we don't risk 
1845                  * leaks or dangling pointers later,
1846                  * and the DN value is '\0' terminated */
1847                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1848                 dn->bv_val = dn2.bv_val;
1849         }
1850
1851         /* All strings are in DN form now. Normalize if needed. */
1852         if ( do_norm ) {
1853                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1854
1855                 /* User DNs were constructed above and must be freed now */
1856                 sl_free( dn->bv_val, op->o_tmpmemctx );
1857
1858                 if ( rc != LDAP_SUCCESS ) {
1859                         dn->bv_val = NULL;
1860                         dn->bv_len = 0;
1861                         return rc;
1862                 }
1863                 *dn = dn2;
1864         }
1865
1866         /* Run thru regexp */
1867         slap_sasl2dn( op, dn, &dn2, flags );
1868         if( dn2.bv_val ) {
1869                 sl_free( dn->bv_val, op->o_tmpmemctx );
1870                 *dn = dn2;
1871 #ifdef NEW_LOGGING
1872                 LDAP_LOG( TRANSPORT, ENTRY, 
1873                         "slap_sasl_getdn: dn:id converted to %s.\n", dn->bv_val, 0, 0 );
1874 #else
1875                 Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
1876                         dn->bv_val, 0, 0 );
1877 #endif
1878         }
1879
1880         return( LDAP_SUCCESS );
1881 }