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