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