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