]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
ignore "schemacheck off" (with warning)
[openldap] / servers / slapd / sasl.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2005 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_tlimit = SLAP_NO_LIMIT;
487                         op.ors_slimit = 1;
488                         op.ors_filter = &generic_filter;
489                         op.ors_filterstr = generic_filterstr;
490
491                         op.o_bd->be_search( &op, &rs );
492                 }
493         }
494 }
495
496 #if SASL_VERSION_FULL >= 0x020110
497 static int
498 slap_auxprop_store(
499         void *glob_context,
500         sasl_server_params_t *sparams,
501         struct propctx *prctx,
502         const char *user,
503         unsigned ulen)
504 {
505         Operation op = {0};
506         SlapReply rs = {REP_RESULT};
507         int rc, i, j;
508         Connection *conn = NULL;
509         const struct propval *pr;
510         Modifications *modlist = NULL, **modtail = &modlist, *mod;
511         slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
512         char textbuf[SLAP_TEXT_BUFLEN];
513         const char *text;
514         size_t textlen = sizeof(textbuf);
515
516         /* just checking if we are enabled */
517         if (!prctx) return SASL_OK;
518
519         if (!sparams || !user) return SASL_BADPARAM;
520
521         pr = sparams->utils->prop_get( sparams->propctx );
522
523         /* Find our DN and conn first */
524         for( i = 0; pr[i].name; i++ ) {
525                 if ( pr[i].name[0] == '*' ) {
526                         if ( !strcmp( pr[i].name, slap_propnames[PROP_CONN] ) ) {
527                                 if ( pr[i].values && pr[i].values[0] )
528                                         AC_MEMCPY( &conn, pr[i].values[0], sizeof( conn ) );
529                                 continue;
530                         }
531                         if ( !strcmp( pr[i].name, slap_propnames[PROP_AUTHC] ) ) {
532                                 if ( pr[i].values && pr[i].values[0] ) {
533                                         AC_MEMCPY( &op.o_req_ndn, pr[i].values[0], sizeof( struct berval ) );
534                                 }
535                         }
536                 }
537         }
538         if (!conn || !op.o_req_ndn.bv_val) return SASL_BADPARAM;
539
540         op.o_bd = select_backend( &op.o_req_ndn, 0, 1 );
541
542         if ( !op.o_bd || !op.o_bd->be_modify ) return SASL_FAIL;
543                 
544         pr = sparams->utils->prop_get( prctx );
545         if (!pr) return SASL_BADPARAM;
546
547         for (i=0; pr[i].name; i++);
548         if (!i) return SASL_BADPARAM;
549
550         for (i=0; pr[i].name; i++) {
551                 mod = (Modifications *)ch_malloc( sizeof(Modifications) );
552                 mod->sml_op = LDAP_MOD_REPLACE;
553                 ber_str2bv( pr[i].name, 0, 0, &mod->sml_type );
554                 mod->sml_values = (struct berval *)ch_malloc( (pr[i].nvalues + 1) *
555                         sizeof(struct berval));
556                 for (j=0; j<pr[i].nvalues; j++) {
557                         ber_str2bv( pr[i].values[j], 0, 1, &mod->sml_values[j]);
558                 }
559                 mod->sml_values[j].bv_val = NULL;
560                 mod->sml_values[j].bv_len = 0;
561                 mod->sml_nvalues = NULL;
562                 mod->sml_desc = NULL;
563                 *modtail = mod;
564                 modtail = &mod->sml_next;
565         }
566         *modtail = NULL;
567
568         rc = slap_mods_check( modlist, 0, &text, textbuf, textlen, NULL );
569
570         if ( rc == LDAP_SUCCESS ) {
571                 rc = slap_mods_opattrs( &op, modlist, modtail, &text, textbuf,
572                         textlen, 1 );
573         }
574
575         if ( rc == LDAP_SUCCESS ) {
576                 op.o_tag = LDAP_REQ_MODIFY;
577                 op.o_protocol = LDAP_VERSION3;
578                 op.o_ndn = op.o_req_ndn;
579                 op.o_callback = &cb;
580                 op.o_time = slap_get_time();
581                 op.o_do_not_cache = 1;
582                 op.o_is_auth_check = 1;
583                 op.o_threadctx = conn->c_sasl_bindop->o_threadctx;
584                 op.o_tmpmemctx = conn->c_sasl_bindop->o_tmpmemctx;
585                 op.o_tmpmfuncs = conn->c_sasl_bindop->o_tmpmfuncs;
586                 op.o_conn = conn;
587                 op.o_connid = conn->c_connid;
588                 op.o_req_dn = op.o_req_ndn;
589                 op.orm_modlist = modlist;
590
591                 rc = op.o_bd->be_modify( &op, &rs );
592         }
593         slap_mods_free( modlist );
594         return rc ? SASL_FAIL : SASL_OK;
595 }
596 #endif /* SASL_VERSION_FULL >= 2.1.16 */
597
598 static sasl_auxprop_plug_t slap_auxprop_plugin = {
599         0,      /* Features */
600         0,      /* spare */
601         NULL,   /* glob_context */
602         NULL,   /* auxprop_free */
603         slap_auxprop_lookup,
604         "slapd",        /* name */
605 #if SASL_VERSION_FULL >= 0x020110
606         slap_auxprop_store      /* the declaration of this member changed
607                                  * in cyrus SASL from 2.1.15 to 2.1.16 */
608 #else
609         NULL
610 #endif
611 };
612
613 static int
614 slap_auxprop_init(
615         const sasl_utils_t *utils,
616         int max_version,
617         int *out_version,
618         sasl_auxprop_plug_t **plug,
619         const char *plugname)
620 {
621         if ( !out_version || !plug ) return SASL_BADPARAM;
622
623         if ( max_version < SASL_AUXPROP_PLUG_VERSION ) return SASL_BADVERS;
624
625         *out_version = SASL_AUXPROP_PLUG_VERSION;
626         *plug = &slap_auxprop_plugin;
627         return SASL_OK;
628 }
629
630 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
631  * auxiliary property, so that we can refer to it in sasl_authorize
632  * without interfering with anything else. Also, the SASL username
633  * buffer is constrained to 256 characters, and our DNs could be
634  * much longer (SLAP_LDAPDN_MAXLEN, currently set to 8192)
635  */
636 static int
637 slap_sasl_canonicalize(
638         sasl_conn_t *sconn,
639         void *context,
640         const char *in,
641         unsigned inlen,
642         unsigned flags,
643         const char *user_realm,
644         char *out,
645         unsigned out_max,
646         unsigned *out_len)
647 {
648         Connection *conn = (Connection *)context;
649         struct propctx *props = sasl_auxprop_getctx( sconn );
650         struct propval auxvals[3];
651         struct berval dn;
652         int rc, which;
653         const char *names[2];
654
655         *out_len = 0;
656
657 #ifdef NEW_LOGGING
658         LDAP_LOG( TRANSPORT, ENTRY, 
659                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
660                 conn ? conn->c_connid : -1,
661                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
662                 in ? in : "<empty>");
663 #else
664         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
665                 conn ? conn->c_connid : -1,
666                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
667                 in ? in : "<empty>");
668 #endif
669
670         /* If name is too big, just truncate. We don't care, we're
671          * using DNs, not the usernames.
672          */
673         if ( inlen > out_max )
674                 inlen = out_max-1;
675
676         /* This is a Simple Bind using SPASSWD. That means the in-directory
677          * userPassword of the Binding user already points at SASL, so it
678          * cannot be used to actually satisfy a password comparison. Just
679          * ignore it, some other mech will process it.
680          */
681         if ( !conn->c_sasl_bindop ||
682                 conn->c_sasl_bindop->orb_method != LDAP_AUTH_SASL ) goto done;
683
684         /* See if we need to add request, can only do it once */
685         prop_getnames( props, slap_propnames, auxvals );
686         if ( !auxvals[0].name )
687                 prop_request( props, slap_propnames );
688
689         if ( flags & SASL_CU_AUTHID )
690                 which = PROP_AUTHC;
691         else
692                 which = PROP_AUTHZ;
693
694         /* Need to store the Connection for auxprop_lookup */
695         if ( !auxvals[PROP_CONN].values ) {
696                 names[0] = slap_propnames[PROP_CONN];
697                 names[1] = NULL;
698                 prop_set( props, names[0], (char *)&conn, sizeof( conn ) );
699         }
700                 
701         /* Already been here? */
702         if ( auxvals[which].values )
703                 goto done;
704
705         /* Normally we require an authzID to have a u: or dn: prefix.
706          * However, SASL frequently gives us an authzID that is just
707          * an exact copy of the authcID, without a prefix. We need to
708          * detect and allow this condition. If SASL calls canonicalize
709          * with SASL_CU_AUTHID|SASL_CU_AUTHZID this is a no-brainer.
710          * But if it's broken into two calls, we need to remember the
711          * authcID so that we can compare the authzID later. We store
712          * the authcID temporarily in conn->c_sasl_dn. We necessarily
713          * finish Canonicalizing before Authorizing, so there is no
714          * conflict with slap_sasl_authorize's use of this temp var.
715          *
716          * The SASL EXTERNAL mech is backwards from all the other mechs,
717          * it does authzID before the authcID. If we see that authzID
718          * has already been done, don't do anything special with authcID.
719          */
720         if ( flags == SASL_CU_AUTHID && !auxvals[PROP_AUTHZ].values ) {
721                 conn->c_sasl_dn.bv_val = (char *) in;
722         } else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
723                 rc = strcmp( in, conn->c_sasl_dn.bv_val );
724                 conn->c_sasl_dn.bv_val = NULL;
725                 /* They were equal, no work needed */
726                 if ( !rc ) goto done;
727         }
728
729         rc = slap_sasl_getdn( conn, NULL, (char *)in, inlen, (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                 conn->c_sasl_dn.bv_val = NULL;
794                 conn->c_sasl_dn.bv_len = 0;
795         }
796
797         /* Skip PROP_CONN */
798         prop_getnames( props, slap_propnames+1, auxvals );
799         
800         /* Should not happen */
801         if ( !auxvals[0].values ) {
802                 sasl_seterror( sconn, 0, "invalid authcid" );
803                 return SASL_NOAUTHZ;
804         }
805
806         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
807
808         /* Nothing to do if no authzID was given */
809         if ( !auxvals[1].name || !auxvals[1].values ) {
810                 conn->c_sasl_dn = authcDN;
811                 goto ok;
812         }
813         
814         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
815
816         rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
817         ch_free( authcDN.bv_val );
818         if ( rc != LDAP_SUCCESS ) {
819 #ifdef NEW_LOGGING
820                 LDAP_LOG( TRANSPORT, INFO, 
821                         "slap_sasl_authorize: conn %ld "
822                         "proxy authorization disallowed (%d)\n",
823                         (long)(conn ? conn->c_connid : -1), rc, 0 );
824 #else
825                 Debug( LDAP_DEBUG_TRACE, "SASL Proxy Authorize [conn=%ld]: "
826                         "proxy authorization disallowed (%d)\n",
827                         (long) (conn ? conn->c_connid : -1), rc, 0 );
828 #endif
829
830                 sasl_seterror( sconn, 0, "not authorized" );
831                 ch_free( authzDN.bv_val );
832                 return SASL_NOAUTHZ;
833         }
834
835         conn->c_sasl_dn = authzDN;
836 ok:
837         if (conn->c_sasl_bindop) {
838                 Statslog( LDAP_DEBUG_STATS,
839                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
840                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
841                         auth_identity, 0, 0);
842         }
843
844 #ifdef NEW_LOGGING
845         LDAP_LOG( TRANSPORT, ENTRY, 
846                 "slap_sasl_authorize: conn %d proxy authorization allowed\n",
847                 (long)(conn ? conn->c_connid : -1), 0, 0 );
848 #else
849         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
850                 " proxy authorization allowed\n",
851                 (long) (conn ? conn->c_connid : -1), 0, 0 );
852 #endif
853         return SASL_OK;
854
855 #else
856 static int
857 slap_sasl_authorize(
858         void *context,
859         char *authcid,
860         char *authzid,
861         const char **user,
862         const char **errstr)
863 {
864         struct berval authcDN, authzDN;
865         int rc;
866         Connection *conn = context;
867         char *realm;
868
869         *user = NULL;
870         if ( conn->c_sasl_dn.bv_val ) {
871                 ch_free( conn->c_sasl_dn.bv_val );
872                 conn->c_sasl_dn.bv_val = NULL;
873                 conn->c_sasl_dn.bv_len = 0;
874         }
875
876 #ifdef NEW_LOGGING
877         LDAP_LOG( TRANSPORT, ENTRY, 
878                 "slap_sasl_authorize: conn %d    authcid=\"%s\" authzid=\"%s\"\n",
879                 conn ? conn->c_connid : -1, authcid ? authcid : "<empty>",
880                 authzid ? authzid : "<empty>" );
881 #else
882         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
883                 "authcid=\"%s\" authzid=\"%s\"\n",
884                 (long) (conn ? conn->c_connid : -1),
885                 authcid ? authcid : "<empty>",
886                 authzid ? authzid : "<empty>" );
887 #endif
888
889         /* Figure out how much data we have for the dn */
890         rc = sasl_getprop( conn->c_sasl_authctx, SASL_REALM, (void **)&realm );
891         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
892 #ifdef NEW_LOGGING
893                 LDAP_LOG( TRANSPORT, ERR,
894                         "slap_sasl_authorize: getprop(REALM) failed.\n", 0, 0, 0 );
895 #else
896                 Debug(LDAP_DEBUG_TRACE,
897                         "authorize: getprop(REALM) failed!\n", 0,0,0);
898 #endif
899                 *errstr = "Could not extract realm";
900                 return SASL_NOAUTHZ;
901         }
902
903         /* Convert the identities to DN's. If no authzid was given, client will
904            be bound as the DN matching their username */
905         rc = slap_sasl_getdn( conn, NULL, (char *)authcid, 0, realm,
906                 &authcDN, SLAP_GETDN_AUTHCID );
907         if( rc != LDAP_SUCCESS ) {
908                 *errstr = ldap_err2string( rc );
909                 return SASL_NOAUTHZ;
910         }
911         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
912 #ifdef NEW_LOGGING
913                 LDAP_LOG( TRANSPORT, ENTRY, 
914                         "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
915                         conn ? conn->c_connid : -1, authcDN.bv_val, 0 );
916 #else
917                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
918                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
919 #endif
920
921                 conn->c_sasl_dn = authcDN;
922                 goto ok;
923         }
924         rc = slap_sasl_getdn( conn, NULL, (char *)authzid, 0, realm,
925                 &authzDN, SLAP_GETDN_AUTHZID );
926         if( rc != LDAP_SUCCESS ) {
927                 ch_free( authcDN.bv_val );
928                 *errstr = ldap_err2string( rc );
929                 return SASL_NOAUTHZ;
930         }
931
932         rc = slap_sasl_authorized(conn->c_sasl_bindop, &authcDN, &authzDN );
933         ch_free( authcDN.bv_val );
934         if( rc ) {
935 #ifdef NEW_LOGGING
936                 LDAP_LOG( TRANSPORT, INFO, 
937                         "slap_sasl_authorize: conn %ld "
938                         "proxy authorization disallowed (%d)\n",
939                         (long)(conn ? conn->c_connid : -1), rc, 0 );
940 #else
941                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
942                         "proxy authorization disallowed (%d)\n",
943                         (long) (conn ? conn->c_connid : -1), rc, 0 );
944 #endif
945
946                 *errstr = "not authorized";
947                 ch_free( authzDN.bv_val );
948                 return SASL_NOAUTHZ;
949         }
950         conn->c_sasl_dn = authzDN;
951
952 ok:
953 #ifdef NEW_LOGGING
954         LDAP_LOG( TRANSPORT, RESULTS, 
955                 "slap_sasl_authorize: conn %d proxy authorization allowed\n",
956            (long)(conn ? conn->c_connid : -1 ), 0, 0 );
957 #else
958         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
959                 " authorization allowed\n",
960                 (long) (conn ? conn->c_connid : -1), 0, 0 );
961 #endif
962
963         if (conn->c_sasl_bindop) {
964                 Statslog( LDAP_DEBUG_STATS,
965                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
966                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
967                         authcid, 0, 0);
968         }
969
970         *errstr = NULL;
971         return SASL_OK;
972 }
973 #endif /* SASL_VERSION_MAJOR >= 2 */
974
975 static int
976 slap_sasl_err2ldap( int saslerr )
977 {
978         int rc;
979
980         switch (saslerr) {
981                 case SASL_OK:
982                         rc = LDAP_SUCCESS;
983                         break;
984                 case SASL_CONTINUE:
985                         rc = LDAP_SASL_BIND_IN_PROGRESS;
986                         break;
987                 case SASL_FAIL:
988                         rc = LDAP_OTHER;
989                         break;
990                 case SASL_NOMEM:
991                         rc = LDAP_OTHER;
992                         break;
993                 case SASL_NOMECH:
994                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
995                         break;
996                 case SASL_BADAUTH:
997                         rc = LDAP_INVALID_CREDENTIALS;
998                         break;
999                 case SASL_NOAUTHZ:
1000                         rc = LDAP_INSUFFICIENT_ACCESS;
1001                         break;
1002                 case SASL_TOOWEAK:
1003                 case SASL_ENCRYPT:
1004                         rc = LDAP_INAPPROPRIATE_AUTH;
1005                         break;
1006                 default:
1007                         rc = LDAP_OTHER;
1008                         break;
1009         }
1010
1011         return rc;
1012 }
1013 #endif
1014
1015 int slap_sasl_init( void )
1016 {
1017 #ifdef HAVE_CYRUS_SASL
1018         int rc;
1019         static sasl_callback_t server_callbacks[] = {
1020                 { SASL_CB_LOG, &slap_sasl_log, NULL },
1021                 { SASL_CB_LIST_END, NULL, NULL }
1022         };
1023
1024 #ifdef HAVE_SASL_VERSION
1025         /* stringify the version number, sasl.h doesn't do it for us */
1026 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
1027 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
1028 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
1029                                 SASL_VERSION_STEP)
1030
1031         sasl_version( NULL, &rc );
1032         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1033                 (rc & 0xffff) < SASL_VERSION_STEP)
1034         {
1035                 char version[sizeof("xxx.xxx.xxxxx")];
1036                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
1037                         rc & 0xffff );
1038 #ifdef NEW_LOGGING
1039                 LDAP_LOG( TRANSPORT, INFO,
1040                 "slap_sasl_init: SASL library version mismatch:"
1041                 " expected " SASL_VERSION_STRING ","
1042                 " got %s\n", version, 0, 0 );
1043 #else
1044                 Debug( LDAP_DEBUG_ANY,
1045                 "slap_sasl_init: SASL library version mismatch:"
1046                 " expected " SASL_VERSION_STRING ","
1047                 " got %s\n", version, 0, 0 );
1048 #endif
1049                 return -1;
1050         }
1051 #endif
1052
1053         /* SASL 2 does its own memory management internally */
1054 #if SASL_VERSION_MAJOR < 2
1055         sasl_set_alloc(
1056                 ber_memalloc,
1057                 ber_memcalloc,
1058                 ber_memrealloc,
1059                 ber_memfree ); 
1060 #endif
1061
1062         sasl_set_mutex(
1063                 ldap_pvt_sasl_mutex_new,
1064                 ldap_pvt_sasl_mutex_lock,
1065                 ldap_pvt_sasl_mutex_unlock,
1066                 ldap_pvt_sasl_mutex_dispose );
1067
1068 #if SASL_VERSION_MAJOR >= 2
1069         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1070
1071         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1072 #endif
1073         /* should provide callbacks for logging */
1074         /* server name should be configurable */
1075         rc = sasl_server_init( server_callbacks, "slapd" );
1076
1077         if( rc != SASL_OK ) {
1078 #ifdef NEW_LOGGING
1079                 LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: init failed.\n", 0, 0, 0 );
1080 #else
1081                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
1082                         0, 0, 0 );
1083 #endif
1084 #if SASL_VERSION_MAJOR < 2
1085                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1086                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1087 #endif
1088
1089                 return -1;
1090         }
1091
1092 #ifdef NEW_LOGGING
1093         LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: initialized!\n", 0, 0, 0 );
1094 #else
1095         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1096                 0, 0, 0 );
1097 #endif
1098
1099         /* default security properties */
1100         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1101         sasl_secprops.max_ssf = INT_MAX;
1102         sasl_secprops.maxbufsize = 65536;
1103         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1104 #endif
1105
1106         return 0;
1107 }
1108
1109 int slap_sasl_destroy( void )
1110 {
1111 #ifdef HAVE_CYRUS_SASL
1112         sasl_done();
1113 #endif
1114         free( global_host );
1115         global_host = NULL;
1116
1117         return 0;
1118 }
1119
1120 int slap_sasl_open( Connection *conn, int reopen )
1121 {
1122         int sc = LDAP_SUCCESS;
1123 #ifdef HAVE_CYRUS_SASL
1124         int cb;
1125
1126         sasl_conn_t *ctx = NULL;
1127         sasl_callback_t *session_callbacks;
1128
1129 #if SASL_VERSION_MAJOR >= 2
1130         char *ipremoteport = NULL, *iplocalport = NULL;
1131 #endif
1132
1133         assert( conn->c_sasl_authctx == NULL );
1134
1135         if ( !reopen ) {
1136                 assert( conn->c_sasl_extra == NULL );
1137
1138                 session_callbacks =
1139 #if SASL_VERSION_MAJOR >= 2
1140                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1141 #else
1142                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1143 #endif
1144                 if( session_callbacks == NULL ) {
1145 #ifdef NEW_LOGGING
1146                         LDAP_LOG( TRANSPORT, ERR, 
1147                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1148 #else
1149                         Debug( LDAP_DEBUG_ANY, 
1150                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1151 #endif
1152                         return -1;
1153                 }
1154                 conn->c_sasl_extra = session_callbacks;
1155
1156                 session_callbacks[cb=0].id = SASL_CB_LOG;
1157                 session_callbacks[cb].proc = &slap_sasl_log;
1158                 session_callbacks[cb++].context = conn;
1159
1160                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1161                 session_callbacks[cb].proc = &slap_sasl_authorize;
1162                 session_callbacks[cb++].context = conn;
1163
1164 #if SASL_VERSION_MAJOR >= 2
1165                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1166                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1167                 session_callbacks[cb++].context = conn;
1168 #endif
1169
1170                 session_callbacks[cb].id = SASL_CB_LIST_END;
1171                 session_callbacks[cb].proc = NULL;
1172                 session_callbacks[cb++].context = NULL;
1173         } else {
1174                 session_callbacks = conn->c_sasl_extra;
1175         }
1176
1177         conn->c_sasl_layers = 0;
1178
1179         if( global_host == NULL ) {
1180                 global_host = ldap_pvt_get_fqdn( NULL );
1181         }
1182
1183         /* create new SASL context */
1184 #if SASL_VERSION_MAJOR >= 2
1185         if ( conn->c_sock_name.bv_len != 0 &&
1186              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1187                 char *p;
1188
1189                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1190                 /* Convert IPv6 addresses to address;port syntax. */
1191                 p = strrchr( iplocalport, ' ' );
1192                 /* Convert IPv4 addresses to address;port syntax. */
1193                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1194                 if ( p != NULL ) {
1195                         *p = ';';
1196                 }
1197         }
1198         if ( conn->c_peer_name.bv_len != 0 &&
1199              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1200                 char *p;
1201
1202                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1203                 /* Convert IPv6 addresses to address;port syntax. */
1204                 p = strrchr( ipremoteport, ' ' );
1205                 /* Convert IPv4 addresses to address;port syntax. */
1206                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1207                 if ( p != NULL ) {
1208                         *p = ';';
1209                 }
1210         }
1211         sc = sasl_server_new( "ldap", global_host, global_realm,
1212                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1213         if ( iplocalport != NULL ) {
1214                 ch_free( iplocalport );
1215         }
1216         if ( ipremoteport != NULL ) {
1217                 ch_free( ipremoteport );
1218         }
1219 #else
1220         sc = sasl_server_new( "ldap", global_host, global_realm,
1221                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1222 #endif
1223
1224         if( sc != SASL_OK ) {
1225 #ifdef NEW_LOGGING
1226                 LDAP_LOG( TRANSPORT, ERR, 
1227                         "slap_sasl_open: sasl_server_new failed: %d\n", sc, 0, 0 );
1228 #else
1229                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1230                         sc, 0, 0 );
1231 #endif
1232
1233                 return -1;
1234         }
1235
1236         conn->c_sasl_authctx = ctx;
1237
1238         if( sc == SASL_OK ) {
1239                 sc = sasl_setprop( ctx,
1240                         SASL_SEC_PROPS, &sasl_secprops );
1241
1242                 if( sc != SASL_OK ) {
1243 #ifdef NEW_LOGGING
1244                         LDAP_LOG( TRANSPORT, ERR, 
1245                                 "slap_sasl_open: sasl_setprop failed: %d \n", sc, 0, 0 );
1246 #else
1247                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1248                                 sc, 0, 0 );
1249 #endif
1250
1251                         slap_sasl_close( conn );
1252                         return -1;
1253                 }
1254         }
1255
1256         sc = slap_sasl_err2ldap( sc );
1257
1258 #elif defined(SLAP_BUILTIN_SASL)
1259         /* built-in SASL implementation */
1260         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1261         if( ctx == NULL ) return -1;
1262
1263         ctx->sc_external_ssf = 0;
1264         ctx->sc_external_id.bv_len = 0;
1265         ctx->sc_external_id.bv_val = NULL;
1266
1267         conn->c_sasl_authctx = ctx;
1268 #endif
1269
1270         return sc;
1271 }
1272
1273 int slap_sasl_external(
1274         Connection *conn,
1275         slap_ssf_t ssf,
1276         struct berval *auth_id )
1277 {
1278 #if SASL_VERSION_MAJOR >= 2
1279         int sc;
1280         sasl_conn_t *ctx = conn->c_sasl_authctx;
1281
1282         if ( ctx == NULL ) {
1283                 return LDAP_UNAVAILABLE;
1284         }
1285
1286         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1287
1288         if ( sc != SASL_OK ) {
1289                 return LDAP_OTHER;
1290         }
1291
1292         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1293                 auth_id ? auth_id->bv_val : NULL );
1294
1295         if ( sc != SASL_OK ) {
1296                 return LDAP_OTHER;
1297         }
1298
1299 #elif defined(HAVE_CYRUS_SASL)
1300         int sc;
1301         sasl_conn_t *ctx = conn->c_sasl_authctx;
1302         sasl_external_properties_t extprops;
1303
1304         if ( ctx == NULL ) {
1305                 return LDAP_UNAVAILABLE;
1306         }
1307
1308         memset( &extprops, '\0', sizeof(extprops) );
1309         extprops.ssf = ssf;
1310         extprops.auth_id = auth_id ? auth_id->bv_val : NULL;
1311
1312         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1313                 (void *) &extprops );
1314
1315         if ( sc != SASL_OK ) {
1316                 return LDAP_OTHER;
1317         }
1318 #elif defined(SLAP_BUILTIN_SASL)
1319         /* built-in SASL implementation */
1320         SASL_CTX *ctx = conn->c_sasl_authctx;
1321         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1322
1323         ctx->sc_external_ssf = ssf;
1324         if( auth_id ) {
1325                 ctx->sc_external_id = *auth_id;
1326                 auth_id->bv_len = 0;
1327                 auth_id->bv_val = NULL;
1328         } else {
1329                 ctx->sc_external_id.bv_len = 0;
1330                 ctx->sc_external_id.bv_val = NULL;
1331         }
1332 #endif
1333
1334         return LDAP_SUCCESS;
1335 }
1336
1337 int slap_sasl_reset( Connection *conn )
1338 {
1339         return LDAP_SUCCESS;
1340 }
1341
1342 char ** slap_sasl_mechs( Connection *conn )
1343 {
1344         char **mechs = NULL;
1345
1346 #ifdef HAVE_CYRUS_SASL
1347         sasl_conn_t *ctx = conn->c_sasl_authctx;
1348
1349         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1350
1351         if( ctx != NULL ) {
1352                 int sc;
1353                 SASL_CONST char *mechstr;
1354
1355                 sc = sasl_listmech( ctx,
1356                         NULL, NULL, ",", NULL,
1357                         &mechstr, NULL, NULL );
1358
1359                 if( sc != SASL_OK ) {
1360 #ifdef NEW_LOGGING
1361                         LDAP_LOG( TRANSPORT, ERR, 
1362                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc, 0, 0 );
1363 #else
1364                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1365                                 sc, 0, 0 );
1366 #endif
1367
1368                         return NULL;
1369                 }
1370
1371                 mechs = ldap_str2charray( mechstr, "," );
1372
1373 #if SASL_VERSION_MAJOR < 2
1374                 ch_free( mechstr );
1375 #endif
1376         }
1377 #elif defined(SLAP_BUILTIN_SASL)
1378         /* builtin SASL implementation */
1379         SASL_CTX *ctx = conn->c_sasl_authctx;
1380         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1381                 /* should check ssf */
1382                 mechs = ldap_str2charray( "EXTERNAL", "," );
1383         }
1384 #endif
1385
1386         return mechs;
1387 }
1388
1389 int slap_sasl_close( Connection *conn )
1390 {
1391 #ifdef HAVE_CYRUS_SASL
1392         sasl_conn_t *ctx = conn->c_sasl_authctx;
1393
1394         if( ctx != NULL ) {
1395                 sasl_dispose( &ctx );
1396         }
1397         if ( conn->c_sasl_sockctx &&
1398                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1399         {
1400                 ctx = conn->c_sasl_sockctx;
1401                 sasl_dispose( &ctx );
1402         }
1403
1404         conn->c_sasl_authctx = NULL;
1405         conn->c_sasl_sockctx = NULL;
1406         conn->c_sasl_done = 0;
1407
1408         free( conn->c_sasl_extra );
1409         conn->c_sasl_extra = NULL;
1410
1411 #elif defined(SLAP_BUILTIN_SASL)
1412         SASL_CTX *ctx = conn->c_sasl_authctx;
1413         if( ctx ) {
1414                 if( ctx->sc_external_id.bv_val ) {
1415                         free( ctx->sc_external_id.bv_val );
1416                         ctx->sc_external_id.bv_val = NULL;
1417                 }
1418                 free( ctx );
1419                 conn->c_sasl_authctx = NULL;
1420         }
1421 #endif
1422
1423         return LDAP_SUCCESS;
1424 }
1425
1426 int slap_sasl_bind( Operation *op, SlapReply *rs )
1427 {
1428 #ifdef HAVE_CYRUS_SASL
1429         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1430         struct berval response;
1431         unsigned reslen = 0;
1432         int sc;
1433
1434 #ifdef NEW_LOGGING
1435         LDAP_LOG( TRANSPORT, ENTRY, 
1436                 "sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1437                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1438                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1439                 op->o_conn->c_sasl_bind_mech.bv_val,
1440                 op->orb_cred.bv_len );
1441 #else
1442         Debug(LDAP_DEBUG_ARGS,
1443                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1444                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1445                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1446                 op->o_conn->c_sasl_bind_mech.bv_val,
1447                 op->orb_cred.bv_len );
1448 #endif
1449
1450         if( ctx == NULL ) {
1451                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1452                         "SASL unavailable on this session" );
1453                 return rs->sr_err;
1454         }
1455
1456 #if SASL_VERSION_MAJOR >= 2
1457 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1458         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1459 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1460         sasl_server_step( ctx, cred, clen, resp, rlen )
1461 #else
1462 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1463         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1464 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1465         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1466 #endif
1467
1468         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1469                 /* If we already authenticated once, must use a new context */
1470                 if ( op->o_conn->c_sasl_done ) {
1471                         slap_ssf_t ssf = 0;
1472                         const char *authid = NULL;
1473 #if SASL_VERSION_MAJOR >= 2
1474                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1475                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1476                         if ( authid ) authid = ch_strdup( authid );
1477 #endif
1478                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1479                                 sasl_dispose( &ctx );
1480                         }
1481                         op->o_conn->c_sasl_authctx = NULL;
1482                                 
1483                         slap_sasl_open( op->o_conn, 1 );
1484                         ctx = op->o_conn->c_sasl_authctx;
1485 #if SASL_VERSION_MAJOR >= 2
1486                         if ( authid ) {
1487                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1488                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1489                                 ch_free( (char *)authid );
1490                         }
1491 #endif
1492                 }
1493                 sc = START( ctx,
1494                         op->o_conn->c_sasl_bind_mech.bv_val,
1495                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1496                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1497
1498         } else {
1499                 sc = STEP( ctx,
1500                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1501                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1502         }
1503
1504         response.bv_len = reslen;
1505
1506         if ( sc == SASL_OK ) {
1507                 sasl_ssf_t *ssf = NULL;
1508
1509                 op->orb_edn = op->o_conn->c_sasl_dn;
1510                 op->o_conn->c_sasl_dn.bv_val = NULL;
1511                 op->o_conn->c_sasl_dn.bv_len = 0;
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, char *id, int len,
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
1721 #ifdef NEW_LOGGING
1722         LDAP_LOG( TRANSPORT, ENTRY, 
1723                 "slap_sasl_getdn: conn %d id=%s [len=%d]\n",
1724                 conn->c_connid, id ? (*id ? id : "<empty>") : "NULL", len );
1725 #else
1726         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: id=%s [len=%d]\n", 
1727                 id ? ( *id ? id : "<empty>" ) : "NULL", len, 0 );
1728 #endif
1729
1730         if ( !op ) {
1731                 op = conn->c_sasl_bindop;
1732         }
1733
1734         dn->bv_val = NULL;
1735         dn->bv_len = 0;
1736
1737         if ( id ) {
1738                 if ( len == 0 ) len = strlen( id );
1739
1740                 /* Blatantly anonymous ID */
1741                 if ( len == sizeof("anonymous") - 1 &&
1742                         !strcasecmp( id, "anonymous" ) ) {
1743                         return( LDAP_SUCCESS );
1744                 }
1745         } else {
1746                 len = 0;
1747         }
1748
1749         if ( conn->c_sasl_bind_mech.bv_len ) {
1750                 mech = &conn->c_sasl_bind_mech;
1751         } else {
1752                 mech = &conn->c_authmech;
1753         }
1754
1755         /* An authcID needs to be converted to authzID form. Set the
1756          * values directly into *dn; they will be normalized later. (and
1757          * normalizing always makes a new copy.) An ID from a TLS certificate
1758          * is already normalized, so copy it and skip normalization.
1759          */
1760         if( flags & SLAP_GETDN_AUTHCID ) {
1761                 if( bvmatch( mech, &ext_bv )) {
1762                         /* EXTERNAL DNs are already normalized */
1763                         do_norm = 0;
1764                         is_dn = SET_DN;
1765                         ber_str2bv_x( id, len, 1, dn, op->o_tmpmemctx );
1766
1767                 } else {
1768                         /* convert to u:<username> form */
1769                         is_dn = SET_U;
1770                         dn->bv_val = id;
1771                         dn->bv_len = len;
1772                 }
1773         }
1774         if( is_dn == SET_NONE ) {
1775                 if( !strncasecmp( id, "u:", sizeof("u:")-1 )) {
1776                         is_dn = SET_U;
1777                         dn->bv_val = id+2;
1778                         dn->bv_len = len-2;
1779                 } else if ( !strncasecmp( id, "dn:", sizeof("dn:")-1) ) {
1780                         is_dn = SET_DN;
1781                         dn->bv_val = id+3;
1782                         dn->bv_len = len-3;
1783                 }
1784         }
1785
1786         /* No other possibilities from here */
1787         if( is_dn == SET_NONE ) {
1788                 dn->bv_val = NULL;
1789                 dn->bv_len = 0;
1790                 return( LDAP_INAPPROPRIATE_AUTH );
1791         }
1792
1793         /* Username strings */
1794         if( is_dn == SET_U ) {
1795                 /* ITS#3419: values may need escape */
1796                 LDAPRDN         DN[ 5 ];
1797                 LDAPAVA         *RDNs[ 4 ][ 2 ];
1798                 LDAPAVA         AVAs[ 4 ];
1799                 int             irdn;
1800  
1801                 irdn = 0;
1802                 DN[ irdn ] = RDNs[ irdn ];
1803                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1804                 BER_BVSTR( &AVAs[ irdn ].la_attr, "uid" );
1805                 AVAs[ irdn ].la_value = *dn;
1806                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1807                 AVAs[ irdn ].la_private = NULL;
1808                 RDNs[ irdn ][ 1 ] = NULL;
1809  
1810                 if ( user_realm && *user_realm ) {
1811                         irdn++;
1812                         DN[ irdn ] = RDNs[ irdn ];
1813                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1814                         BER_BVSTR( &AVAs[ irdn ].la_attr, "cn" );
1815                         ber_str2bv( user_realm, 0, 0, &AVAs[ irdn ].la_value );
1816                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1817                         AVAs[ irdn ].la_private = NULL;
1818                         RDNs[ irdn ][ 1 ] = NULL;
1819                 }
1820  
1821                 if ( !BER_BVISNULL( mech ) ) {
1822                         irdn++;
1823                         DN[ irdn ] = RDNs[ irdn ];
1824                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1825                         BER_BVSTR( &AVAs[ irdn ].la_attr, "cn" );
1826                         AVAs[ irdn ].la_value = *mech;
1827                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1828                         AVAs[ irdn ].la_private = NULL;
1829                         RDNs[ irdn ][ 1 ] = NULL;
1830                 }
1831  
1832                 irdn++;
1833                 DN[ irdn ] = RDNs[ irdn ];
1834                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1835                 BER_BVSTR( &AVAs[ irdn ].la_attr, "cn" );
1836                 BER_BVSTR( &AVAs[ irdn ].la_value, "auth" );
1837                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1838                 AVAs[ irdn ].la_private = NULL;
1839                 RDNs[ irdn ][ 1 ] = NULL;
1840   
1841                 irdn++;
1842                 DN[ irdn ] = NULL;
1843   
1844                 rc = ldap_dn2bv_x( DN, dn, LDAP_DN_FORMAT_LDAPV3, op->o_tmpmemctx );
1845                 if ( rc != LDAP_SUCCESS ) {
1846                         BER_BVZERO( dn );
1847                         return rc;
1848                 }
1849   
1850 #ifdef NEW_LOGGING
1851                 LDAP_LOG( TRANSPORT, ENTRY, 
1852                         "slap_sasl_getdn: u:id converted to %s.\n", dn->bv_val, 0, 0 );
1853 #else
1854                 Debug( LDAP_DEBUG_TRACE, "slap_sasl_getdn: u:id converted to %s\n", dn->bv_val,0,0 );
1855 #endif
1856         } else {
1857                 
1858                 /* Dup the DN in any case, so we don't risk 
1859                  * leaks or dangling pointers later,
1860                  * and the DN value is '\0' terminated */
1861                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1862                 dn->bv_val = dn2.bv_val;
1863         }
1864
1865         /* All strings are in DN form now. Normalize if needed. */
1866         if ( do_norm ) {
1867                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1868
1869                 /* User DNs were constructed above and must be freed now */
1870                 sl_free( dn->bv_val, op->o_tmpmemctx );
1871
1872                 if ( rc != LDAP_SUCCESS ) {
1873                         dn->bv_val = NULL;
1874                         dn->bv_len = 0;
1875                         return rc;
1876                 }
1877                 *dn = dn2;
1878         }
1879
1880         /* Run thru regexp */
1881         slap_sasl2dn( op, dn, &dn2, flags );
1882         if( dn2.bv_val ) {
1883                 sl_free( dn->bv_val, op->o_tmpmemctx );
1884                 *dn = dn2;
1885 #ifdef NEW_LOGGING
1886                 LDAP_LOG( TRANSPORT, ENTRY, 
1887                         "slap_sasl_getdn: dn:id converted to %s.\n", dn->bv_val, 0, 0 );
1888 #else
1889                 Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
1890                         dn->bv_val, 0, 0 );
1891 #endif
1892         }
1893
1894         return( LDAP_SUCCESS );
1895 }