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