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