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