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