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