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