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