]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
Improved bignum detection/use
[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 int slap_sasl_open( Connection *conn, int reopen )
1052 {
1053         int sc = LDAP_SUCCESS;
1054 #ifdef HAVE_CYRUS_SASL
1055         int cb;
1056
1057         sasl_conn_t *ctx = NULL;
1058         sasl_callback_t *session_callbacks;
1059
1060 #if SASL_VERSION_MAJOR >= 2
1061         char *ipremoteport = NULL, *iplocalport = NULL;
1062 #endif
1063
1064         assert( conn->c_sasl_authctx == NULL );
1065
1066         if ( !reopen ) {
1067                 assert( conn->c_sasl_extra == NULL );
1068
1069                 session_callbacks =
1070 #if SASL_VERSION_MAJOR >= 2
1071                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1072 #else
1073                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1074 #endif
1075                 if( session_callbacks == NULL ) {
1076                         Debug( LDAP_DEBUG_ANY, 
1077                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1078                         return -1;
1079                 }
1080                 conn->c_sasl_extra = session_callbacks;
1081
1082                 session_callbacks[cb=0].id = SASL_CB_LOG;
1083                 session_callbacks[cb].proc = &slap_sasl_log;
1084                 session_callbacks[cb++].context = conn;
1085
1086                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1087                 session_callbacks[cb].proc = &slap_sasl_authorize;
1088                 session_callbacks[cb++].context = conn;
1089
1090 #if SASL_VERSION_MAJOR >= 2
1091                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1092                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1093                 session_callbacks[cb++].context = conn;
1094 #endif
1095
1096                 session_callbacks[cb].id = SASL_CB_LIST_END;
1097                 session_callbacks[cb].proc = NULL;
1098                 session_callbacks[cb++].context = NULL;
1099         } else {
1100                 session_callbacks = conn->c_sasl_extra;
1101         }
1102
1103         conn->c_sasl_layers = 0;
1104
1105         if( global_host == NULL ) {
1106                 global_host = ldap_pvt_get_fqdn( NULL );
1107         }
1108
1109         /* create new SASL context */
1110 #if SASL_VERSION_MAJOR >= 2
1111         if ( conn->c_sock_name.bv_len != 0 &&
1112              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1113                 char *p;
1114
1115                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1116                 /* Convert IPv6 addresses to address;port syntax. */
1117                 p = strrchr( iplocalport, ' ' );
1118                 /* Convert IPv4 addresses to address;port syntax. */
1119                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1120                 if ( p != NULL ) {
1121                         *p = ';';
1122                 }
1123         }
1124         if ( conn->c_peer_name.bv_len != 0 &&
1125              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1126                 char *p;
1127
1128                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1129                 /* Convert IPv6 addresses to address;port syntax. */
1130                 p = strrchr( ipremoteport, ' ' );
1131                 /* Convert IPv4 addresses to address;port syntax. */
1132                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1133                 if ( p != NULL ) {
1134                         *p = ';';
1135                 }
1136         }
1137         sc = sasl_server_new( "ldap", global_host, global_realm,
1138                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1139         if ( iplocalport != NULL ) {
1140                 ch_free( iplocalport );
1141         }
1142         if ( ipremoteport != NULL ) {
1143                 ch_free( ipremoteport );
1144         }
1145 #else
1146         sc = sasl_server_new( "ldap", global_host, global_realm,
1147                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1148 #endif
1149
1150         if( sc != SASL_OK ) {
1151                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1152                         sc, 0, 0 );
1153
1154                 return -1;
1155         }
1156
1157         conn->c_sasl_authctx = ctx;
1158
1159         if( sc == SASL_OK ) {
1160                 sc = sasl_setprop( ctx,
1161                         SASL_SEC_PROPS, &sasl_secprops );
1162
1163                 if( sc != SASL_OK ) {
1164                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1165                                 sc, 0, 0 );
1166
1167                         slap_sasl_close( conn );
1168                         return -1;
1169                 }
1170         }
1171
1172         sc = slap_sasl_err2ldap( sc );
1173
1174 #elif defined(SLAP_BUILTIN_SASL)
1175         /* built-in SASL implementation */
1176         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1177         if( ctx == NULL ) return -1;
1178
1179         ctx->sc_external_ssf = 0;
1180         BER_BVZERO( &ctx->sc_external_id );
1181
1182         conn->c_sasl_authctx = ctx;
1183 #endif
1184
1185         return sc;
1186 }
1187
1188 int slap_sasl_external(
1189         Connection *conn,
1190         slap_ssf_t ssf,
1191         struct berval *auth_id )
1192 {
1193 #if SASL_VERSION_MAJOR >= 2
1194         int sc;
1195         sasl_conn_t *ctx = conn->c_sasl_authctx;
1196
1197         if ( ctx == NULL ) {
1198                 return LDAP_UNAVAILABLE;
1199         }
1200
1201         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1202
1203         if ( sc != SASL_OK ) {
1204                 return LDAP_OTHER;
1205         }
1206
1207         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1208                 auth_id ? auth_id->bv_val : NULL );
1209
1210         if ( sc != SASL_OK ) {
1211                 return LDAP_OTHER;
1212         }
1213
1214 #elif defined(HAVE_CYRUS_SASL)
1215         int sc;
1216         sasl_conn_t *ctx = conn->c_sasl_authctx;
1217         sasl_external_properties_t extprops;
1218
1219         if ( ctx == NULL ) {
1220                 return LDAP_UNAVAILABLE;
1221         }
1222
1223         memset( &extprops, '\0', sizeof(extprops) );
1224         extprops.ssf = ssf;
1225         extprops.auth_id = auth_id ? auth_id->bv_val : NULL;
1226
1227         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1228                 (void *) &extprops );
1229
1230         if ( sc != SASL_OK ) {
1231                 return LDAP_OTHER;
1232         }
1233 #elif defined(SLAP_BUILTIN_SASL)
1234         /* built-in SASL implementation */
1235         SASL_CTX *ctx = conn->c_sasl_authctx;
1236         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1237
1238         ctx->sc_external_ssf = ssf;
1239         if( auth_id ) {
1240                 ctx->sc_external_id = *auth_id;
1241                 BER_BVZERO( auth_id );
1242         } else {
1243                 BER_BVZERO( &ctx->sc_external_id );
1244         }
1245 #endif
1246
1247         return LDAP_SUCCESS;
1248 }
1249
1250 int slap_sasl_reset( Connection *conn )
1251 {
1252         return LDAP_SUCCESS;
1253 }
1254
1255 char ** slap_sasl_mechs( Connection *conn )
1256 {
1257         char **mechs = NULL;
1258
1259 #ifdef HAVE_CYRUS_SASL
1260         sasl_conn_t *ctx = conn->c_sasl_authctx;
1261
1262         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1263
1264         if( ctx != NULL ) {
1265                 int sc;
1266                 SASL_CONST char *mechstr;
1267
1268                 sc = sasl_listmech( ctx,
1269                         NULL, NULL, ",", NULL,
1270                         &mechstr, NULL, NULL );
1271
1272                 if( sc != SASL_OK ) {
1273                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1274                                 sc, 0, 0 );
1275
1276                         return NULL;
1277                 }
1278
1279                 mechs = ldap_str2charray( mechstr, "," );
1280
1281 #if SASL_VERSION_MAJOR < 2
1282                 ch_free( mechstr );
1283 #endif
1284         }
1285 #elif defined(SLAP_BUILTIN_SASL)
1286         /* builtin SASL implementation */
1287         SASL_CTX *ctx = conn->c_sasl_authctx;
1288         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1289                 /* should check ssf */
1290                 mechs = ldap_str2charray( "EXTERNAL", "," );
1291         }
1292 #endif
1293
1294         return mechs;
1295 }
1296
1297 int slap_sasl_close( Connection *conn )
1298 {
1299 #ifdef HAVE_CYRUS_SASL
1300         sasl_conn_t *ctx = conn->c_sasl_authctx;
1301
1302         if( ctx != NULL ) {
1303                 sasl_dispose( &ctx );
1304         }
1305         if ( conn->c_sasl_sockctx &&
1306                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1307         {
1308                 ctx = conn->c_sasl_sockctx;
1309                 sasl_dispose( &ctx );
1310         }
1311
1312         conn->c_sasl_authctx = NULL;
1313         conn->c_sasl_sockctx = NULL;
1314         conn->c_sasl_done = 0;
1315
1316         free( conn->c_sasl_extra );
1317         conn->c_sasl_extra = NULL;
1318
1319 #elif defined(SLAP_BUILTIN_SASL)
1320         SASL_CTX *ctx = conn->c_sasl_authctx;
1321         if( ctx ) {
1322                 if( ctx->sc_external_id.bv_val ) {
1323                         free( ctx->sc_external_id.bv_val );
1324                         BER_BVZERO( &ctx->sc_external_id );
1325                 }
1326                 free( ctx );
1327                 conn->c_sasl_authctx = NULL;
1328         }
1329 #endif
1330
1331         return LDAP_SUCCESS;
1332 }
1333
1334 int slap_sasl_bind( Operation *op, SlapReply *rs )
1335 {
1336 #ifdef HAVE_CYRUS_SASL
1337         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1338         struct berval response;
1339         unsigned reslen = 0;
1340         int sc;
1341
1342         Debug(LDAP_DEBUG_ARGS,
1343                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1344                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1345                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1346                 op->o_conn->c_sasl_bind_mech.bv_val,
1347                 op->orb_cred.bv_len );
1348
1349         if( ctx == NULL ) {
1350                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1351                         "SASL unavailable on this session" );
1352                 return rs->sr_err;
1353         }
1354
1355 #if SASL_VERSION_MAJOR >= 2
1356 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1357         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1358 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1359         sasl_server_step( ctx, cred, clen, resp, rlen )
1360 #else
1361 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1362         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1363 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1364         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1365 #endif
1366
1367         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1368                 /* If we already authenticated once, must use a new context */
1369                 if ( op->o_conn->c_sasl_done ) {
1370                         slap_ssf_t ssf = 0;
1371                         const char *authid = NULL;
1372 #if SASL_VERSION_MAJOR >= 2
1373                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1374                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1375                         if ( authid ) authid = ch_strdup( authid );
1376 #endif
1377                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1378                                 sasl_dispose( &ctx );
1379                         }
1380                         op->o_conn->c_sasl_authctx = NULL;
1381                                 
1382                         slap_sasl_open( op->o_conn, 1 );
1383                         ctx = op->o_conn->c_sasl_authctx;
1384 #if SASL_VERSION_MAJOR >= 2
1385                         if ( authid ) {
1386                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1387                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1388                                 ch_free( (char *)authid );
1389                         }
1390 #endif
1391                 }
1392                 sc = START( ctx,
1393                         op->o_conn->c_sasl_bind_mech.bv_val,
1394                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1395                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1396
1397         } else {
1398                 sc = STEP( ctx,
1399                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1400                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1401         }
1402
1403         response.bv_len = reslen;
1404
1405         if ( sc == SASL_OK ) {
1406                 sasl_ssf_t *ssf = NULL;
1407
1408                 op->orb_edn = op->o_conn->c_sasl_dn;
1409                 BER_BVZERO( &op->o_conn->c_sasl_dn );
1410                 op->o_conn->c_sasl_done = 1;
1411
1412                 rs->sr_err = LDAP_SUCCESS;
1413
1414                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1415                 op->orb_ssf = ssf ? *ssf : 0;
1416
1417                 ctx = NULL;
1418                 if( op->orb_ssf ) {
1419                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1420                         op->o_conn->c_sasl_layers++;
1421
1422                         /* If there's an old layer, set sockctx to NULL to
1423                          * tell connection_read() to wait for us to finish.
1424                          * Otherwise there is a race condition: we have to
1425                          * send the Bind response using the old security
1426                          * context and then remove it before reading any
1427                          * new messages.
1428                          */
1429                         if ( op->o_conn->c_sasl_sockctx ) {
1430                                 ctx = op->o_conn->c_sasl_sockctx;
1431                                 op->o_conn->c_sasl_sockctx = NULL;
1432                         } else {
1433                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1434                         }
1435                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1436                 }
1437
1438                 /* Must send response using old security layer */
1439                 if (response.bv_len) rs->sr_sasldata = &response;
1440                 send_ldap_sasl( op, rs );
1441                 
1442                 /* Now dispose of the old security layer.
1443                  */
1444                 if ( ctx ) {
1445                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1446                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1447                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1448                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1449                         sasl_dispose( &ctx );
1450                 }
1451         } else if ( sc == SASL_CONTINUE ) {
1452                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1453 #if SASL_VERSION_MAJOR >= 2
1454                 rs->sr_text = sasl_errdetail( ctx );
1455 #endif
1456                 rs->sr_sasldata = &response;
1457                 send_ldap_sasl( op, rs );
1458
1459         } else {
1460 #if SASL_VERSION_MAJOR >= 2
1461                 rs->sr_text = sasl_errdetail( ctx );
1462 #endif
1463                 rs->sr_err = slap_sasl_err2ldap( sc ),
1464                 send_ldap_result( op, rs );
1465         }
1466
1467 #if SASL_VERSION_MAJOR < 2
1468         if( response.bv_len ) ch_free( response.bv_val );
1469 #endif
1470
1471         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1472
1473 #elif defined(SLAP_BUILTIN_SASL)
1474         /* built-in SASL implementation */
1475         SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1476
1477         if ( ctx == NULL ) {
1478                 send_ldap_error( op, rs, LDAP_OTHER,
1479                         "Internal SASL Error" );
1480
1481         } else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1482                 /* EXTERNAL */
1483
1484                 if( op->orb_cred.bv_len ) {
1485                         rs->sr_text = "proxy authorization not support";
1486                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1487                         send_ldap_result( op, rs );
1488
1489                 } else {
1490                         op->orb_edn = ctx->sc_external_id;
1491                         rs->sr_err = LDAP_SUCCESS;
1492                         rs->sr_sasldata = NULL;
1493                         send_ldap_sasl( op, rs );
1494                 }
1495
1496         } else {
1497                 send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1498                         "requested SASL mechanism not supported" );
1499         }
1500 #else
1501         send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1502                 "SASL not supported" );
1503 #endif
1504
1505         return rs->sr_err;
1506 }
1507
1508 char* slap_sasl_secprops( const char *in )
1509 {
1510 #ifdef HAVE_CYRUS_SASL
1511         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1512
1513         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1514 #else
1515         return "SASL not supported";
1516 #endif
1517 }
1518
1519 void slap_sasl_secprops_unparse( struct berval *bv )
1520 {
1521 #ifdef HAVE_CYRUS_SASL
1522         ldap_pvt_sasl_secprops_unparse( &sasl_secprops, bv );
1523 #endif
1524 }
1525
1526 #ifdef HAVE_CYRUS_SASL
1527 int
1528 slap_sasl_setpass( Operation *op, SlapReply *rs )
1529 {
1530         struct berval id = BER_BVNULL;  /* needs to come from connection */
1531         struct berval new = BER_BVNULL;
1532         struct berval old = BER_BVNULL;
1533
1534         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1535
1536         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1537                 (SASL_CONST void **)&id.bv_val );
1538
1539         if( rs->sr_err != SASL_OK ) {
1540                 rs->sr_text = "unable to retrieve SASL username";
1541                 rs->sr_err = LDAP_OTHER;
1542                 goto done;
1543         }
1544
1545         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1546                 id.bv_val ? id.bv_val : "", 0, 0 );
1547
1548         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1549                 NULL, &old, &new, &rs->sr_text );
1550
1551         if( rs->sr_err != LDAP_SUCCESS ) {
1552                 goto done;
1553         }
1554
1555         if( new.bv_len == 0 ) {
1556                 slap_passwd_generate(&new);
1557
1558                 if( new.bv_len == 0 ) {
1559                         rs->sr_text = "password generation failed.";
1560                         rs->sr_err = LDAP_OTHER;
1561                         goto done;
1562                 }
1563                 
1564                 rs->sr_rspdata = slap_passwd_return( &new );
1565         }
1566
1567 #if SASL_VERSION_MAJOR < 2
1568         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx,
1569                 id.bv_val, new.bv_val, new.bv_len, 0, &rs->sr_text );
1570 #else
1571         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1572                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1573         if( rs->sr_err != SASL_OK ) {
1574                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1575         }
1576 #endif
1577         switch(rs->sr_err) {
1578                 case SASL_OK:
1579                         rs->sr_err = LDAP_SUCCESS;
1580                         break;
1581
1582                 case SASL_NOCHANGE:
1583                 case SASL_NOMECH:
1584                 case SASL_DISABLED:
1585                 case SASL_PWLOCK:
1586                 case SASL_FAIL:
1587                 case SASL_BADPARAM:
1588                 default:
1589                         rs->sr_err = LDAP_OTHER;
1590         }
1591
1592 done:
1593         return rs->sr_err;
1594 }
1595 #endif /* HAVE_CYRUS_SASL */
1596
1597 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1598  * string returned in *dn is in its own allocated memory, and must be free'd 
1599  * by the calling process.  -Mark Adamson, Carnegie Mellon
1600  *
1601  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1602  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1603  */
1604
1605 #define SET_NONE        0
1606 #define SET_DN          1
1607 #define SET_U           2
1608
1609 int slap_sasl_getdn( Connection *conn, Operation *op, struct berval *id,
1610         char *user_realm, struct berval *dn, int flags )
1611 {
1612         int rc, is_dn = SET_NONE, do_norm = 1;
1613         struct berval dn2, *mech;
1614
1615         assert( conn != NULL );
1616         assert( id != NULL );
1617
1618         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: conn %lu id=%s [len=%lu]\n", 
1619                 conn->c_connid,
1620                 BER_BVISNULL( id ) ? "NULL" : ( BER_BVISEMPTY( id ) ? "<empty>" : id->bv_val ),
1621                 BER_BVISNULL( id ) ? 0 : ( BER_BVISEMPTY( id ) ? 0 :
1622                                            (unsigned long) id->bv_len ) );
1623
1624         if ( !op ) {
1625                 op = conn->c_sasl_bindop;
1626         }
1627         assert( op != NULL );
1628
1629         BER_BVZERO( dn );
1630
1631         if ( !BER_BVISNULL( id ) ) {
1632                 /* Blatantly anonymous ID */
1633                 static struct berval bv_anonymous = BER_BVC( "anonymous" );
1634
1635                 if ( ber_bvstrcasecmp( id, &bv_anonymous ) == 0 ) {
1636                         return( LDAP_SUCCESS );
1637                 }
1638
1639         } else {
1640                 /* FIXME: if empty, should we stop? */
1641                 BER_BVSTR( id, "" );
1642         }
1643
1644         if ( !BER_BVISEMPTY( &conn->c_sasl_bind_mech ) ) {
1645                 mech = &conn->c_sasl_bind_mech;
1646         } else {
1647                 mech = &conn->c_authmech;
1648         }
1649
1650         /* An authcID needs to be converted to authzID form. Set the
1651          * values directly into *dn; they will be normalized later. (and
1652          * normalizing always makes a new copy.) An ID from a TLS certificate
1653          * is already normalized, so copy it and skip normalization.
1654          */
1655         if( flags & SLAP_GETDN_AUTHCID ) {
1656                 if( bvmatch( mech, &ext_bv )) {
1657                         /* EXTERNAL DNs are already normalized */
1658                         assert( !BER_BVISNULL( id ) );
1659
1660                         do_norm = 0;
1661                         is_dn = SET_DN;
1662                         ber_dupbv_x( dn, id, op->o_tmpmemctx );
1663
1664                 } else {
1665                         /* convert to u:<username> form */
1666                         is_dn = SET_U;
1667                         *dn = *id;
1668                 }
1669         }
1670
1671         if( is_dn == SET_NONE ) {
1672                 if( !strncasecmp( id->bv_val, "u:", STRLENOF( "u:" ) ) ) {
1673                         is_dn = SET_U;
1674                         dn->bv_val = id->bv_val + STRLENOF( "u:" );
1675                         dn->bv_len = id->bv_len - STRLENOF( "u:" );
1676
1677                 } else if ( !strncasecmp( id->bv_val, "dn:", STRLENOF( "dn:" ) ) ) {
1678                         is_dn = SET_DN;
1679                         dn->bv_val = id->bv_val + STRLENOF( "dn:" );
1680                         dn->bv_len = id->bv_len - STRLENOF( "dn:" );
1681                 }
1682         }
1683
1684         /* No other possibilities from here */
1685         if( is_dn == SET_NONE ) {
1686                 BER_BVZERO( dn );
1687                 return( LDAP_INAPPROPRIATE_AUTH );
1688         }
1689
1690         /* Username strings */
1691         if( is_dn == SET_U ) {
1692                 /* ITS#3419: values may need escape */
1693                 LDAPRDN         DN[ 5 ];
1694                 LDAPAVA         *RDNs[ 4 ][ 2 ];
1695                 LDAPAVA         AVAs[ 4 ];
1696                 int             irdn;
1697
1698                 irdn = 0;
1699                 DN[ irdn ] = RDNs[ irdn ];
1700                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1701                 AVAs[ irdn ].la_attr = slap_schema.si_ad_uid->ad_cname;
1702                 AVAs[ irdn ].la_value = *dn;
1703                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1704                 AVAs[ irdn ].la_private = NULL;
1705                 RDNs[ irdn ][ 1 ] = NULL;
1706
1707                 if ( user_realm && *user_realm ) {
1708                         irdn++;
1709                         DN[ irdn ] = RDNs[ irdn ];
1710                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1711                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1712                         ber_str2bv( user_realm, 0, 0, &AVAs[ irdn ].la_value );
1713                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1714                         AVAs[ irdn ].la_private = NULL;
1715                         RDNs[ irdn ][ 1 ] = NULL;
1716                 }
1717
1718                 if ( !BER_BVISNULL( mech ) ) {
1719                         irdn++;
1720                         DN[ irdn ] = RDNs[ irdn ];
1721                         RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1722                         AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1723                         AVAs[ irdn ].la_value = *mech;
1724                         AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1725                         AVAs[ irdn ].la_private = NULL;
1726                         RDNs[ irdn ][ 1 ] = NULL;
1727                 }
1728
1729                 irdn++;
1730                 DN[ irdn ] = RDNs[ irdn ];
1731                 RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1732                 AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1733                 BER_BVSTR( &AVAs[ irdn ].la_value, "auth" );
1734                 AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1735                 AVAs[ irdn ].la_private = NULL;
1736                 RDNs[ irdn ][ 1 ] = NULL;
1737
1738                 irdn++;
1739                 DN[ irdn ] = NULL;
1740
1741                 rc = ldap_dn2bv_x( DN, dn, LDAP_DN_FORMAT_LDAPV3,
1742                                 op->o_tmpmemctx );
1743                 if ( rc != LDAP_SUCCESS ) {
1744                         BER_BVZERO( dn );
1745                         return rc;
1746                 }
1747
1748                 Debug( LDAP_DEBUG_TRACE,
1749                         "slap_sasl_getdn: u:id converted to %s\n",
1750                         dn->bv_val, 0, 0 );
1751
1752         } else {
1753                 
1754                 /* Dup the DN in any case, so we don't risk 
1755                  * leaks or dangling pointers later,
1756                  * and the DN value is '\0' terminated */
1757                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1758                 dn->bv_val = dn2.bv_val;
1759         }
1760
1761         /* All strings are in DN form now. Normalize if needed. */
1762         if ( do_norm ) {
1763                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1764
1765                 /* User DNs were constructed above and must be freed now */
1766                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1767
1768                 if ( rc != LDAP_SUCCESS ) {
1769                         BER_BVZERO( dn );
1770                         return rc;
1771                 }
1772                 *dn = dn2;
1773         }
1774
1775         /* Run thru regexp */
1776         slap_sasl2dn( op, dn, &dn2, flags );
1777         if( !BER_BVISNULL( &dn2 ) ) {
1778                 slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1779                 *dn = dn2;
1780                 Debug( LDAP_DEBUG_TRACE,
1781                         "slap_sasl_getdn: dn:id converted to %s\n",
1782                         dn->bv_val, 0, 0 );
1783         }
1784
1785         return( LDAP_SUCCESS );
1786 }