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