]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
(mostly blind) fix of possible leak/dangling pointer and cleanup
[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_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, slap_cb_null_sreference, 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",
614                 in ? in : "<empty>");
615 #else
616         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %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,
689                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
690 #else
691         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
692                 conn ? conn->c_connid : -1, names[0]+1,
693                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
694 #endif
695
696 done:
697         AC_MEMCPY( out, in, inlen );
698         out[inlen] = '\0';
699
700         *out_len = inlen;
701
702         return SASL_OK;
703 }
704
705 static int
706 slap_sasl_authorize(
707         sasl_conn_t *sconn,
708         void *context,
709         char *requested_user,
710         unsigned rlen,
711         char *auth_identity,
712         unsigned alen,
713         const char *def_realm,
714         unsigned urlen,
715         struct propctx *props)
716 {
717         Connection *conn = (Connection *)context;
718         struct propval auxvals[3];
719         struct berval authcDN, authzDN;
720         int rc;
721
722 #ifdef NEW_LOGGING
723         LDAP_LOG( TRANSPORT, ENTRY, 
724                 "slap_sasl_authorize: conn %d authcid=\"%s\" authzid=\"%s\"\n",
725                 conn ? conn->c_connid : -1, auth_identity, requested_user);
726 #else
727         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
728                 "authcid=\"%s\" authzid=\"%s\"\n",
729                 conn ? conn->c_connid : -1, auth_identity, requested_user );
730 #endif
731         if ( conn->c_sasl_dn.bv_val ) {
732                 ch_free( conn->c_sasl_dn.bv_val );
733                 conn->c_sasl_dn.bv_val = NULL;
734                 conn->c_sasl_dn.bv_len = 0;
735         }
736
737         /* Skip PROP_CONN */
738         prop_getnames( props, slap_propnames+1, auxvals );
739         
740         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
741
742         /* Nothing to do if no authzID was given */
743         if ( !auxvals[1].name || !auxvals[1].values ) {
744                 conn->c_sasl_dn = authcDN;
745                 goto ok;
746         }
747         
748         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
749
750         rc = slap_sasl_authorized( conn, &authcDN, &authzDN );
751         ch_free( authcDN.bv_val );
752         if ( rc != LDAP_SUCCESS ) {
753 #ifdef NEW_LOGGING
754                 LDAP_LOG( TRANSPORT, INFO, 
755                         "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
756                         (long)(conn ? conn->c_connid : -1), rc, 0 );
757 #else
758                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
759                         " authorization disallowed (%d)\n",
760                         (long) (conn ? conn->c_connid : -1), rc, 0 );
761 #endif
762
763                 sasl_seterror( sconn, 0, "not authorized" );
764                 ch_free( authzDN.bv_val );
765                 return SASL_NOAUTHZ;
766         }
767
768         conn->c_sasl_dn = authzDN;
769 ok:
770         if (conn->c_sasl_bindop) {
771                 Statslog( LDAP_DEBUG_STATS,
772                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
773                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
774                         auth_identity, 0, 0);
775         }
776
777 #ifdef NEW_LOGGING
778         LDAP_LOG( TRANSPORT, ENTRY, 
779                 "slap_sasl_authorize: conn %d authorization allowed\n",
780                 (long)(conn ? conn->c_connid : -1), 0, 0 );
781 #else
782         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
783                 " authorization allowed\n",
784                 (long) (conn ? conn->c_connid : -1), 0, 0 );
785 #endif
786         return SASL_OK;
787
788 #else
789 static int
790 slap_sasl_authorize(
791         void *context,
792         char *authcid,
793         char *authzid,
794         const char **user,
795         const char **errstr)
796 {
797         struct berval authcDN, authzDN;
798         int rc;
799         Connection *conn = context;
800         char *realm;
801
802         *user = NULL;
803         if ( conn->c_sasl_dn.bv_val ) {
804                 ch_free( conn->c_sasl_dn.bv_val );
805                 conn->c_sasl_dn.bv_val = NULL;
806                 conn->c_sasl_dn.bv_len = 0;
807         }
808
809 #ifdef NEW_LOGGING
810         LDAP_LOG( TRANSPORT, ENTRY, 
811                 "slap_sasl_authorize: conn %d    authcid=\"%s\" authzid=\"%s\"\n",
812                 conn ? conn->c_connid : -1, authcid ? authcid : "<empty>",
813                 authzid ? authzid : "<empty>" );
814 #else
815         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
816                 "authcid=\"%s\" authzid=\"%s\"\n",
817                 (long) (conn ? conn->c_connid : -1),
818                 authcid ? authcid : "<empty>",
819                 authzid ? authzid : "<empty>" );
820 #endif
821
822         /* Figure out how much data we have for the dn */
823         rc = sasl_getprop( conn->c_sasl_context, SASL_REALM, (void **)&realm );
824         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
825 #ifdef NEW_LOGGING
826                 LDAP_LOG( TRANSPORT, ERR,
827                         "slap_sasl_authorize: getprop(REALM) failed.\n", 0, 0, 0 );
828 #else
829                 Debug(LDAP_DEBUG_TRACE,
830                         "authorize: getprop(REALM) failed!\n", 0,0,0);
831 #endif
832                 *errstr = "Could not extract realm";
833                 return SASL_NOAUTHZ;
834         }
835
836         /* Convert the identities to DN's. If no authzid was given, client will
837            be bound as the DN matching their username */
838         rc = slap_sasl_getdn( conn, (char *)authcid, 0, realm,
839                 &authcDN, SLAP_GETDN_AUTHCID );
840         if( rc != LDAP_SUCCESS ) {
841                 *errstr = ldap_err2string( rc );
842                 return SASL_NOAUTHZ;
843         }
844         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
845 #ifdef NEW_LOGGING
846                 LDAP_LOG( TRANSPORT, ENTRY, 
847                         "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
848                         conn ? conn->c_connid : -1, authcDN.bv_val, 0 );
849 #else
850                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
851                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
852 #endif
853
854                 conn->c_sasl_dn = authcDN;
855                 goto ok;
856         }
857         rc = slap_sasl_getdn( conn, (char *)authzid, 0, realm,
858                 &authzDN, SLAP_GETDN_AUTHZID );
859         if( rc != LDAP_SUCCESS ) {
860                 ch_free( authcDN.bv_val );
861                 *errstr = ldap_err2string( rc );
862                 return SASL_NOAUTHZ;
863         }
864
865         rc = slap_sasl_authorized(conn, &authcDN, &authzDN );
866         ch_free( authcDN.bv_val );
867         if( rc ) {
868 #ifdef NEW_LOGGING
869                 LDAP_LOG( TRANSPORT, INFO, 
870                         "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
871                         (long)(conn ? conn->c_connid : -1), rc, 0 );
872 #else
873                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
874                         " authorization disallowed (%d)\n",
875                         (long) (conn ? conn->c_connid : -1), rc, 0 );
876 #endif
877
878                 *errstr = "not authorized";
879                 ch_free( authzDN.bv_val );
880                 return SASL_NOAUTHZ;
881         }
882         conn->c_sasl_dn = authzDN;
883
884 ok:
885 #ifdef NEW_LOGGING
886         LDAP_LOG( TRANSPORT, RESULTS, 
887                 "slap_sasl_authorize: conn %d authorization allowed\n",
888            (long)(conn ? conn->c_connid : -1 ), 0, 0 );
889 #else
890         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
891                 " authorization allowed\n",
892                 (long) (conn ? conn->c_connid : -1), 0, 0 );
893 #endif
894
895         if (conn->c_sasl_bindop) {
896                 Statslog( LDAP_DEBUG_STATS,
897                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
898                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
899                         authcid, 0, 0);
900         }
901
902         *errstr = NULL;
903         return SASL_OK;
904 }
905 #endif /* SASL_VERSION_MAJOR >= 2 */
906
907 static int
908 slap_sasl_err2ldap( int saslerr )
909 {
910         int rc;
911
912         switch (saslerr) {
913                 case SASL_CONTINUE:
914                         rc = LDAP_SASL_BIND_IN_PROGRESS;
915                         break;
916                 case SASL_FAIL:
917                         rc = LDAP_OTHER;
918                         break;
919                 case SASL_NOMEM:
920                         rc = LDAP_OTHER;
921                         break;
922                 case SASL_NOMECH:
923                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
924                         break;
925                 case SASL_BADAUTH:
926                         rc = LDAP_INVALID_CREDENTIALS;
927                         break;
928                 case SASL_NOAUTHZ:
929                         rc = LDAP_INSUFFICIENT_ACCESS;
930                         break;
931                 case SASL_TOOWEAK:
932                 case SASL_ENCRYPT:
933                         rc = LDAP_INAPPROPRIATE_AUTH;
934                         break;
935                 default:
936                         rc = LDAP_OTHER;
937                         break;
938         }
939
940         return rc;
941 }
942 #endif
943
944 int slap_sasl_init( void )
945 {
946 #ifdef HAVE_CYRUS_SASL
947         int rc;
948         static sasl_callback_t server_callbacks[] = {
949                 { SASL_CB_LOG, &slap_sasl_log, NULL },
950                 { SASL_CB_LIST_END, NULL, NULL }
951         };
952
953 #ifdef HAVE_SASL_VERSION
954 #define SASL_BUILD_VERSION ((SASL_VERSION_MAJOR << 24) |\
955         (SASL_VERSION_MINOR << 16) | SASL_VERSION_STEP)
956
957         sasl_version( NULL, &rc );
958         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
959                 (rc & 0xffff) < SASL_VERSION_STEP) {
960
961 #ifdef NEW_LOGGING
962                 LDAP_LOG( TRANSPORT, INFO,
963                 "slap_sasl_init: SASL version mismatch, got %x, wanted %x.\n",
964                         rc, SASL_BUILD_VERSION, 0 );
965 #else
966                 Debug( LDAP_DEBUG_ANY,
967                 "slap_sasl_init: SASL version mismatch, got %x, wanted %x.\n",
968                         rc, SASL_BUILD_VERSION, 0 );
969 #endif
970                 return -1;
971         }
972 #endif
973
974         /* SASL 2 does its own memory management internally */
975 #if SASL_VERSION_MAJOR < 2
976         sasl_set_alloc(
977                 ber_memalloc,
978                 ber_memcalloc,
979                 ber_memrealloc,
980                 ber_memfree ); 
981 #endif
982
983         sasl_set_mutex(
984                 ldap_pvt_sasl_mutex_new,
985                 ldap_pvt_sasl_mutex_lock,
986                 ldap_pvt_sasl_mutex_unlock,
987                 ldap_pvt_sasl_mutex_dispose );
988
989 #if SASL_VERSION_MAJOR >= 2
990         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
991 #endif
992         /* should provide callbacks for logging */
993         /* server name should be configurable */
994         rc = sasl_server_init( server_callbacks, "slapd" );
995
996         if( rc != SASL_OK ) {
997 #ifdef NEW_LOGGING
998                 LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: init failed.\n", 0, 0, 0 );
999 #else
1000                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
1001                         0, 0, 0 );
1002 #endif
1003 #if SASL_VERSION_MAJOR < 2
1004                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1005                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1006 #endif
1007
1008                 return -1;
1009         }
1010
1011 #ifdef NEW_LOGGING
1012         LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: initialized!\n", 0, 0, 0 );
1013 #else
1014         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1015                 0, 0, 0 );
1016 #endif
1017
1018
1019         /* default security properties */
1020         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1021         sasl_secprops.max_ssf = INT_MAX;
1022         sasl_secprops.maxbufsize = 65536;
1023         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1024 #endif
1025
1026         return 0;
1027 }
1028
1029 int slap_sasl_destroy( void )
1030 {
1031 #ifdef HAVE_CYRUS_SASL
1032         sasl_done();
1033 #endif
1034 #if SASL_VERSION_MAJOR >= 2
1035         filter_free( generic_filter );
1036 #endif
1037         free( global_host );
1038         global_host = NULL;
1039
1040         return 0;
1041 }
1042
1043 int slap_sasl_open( Connection *conn )
1044 {
1045         int cb, sc = LDAP_SUCCESS;
1046 #if SASL_VERSION_MAJOR >= 2
1047         char *ipremoteport = NULL, *iplocalport = NULL;
1048 #endif
1049
1050 #ifdef HAVE_CYRUS_SASL
1051         sasl_conn_t *ctx = NULL;
1052         sasl_callback_t *session_callbacks;
1053
1054         assert( conn->c_sasl_context == NULL );
1055         assert( conn->c_sasl_extra == NULL );
1056
1057         conn->c_sasl_layers = 0;
1058
1059         session_callbacks =
1060 #if SASL_VERSION_MAJOR >= 2
1061                 SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1062 #else
1063                 SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1064 #endif
1065         if( session_callbacks == NULL ) {
1066 #ifdef NEW_LOGGING
1067                         LDAP_LOG( TRANSPORT, ERR, 
1068                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1069 #else
1070                         Debug( LDAP_DEBUG_ANY, 
1071                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1072 #endif
1073                         return -1;
1074         }
1075         conn->c_sasl_extra = session_callbacks;
1076
1077         session_callbacks[cb=0].id = SASL_CB_LOG;
1078         session_callbacks[cb].proc = &slap_sasl_log;
1079         session_callbacks[cb++].context = conn;
1080
1081         session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1082         session_callbacks[cb].proc = &slap_sasl_authorize;
1083         session_callbacks[cb++].context = conn;
1084
1085 #if SASL_VERSION_MAJOR >= 2
1086         session_callbacks[cb].id = SASL_CB_CANON_USER;
1087         session_callbacks[cb].proc = &slap_sasl_canonicalize;
1088         session_callbacks[cb++].context = conn;
1089
1090         /* XXXX: this should be conditional */
1091         session_callbacks[cb].id = SASL_CB_SERVER_USERDB_CHECKPASS;
1092         session_callbacks[cb].proc = &slap_sasl_checkpass;
1093         session_callbacks[cb++].context = conn;
1094 #endif
1095
1096         session_callbacks[cb].id = SASL_CB_LIST_END;
1097         session_callbacks[cb].proc = NULL;
1098         session_callbacks[cb++].context = NULL;
1099
1100         if( global_host == NULL ) {
1101                 global_host = ldap_pvt_get_fqdn( NULL );
1102         }
1103
1104         /* create new SASL context */
1105 #if SASL_VERSION_MAJOR >= 2
1106         if ( generic_filter == NULL ) {
1107                 generic_filter = str2filter( "(objectclass=*)" );
1108         }
1109         if ( conn->c_sock_name.bv_len != 0 &&
1110              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1111                 char *p;
1112
1113                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1114                 /* Convert IPv6 addresses to address;port syntax. */
1115                 p = strrchr( iplocalport, ' ' );
1116                 /* Convert IPv4 addresses to address;port syntax. */
1117                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1118                 if ( p != NULL ) {
1119                         *p = ';';
1120                 }
1121         }
1122         if ( conn->c_peer_name.bv_len != 0 &&
1123              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1124                 char *p;
1125
1126                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1127                 /* Convert IPv6 addresses to address;port syntax. */
1128                 p = strrchr( ipremoteport, ' ' );
1129                 /* Convert IPv4 addresses to address;port syntax. */
1130                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1131                 if ( p != NULL ) {
1132                         *p = ';';
1133                 }
1134         }
1135         sc = sasl_server_new( "ldap", global_host, global_realm,
1136                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1137         if ( iplocalport != NULL ) {
1138                 ch_free( iplocalport );
1139         }
1140         if ( ipremoteport != NULL ) {
1141                 ch_free( ipremoteport );
1142         }
1143 #else
1144         sc = sasl_server_new( "ldap", global_host, global_realm,
1145                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1146 #endif
1147
1148         if( sc != SASL_OK ) {
1149 #ifdef NEW_LOGGING
1150                 LDAP_LOG( TRANSPORT, ERR, 
1151                         "slap_sasl_open: sasl_server_new failed: %d\n", sc, 0, 0 );
1152 #else
1153                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1154                         sc, 0, 0 );
1155 #endif
1156
1157                 return -1;
1158         }
1159
1160         conn->c_sasl_context = ctx;
1161
1162         if( sc == SASL_OK ) {
1163                 sc = sasl_setprop( ctx,
1164                         SASL_SEC_PROPS, &sasl_secprops );
1165
1166                 if( sc != SASL_OK ) {
1167 #ifdef NEW_LOGGING
1168                         LDAP_LOG( TRANSPORT, ERR, 
1169                                 "slap_sasl_open: sasl_setprop failed: %d \n", sc, 0, 0 );
1170 #else
1171                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1172                                 sc, 0, 0 );
1173 #endif
1174
1175                         slap_sasl_close( conn );
1176                         return -1;
1177                 }
1178         }
1179
1180         sc = slap_sasl_err2ldap( sc );
1181 #endif
1182         return sc;
1183 }
1184
1185 int slap_sasl_external(
1186         Connection *conn,
1187         slap_ssf_t ssf,
1188         const char *auth_id )
1189 {
1190 #if SASL_VERSION_MAJOR >= 2
1191         int sc;
1192         sasl_conn_t *ctx = conn->c_sasl_context;
1193
1194         if ( ctx == NULL ) {
1195                 return LDAP_UNAVAILABLE;
1196         }
1197
1198         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1199
1200         if ( sc != SASL_OK ) {
1201                 return LDAP_OTHER;
1202         }
1203
1204         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL, auth_id );
1205
1206         if ( sc != SASL_OK ) {
1207                 return LDAP_OTHER;
1208         }
1209
1210 #elif defined(HAVE_CYRUS_SASL)
1211         int sc;
1212         sasl_conn_t *ctx = conn->c_sasl_context;
1213         sasl_external_properties_t extprops;
1214
1215         if ( ctx == NULL ) {
1216                 return LDAP_UNAVAILABLE;
1217         }
1218
1219         memset( &extprops, '\0', sizeof(extprops) );
1220         extprops.ssf = ssf;
1221         extprops.auth_id = (char *) auth_id;
1222
1223         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1224                 (void *) &extprops );
1225
1226         if ( sc != SASL_OK ) {
1227                 return LDAP_OTHER;
1228         }
1229 #endif
1230
1231         return LDAP_SUCCESS;
1232 }
1233
1234 int slap_sasl_reset( Connection *conn )
1235 {
1236 #ifdef HAVE_CYRUS_SASL
1237         sasl_conn_t *ctx = conn->c_sasl_context;
1238
1239         if( ctx != NULL ) {
1240         }
1241 #endif
1242         /* must return "anonymous" */
1243         return LDAP_SUCCESS;
1244 }
1245
1246 char ** slap_sasl_mechs( Connection *conn )
1247 {
1248         char **mechs = NULL;
1249
1250 #ifdef HAVE_CYRUS_SASL
1251         sasl_conn_t *ctx = conn->c_sasl_context;
1252
1253         if( ctx != NULL ) {
1254                 int sc;
1255                 SASL_CONST char *mechstr;
1256
1257                 sc = sasl_listmech( ctx,
1258                         NULL, NULL, ",", NULL,
1259                         &mechstr, NULL, NULL );
1260
1261                 if( sc != SASL_OK ) {
1262 #ifdef NEW_LOGGING
1263                         LDAP_LOG( TRANSPORT, ERR, 
1264                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc, 0, 0 );
1265 #else
1266                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1267                                 sc, 0, 0 );
1268 #endif
1269
1270                         return NULL;
1271                 }
1272
1273                 mechs = ldap_str2charray( mechstr, "," );
1274
1275 #if SASL_VERSION_MAJOR < 2
1276                 ch_free( mechstr );
1277 #endif
1278         }
1279 #endif
1280
1281         return mechs;
1282 }
1283
1284 int slap_sasl_close( Connection *conn )
1285 {
1286 #ifdef HAVE_CYRUS_SASL
1287         sasl_conn_t *ctx = conn->c_sasl_context;
1288
1289         if( ctx != NULL ) {
1290                 sasl_dispose( &ctx );
1291         }
1292
1293         conn->c_sasl_context = NULL;
1294
1295         free( conn->c_sasl_extra );
1296         conn->c_sasl_extra = NULL;
1297 #endif
1298
1299         return LDAP_SUCCESS;
1300 }
1301
1302 int slap_sasl_bind(
1303     Connection          *conn,
1304     Operation           *op,  
1305     struct berval       *dn,  
1306     struct berval       *ndn,
1307     struct berval       *cred,
1308         struct berval                   *edn,
1309         slap_ssf_t              *ssfp )
1310 {
1311         int rc = 1;
1312
1313 #ifdef HAVE_CYRUS_SASL
1314         sasl_conn_t *ctx = conn->c_sasl_context;
1315         struct berval response;
1316         unsigned reslen = 0;
1317         const char *errstr = NULL;
1318         int sc;
1319
1320 #ifdef NEW_LOGGING
1321         LDAP_LOG( TRANSPORT, ENTRY, 
1322                 "sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1323                 dn->bv_len ? dn->bv_val : "",
1324                 conn->c_sasl_bind_in_progress ? "<continuing>" : 
1325                 conn->c_sasl_bind_mech.bv_val,
1326                 cred ? cred->bv_len : 0 );
1327 #else
1328         Debug(LDAP_DEBUG_ARGS,
1329                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1330                 dn->bv_len ? dn->bv_val : "",
1331                 conn->c_sasl_bind_in_progress ? "<continuing>":conn->c_sasl_bind_mech.bv_val,
1332                 cred ? cred->bv_len : 0 );
1333 #endif
1334
1335
1336         if( ctx == NULL ) {
1337                 send_ldap_result( conn, op, LDAP_UNAVAILABLE,
1338                         NULL, "SASL unavailable on this session", NULL, NULL );
1339                 return rc;
1340         }
1341
1342 #if SASL_VERSION_MAJOR >= 2
1343 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1344         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1345 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1346         sasl_server_step( ctx, cred, clen, resp, rlen )
1347 #else
1348 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1349         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1350 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1351         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1352 #endif
1353
1354         if ( !conn->c_sasl_bind_in_progress ) {
1355                 sc = START( ctx,
1356                         conn->c_sasl_bind_mech.bv_val,
1357                         cred->bv_val, cred->bv_len,
1358                         (SASL_CONST char **)&response.bv_val, &reslen, &errstr );
1359
1360         } else {
1361                 sc = STEP( ctx,
1362                         cred->bv_val, cred->bv_len,
1363                         (SASL_CONST char **)&response.bv_val, &reslen, &errstr );
1364         }
1365
1366         response.bv_len = reslen;
1367
1368         if ( sc == SASL_OK ) {
1369                 sasl_ssf_t *ssf = NULL;
1370
1371                 *edn = conn->c_sasl_dn;
1372                 conn->c_sasl_dn.bv_val = NULL;
1373                 conn->c_sasl_dn.bv_len = 0;
1374
1375                 rc = LDAP_SUCCESS;
1376
1377                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1378                 *ssfp = ssf ? *ssf : 0;
1379
1380                 if( *ssfp ) {
1381                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1382                         conn->c_sasl_layers++;
1383                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1384                 }
1385
1386                 send_ldap_sasl( conn, op, rc,
1387                         NULL, NULL, NULL, NULL,
1388                         response.bv_len ? &response : NULL );
1389
1390         } else if ( sc == SASL_CONTINUE ) {
1391                 send_ldap_sasl( conn, op, rc = LDAP_SASL_BIND_IN_PROGRESS,
1392                         NULL, NULL, NULL, NULL, &response );
1393
1394         } else {
1395 #if SASL_VERSION_MAJOR >= 2
1396                 errstr = sasl_errdetail( ctx );
1397 #endif
1398                 send_ldap_result( conn, op, rc = slap_sasl_err2ldap( sc ),
1399                         NULL, errstr, NULL, NULL );
1400         }
1401
1402 #if SASL_VERSION_MAJOR < 2
1403         if( response.bv_len ) {
1404                 ch_free( response.bv_val );
1405         }
1406 #endif
1407
1408 #ifdef NEW_LOGGING
1409         LDAP_LOG( TRANSPORT, RESULTS, "slap_sasl_bind: rc=%d\n", rc, 0, 0 );
1410 #else
1411         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rc, 0, 0);
1412 #endif
1413
1414
1415 #else
1416         send_ldap_result( conn, op, rc = LDAP_UNAVAILABLE,
1417                 NULL, "SASL not supported", NULL, NULL );
1418 #endif
1419
1420         return rc;
1421 }
1422
1423 char* slap_sasl_secprops( const char *in )
1424 {
1425 #ifdef HAVE_CYRUS_SASL
1426         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1427
1428         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1429 #else
1430         return "SASL not supported";
1431 #endif
1432 }
1433
1434 #ifdef HAVE_CYRUS_SASL
1435 int
1436 slap_sasl_setpass(
1437         Connection      *conn,
1438         Operation       *op,
1439         const char      *reqoid,
1440         struct berval   *reqdata,
1441         char            **rspoid,
1442         struct berval   **rspdata,
1443         LDAPControl     *** rspctrls,
1444         const char      **text )
1445 {
1446         int rc;
1447         struct berval id = { 0, NULL }; /* needs to come from connection */
1448         struct berval new = { 0, NULL };
1449         struct berval old = { 0, NULL };
1450
1451         assert( reqoid != NULL );
1452         assert( strcmp( LDAP_EXOP_MODIFY_PASSWD, reqoid ) == 0 );
1453
1454         rc = sasl_getprop( conn->c_sasl_context, SASL_USERNAME,
1455                 (SASL_CONST void **)&id.bv_val );
1456
1457         if( rc != SASL_OK ) {
1458                 *text = "unable to retrieve SASL username";
1459                 rc = LDAP_OTHER;
1460                 goto done;
1461         }
1462
1463 #ifdef NEW_LOGGING
1464         LDAP_LOG( BACKEND, ENTRY,
1465                 "slap_sasl_setpass: \"%s\"\n",
1466                 id.bv_val ? id.bv_val : "", 0, 0);
1467 #else
1468         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1469                 id.bv_val ? id.bv_val : "", 0, 0 );
1470 #endif
1471
1472         rc = slap_passwd_parse( reqdata,
1473                 NULL, &old, &new, text );
1474
1475         if( rc != LDAP_SUCCESS ) {
1476                 goto done;
1477         }
1478
1479         if( new.bv_len == 0 ) {
1480                 slap_passwd_generate(&new);
1481
1482                 if( new.bv_len == 0 ) {
1483                         *text = "password generation failed.";
1484                         rc = LDAP_OTHER;
1485                         goto done;
1486                 }
1487                 
1488                 *rspdata = slap_passwd_return( &new );
1489         }
1490
1491 #if SASL_VERSION_MAJOR < 2
1492         rc = sasl_setpass( conn->c_sasl_context,
1493                 id.bv_val, new.bv_val, new.bv_len, 0, text );
1494 #else
1495         rc = sasl_setpass( conn->c_sasl_context, id.bv_val,
1496                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1497         if( rc != SASL_OK ) {
1498                 *text = sasl_errdetail( conn->c_sasl_context );
1499         }
1500 #endif
1501         switch(rc) {
1502                 case SASL_OK:
1503                         rc = LDAP_SUCCESS;
1504                         break;
1505
1506                 case SASL_NOCHANGE:
1507                 case SASL_NOMECH:
1508                 case SASL_DISABLED:
1509                 case SASL_PWLOCK:
1510                 case SASL_FAIL:
1511                 case SASL_BADPARAM:
1512                 default:
1513                         rc = LDAP_OTHER;
1514         }
1515
1516 done:
1517         return rc;
1518 }
1519 #endif /* HAVE_CYRUS_SASL */
1520
1521 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1522    string returned in *dn is in its own allocated memory, and must be free'd 
1523    by the calling process.
1524    -Mark Adamson, Carnegie Mellon
1525
1526    The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1527    on strings passed in directly from SASL.
1528    -Howard Chu, Symas Corp.
1529 */
1530
1531 #define SET_NONE        0
1532 #define SET_DN          1
1533 #define SET_U           2
1534
1535 static struct berval ext_bv = BER_BVC( "EXTERNAL" );
1536
1537 int slap_sasl_getdn( Connection *conn, char *id, int len,
1538         char *user_realm, struct berval *dn, int flags )
1539 {
1540         char *c1;
1541         int rc, is_dn = SET_NONE, do_norm = 1;
1542         struct berval dn2;
1543
1544 #ifdef NEW_LOGGING
1545         LDAP_LOG( TRANSPORT, ENTRY, 
1546                 "slap_sasl_getdn: conn %d id=%s [len=%d]\n",
1547                 conn ? conn->c_connid : -1, id ? (*id ? id : "<empty>") : "NULL", len );
1548 #else
1549         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: id=%s [len=%d]\n", 
1550                 id ? ( *id ? id : "<empty>" ) : "NULL", len, 0 );
1551 #endif
1552
1553         dn->bv_val = NULL;
1554         dn->bv_len = 0;
1555
1556         if ( id ) {
1557                 if ( len == 0 ) len = strlen( id );
1558
1559                 /* Blatantly anonymous ID */
1560                 if ( len == sizeof("anonymous") - 1 &&
1561                         !strcasecmp( id, "anonymous" ) ) {
1562                         return( LDAP_SUCCESS );
1563                 }
1564         } else {
1565                 len = 0;
1566         }
1567
1568         /* An authcID needs to be converted to authzID form. Set the
1569          * values directly into *dn; they will be normalized later. (and
1570          * normalizing always makes a new copy.) An ID from a TLS certificate
1571          * is already normalized, so copy it and skip normalization.
1572          */
1573         if( flags & SLAP_GETDN_AUTHCID ) {
1574                 if( conn->c_sasl_bind_mech.bv_len == ext_bv.bv_len &&
1575                         strcasecmp( ext_bv.bv_val, conn->c_sasl_bind_mech.bv_val ) == 0 )
1576                 {
1577                         /* EXTERNAL DNs are already normalized */
1578                         do_norm = 0;
1579                         is_dn = SET_DN;
1580                         ber_str2bv( id, len, 1, dn );
1581
1582                 } else {
1583                         /* convert to u:<username> form */
1584                         is_dn = SET_U;
1585                         dn->bv_val = id;
1586                         dn->bv_len = len;
1587                 }
1588         }
1589         if( is_dn == SET_NONE ) {
1590                 if( !strncasecmp( id, "u:", sizeof("u:")-1 )) {
1591                         is_dn = SET_U;
1592                         dn->bv_val = id+2;
1593                         dn->bv_len = len-2;
1594                 } else if ( !strncasecmp( id, "dn:", sizeof("dn:")-1) ) {
1595                         is_dn = SET_DN;
1596                         dn->bv_val = id+3;
1597                         dn->bv_len = len-3;
1598                 }
1599         }
1600
1601         /* No other possibilities from here */
1602         if( is_dn == SET_NONE ) {
1603                 dn->bv_val = NULL;
1604                 dn->bv_len = 0;
1605                 return( LDAP_INAPPROPRIATE_AUTH );
1606         }
1607
1608         /* Username strings */
1609         if( is_dn == SET_U ) {
1610                 char *p, *realm;
1611                 len = dn->bv_len + sizeof("uid=")-1 + sizeof(",cn=auth")-1;
1612
1613                 /* username may have embedded realm name */
1614                 if( ( realm = strchr( dn->bv_val, '@') ) ) {
1615                         *realm++ = '\0';
1616                         len += sizeof(",cn=")-2;
1617                 } else if( user_realm && *user_realm ) {
1618                         len += strlen( user_realm ) + sizeof(",cn=")-1;
1619                 }
1620
1621                 if( conn->c_sasl_bind_mech.bv_len ) {
1622                         len += conn->c_sasl_bind_mech.bv_len + sizeof(",cn=")-1;
1623                 }
1624
1625                 /* Build the new dn */
1626                 c1 = dn->bv_val;
1627                 dn->bv_val = SLAP_MALLOC( len+1 );
1628                 if( dn->bv_val == NULL ) {
1629 #ifdef NEW_LOGGING
1630                         LDAP_LOG( TRANSPORT, ERR, 
1631                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1632 #else
1633                         Debug( LDAP_DEBUG_ANY, 
1634                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1635 #endif
1636                         return LDAP_OTHER;
1637                 }
1638                 p = lutil_strcopy( dn->bv_val, "uid=" );
1639                 p = lutil_strncopy( p, c1, dn->bv_len );
1640
1641                 if( realm ) {
1642                         int rlen = dn->bv_len - ( realm - c1 );
1643                         p = lutil_strcopy( p, ",cn=" );
1644                         p = lutil_strncopy( p, realm, rlen );
1645                         realm[-1] = '@';
1646                 } else if( user_realm && *user_realm ) {
1647                         p = lutil_strcopy( p, ",cn=" );
1648                         p = lutil_strcopy( p, user_realm );
1649                 }
1650
1651                 if( conn->c_sasl_bind_mech.bv_len ) {
1652                         p = lutil_strcopy( p, ",cn=" );
1653                         p = lutil_strcopy( p, conn->c_sasl_bind_mech.bv_val );
1654                 }
1655                 p = lutil_strcopy( p, ",cn=auth" );
1656                 dn->bv_len = p - dn->bv_val;
1657
1658 #ifdef NEW_LOGGING
1659                 LDAP_LOG( TRANSPORT, ENTRY, 
1660                         "slap_sasl_getdn: u:id converted to %s.\n", dn->bv_val, 0, 0 );
1661 #else
1662                 Debug( LDAP_DEBUG_TRACE, "getdn: u:id converted to %s\n", dn->bv_val,0,0 );
1663 #endif
1664         } else {
1665                 
1666                 /* Dup the DN in any case, so we don't risk 
1667                  * leaks or dangling pointers later,
1668                  * and the DN value is '\0' terminated */
1669                 ber_dupbv( &dn2, dn );
1670                 dn->bv_val = dn2.bv_val;
1671         }
1672
1673         /* All strings are in DN form now. Normalize if needed. */
1674         if ( do_norm ) {
1675                 rc = dnNormalize2( NULL, dn, &dn2 );
1676
1677                 /* User DNs were constructed above and must be freed now */
1678                 ch_free( dn->bv_val );
1679
1680                 if ( rc != LDAP_SUCCESS ) {
1681                         dn->bv_val = NULL;
1682                         dn->bv_len = 0;
1683                         return rc;
1684                 }
1685                 *dn = dn2;
1686         }
1687
1688         /* Run thru regexp */
1689         slap_sasl2dn( conn, dn, &dn2 );
1690         if( dn2.bv_val ) {
1691                 ch_free( dn->bv_val );
1692                 *dn = dn2;
1693 #ifdef NEW_LOGGING
1694                 LDAP_LOG( TRANSPORT, ENTRY, 
1695                         "slap_sasl_getdn: dn:id converted to %s.\n", dn->bv_val, 0, 0 );
1696 #else
1697                 Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
1698                         dn->bv_val, 0, 0 );
1699 #endif
1700         }
1701
1702         return( LDAP_SUCCESS );
1703 }