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