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