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