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