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