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