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