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