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