]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
Sync with HEAD for OL 2.4.5
[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, 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, 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                 conn->c_sasl_dn.bv_len = 0;
614         } else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
615                 rc = strcmp( in, conn->c_sasl_dn.bv_val );
616                 conn->c_sasl_dn.bv_val = NULL;
617                 /* They were equal, no work needed */
618                 if ( !rc ) goto done;
619         }
620
621         bvin.bv_val = (char *)in;
622         bvin.bv_len = inlen;
623         rc = slap_sasl_getdn( conn, NULL, &bvin, (char *)user_realm, &dn,
624                 (flags & SASL_CU_AUTHID) ? SLAP_GETDN_AUTHCID : SLAP_GETDN_AUTHZID );
625         if ( rc != LDAP_SUCCESS ) {
626                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
627                 return SASL_NOAUTHZ;
628         }
629
630         names[0] = slap_propnames[which];
631         names[1] = NULL;
632
633         prop_set( props, names[0], (char *)&dn, sizeof( dn ) );
634
635         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
636                 conn ? conn->c_connid : -1, names[0]+1,
637                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
638
639 done:
640         AC_MEMCPY( out, in, inlen );
641         out[inlen] = '\0';
642
643         *out_len = inlen;
644
645         return SASL_OK;
646 }
647
648 static int
649 slap_sasl_authorize(
650         sasl_conn_t *sconn,
651         void *context,
652         char *requested_user,
653         unsigned rlen,
654         char *auth_identity,
655         unsigned alen,
656         const char *def_realm,
657         unsigned urlen,
658         struct propctx *props)
659 {
660         Connection *conn = (Connection *)context;
661         /* actually:
662          *      (SLAP_SASL_PROP_COUNT - 1)      because we skip "conn",
663          *      + 1                             for NULL termination?
664          */
665         struct propval auxvals[ SLAP_SASL_PROP_COUNT ] = { { 0 } };
666         struct berval authcDN, authzDN = BER_BVNULL;
667         int rc;
668
669         /* Simple Binds don't support proxy authorization, ignore it */
670         if ( !conn->c_sasl_bindop ||
671                 conn->c_sasl_bindop->orb_method != LDAP_AUTH_SASL ) return SASL_OK;
672
673         Debug( LDAP_DEBUG_ARGS, "SASL proxy authorize [conn=%ld]: "
674                 "authcid=\"%s\" authzid=\"%s\"\n",
675                 conn ? conn->c_connid : -1, auth_identity, requested_user );
676         if ( conn->c_sasl_dn.bv_val ) {
677                 ch_free( conn->c_sasl_dn.bv_val );
678                 BER_BVZERO( &conn->c_sasl_dn );
679         }
680
681         /* Skip SLAP_SASL_PROP_CONN */
682         prop_getnames( props, slap_propnames+1, auxvals );
683         
684         /* Should not happen */
685         if ( !auxvals[0].values ) {
686                 sasl_seterror( sconn, 0, "invalid authcid" );
687                 return SASL_NOAUTHZ;
688         }
689
690         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
691         conn->c_sasl_dn = authcDN;
692
693         /* Nothing to do if no authzID was given */
694         if ( !auxvals[1].name || !auxvals[1].values ) {
695                 goto ok;
696         }
697         
698         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
699
700         rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
701         if ( rc != LDAP_SUCCESS ) {
702                 Debug( LDAP_DEBUG_TRACE, "SASL Proxy Authorize [conn=%ld]: "
703                         "proxy authorization disallowed (%d)\n",
704                         (long) (conn ? conn->c_connid : -1), rc, 0 );
705
706                 sasl_seterror( sconn, 0, "not authorized" );
707                 ch_free( authzDN.bv_val );
708                 return SASL_NOAUTHZ;
709         }
710
711         /* FIXME: we need yet another dup because slap_sasl_getdn()
712          * is using the bind operation slab */
713         if ( conn->c_sasl_bindop ) {
714                 ber_dupbv( &conn->c_sasl_authz_dn, &authzDN );
715                 slap_sl_free( authzDN.bv_val,
716                                 conn->c_sasl_bindop->o_tmpmemctx );
717
718         } else {
719                 conn->c_sasl_authz_dn = authzDN;
720         }
721
722 ok:
723         if (conn->c_sasl_bindop) {
724                 Statslog( LDAP_DEBUG_STATS,
725                         "%s BIND authcid=\"%s\" authzid=\"%s\"\n",
726                         conn->c_sasl_bindop->o_log_prefix, 
727                         auth_identity, requested_user, 0, 0 );
728         }
729
730         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
731                 " proxy authorization allowed authzDN=\"%s\"\n",
732                 (long) (conn ? conn->c_connid : -1), 
733                 authzDN.bv_val ? authzDN.bv_val : "", 0 );
734         return SASL_OK;
735
736 #else
737 static int
738 slap_sasl_authorize(
739         void *context,
740         char *authcid,
741         char *authzid,
742         const char **user,
743         const char **errstr)
744 {
745         struct berval authcDN, authzDN = BER_BVNULL;
746         int rc;
747         Connection *conn = context;
748         char *realm;
749         struct berval   bvauthcid, bvauthzid;
750
751         *user = NULL;
752         if ( conn->c_sasl_dn.bv_val ) {
753                 ch_free( conn->c_sasl_dn.bv_val );
754                 BER_BVZERO( &conn->c_sasl_dn );
755         }
756
757         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
758                 "authcid=\"%s\" authzid=\"%s\"\n",
759                 (long) (conn ? conn->c_connid : -1),
760                 authcid ? authcid : "<empty>",
761                 authzid ? authzid : "<empty>" );
762
763         /* Figure out how much data we have for the dn */
764         rc = sasl_getprop( conn->c_sasl_authctx, SASL_REALM, (void **)&realm );
765         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
766                 Debug(LDAP_DEBUG_TRACE,
767                         "authorize: getprop(REALM) failed!\n", 0,0,0);
768                 *errstr = "Could not extract realm";
769                 return SASL_NOAUTHZ;
770         }
771
772         /* Convert the identities to DN's. If no authzid was given, client will
773            be bound as the DN matching their username */
774         bvauthcid.bv_val = authcid;
775         bvauthcid.bv_len = authcid ? strlen( authcid ) : 0;
776         rc = slap_sasl_getdn( conn, NULL, &bvauthcid, realm,
777                 &authcDN, SLAP_GETDN_AUTHCID );
778         if( rc != LDAP_SUCCESS ) {
779                 *errstr = ldap_err2string( rc );
780                 return SASL_NOAUTHZ;
781         }
782         conn->c_sasl_dn = authcDN;
783         if( ( authzid == NULL ) || !strcmp( authcid, authzid ) ) {
784                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
785                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
786
787                 goto ok;
788         }
789
790         bvauthzid.bv_val = authzid;
791         bvauthzid.bv_len = authzid ? strlen( authzid ) : 0;
792         rc = slap_sasl_getdn( conn, NULL, &bvauthzid, realm,
793                 &authzDN, SLAP_GETDN_AUTHZID );
794         if( rc != LDAP_SUCCESS ) {
795                 *errstr = ldap_err2string( rc );
796                 return SASL_NOAUTHZ;
797         }
798
799         rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
800         if( rc ) {
801                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
802                         "proxy authorization disallowed (%d)\n",
803                         (long) (conn ? conn->c_connid : -1), rc, 0 );
804
805                 *errstr = "not authorized";
806                 ch_free( authzDN.bv_val );
807                 return SASL_NOAUTHZ;
808         }
809
810         /* FIXME: we need yet another dup because slap_sasl_getdn()
811          * is using the bind operation slab */
812         if ( conn->c_sasl_bindop ) {
813                 ber_dupbv( &conn->c_sasl_authz_dn, &authzDN );
814                 slap_sl_free( authzDN.bv_val,
815                                 conn->c_sasl_bindop->o_tmpmemctx );
816
817         } else {
818                 conn->c_sasl_authz_dn = authzDN;
819         }
820
821 ok:
822         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
823                 " authorization allowed authzDN=\"%s\"\n",
824                 (long) (conn ? conn->c_connid : -1),
825                 authzDN.bv_val ? authzDN.bv_val : "", 0 );
826
827         if ( conn->c_sasl_bindop ) {
828                 Statslog( LDAP_DEBUG_STATS,
829                         "%s BIND authcid=\"%s\" authzid=\"%s\"\n",
830                         conn->c_sasl_bindop->o_log_prefix, 
831                         authcid, authzid ? authzid : "", 0, 0 );
832         }
833
834         *errstr = NULL;
835         return SASL_OK;
836 }
837 #endif /* SASL_VERSION_MAJOR >= 2 */
838
839 static int
840 slap_sasl_err2ldap( int saslerr )
841 {
842         int rc;
843
844         /* map SASL errors to LDAP resultCode returned by:
845          *      sasl_server_new()
846          *              SASL_OK, SASL_NOMEM
847          *      sasl_server_step()
848          *              SASL_OK, SASL_CONTINUE, SASL_TRANS, SASL_BADPARAM, SASL_BADPROT,
849          *      ...
850          *      sasl_server_start()
851          *      + SASL_NOMECH
852          *      sasl_setprop()
853          *              SASL_OK, SASL_BADPARAM
854          */
855
856         switch (saslerr) {
857                 case SASL_OK:
858                         rc = LDAP_SUCCESS;
859                         break;
860                 case SASL_CONTINUE:
861                         rc = LDAP_SASL_BIND_IN_PROGRESS;
862                         break;
863                 case SASL_FAIL:
864                 case SASL_NOMEM:
865                         rc = LDAP_OTHER;
866                         break;
867                 case SASL_NOMECH:
868                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
869                         break;
870                 case SASL_BADAUTH:
871                 case SASL_NOUSER:
872                 case SASL_TRANS:
873                 case SASL_EXPIRED:
874                         rc = LDAP_INVALID_CREDENTIALS;
875                         break;
876                 case SASL_NOAUTHZ:
877                         rc = LDAP_INSUFFICIENT_ACCESS;
878                         break;
879                 case SASL_TOOWEAK:
880                 case SASL_ENCRYPT:
881                         rc = LDAP_INAPPROPRIATE_AUTH;
882                         break;
883                 case SASL_UNAVAIL:
884                 case SASL_TRYAGAIN:
885                         rc = LDAP_UNAVAILABLE;
886                         break;
887                 case SASL_DISABLED:
888                         rc = LDAP_UNWILLING_TO_PERFORM;
889                         break;
890                 default:
891                         rc = LDAP_OTHER;
892                         break;
893         }
894
895         return rc;
896 }
897
898 #ifdef SLAPD_SPASSWD
899
900 static struct berval sasl_pwscheme = BER_BVC("{SASL}");
901
902 static int chk_sasl(
903         const struct berval *sc,
904         const struct berval * passwd,
905         const struct berval * cred,
906         const char **text )
907 {
908         unsigned int i;
909         int rtn;
910         void *ctx, *sconn = NULL;
911
912         for( i=0; i<cred->bv_len; i++) {
913                 if(cred->bv_val[i] == '\0') {
914                         return LUTIL_PASSWD_ERR;        /* NUL character in password */
915                 }
916         }
917
918         if( cred->bv_val[i] != '\0' ) {
919                 return LUTIL_PASSWD_ERR;        /* cred must behave like a string */
920         }
921
922         for( i=0; i<passwd->bv_len; i++) {
923                 if(passwd->bv_val[i] == '\0') {
924                         return LUTIL_PASSWD_ERR;        /* NUL character in password */
925                 }
926         }
927
928         if( passwd->bv_val[i] != '\0' ) {
929                 return LUTIL_PASSWD_ERR;        /* passwd must behave like a string */
930         }
931
932         rtn = LUTIL_PASSWD_ERR;
933
934         ctx = ldap_pvt_thread_pool_context();
935         ldap_pvt_thread_pool_getkey( ctx, slap_sasl_bind, &sconn, NULL );
936
937         if( sconn != NULL ) {
938                 int sc;
939 # if SASL_VERSION_MAJOR < 2
940                 sc = sasl_checkpass( sconn,
941                         passwd->bv_val, passwd->bv_len,
942                         cred->bv_val, cred->bv_len,
943                         text );
944 # else
945                 sc = sasl_checkpass( sconn,
946                         passwd->bv_val, passwd->bv_len,
947                         cred->bv_val, cred->bv_len );
948 # endif
949                 rtn = ( sc != SASL_OK ) ? LUTIL_PASSWD_ERR : LUTIL_PASSWD_OK;
950         }
951
952         return rtn;
953 }
954 #endif /* SLAPD_SPASSWD */
955
956 #endif /* HAVE_CYRUS_SASL */
957
958 #ifdef ENABLE_REWRITE
959
960 typedef struct slapd_map_data {
961         struct berval base;
962         struct berval filter;
963         AttributeName attrs[2];
964         int scope;
965 } slapd_map_data;
966
967 static void *
968 slapd_rw_config( const char *fname, int lineno, int argc, char **argv )
969 {
970         slapd_map_data *ret = NULL;
971         LDAPURLDesc *lud = NULL;
972         char *uri;
973         AttributeDescription *ad = NULL;
974         int rc, flen = 0;
975         struct berval dn, ndn;
976
977         if ( argc != 1 ) {
978                 Debug( LDAP_DEBUG_ANY,
979                         "[%s:%d] slapd map needs URI\n",
980                         fname, lineno, 0 );
981         return NULL;
982         }
983
984         uri = argv[0];
985         if ( strncasecmp( uri, "uri=", STRLENOF( "uri=" ) ) == 0 ) {
986                 uri += STRLENOF( "uri=" );
987         }
988
989         if ( ldap_url_parse( uri, &lud ) != LDAP_URL_SUCCESS ) {
990                 Debug( LDAP_DEBUG_ANY,
991                         "[%s:%d] illegal URI '%s'\n",
992                         fname, lineno, uri );
993         return NULL;
994         }
995
996         if ( strcasecmp( lud->lud_scheme, "ldap" )) {
997                 Debug( LDAP_DEBUG_ANY,
998                         "[%s:%d] illegal URI scheme '%s'\n",
999                         fname, lineno, lud->lud_scheme );
1000                 goto done;
1001         }
1002
1003         if (( lud->lud_host && lud->lud_host[0] ) || lud->lud_exts
1004                 || !lud->lud_dn ) {
1005                 Debug( LDAP_DEBUG_ANY,
1006                         "[%s:%d] illegal URI '%s'\n",
1007                         fname, lineno, uri );
1008                 goto done;
1009         }
1010
1011         if ( lud->lud_attrs ) {
1012                 if ( lud->lud_attrs[1] ) {
1013                         Debug( LDAP_DEBUG_ANY,
1014                                 "[%s:%d] only one attribute allowed in URI\n",
1015                                 fname, lineno, 0 );
1016                         goto done;
1017                 }
1018                 if ( strcasecmp( lud->lud_attrs[0], "dn" ) &&
1019                         strcasecmp( lud->lud_attrs[0], "entryDN" )) {
1020                         const char *text;
1021                         rc = slap_str2ad( lud->lud_attrs[0], &ad, &text );
1022                         if ( rc )
1023                                 goto done;
1024                 }
1025         }
1026         ber_str2bv( lud->lud_dn, 0, 0, &dn );
1027         if ( dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL ))
1028                 goto done;
1029
1030         if ( lud->lud_filter ) {
1031                 flen = strlen( lud->lud_filter ) + 1;
1032         }
1033         ret = ch_malloc( sizeof( slapd_map_data ) + flen );
1034         ret->base = ndn;
1035         if ( flen ) {
1036                 ret->filter.bv_val = (char *)(ret+1);
1037                 ret->filter.bv_len = flen - 1;
1038                 strcpy( ret->filter.bv_val, lud->lud_filter );
1039         } else {
1040                 BER_BVZERO( &ret->filter );
1041         }
1042         ret->scope = lud->lud_scope;
1043         if ( ad ) {
1044                 ret->attrs[0].an_name = ad->ad_cname;
1045         } else {
1046                 BER_BVZERO( &ret->attrs[0].an_name );
1047         }
1048         ret->attrs[0].an_desc = ad;
1049         BER_BVZERO( &ret->attrs[1].an_name );
1050 done:
1051         ldap_free_urldesc( lud );
1052         return ret;
1053 }
1054
1055 struct slapd_rw_info {
1056         slapd_map_data *si_data;
1057         struct berval si_val;
1058 };
1059
1060 static int
1061 slapd_rw_cb( Operation *op, SlapReply *rs )
1062 {
1063         if ( rs->sr_type == REP_SEARCH ) {
1064                 struct slapd_rw_info *si = op->o_callback->sc_private;
1065
1066                 if ( si->si_data->attrs[0].an_desc ) {
1067                         Attribute *a;
1068
1069                         a = attr_find( rs->sr_entry->e_attrs,
1070                                 si->si_data->attrs[0].an_desc );
1071                         if ( a ) {
1072                                 ber_dupbv( &si->si_val, a->a_vals );
1073                         }
1074                 } else {
1075                         ber_dupbv( &si->si_val, &rs->sr_entry->e_name );
1076                 }
1077         }
1078         return LDAP_SUCCESS;
1079 }
1080
1081 static int
1082 slapd_rw_apply( void *private, const char *filter, struct berval *val )
1083 {
1084         slapd_map_data *sl = private;
1085         slap_callback cb = { NULL };
1086         Connection conn = {0};
1087         OperationBuffer opbuf;
1088         Operation *op;
1089         void *thrctx;
1090         SlapReply rs = {REP_RESULT};
1091         struct slapd_rw_info si;
1092         char *ptr;
1093         int rc;
1094
1095         thrctx = ldap_pvt_thread_pool_context();
1096         connection_fake_init2( &conn, &opbuf, thrctx, 0 );
1097         op = &opbuf.ob_op;
1098
1099         op->o_tag = LDAP_REQ_SEARCH;
1100         op->o_req_dn = op->o_req_ndn = sl->base;
1101         op->o_bd = select_backend( &op->o_req_ndn, 1 );
1102         if ( !op->o_bd ) {
1103                 return REWRITE_ERR;
1104         }
1105         si.si_data = sl;
1106         BER_BVZERO( &si.si_val );
1107         op->ors_scope = sl->scope;
1108         op->ors_deref = LDAP_DEREF_NEVER;
1109         op->ors_slimit = 1;
1110         op->ors_tlimit = SLAP_NO_LIMIT;
1111         if ( sl->attrs[0].an_desc ) {
1112                 op->ors_attrs = sl->attrs;
1113         } else {
1114                 op->ors_attrs = slap_anlist_no_attrs;
1115         }
1116         if ( filter ) {
1117                 rc = strlen( filter );
1118         } else {
1119                 rc = 0;
1120         }
1121         rc += sl->filter.bv_len;
1122         ptr = op->ors_filterstr.bv_val = op->o_tmpalloc( rc + 1, op->o_tmpmemctx );
1123         if ( sl->filter.bv_len ) {
1124                 ptr = lutil_strcopy( ptr, sl->filter.bv_val );
1125         } else {
1126                 *ptr = '\0';
1127         }
1128         if ( filter ) {
1129                 strcpy( ptr, filter );
1130         }
1131         op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
1132         if ( !op->ors_filter ) {
1133                 op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1134                 return REWRITE_ERR;
1135         }
1136
1137         op->ors_attrsonly = 0;
1138         op->o_dn = op->o_bd->be_rootdn;
1139         op->o_ndn = op->o_bd->be_rootndn;
1140         op->o_do_not_cache = 1;
1141
1142         cb.sc_response = slapd_rw_cb;
1143         cb.sc_private = &si;
1144         op->o_callback = &cb;
1145
1146         rc = op->o_bd->be_search( op, &rs );
1147         if ( rc == LDAP_SUCCESS && !BER_BVISNULL( &si.si_val )) {
1148                 *val = si.si_val;
1149                 rc = REWRITE_SUCCESS;
1150         } else {
1151                 if ( !BER_BVISNULL( &si.si_val )) {
1152                         ch_free( si.si_val.bv_val );
1153                 }
1154                 rc = REWRITE_ERR;
1155         }
1156         filter_free_x( op, op->ors_filter );
1157         op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1158         return rc;
1159 }
1160
1161 static int
1162 slapd_rw_destroy( void *private )
1163 {
1164         slapd_map_data *md = private;
1165
1166         assert( private != NULL );
1167
1168         ch_free( md->base.bv_val );
1169         ch_free( md->filter.bv_val );
1170         ch_free( md );
1171
1172         return 0;
1173 }
1174
1175 static const rewrite_mapper slapd_mapper = {
1176         "slapd",
1177         slapd_rw_config,
1178         slapd_rw_apply,
1179         slapd_rw_destroy
1180 };
1181 #endif
1182
1183 int slap_sasl_init( void )
1184 {
1185 #ifdef HAVE_CYRUS_SASL
1186         int rc;
1187         static sasl_callback_t server_callbacks[] = {
1188                 { SASL_CB_LOG, &slap_sasl_log, NULL },
1189                 { SASL_CB_LIST_END, NULL, NULL }
1190         };
1191 #endif
1192
1193 #ifdef ENABLE_REWRITE
1194         rewrite_mapper_register( &slapd_mapper );
1195 #endif
1196
1197 #ifdef HAVE_CYRUS_SASL
1198 #ifdef HAVE_SASL_VERSION
1199         /* stringify the version number, sasl.h doesn't do it for us */
1200 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
1201 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
1202 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
1203                                 SASL_VERSION_STEP)
1204
1205         sasl_version( NULL, &rc );
1206         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1207                 (rc & 0xffff) < SASL_VERSION_STEP)
1208         {
1209                 char version[sizeof("xxx.xxx.xxxxx")];
1210                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
1211                         rc & 0xffff );
1212                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: SASL library version mismatch:"
1213                         " expected %s, got %s\n",
1214                         SASL_VERSION_STRING, version, 0 );
1215                 return -1;
1216         }
1217 #endif
1218
1219         /* SASL 2 does its own memory management internally */
1220 #if SASL_VERSION_MAJOR < 2
1221         sasl_set_alloc(
1222                 ber_memalloc,
1223                 ber_memcalloc,
1224                 ber_memrealloc,
1225                 ber_memfree ); 
1226 #endif
1227
1228         sasl_set_mutex(
1229                 ldap_pvt_sasl_mutex_new,
1230                 ldap_pvt_sasl_mutex_lock,
1231                 ldap_pvt_sasl_mutex_unlock,
1232                 ldap_pvt_sasl_mutex_dispose );
1233
1234 #if SASL_VERSION_MAJOR >= 2
1235         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1236
1237         rc = sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1238         if( rc != SASL_OK ) {
1239                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: auxprop add plugin failed\n",
1240                         0, 0, 0 );
1241                 return -1;
1242         }
1243 #endif
1244         /* should provide callbacks for logging */
1245         /* server name should be configurable */
1246         rc = sasl_server_init( server_callbacks, "slapd" );
1247
1248         if( rc != SASL_OK ) {
1249                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: server init failed\n",
1250                         0, 0, 0 );
1251 #if SASL_VERSION_MAJOR < 2
1252                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1253                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1254 #endif
1255
1256                 return -1;
1257         }
1258
1259 #ifdef SLAPD_SPASSWD
1260         lutil_passwd_add( &sasl_pwscheme, chk_sasl, NULL );
1261 #endif
1262
1263         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1264                 0, 0, 0 );
1265
1266         /* default security properties */
1267         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1268         sasl_secprops.max_ssf = INT_MAX;
1269         sasl_secprops.maxbufsize = 65536;
1270         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1271 #endif
1272
1273         return 0;
1274 }
1275
1276 int slap_sasl_destroy( void )
1277 {
1278 #ifdef HAVE_CYRUS_SASL
1279         sasl_done();
1280 #endif
1281         free( global_host );
1282         global_host = NULL;
1283
1284         return 0;
1285 }
1286
1287 #if SASL_VERSION_MAJOR >= 2
1288 static char *
1289 slap_sasl_peer2ipport( struct berval *peer )
1290 {
1291         int             isv6 = 0;
1292         char            *ipport, *p,
1293                         *addr = &peer->bv_val[ STRLENOF( "IP=" ) ];
1294         ber_len_t       plen = peer->bv_len - STRLENOF( "IP=" );
1295
1296         /* IPv6? */
1297         if ( addr[0] == '[' ) {
1298                 isv6 = 1;
1299                 plen--;
1300         }
1301         ipport = ch_strdup( &addr[isv6] );
1302
1303         /* Convert IPv6/IPv4 addresses to address;port syntax. */
1304         p = strrchr( ipport, ':' );
1305         if ( p != NULL ) {
1306                 *p = ';';
1307                 if ( isv6 ) {
1308                         assert( p[-1] == ']' );
1309                         AC_MEMCPY( &p[-1], p, plen - ( p - ipport ) + 1 );
1310                 }
1311
1312         } else if ( isv6 ) {
1313                 /* trim ']' */
1314                 plen--;
1315                 assert( addr[plen] == ']' );
1316                 addr[plen] = '\0';
1317         }
1318
1319         return ipport;
1320 }
1321 #endif
1322
1323 int slap_sasl_open( Connection *conn, int reopen )
1324 {
1325         int sc = LDAP_SUCCESS;
1326 #ifdef HAVE_CYRUS_SASL
1327         int cb;
1328
1329         sasl_conn_t *ctx = NULL;
1330         sasl_callback_t *session_callbacks;
1331
1332 #if SASL_VERSION_MAJOR >= 2
1333         char *ipremoteport = NULL, *iplocalport = NULL;
1334 #endif
1335
1336         assert( conn->c_sasl_authctx == NULL );
1337
1338         if ( !reopen ) {
1339                 assert( conn->c_sasl_extra == NULL );
1340
1341                 session_callbacks =
1342 #if SASL_VERSION_MAJOR >= 2
1343                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1344 #else
1345                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1346 #endif
1347                 if( session_callbacks == NULL ) {
1348                         Debug( LDAP_DEBUG_ANY, 
1349                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1350                         return -1;
1351                 }
1352                 conn->c_sasl_extra = session_callbacks;
1353
1354                 session_callbacks[cb=0].id = SASL_CB_LOG;
1355                 session_callbacks[cb].proc = &slap_sasl_log;
1356                 session_callbacks[cb++].context = conn;
1357
1358                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1359                 session_callbacks[cb].proc = &slap_sasl_authorize;
1360                 session_callbacks[cb++].context = conn;
1361
1362 #if SASL_VERSION_MAJOR >= 2
1363                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1364                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1365                 session_callbacks[cb++].context = conn;
1366 #endif
1367
1368                 session_callbacks[cb].id = SASL_CB_LIST_END;
1369                 session_callbacks[cb].proc = NULL;
1370                 session_callbacks[cb++].context = NULL;
1371         } else {
1372                 session_callbacks = conn->c_sasl_extra;
1373         }
1374
1375         conn->c_sasl_layers = 0;
1376
1377         /* create new SASL context */
1378 #if SASL_VERSION_MAJOR >= 2
1379         if ( conn->c_sock_name.bv_len != 0 &&
1380                 strncmp( conn->c_sock_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1381         {
1382                 iplocalport = slap_sasl_peer2ipport( &conn->c_sock_name );
1383         }
1384
1385         if ( conn->c_peer_name.bv_len != 0 &&
1386                 strncmp( conn->c_peer_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1387         {
1388                 ipremoteport = slap_sasl_peer2ipport( &conn->c_peer_name );
1389         }
1390
1391         sc = sasl_server_new( "ldap", global_host, global_realm,
1392                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1393         if ( iplocalport != NULL ) {
1394                 ch_free( iplocalport );
1395         }
1396         if ( ipremoteport != NULL ) {
1397                 ch_free( ipremoteport );
1398         }
1399 #else
1400         sc = sasl_server_new( "ldap", global_host, global_realm,
1401                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1402 #endif
1403
1404         if( sc != SASL_OK ) {
1405                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1406                         sc, 0, 0 );
1407
1408                 return -1;
1409         }
1410
1411         conn->c_sasl_authctx = ctx;
1412
1413         if( sc == SASL_OK ) {
1414                 sc = sasl_setprop( ctx,
1415                         SASL_SEC_PROPS, &sasl_secprops );
1416
1417                 if( sc != SASL_OK ) {
1418                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1419                                 sc, 0, 0 );
1420
1421                         slap_sasl_close( conn );
1422                         return -1;
1423                 }
1424         }
1425
1426         sc = slap_sasl_err2ldap( sc );
1427
1428 #elif defined(SLAP_BUILTIN_SASL)
1429         /* built-in SASL implementation */
1430         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1431         if( ctx == NULL ) return -1;
1432
1433         ctx->sc_external_ssf = 0;
1434         BER_BVZERO( &ctx->sc_external_id );
1435
1436         conn->c_sasl_authctx = ctx;
1437 #endif
1438
1439         return sc;
1440 }
1441
1442 int slap_sasl_external(
1443         Connection *conn,
1444         slap_ssf_t ssf,
1445         struct berval *auth_id )
1446 {
1447 #if SASL_VERSION_MAJOR >= 2
1448         int sc;
1449         sasl_conn_t *ctx = conn->c_sasl_authctx;
1450
1451         if ( ctx == NULL ) {
1452                 return LDAP_UNAVAILABLE;
1453         }
1454
1455         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1456
1457         if ( sc != SASL_OK ) {
1458                 return LDAP_OTHER;
1459         }
1460
1461         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1462                 auth_id ? auth_id->bv_val : NULL );
1463
1464         if ( sc != SASL_OK ) {
1465                 return LDAP_OTHER;
1466         }
1467
1468 #elif defined(HAVE_CYRUS_SASL)
1469         int sc;
1470         sasl_conn_t *ctx = conn->c_sasl_authctx;
1471         sasl_external_properties_t extprops;
1472
1473         if ( ctx == NULL ) {
1474                 return LDAP_UNAVAILABLE;
1475         }
1476
1477         memset( &extprops, '\0', sizeof(extprops) );
1478         extprops.ssf = ssf;
1479         extprops.auth_id = auth_id ? auth_id->bv_val : NULL;
1480
1481         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1482                 (void *) &extprops );
1483
1484         if ( sc != SASL_OK ) {
1485                 return LDAP_OTHER;
1486         }
1487 #elif defined(SLAP_BUILTIN_SASL)
1488         /* built-in SASL implementation */
1489         SASL_CTX *ctx = conn->c_sasl_authctx;
1490         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1491
1492         ctx->sc_external_ssf = ssf;
1493         if( auth_id ) {
1494                 ctx->sc_external_id = *auth_id;
1495                 BER_BVZERO( auth_id );
1496         } else {
1497                 BER_BVZERO( &ctx->sc_external_id );
1498         }
1499 #endif
1500
1501         return LDAP_SUCCESS;
1502 }
1503
1504 int slap_sasl_reset( Connection *conn )
1505 {
1506         return LDAP_SUCCESS;
1507 }
1508
1509 char ** slap_sasl_mechs( Connection *conn )
1510 {
1511         char **mechs = NULL;
1512
1513 #ifdef HAVE_CYRUS_SASL
1514         sasl_conn_t *ctx = conn->c_sasl_authctx;
1515
1516         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1517
1518         if( ctx != NULL ) {
1519                 int sc;
1520                 SASL_CONST char *mechstr;
1521
1522                 sc = sasl_listmech( ctx,
1523                         NULL, NULL, ",", NULL,
1524                         &mechstr, NULL, NULL );
1525
1526                 if( sc != SASL_OK ) {
1527                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1528                                 sc, 0, 0 );
1529
1530                         return NULL;
1531                 }
1532
1533                 mechs = ldap_str2charray( mechstr, "," );
1534
1535 #if SASL_VERSION_MAJOR < 2
1536                 ch_free( mechstr );
1537 #endif
1538         }
1539 #elif defined(SLAP_BUILTIN_SASL)
1540         /* builtin SASL implementation */
1541         SASL_CTX *ctx = conn->c_sasl_authctx;
1542         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1543                 /* should check ssf */
1544                 mechs = ldap_str2charray( "EXTERNAL", "," );
1545         }
1546 #endif
1547
1548         return mechs;
1549 }
1550
1551 int slap_sasl_close( Connection *conn )
1552 {
1553 #ifdef HAVE_CYRUS_SASL
1554         sasl_conn_t *ctx = conn->c_sasl_authctx;
1555
1556         if( ctx != NULL ) {
1557                 sasl_dispose( &ctx );
1558         }
1559         if ( conn->c_sasl_sockctx &&
1560                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1561         {
1562                 ctx = conn->c_sasl_sockctx;
1563                 sasl_dispose( &ctx );
1564         }
1565
1566         conn->c_sasl_authctx = NULL;
1567         conn->c_sasl_sockctx = NULL;
1568         conn->c_sasl_done = 0;
1569
1570         free( conn->c_sasl_extra );
1571         conn->c_sasl_extra = NULL;
1572
1573 #elif defined(SLAP_BUILTIN_SASL)
1574         SASL_CTX *ctx = conn->c_sasl_authctx;
1575         if( ctx ) {
1576                 if( ctx->sc_external_id.bv_val ) {
1577                         free( ctx->sc_external_id.bv_val );
1578                         BER_BVZERO( &ctx->sc_external_id );
1579                 }
1580                 free( ctx );
1581                 conn->c_sasl_authctx = NULL;
1582         }
1583 #endif
1584
1585         return LDAP_SUCCESS;
1586 }
1587
1588 int slap_sasl_bind( Operation *op, SlapReply *rs )
1589 {
1590 #ifdef HAVE_CYRUS_SASL
1591         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1592         struct berval response;
1593         unsigned reslen = 0;
1594         int sc;
1595
1596         Debug(LDAP_DEBUG_ARGS,
1597                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1598                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1599                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1600                 op->o_conn->c_sasl_bind_mech.bv_val,
1601                 op->orb_cred.bv_len );
1602
1603         if( ctx == NULL ) {
1604                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1605                         "SASL unavailable on this session" );
1606                 return rs->sr_err;
1607         }
1608
1609 #if SASL_VERSION_MAJOR >= 2
1610 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1611         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1612 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1613         sasl_server_step( ctx, cred, clen, resp, rlen )
1614 #else
1615 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1616         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1617 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1618         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1619 #endif
1620
1621         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1622                 /* If we already authenticated once, must use a new context */
1623                 if ( op->o_conn->c_sasl_done ) {
1624                         slap_ssf_t ssf = 0;
1625                         const char *authid = NULL;
1626 #if SASL_VERSION_MAJOR >= 2
1627                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1628                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1629                         if ( authid ) authid = ch_strdup( authid );
1630 #endif
1631                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1632                                 sasl_dispose( &ctx );
1633                         }
1634                         op->o_conn->c_sasl_authctx = NULL;
1635                                 
1636                         slap_sasl_open( op->o_conn, 1 );
1637                         ctx = op->o_conn->c_sasl_authctx;
1638 #if SASL_VERSION_MAJOR >= 2
1639                         if ( authid ) {
1640                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1641                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1642                                 ch_free( (char *)authid );
1643                         }
1644 #endif
1645                 }
1646                 sc = START( ctx,
1647                         op->o_conn->c_sasl_bind_mech.bv_val,
1648                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1649                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1650
1651         } else {
1652                 sc = STEP( ctx,
1653                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1654                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1655         }
1656
1657         response.bv_len = reslen;
1658
1659         if ( sc == SASL_OK ) {
1660                 sasl_ssf_t *ssf = NULL;
1661
1662                 op->orb_edn = op->o_conn->c_sasl_dn;
1663                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1664                 op->o_conn->c_sasl_done = 1;
1665
1666                 rs->sr_err = LDAP_SUCCESS;
1667
1668                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1669                 op->orb_ssf = ssf ? *ssf : 0;
1670
1671                 ctx = NULL;
1672                 if( op->orb_ssf ) {
1673                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1674                         op->o_conn->c_sasl_layers++;
1675
1676                         /* If there's an old layer, set sockctx to NULL to
1677                          * tell connection_read() to wait for us to finish.
1678                          * Otherwise there is a race condition: we have to
1679                          * send the Bind response using the old security
1680                          * context and then remove it before reading any
1681                          * new messages.
1682                          */
1683                         if ( op->o_conn->c_sasl_sockctx ) {
1684                                 ctx = op->o_conn->c_sasl_sockctx;
1685                                 op->o_conn->c_sasl_sockctx = NULL;
1686                         } else {
1687                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1688                         }
1689                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1690                 }
1691
1692                 /* Must send response using old security layer */
1693                 if (response.bv_len) rs->sr_sasldata = &response;
1694                 send_ldap_sasl( op, rs );
1695                 
1696                 /* Now dispose of the old security layer.
1697                  */
1698                 if ( ctx ) {
1699                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1700                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1701                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1702                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1703                         sasl_dispose( &ctx );
1704                 }
1705         } else if ( sc == SASL_CONTINUE ) {
1706                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1707 #if SASL_VERSION_MAJOR >= 2
1708                 rs->sr_text = sasl_errdetail( ctx );
1709 #endif
1710                 rs->sr_sasldata = &response;
1711                 send_ldap_sasl( op, rs );
1712
1713         } else {
1714                 if ( op->o_conn->c_sasl_dn.bv_len )
1715                         ch_free( op->o_conn->c_sasl_dn.bv_val );
1716                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1717 #if SASL_VERSION_MAJOR >= 2
1718                 rs->sr_text = sasl_errdetail( ctx );
1719 #endif
1720                 rs->sr_err = slap_sasl_err2ldap( sc ),
1721                 send_ldap_result( op, rs );
1722         }
1723
1724 #if SASL_VERSION_MAJOR < 2
1725         if( response.bv_len ) ch_free( response.bv_val );
1726 #endif
1727
1728         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1729
1730 #elif defined(SLAP_BUILTIN_SASL)
1731         /* built-in SASL implementation */
1732         SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1733
1734         if ( ctx == NULL ) {
1735                 send_ldap_error( op, rs, LDAP_OTHER,
1736                         "Internal SASL Error" );
1737
1738         } else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1739                 /* EXTERNAL */
1740
1741                 if( op->orb_cred.bv_len ) {
1742                         rs->sr_text = "proxy authorization not support";
1743                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1744                         send_ldap_result( op, rs );
1745
1746                 } else {
1747                         op->orb_edn = ctx->sc_external_id;
1748                         rs->sr_err = LDAP_SUCCESS;
1749                         rs->sr_sasldata = NULL;
1750                         send_ldap_sasl( op, rs );
1751                 }
1752
1753         } else {
1754                 send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1755                         "requested SASL mechanism not supported" );
1756         }
1757 #else
1758         send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1759                 "SASL not supported" );
1760 #endif
1761
1762         return rs->sr_err;
1763 }
1764
1765 char* slap_sasl_secprops( const char *in )
1766 {
1767 #ifdef HAVE_CYRUS_SASL
1768         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1769
1770         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1771 #else
1772         return "SASL not supported";
1773 #endif
1774 }
1775
1776 void slap_sasl_secprops_unparse( struct berval *bv )
1777 {
1778 #ifdef HAVE_CYRUS_SASL
1779         ldap_pvt_sasl_secprops_unparse( &sasl_secprops, bv );
1780 #endif
1781 }
1782
1783 #ifdef HAVE_CYRUS_SASL
1784 int
1785 slap_sasl_setpass( Operation *op, SlapReply *rs )
1786 {
1787         struct berval id = BER_BVNULL;  /* needs to come from connection */
1788         struct berval new = BER_BVNULL;
1789         struct berval old = BER_BVNULL;
1790
1791         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1792
1793         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1794                 (SASL_CONST void **)(char *)&id.bv_val );
1795
1796         if( rs->sr_err != SASL_OK ) {
1797                 rs->sr_text = "unable to retrieve SASL username";
1798                 rs->sr_err = LDAP_OTHER;
1799                 goto done;
1800         }
1801
1802         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1803                 id.bv_val ? id.bv_val : "", 0, 0 );
1804
1805         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1806                 NULL, &old, &new, &rs->sr_text );
1807
1808         if( rs->sr_err != LDAP_SUCCESS ) {
1809                 goto done;
1810         }
1811
1812         if( new.bv_len == 0 ) {
1813                 slap_passwd_generate(&new);
1814
1815                 if( new.bv_len == 0 ) {
1816                         rs->sr_text = "password generation failed.";
1817                         rs->sr_err = LDAP_OTHER;
1818                         goto done;
1819                 }
1820                 
1821                 rs->sr_rspdata = slap_passwd_return( &new );
1822         }
1823
1824 #if SASL_VERSION_MAJOR < 2
1825         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx,
1826                 id.bv_val, new.bv_val, new.bv_len, 0, &rs->sr_text );
1827 #else
1828         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1829                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1830         if( rs->sr_err != SASL_OK ) {
1831                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1832         }
1833 #endif
1834         switch(rs->sr_err) {
1835                 case SASL_OK:
1836                         rs->sr_err = LDAP_SUCCESS;
1837                         break;
1838
1839                 case SASL_NOCHANGE:
1840                 case SASL_NOMECH:
1841                 case SASL_DISABLED:
1842                 case SASL_PWLOCK:
1843                 case SASL_FAIL:
1844                 case SASL_BADPARAM:
1845                 default:
1846                         rs->sr_err = LDAP_OTHER;
1847         }
1848
1849 done:
1850         return rs->sr_err;
1851 }
1852 #endif /* HAVE_CYRUS_SASL */
1853
1854 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1855  * string returned in *dn is in its own allocated memory, and must be free'd 
1856  * by the calling process.  -Mark Adamson, Carnegie Mellon
1857  *
1858  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1859  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1860  */
1861
1862 #define SET_NONE        0
1863 #define SET_DN          1
1864 #define SET_U           2
1865
1866 int slap_sasl_getdn( Connection *conn, Operation *op, struct berval *id,
1867         char *user_realm, struct berval *dn, int flags )
1868 {
1869         int rc, is_dn = SET_NONE, do_norm = 1;
1870         struct berval dn2, *mech;
1871
1872         assert( conn != NULL );
1873         assert( id != NULL );
1874
1875         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: conn %lu id=%s [len=%lu]\n", 
1876                 conn->c_connid,
1877                 BER_BVISNULL( id ) ? "NULL" : ( BER_BVISEMPTY( id ) ? "<empty>" : id->bv_val ),
1878                 BER_BVISNULL( id ) ? 0 : ( BER_BVISEMPTY( id ) ? 0 :
1879                                            (unsigned long) id->bv_len ) );
1880
1881         if ( !op ) {
1882                 op = conn->c_sasl_bindop;
1883         }
1884         assert( op != NULL );
1885
1886         BER_BVZERO( dn );
1887
1888         if ( !BER_BVISNULL( id ) ) {
1889                 /* Blatantly anonymous ID */
1890                 static struct berval bv_anonymous = BER_BVC( "anonymous" );
1891
1892                 if ( ber_bvstrcasecmp( id, &bv_anonymous ) == 0 ) {
1893                         return( LDAP_SUCCESS );
1894                 }
1895
1896         } else {
1897                 /* FIXME: if empty, should we stop? */
1898                 BER_BVSTR( id, "" );
1899         }
1900
1901         if ( !BER_BVISEMPTY( &conn->c_sasl_bind_mech ) ) {
1902                 mech = &conn->c_sasl_bind_mech;
1903         } else {
1904                 mech = &conn->c_authmech;
1905         }
1906
1907         /* An authcID needs to be converted to authzID form. Set the
1908          * values directly into *dn; they will be normalized later. (and
1909          * normalizing always makes a new copy.) An ID from a TLS certificate
1910          * is already normalized, so copy it and skip normalization.
1911          */
1912         if( flags & SLAP_GETDN_AUTHCID ) {
1913                 if( bvmatch( mech, &ext_bv )) {
1914                         /* EXTERNAL DNs are already normalized */
1915                         assert( !BER_BVISNULL( id ) );
1916
1917                         do_norm = 0;
1918                         is_dn = SET_DN;
1919                         ber_dupbv_x( dn, id, op->o_tmpmemctx );
1920
1921                 } else {
1922                         /* convert to u:<username> form */
1923                         is_dn = SET_U;
1924                         *dn = *id;
1925                 }
1926         }
1927
1928         if( is_dn == SET_NONE ) {
1929                 if( !strncasecmp( id->bv_val, "u:", STRLENOF( "u:" ) ) ) {
1930                         is_dn = SET_U;
1931                         dn->bv_val = id->bv_val + STRLENOF( "u:" );
1932                         dn->bv_len = id->bv_len - STRLENOF( "u:" );
1933
1934                 } else if ( !strncasecmp( id->bv_val, "dn:", STRLENOF( "dn:" ) ) ) {
1935                         is_dn = SET_DN;
1936                         dn->bv_val = id->bv_val + STRLENOF( "dn:" );
1937                         dn->bv_len = id->bv_len - STRLENOF( "dn:" );
1938                 }
1939         }
1940
1941         /* No other possibilities from here */
1942         if( is_dn == SET_NONE ) {
1943                 BER_BVZERO( dn );
1944                 return( LDAP_INAPPROPRIATE_AUTH );
1945         }
1946
1947         /* Username strings */
1948         if( is_dn == SET_U ) {
1949                 /* ITS#3419: values may need escape */
1950                 LDAPRDN         DN[ 5 ];
1951                 LDAPAVA         *RDNs[ 4 ][ 2 ];
1952                 LDAPAVA         AVAs[ 4 ];
1953                 int             irdn;
1954
1955                 irdn = 0;
1956                 DN[ irdn ] = RDNs[ irdn ];
1957                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1958                 AVAs[ irdn ].la_attr = slap_schema.si_ad_uid->ad_cname;
1959                 AVAs[ irdn ].la_value = *dn;
1960                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1961                 AVAs[ irdn ].la_private = NULL;
1962                 RDNs[ irdn ][ 1 ] = NULL;
1963
1964                 if ( user_realm && *user_realm ) {
1965                         irdn++;
1966                         DN[ irdn ] = RDNs[ irdn ];
1967                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1968                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1969                         ber_str2bv( user_realm, 0, 0, &AVAs[ irdn ].la_value );
1970                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1971                         AVAs[ irdn ].la_private = NULL;
1972                         RDNs[ irdn ][ 1 ] = NULL;
1973                 }
1974
1975                 if ( !BER_BVISNULL( mech ) ) {
1976                         irdn++;
1977                         DN[ irdn ] = RDNs[ irdn ];
1978                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1979                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1980                         AVAs[ irdn ].la_value = *mech;
1981                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1982                         AVAs[ irdn ].la_private = NULL;
1983                         RDNs[ irdn ][ 1 ] = NULL;
1984                 }
1985
1986                 irdn++;
1987                 DN[ irdn ] = RDNs[ irdn ];
1988                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1989                 AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1990                 BER_BVSTR( &AVAs[ irdn ].la_value, "auth" );
1991                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1992                 AVAs[ irdn ].la_private = NULL;
1993                 RDNs[ irdn ][ 1 ] = NULL;
1994
1995                 irdn++;
1996                 DN[ irdn ] = NULL;
1997
1998                 rc = ldap_dn2bv_x( DN, dn, LDAP_DN_FORMAT_LDAPV3,
1999                                 op->o_tmpmemctx );
2000                 if ( rc != LDAP_SUCCESS ) {
2001                         BER_BVZERO( dn );
2002                         return rc;
2003                 }
2004
2005                 Debug( LDAP_DEBUG_TRACE,
2006                         "slap_sasl_getdn: u:id converted to %s\n",
2007                         dn->bv_val, 0, 0 );
2008
2009         } else {
2010                 
2011                 /* Dup the DN in any case, so we don't risk 
2012                  * leaks or dangling pointers later,
2013                  * and the DN value is '\0' terminated */
2014                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
2015                 dn->bv_val = dn2.bv_val;
2016         }
2017
2018         /* All strings are in DN form now. Normalize if needed. */
2019         if ( do_norm ) {
2020                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
2021
2022                 /* User DNs were constructed above and must be freed now */
2023                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
2024
2025                 if ( rc != LDAP_SUCCESS ) {
2026                         BER_BVZERO( dn );
2027                         return rc;
2028                 }
2029                 *dn = dn2;
2030         }
2031
2032         /* Run thru regexp */
2033         slap_sasl2dn( op, dn, &dn2, flags );
2034         if( !BER_BVISNULL( &dn2 ) ) {
2035                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
2036                 *dn = dn2;
2037                 Debug( LDAP_DEBUG_TRACE,
2038                         "slap_sasl_getdn: dn:id converted to %s\n",
2039                         dn->bv_val, 0, 0 );
2040         }
2041
2042         return( LDAP_SUCCESS );
2043 }