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