]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
6051a506eb8bd8f6097a29085454dd546f6a33cd
[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         conn->c_sasl_authz_dn = authzDN;
658 ok:
659         if (conn->c_sasl_bindop) {
660                 Statslog( LDAP_DEBUG_STATS,
661                         "conn=%lu op=%lu BIND authcid=\"%s\" authzid=\"%s\"\n",
662                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
663                         auth_identity, requested_user, 0);
664         }
665
666         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
667                 " proxy authorization allowed authzDN=\"%s\"\n",
668                 (long) (conn ? conn->c_connid : -1), 
669                 authzDN.bv_val ? authzDN.bv_val : "", 0 );
670         return SASL_OK;
671
672 #else
673 static int
674 slap_sasl_authorize(
675         void *context,
676         char *authcid,
677         char *authzid,
678         const char **user,
679         const char **errstr)
680 {
681         struct berval authcDN, authzDN;
682         int rc;
683         Connection *conn = context;
684         char *realm;
685         struct berval   bvauthcid, bvauthzid;
686
687         *user = NULL;
688         if ( conn->c_sasl_dn.bv_val ) {
689                 ch_free( conn->c_sasl_dn.bv_val );
690                 BER_BVZERO( &conn->c_sasl_dn );
691         }
692
693         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
694                 "authcid=\"%s\" authzid=\"%s\"\n",
695                 (long) (conn ? conn->c_connid : -1),
696                 authcid ? authcid : "<empty>",
697                 authzid ? authzid : "<empty>" );
698
699         /* Figure out how much data we have for the dn */
700         rc = sasl_getprop( conn->c_sasl_authctx, SASL_REALM, (void **)&realm );
701         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
702                 Debug(LDAP_DEBUG_TRACE,
703                         "authorize: getprop(REALM) failed!\n", 0,0,0);
704                 *errstr = "Could not extract realm";
705                 return SASL_NOAUTHZ;
706         }
707
708         /* Convert the identities to DN's. If no authzid was given, client will
709            be bound as the DN matching their username */
710         bvauthcid.bv_val = authcid;
711         bvauthcid.bv_len = authcid ? strlen( authcid ) : 0;
712         rc = slap_sasl_getdn( conn, NULL, &bvauthcid, realm,
713                 &authcDN, SLAP_GETDN_AUTHCID );
714         if( rc != LDAP_SUCCESS ) {
715                 *errstr = ldap_err2string( rc );
716                 return SASL_NOAUTHZ;
717         }
718         conn->c_sasl_dn = authcDN;
719         if( ( authzid == NULL ) || !strcmp( authcid, authzid ) ) {
720                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
721                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
722
723                 goto ok;
724         }
725
726         bvauthzid.bv_val = authzid;
727         bvauthzid.bv_len = authzid ? strlen( authzid ) : 0;
728         rc = slap_sasl_getdn( conn, NULL, &bvauthzid, realm,
729                 &authzDN, SLAP_GETDN_AUTHZID );
730         if( rc != LDAP_SUCCESS ) {
731                 *errstr = ldap_err2string( rc );
732                 return SASL_NOAUTHZ;
733         }
734
735         rc = slap_sasl_authorized(conn->c_sasl_bindop, &authcDN, &authzDN );
736         if( rc ) {
737                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
738                         "proxy authorization disallowed (%d)\n",
739                         (long) (conn ? conn->c_connid : -1), rc, 0 );
740
741                 *errstr = "not authorized";
742                 ch_free( authzDN.bv_val );
743                 return SASL_NOAUTHZ;
744         }
745         conn->c_sasl_authz_dn = authzDN;
746
747 ok:
748         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
749                 " authorization allowed authzDN=\"%s\"\n",
750                 (long) (conn ? conn->c_connid : -1),
751                 authzDN.bv_val ? authzDN.bv_val : "", 0 );
752
753         if (conn->c_sasl_bindop) {
754                 Statslog( LDAP_DEBUG_STATS,
755                         "conn=%lu op=%lu BIND authcid=\"%s\" authzid=\"%s\"\n",
756                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
757                         authcid, authzid ? authzid : "", 0);
758         }
759
760         *errstr = NULL;
761         return SASL_OK;
762 }
763 #endif /* SASL_VERSION_MAJOR >= 2 */
764
765 static int
766 slap_sasl_err2ldap( int saslerr )
767 {
768         int rc;
769
770         switch (saslerr) {
771                 case SASL_OK:
772                         rc = LDAP_SUCCESS;
773                         break;
774                 case SASL_CONTINUE:
775                         rc = LDAP_SASL_BIND_IN_PROGRESS;
776                         break;
777                 case SASL_FAIL:
778                         rc = LDAP_OTHER;
779                         break;
780                 case SASL_NOMEM:
781                         rc = LDAP_OTHER;
782                         break;
783                 case SASL_NOMECH:
784                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
785                         break;
786                 case SASL_BADAUTH:
787                         rc = LDAP_INVALID_CREDENTIALS;
788                         break;
789                 case SASL_NOAUTHZ:
790                         rc = LDAP_INSUFFICIENT_ACCESS;
791                         break;
792                 case SASL_TOOWEAK:
793                 case SASL_ENCRYPT:
794                         rc = LDAP_INAPPROPRIATE_AUTH;
795                         break;
796                 default:
797                         rc = LDAP_OTHER;
798                         break;
799         }
800
801         return rc;
802 }
803
804 #ifdef SLAPD_SPASSWD
805
806 static struct berval sasl_pwscheme = BER_BVC("{SASL}");
807
808 static int chk_sasl(
809         const struct berval *sc,
810         const struct berval * passwd,
811         const struct berval * cred,
812         const char **text )
813 {
814         unsigned int i;
815         int rtn;
816         void *ctx, *sconn = NULL;
817
818         for( i=0; i<cred->bv_len; i++) {
819                 if(cred->bv_val[i] == '\0') {
820                         return LUTIL_PASSWD_ERR;        /* NUL character in password */
821                 }
822         }
823
824         if( cred->bv_val[i] != '\0' ) {
825                 return LUTIL_PASSWD_ERR;        /* cred must behave like a string */
826         }
827
828         for( i=0; i<passwd->bv_len; i++) {
829                 if(passwd->bv_val[i] == '\0') {
830                         return LUTIL_PASSWD_ERR;        /* NUL character in password */
831                 }
832         }
833
834         if( passwd->bv_val[i] != '\0' ) {
835                 return LUTIL_PASSWD_ERR;        /* passwd must behave like a string */
836         }
837
838         rtn = LUTIL_PASSWD_ERR;
839
840         ctx = ldap_pvt_thread_pool_context();
841         ldap_pvt_thread_pool_getkey( ctx, slap_sasl_bind, &sconn, NULL );
842
843         if( sconn != NULL ) {
844                 int sc;
845 # if SASL_VERSION_MAJOR < 2
846                 sc = sasl_checkpass( sconn,
847                         passwd->bv_val, passwd->bv_len,
848                         cred->bv_val, cred->bv_len,
849                         text );
850 # else
851                 sc = sasl_checkpass( sconn,
852                         passwd->bv_val, passwd->bv_len,
853                         cred->bv_val, cred->bv_len );
854 # endif
855                 rtn = ( sc != SASL_OK ) ? LUTIL_PASSWD_ERR : LUTIL_PASSWD_OK;
856         }
857
858         return rtn;
859 }
860 #endif /* SLAPD_SPASSWD */
861
862 #endif /* HAVE_CYRUS_SASL */
863
864 int slap_sasl_init( void )
865 {
866 #ifdef HAVE_CYRUS_SASL
867         int rc;
868         static sasl_callback_t server_callbacks[] = {
869                 { SASL_CB_LOG, &slap_sasl_log, NULL },
870                 { SASL_CB_LIST_END, NULL, NULL }
871         };
872
873 #ifdef HAVE_SASL_VERSION
874         /* stringify the version number, sasl.h doesn't do it for us */
875 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
876 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
877 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
878                                 SASL_VERSION_STEP)
879
880         sasl_version( NULL, &rc );
881         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
882                 (rc & 0xffff) < SASL_VERSION_STEP)
883         {
884                 char version[sizeof("xxx.xxx.xxxxx")];
885                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
886                         rc & 0xffff );
887                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: SASL library version mismatch:"
888                         " expected " SASL_VERSION_STRING ","
889                         " got %s\n", version, 0, 0 );
890                 return -1;
891         }
892 #endif
893
894         /* SASL 2 does its own memory management internally */
895 #if SASL_VERSION_MAJOR < 2
896         sasl_set_alloc(
897                 ber_memalloc,
898                 ber_memcalloc,
899                 ber_memrealloc,
900                 ber_memfree ); 
901 #endif
902
903         sasl_set_mutex(
904                 ldap_pvt_sasl_mutex_new,
905                 ldap_pvt_sasl_mutex_lock,
906                 ldap_pvt_sasl_mutex_unlock,
907                 ldap_pvt_sasl_mutex_dispose );
908
909 #if SASL_VERSION_MAJOR >= 2
910         generic_filter.f_desc = slap_schema.si_ad_objectClass;
911
912         rc = sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
913         if( rc != SASL_OK ) {
914                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: auxprop add plugin failed\n",
915                         0, 0, 0 );
916                 return -1;
917         }
918 #endif
919         /* should provide callbacks for logging */
920         /* server name should be configurable */
921         rc = sasl_server_init( server_callbacks, "slapd" );
922
923         if( rc != SASL_OK ) {
924                 Debug( LDAP_DEBUG_ANY, "slap_sasl_init: server init failed\n",
925                         0, 0, 0 );
926 #if SASL_VERSION_MAJOR < 2
927                 /* A no-op used to make sure we linked with Cyrus 1.5 */
928                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
929 #endif
930
931                 return -1;
932         }
933
934 #ifdef SLAPD_SPASSWD
935         lutil_passwd_add( &sasl_pwscheme, chk_sasl, NULL );
936 #endif
937
938         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
939                 0, 0, 0 );
940
941         /* default security properties */
942         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
943         sasl_secprops.max_ssf = INT_MAX;
944         sasl_secprops.maxbufsize = 65536;
945         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
946 #endif
947
948         return 0;
949 }
950
951 int slap_sasl_destroy( void )
952 {
953 #ifdef HAVE_CYRUS_SASL
954         sasl_done();
955 #endif
956         free( global_host );
957         global_host = NULL;
958
959         return 0;
960 }
961
962 int slap_sasl_open( Connection *conn, int reopen )
963 {
964         int sc = LDAP_SUCCESS;
965 #ifdef HAVE_CYRUS_SASL
966         int cb;
967
968         sasl_conn_t *ctx = NULL;
969         sasl_callback_t *session_callbacks;
970
971 #if SASL_VERSION_MAJOR >= 2
972         char *ipremoteport = NULL, *iplocalport = NULL;
973 #endif
974
975         assert( conn->c_sasl_authctx == NULL );
976
977         if ( !reopen ) {
978                 assert( conn->c_sasl_extra == NULL );
979
980                 session_callbacks =
981 #if SASL_VERSION_MAJOR >= 2
982                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
983 #else
984                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
985 #endif
986                 if( session_callbacks == NULL ) {
987                         Debug( LDAP_DEBUG_ANY, 
988                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
989                         return -1;
990                 }
991                 conn->c_sasl_extra = session_callbacks;
992
993                 session_callbacks[cb=0].id = SASL_CB_LOG;
994                 session_callbacks[cb].proc = &slap_sasl_log;
995                 session_callbacks[cb++].context = conn;
996
997                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
998                 session_callbacks[cb].proc = &slap_sasl_authorize;
999                 session_callbacks[cb++].context = conn;
1000
1001 #if SASL_VERSION_MAJOR >= 2
1002                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1003                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1004                 session_callbacks[cb++].context = conn;
1005 #endif
1006
1007                 session_callbacks[cb].id = SASL_CB_LIST_END;
1008                 session_callbacks[cb].proc = NULL;
1009                 session_callbacks[cb++].context = NULL;
1010         } else {
1011                 session_callbacks = conn->c_sasl_extra;
1012         }
1013
1014         conn->c_sasl_layers = 0;
1015
1016         if( global_host == NULL ) {
1017                 global_host = ldap_pvt_get_fqdn( NULL );
1018         }
1019
1020         /* create new SASL context */
1021 #if SASL_VERSION_MAJOR >= 2
1022         if ( conn->c_sock_name.bv_len != 0 &&
1023              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1024                 char *p;
1025
1026                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1027                 /* Convert IPv6 addresses to address;port syntax. */
1028                 p = strrchr( iplocalport, ' ' );
1029                 /* Convert IPv4 addresses to address;port syntax. */
1030                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1031                 if ( p != NULL ) {
1032                         *p = ';';
1033                 }
1034         }
1035         if ( conn->c_peer_name.bv_len != 0 &&
1036              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1037                 char *p;
1038
1039                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1040                 /* Convert IPv6 addresses to address;port syntax. */
1041                 p = strrchr( ipremoteport, ' ' );
1042                 /* Convert IPv4 addresses to address;port syntax. */
1043                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1044                 if ( p != NULL ) {
1045                         *p = ';';
1046                 }
1047         }
1048         sc = sasl_server_new( "ldap", global_host, global_realm,
1049                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1050         if ( iplocalport != NULL ) {
1051                 ch_free( iplocalport );
1052         }
1053         if ( ipremoteport != NULL ) {
1054                 ch_free( ipremoteport );
1055         }
1056 #else
1057         sc = sasl_server_new( "ldap", global_host, global_realm,
1058                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1059 #endif
1060
1061         if( sc != SASL_OK ) {
1062                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1063                         sc, 0, 0 );
1064
1065                 return -1;
1066         }
1067
1068         conn->c_sasl_authctx = ctx;
1069
1070         if( sc == SASL_OK ) {
1071                 sc = sasl_setprop( ctx,
1072                         SASL_SEC_PROPS, &sasl_secprops );
1073
1074                 if( sc != SASL_OK ) {
1075                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1076                                 sc, 0, 0 );
1077
1078                         slap_sasl_close( conn );
1079                         return -1;
1080                 }
1081         }
1082
1083         sc = slap_sasl_err2ldap( sc );
1084
1085 #elif defined(SLAP_BUILTIN_SASL)
1086         /* built-in SASL implementation */
1087         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1088         if( ctx == NULL ) return -1;
1089
1090         ctx->sc_external_ssf = 0;
1091         BER_BVZERO( &ctx->sc_external_id );
1092
1093         conn->c_sasl_authctx = ctx;
1094 #endif
1095
1096         return sc;
1097 }
1098
1099 int slap_sasl_external(
1100         Connection *conn,
1101         slap_ssf_t ssf,
1102         struct berval *auth_id )
1103 {
1104 #if SASL_VERSION_MAJOR >= 2
1105         int sc;
1106         sasl_conn_t *ctx = conn->c_sasl_authctx;
1107
1108         if ( ctx == NULL ) {
1109                 return LDAP_UNAVAILABLE;
1110         }
1111
1112         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1113
1114         if ( sc != SASL_OK ) {
1115                 return LDAP_OTHER;
1116         }
1117
1118         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1119                 auth_id ? auth_id->bv_val : NULL );
1120
1121         if ( sc != SASL_OK ) {
1122                 return LDAP_OTHER;
1123         }
1124
1125 #elif defined(HAVE_CYRUS_SASL)
1126         int sc;
1127         sasl_conn_t *ctx = conn->c_sasl_authctx;
1128         sasl_external_properties_t extprops;
1129
1130         if ( ctx == NULL ) {
1131                 return LDAP_UNAVAILABLE;
1132         }
1133
1134         memset( &extprops, '\0', sizeof(extprops) );
1135         extprops.ssf = ssf;
1136         extprops.auth_id = auth_id ? auth_id->bv_val : NULL;
1137
1138         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1139                 (void *) &extprops );
1140
1141         if ( sc != SASL_OK ) {
1142                 return LDAP_OTHER;
1143         }
1144 #elif defined(SLAP_BUILTIN_SASL)
1145         /* built-in SASL implementation */
1146         SASL_CTX *ctx = conn->c_sasl_authctx;
1147         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1148
1149         ctx->sc_external_ssf = ssf;
1150         if( auth_id ) {
1151                 ctx->sc_external_id = *auth_id;
1152                 BER_BVZERO( auth_id );
1153         } else {
1154                 BER_BVZERO( &ctx->sc_external_id );
1155         }
1156 #endif
1157
1158         return LDAP_SUCCESS;
1159 }
1160
1161 int slap_sasl_reset( Connection *conn )
1162 {
1163         return LDAP_SUCCESS;
1164 }
1165
1166 char ** slap_sasl_mechs( Connection *conn )
1167 {
1168         char **mechs = NULL;
1169
1170 #ifdef HAVE_CYRUS_SASL
1171         sasl_conn_t *ctx = conn->c_sasl_authctx;
1172
1173         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1174
1175         if( ctx != NULL ) {
1176                 int sc;
1177                 SASL_CONST char *mechstr;
1178
1179                 sc = sasl_listmech( ctx,
1180                         NULL, NULL, ",", NULL,
1181                         &mechstr, NULL, NULL );
1182
1183                 if( sc != SASL_OK ) {
1184                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1185                                 sc, 0, 0 );
1186
1187                         return NULL;
1188                 }
1189
1190                 mechs = ldap_str2charray( mechstr, "," );
1191
1192 #if SASL_VERSION_MAJOR < 2
1193                 ch_free( mechstr );
1194 #endif
1195         }
1196 #elif defined(SLAP_BUILTIN_SASL)
1197         /* builtin SASL implementation */
1198         SASL_CTX *ctx = conn->c_sasl_authctx;
1199         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1200                 /* should check ssf */
1201                 mechs = ldap_str2charray( "EXTERNAL", "," );
1202         }
1203 #endif
1204
1205         return mechs;
1206 }
1207
1208 int slap_sasl_close( Connection *conn )
1209 {
1210 #ifdef HAVE_CYRUS_SASL
1211         sasl_conn_t *ctx = conn->c_sasl_authctx;
1212
1213         if( ctx != NULL ) {
1214                 sasl_dispose( &ctx );
1215         }
1216         if ( conn->c_sasl_sockctx &&
1217                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1218         {
1219                 ctx = conn->c_sasl_sockctx;
1220                 sasl_dispose( &ctx );
1221         }
1222
1223         conn->c_sasl_authctx = NULL;
1224         conn->c_sasl_sockctx = NULL;
1225         conn->c_sasl_done = 0;
1226
1227         free( conn->c_sasl_extra );
1228         conn->c_sasl_extra = NULL;
1229
1230 #elif defined(SLAP_BUILTIN_SASL)
1231         SASL_CTX *ctx = conn->c_sasl_authctx;
1232         if( ctx ) {
1233                 if( ctx->sc_external_id.bv_val ) {
1234                         free( ctx->sc_external_id.bv_val );
1235                         BER_BVZERO( &ctx->sc_external_id );
1236                 }
1237                 free( ctx );
1238                 conn->c_sasl_authctx = NULL;
1239         }
1240 #endif
1241
1242         return LDAP_SUCCESS;
1243 }
1244
1245 int slap_sasl_bind( Operation *op, SlapReply *rs )
1246 {
1247 #ifdef HAVE_CYRUS_SASL
1248         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1249         struct berval response;
1250         unsigned reslen = 0;
1251         int sc;
1252
1253         Debug(LDAP_DEBUG_ARGS,
1254                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1255                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1256                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1257                 op->o_conn->c_sasl_bind_mech.bv_val,
1258                 op->orb_cred.bv_len );
1259
1260         if( ctx == NULL ) {
1261                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1262                         "SASL unavailable on this session" );
1263                 return rs->sr_err;
1264         }
1265
1266 #if SASL_VERSION_MAJOR >= 2
1267 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1268         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1269 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1270         sasl_server_step( ctx, cred, clen, resp, rlen )
1271 #else
1272 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1273         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1274 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1275         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1276 #endif
1277
1278         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1279                 /* If we already authenticated once, must use a new context */
1280                 if ( op->o_conn->c_sasl_done ) {
1281                         slap_ssf_t ssf = 0;
1282                         const char *authid = NULL;
1283 #if SASL_VERSION_MAJOR >= 2
1284                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1285                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1286                         if ( authid ) authid = ch_strdup( authid );
1287 #endif
1288                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1289                                 sasl_dispose( &ctx );
1290                         }
1291                         op->o_conn->c_sasl_authctx = NULL;
1292                                 
1293                         slap_sasl_open( op->o_conn, 1 );
1294                         ctx = op->o_conn->c_sasl_authctx;
1295 #if SASL_VERSION_MAJOR >= 2
1296                         if ( authid ) {
1297                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1298                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1299                                 ch_free( (char *)authid );
1300                         }
1301 #endif
1302                 }
1303                 sc = START( ctx,
1304                         op->o_conn->c_sasl_bind_mech.bv_val,
1305                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1306                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1307
1308         } else {
1309                 sc = STEP( ctx,
1310                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1311                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1312         }
1313
1314         response.bv_len = reslen;
1315
1316         if ( sc == SASL_OK ) {
1317                 sasl_ssf_t *ssf = NULL;
1318
1319                 op->orb_edn = op->o_conn->c_sasl_dn;
1320                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1321                 op->o_conn->c_sasl_done = 1;
1322
1323                 rs->sr_err = LDAP_SUCCESS;
1324
1325                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1326                 op->orb_ssf = ssf ? *ssf : 0;
1327
1328                 ctx = NULL;
1329                 if( op->orb_ssf ) {
1330                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1331                         op->o_conn->c_sasl_layers++;
1332
1333                         /* If there's an old layer, set sockctx to NULL to
1334                          * tell connection_read() to wait for us to finish.
1335                          * Otherwise there is a race condition: we have to
1336                          * send the Bind response using the old security
1337                          * context and then remove it before reading any
1338                          * new messages.
1339                          */
1340                         if ( op->o_conn->c_sasl_sockctx ) {
1341                                 ctx = op->o_conn->c_sasl_sockctx;
1342                                 op->o_conn->c_sasl_sockctx = NULL;
1343                         } else {
1344                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1345                         }
1346                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1347                 }
1348
1349                 /* Must send response using old security layer */
1350                 if (response.bv_len) rs->sr_sasldata = &response;
1351                 send_ldap_sasl( op, rs );
1352                 
1353                 /* Now dispose of the old security layer.
1354                  */
1355                 if ( ctx ) {
1356                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1357                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1358                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1359                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1360                         sasl_dispose( &ctx );
1361                 }
1362         } else if ( sc == SASL_CONTINUE ) {
1363                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1364                 rs->sr_sasldata = &response;
1365                 send_ldap_sasl( op, rs );
1366
1367         } else {
1368 #if SASL_VERSION_MAJOR >= 2
1369                 rs->sr_text = sasl_errdetail( ctx );
1370 #endif
1371                 rs->sr_err = slap_sasl_err2ldap( sc ),
1372                 send_ldap_result( op, rs );
1373         }
1374
1375 #if SASL_VERSION_MAJOR < 2
1376         if( response.bv_len ) {
1377                 ch_free( response.bv_val );
1378         }
1379 #endif
1380
1381         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1382
1383 #elif defined(SLAP_BUILTIN_SASL)
1384         /* built-in SASL implementation */
1385         SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1386
1387         if ( ctx == NULL ) {
1388                 send_ldap_error( op, rs, LDAP_OTHER,
1389                         "Internal SASL Error" );
1390
1391         } else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1392                 /* EXTERNAL */
1393
1394                 if( op->orb_cred.bv_len ) {
1395                         rs->sr_text = "proxy authorization not support";
1396                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1397                         send_ldap_result( op, rs );
1398
1399                 } else {
1400                         op->orb_edn = ctx->sc_external_id;
1401                         rs->sr_err = LDAP_SUCCESS;
1402                         rs->sr_sasldata = NULL;
1403                         send_ldap_sasl( op, rs );
1404                 }
1405
1406         } else {
1407                 send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1408                         "requested SASL mechanism not supported" );
1409         }
1410 #else
1411         send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1412                 "SASL not supported" );
1413 #endif
1414
1415         return rs->sr_err;
1416 }
1417
1418 char* slap_sasl_secprops( const char *in )
1419 {
1420 #ifdef HAVE_CYRUS_SASL
1421         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1422
1423         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1424 #else
1425         return "SASL not supported";
1426 #endif
1427 }
1428
1429 void slap_sasl_secprops_unparse( struct berval *bv )
1430 {
1431 #ifdef HAVE_CYRUS_SASL
1432         ldap_pvt_sasl_secprops_unparse( &sasl_secprops, bv );
1433 #endif
1434 }
1435
1436 #ifdef HAVE_CYRUS_SASL
1437 int
1438 slap_sasl_setpass( Operation *op, SlapReply *rs )
1439 {
1440         struct berval id = BER_BVNULL;  /* needs to come from connection */
1441         struct berval new = BER_BVNULL;
1442         struct berval old = BER_BVNULL;
1443
1444         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1445
1446         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1447                 (SASL_CONST void **)&id.bv_val );
1448
1449         if( rs->sr_err != SASL_OK ) {
1450                 rs->sr_text = "unable to retrieve SASL username";
1451                 rs->sr_err = LDAP_OTHER;
1452                 goto done;
1453         }
1454
1455         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1456                 id.bv_val ? id.bv_val : "", 0, 0 );
1457
1458         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1459                 NULL, &old, &new, &rs->sr_text );
1460
1461         if( rs->sr_err != LDAP_SUCCESS ) {
1462                 goto done;
1463         }
1464
1465         if( new.bv_len == 0 ) {
1466                 slap_passwd_generate(&new);
1467
1468                 if( new.bv_len == 0 ) {
1469                         rs->sr_text = "password generation failed.";
1470                         rs->sr_err = LDAP_OTHER;
1471                         goto done;
1472                 }
1473                 
1474                 rs->sr_rspdata = slap_passwd_return( &new );
1475         }
1476
1477 #if SASL_VERSION_MAJOR < 2
1478         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx,
1479                 id.bv_val, new.bv_val, new.bv_len, 0, &rs->sr_text );
1480 #else
1481         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1482                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1483         if( rs->sr_err != SASL_OK ) {
1484                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1485         }
1486 #endif
1487         switch(rs->sr_err) {
1488                 case SASL_OK:
1489                         rs->sr_err = LDAP_SUCCESS;
1490                         break;
1491
1492                 case SASL_NOCHANGE:
1493                 case SASL_NOMECH:
1494                 case SASL_DISABLED:
1495                 case SASL_PWLOCK:
1496                 case SASL_FAIL:
1497                 case SASL_BADPARAM:
1498                 default:
1499                         rs->sr_err = LDAP_OTHER;
1500         }
1501
1502 done:
1503         return rs->sr_err;
1504 }
1505 #endif /* HAVE_CYRUS_SASL */
1506
1507 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1508  * string returned in *dn is in its own allocated memory, and must be free'd 
1509  * by the calling process.  -Mark Adamson, Carnegie Mellon
1510  *
1511  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1512  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1513  */
1514
1515 #define SET_NONE        0
1516 #define SET_DN          1
1517 #define SET_U           2
1518
1519 int slap_sasl_getdn( Connection *conn, Operation *op, struct berval *id,
1520         char *user_realm, struct berval *dn, int flags )
1521 {
1522         int rc, is_dn = SET_NONE, do_norm = 1;
1523         struct berval dn2, *mech;
1524
1525         assert( conn != NULL );
1526         assert( id != NULL );
1527
1528         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: conn %lu id=%s [len=%lu]\n", 
1529                 conn->c_connid,
1530                 BER_BVISNULL( id ) ? "NULL" : ( BER_BVISEMPTY( id ) ? "<empty>" : id->bv_val ),
1531                 BER_BVISNULL( id ) ? 0 : ( BER_BVISEMPTY( id ) ? 0 :
1532                                            (unsigned long) id->bv_len ) );
1533
1534         if ( !op ) {
1535                 op = conn->c_sasl_bindop;
1536         }
1537
1538         BER_BVZERO( dn );
1539
1540         if ( !BER_BVISNULL( id ) ) {
1541                 /* Blatantly anonymous ID */
1542                 static struct berval bv_anonymous = BER_BVC( "anonymous" );
1543
1544                 if ( ber_bvstrcasecmp( id, &bv_anonymous ) == 0 ) {
1545                         return( LDAP_SUCCESS );
1546                 }
1547
1548         } else {
1549                 /* FIXME: if empty, should we stop? */
1550                 BER_BVSTR( id, "" );
1551         }
1552
1553         if ( !BER_BVISEMPTY( &conn->c_sasl_bind_mech ) ) {
1554                 mech = &conn->c_sasl_bind_mech;
1555         } else {
1556                 mech = &conn->c_authmech;
1557         }
1558
1559         /* An authcID needs to be converted to authzID form. Set the
1560          * values directly into *dn; they will be normalized later. (and
1561          * normalizing always makes a new copy.) An ID from a TLS certificate
1562          * is already normalized, so copy it and skip normalization.
1563          */
1564         if( flags & SLAP_GETDN_AUTHCID ) {
1565                 if( bvmatch( mech, &ext_bv )) {
1566                         /* EXTERNAL DNs are already normalized */
1567                         assert( !BER_BVISNULL( id ) );
1568
1569                         do_norm = 0;
1570                         is_dn = SET_DN;
1571                         ber_dupbv_x( dn, id, op->o_tmpmemctx );
1572
1573                 } else {
1574                         /* convert to u:<username> form */
1575                         is_dn = SET_U;
1576                         *dn = *id;
1577                 }
1578         }
1579
1580         if( is_dn == SET_NONE ) {
1581                 if( !strncasecmp( id->bv_val, "u:", STRLENOF( "u:" ) ) ) {
1582                         is_dn = SET_U;
1583                         dn->bv_val = id->bv_val + STRLENOF( "u:" );
1584                         dn->bv_len = id->bv_len - STRLENOF( "u:" );
1585
1586                 } else if ( !strncasecmp( id->bv_val, "dn:", STRLENOF( "dn:" ) ) ) {
1587                         is_dn = SET_DN;
1588                         dn->bv_val = id->bv_val + STRLENOF( "dn:" );
1589                         dn->bv_len = id->bv_len - STRLENOF( "dn:" );
1590                 }
1591         }
1592
1593         /* No other possibilities from here */
1594         if( is_dn == SET_NONE ) {
1595                 BER_BVZERO( dn );
1596                 return( LDAP_INAPPROPRIATE_AUTH );
1597         }
1598
1599         /* Username strings */
1600         if( is_dn == SET_U ) {
1601                 /* ITS#3419: values may need escape */
1602                 LDAPRDN         DN[ 5 ];
1603                 LDAPAVA         *RDNs[ 4 ][ 2 ];
1604                 LDAPAVA         AVAs[ 4 ];
1605                 int             irdn;
1606
1607                 irdn = 0;
1608                 DN[ irdn ] = RDNs[ irdn ];
1609                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1610                 AVAs[ irdn ].la_attr = slap_schema.si_ad_uid->ad_cname;
1611                 AVAs[ irdn ].la_value = *dn;
1612                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1613                 AVAs[ irdn ].la_private = NULL;
1614                 RDNs[ irdn ][ 1 ] = NULL;
1615
1616                 if ( user_realm && *user_realm ) {
1617                         irdn++;
1618                         DN[ irdn ] = RDNs[ irdn ];
1619                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1620                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1621                         ber_str2bv( user_realm, 0, 0, &AVAs[ irdn ].la_value );
1622                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1623                         AVAs[ irdn ].la_private = NULL;
1624                         RDNs[ irdn ][ 1 ] = NULL;
1625                 }
1626
1627                 if ( !BER_BVISNULL( mech ) ) {
1628                         irdn++;
1629                         DN[ irdn ] = RDNs[ irdn ];
1630                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1631                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1632                         AVAs[ irdn ].la_value = *mech;
1633                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1634                         AVAs[ irdn ].la_private = NULL;
1635                         RDNs[ irdn ][ 1 ] = NULL;
1636                 }
1637
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_BVSTR( &AVAs[ irdn ].la_value, "auth" );
1643                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1644                 AVAs[ irdn ].la_private = NULL;
1645                 RDNs[ irdn ][ 1 ] = NULL;
1646
1647                 irdn++;
1648                 DN[ irdn ] = NULL;
1649
1650                 rc = ldap_dn2bv_x( DN, dn, LDAP_DN_FORMAT_LDAPV3, op->o_tmpmemctx );
1651                 if ( rc != LDAP_SUCCESS ) {
1652                         BER_BVZERO( dn );
1653                         return rc;
1654                 }
1655
1656                 Debug( LDAP_DEBUG_TRACE, "slap_sasl_getdn: u:id converted to %s\n", dn->bv_val,0,0 );
1657
1658         } else {
1659                 
1660                 /* Dup the DN in any case, so we don't risk 
1661                  * leaks or dangling pointers later,
1662                  * and the DN value is '\0' terminated */
1663                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1664                 dn->bv_val = dn2.bv_val;
1665         }
1666
1667         /* All strings are in DN form now. Normalize if needed. */
1668         if ( do_norm ) {
1669                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1670
1671                 /* User DNs were constructed above and must be freed now */
1672                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1673
1674                 if ( rc != LDAP_SUCCESS ) {
1675                         BER_BVZERO( dn );
1676                         return rc;
1677                 }
1678                 *dn = dn2;
1679         }
1680
1681         /* Run thru regexp */
1682         slap_sasl2dn( op, dn, &dn2, flags );
1683         if( !BER_BVISNULL( &dn2 ) ) {
1684                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1685                 *dn = dn2;
1686                 Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
1687                         dn->bv_val, 0, 0 );
1688         }
1689
1690         return( LDAP_SUCCESS );
1691 }