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