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