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