]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
feb4d5ecb6385d94562446b43d7763095d7221e8
[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 = { LDAP_FILTER_PRESENT };
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 slap_response sasl_ap_lookup, sasl_cb_checkpass;
309
310 static int
311 sasl_ap_lookup( Operation *op, SlapReply *rs )
312 {
313         BerVarray bv;
314         AttributeDescription *ad;
315         Attribute *a;
316         const char *text;
317         int rc, i;
318         slap_callback *tmp = op->o_callback;
319         lookup_info *sl = tmp->sc_private;
320
321         if (rs->sr_type != REP_SEARCH) return 0;
322
323         for( i = 0; i < sl->last; i++ ) {
324                 const char *name = sl->list[i].name;
325
326                 if ( name[0] == '*' ) {
327                         if ( sl->flags & SASL_AUXPROP_AUTHZID ) continue;
328                         name++;
329                 } else if ( !(sl->flags & SASL_AUXPROP_AUTHZID ) )
330                         continue;
331
332                 if ( sl->list[i].values ) {
333                         if ( !(sl->flags & SASL_AUXPROP_OVERRIDE) ) continue;
334                 }
335                 ad = NULL;
336                 rc = slap_str2ad( name, &ad, &text );
337                 if ( rc != LDAP_SUCCESS ) {
338 #ifdef NEW_LOGGING
339                         LDAP_LOG( TRANSPORT, DETAIL1, 
340                                 "slap_auxprop: str2ad(%s): %s\n", name, text, 0 );
341 #else
342                         Debug( LDAP_DEBUG_TRACE,
343                                 "slap_auxprop: str2ad(%s): %s\n", name, text, 0 );
344 #endif
345                         continue;
346                 }
347                 a = attr_find( rs->sr_entry->e_attrs, ad );
348                 if ( !a ) continue;
349                 if ( ! access_allowed( op, rs->sr_entry, ad, NULL, ACL_AUTH, NULL ) ) {
350                         continue;
351                 }
352                 if ( sl->list[i].values && ( sl->flags & SASL_AUXPROP_OVERRIDE ) ) {
353                         sl->sparams->utils->prop_erase( sl->sparams->propctx,
354                         sl->list[i].name );
355                 }
356                 for ( bv = a->a_vals; bv->bv_val; bv++ ) {
357                         sl->sparams->utils->prop_set( sl->sparams->propctx,
358                                 sl->list[i].name, 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         Operation op = {0};
373         int rc, i, doit=0;
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( &op.o_req_ndn, sl.list[i].values[0], sizeof( struct berval ) );
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( &op.o_req_ndn, sl.list[i].values[0], sizeof( struct berval ) );
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                 slap_callback cb = { sasl_ap_lookup, NULL };
426
427                 cb.sc_private = &sl;
428
429                 op.o_bd = select_backend( &op.o_req_ndn, 0, 1 );
430
431                 if ( op.o_bd && op.o_bd->be_search ) {
432                         SlapReply rs = {REP_RESULT};
433                         op.o_tag = LDAP_REQ_SEARCH;
434                         op.o_protocol = LDAP_VERSION3;
435                         op.o_ndn = conn->c_ndn;
436                         op.o_callback = &cb;
437                         op.o_time = slap_get_time();
438                         op.o_do_not_cache = 1;
439                         op.o_is_auth_check = 1;
440                         op.o_threadctx = conn->c_sasl_bindop->o_threadctx;
441                         op.o_tmpmemctx = conn->c_sasl_bindop->o_tmpmemctx;
442                         op.o_tmpmfuncs = conn->c_sasl_bindop->o_tmpmfuncs;
443 #ifdef LDAP_SLAPI
444                         op.o_pb = conn->c_sasl_bindop->o_pb;
445 #endif
446                         op.o_conn = conn;
447                         op.o_connid = conn->c_connid;
448                         op.ors_scope = LDAP_SCOPE_BASE;
449                         op.ors_deref = LDAP_DEREF_NEVER;
450                         op.ors_slimit = 1;
451                         op.ors_filter = &generic_filter;
452
453                         op.o_bd->be_search( &op, &rs );
454                 }
455         }
456 }
457
458 static sasl_auxprop_plug_t slap_auxprop_plugin = {
459         0,      /* Features */
460         0,      /* spare */
461         NULL,   /* glob_context */
462         NULL,   /* auxprop_free */
463         slap_auxprop_lookup,
464         "slapd",        /* name */
465         NULL    /* spare */
466 };
467
468 static int
469 slap_auxprop_init(
470         const sasl_utils_t *utils,
471         int max_version,
472         int *out_version,
473         sasl_auxprop_plug_t **plug,
474         const char *plugname)
475 {
476         if ( !out_version | !plug ) return SASL_BADPARAM;
477
478         if ( max_version < SASL_AUXPROP_PLUG_VERSION ) return SASL_BADVERS;
479
480         *out_version = SASL_AUXPROP_PLUG_VERSION;
481         *plug = &slap_auxprop_plugin;
482         return SASL_OK;
483 }
484
485 typedef struct checkpass_info {
486         int rc;
487         struct berval cred;
488 } checkpass_info;
489
490 static int
491 sasl_cb_checkpass( Operation *op, SlapReply *rs )
492 {
493         slap_callback *tmp = op->o_callback;
494         checkpass_info *ci = tmp->sc_private;
495         Attribute *a;
496         struct berval *bv;
497         
498         if (rs->sr_type != REP_SEARCH) return 0;
499
500         ci->rc = SASL_NOVERIFY;
501
502         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_userPassword );
503         if ( !a ) return 0;
504         if ( ! access_allowed( op, rs->sr_entry, slap_schema.si_ad_userPassword,
505                 NULL, ACL_AUTH, NULL ) ) return 0;
506
507         for ( bv = a->a_vals; bv->bv_val != NULL; bv++ ) {
508                 if ( !lutil_passwd( bv, &ci->cred, NULL, &rs->sr_text ) ) {
509                         ci->rc = SASL_OK;
510                         break;
511                 }
512         }
513         return 0;
514 }
515
516 static int
517 slap_sasl_checkpass(
518         sasl_conn_t *sconn,
519         void *context,
520         const char *username,
521         const char *pass,
522         unsigned passlen,
523         struct propctx *propctx)
524 {
525         Connection *conn = (Connection *)context;
526         Operation op = {0};
527         int rc;
528         checkpass_info ci;
529
530         ci.rc = SASL_NOUSER;
531
532         /* SASL will fallback to its own mechanisms if we don't
533          * find an answer here.
534          */
535
536         rc = slap_sasl_getdn( conn, NULL, (char *)username, 0, NULL, &op.o_req_ndn,
537                 SLAP_GETDN_AUTHCID );
538         if ( rc != LDAP_SUCCESS ) {
539                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
540                 return SASL_NOUSER;
541         }
542
543         if ( op.o_req_ndn.bv_len == 0 ) {
544                 sasl_seterror( sconn, 0,
545                         "No password is associated with the Root DSE" );
546                 if ( op.o_req_ndn.bv_val != NULL ) {
547                         ch_free( op.o_req_ndn.bv_val );
548                 }
549                 return SASL_NOUSER;
550         }
551
552         op.o_bd = select_backend( &op.o_req_ndn, 0, 1 );
553         if ( op.o_bd && op.o_bd->be_search ) {
554                 slap_callback cb = { sasl_cb_checkpass, NULL };
555                 SlapReply rs = {REP_RESULT};
556
557                 ci.cred.bv_val = (char *)pass;
558                 ci.cred.bv_len = passlen;
559
560                 cb.sc_private = &ci;
561                 op.o_tag = LDAP_REQ_SEARCH;
562                 op.o_protocol = LDAP_VERSION3;
563                 op.o_ndn = conn->c_ndn;
564                 op.o_callback = &cb;
565                 op.o_time = slap_get_time();
566                 op.o_do_not_cache = 1;
567                 op.o_is_auth_check = 1;
568                 op.o_threadctx = conn->c_sasl_bindop->o_threadctx;
569                 op.o_tmpmemctx = conn->c_sasl_bindop->o_tmpmemctx;
570                 op.o_tmpmfuncs = conn->c_sasl_bindop->o_tmpmfuncs;
571 #ifdef LDAP_SLAPI
572                 op.o_pb = conn->c_sasl_bindop->o_pb;
573 #endif
574                 op.o_conn = conn;
575                 op.o_connid = conn->c_connid;
576                 op.ors_scope = LDAP_SCOPE_BASE;
577                 op.ors_deref = LDAP_DEREF_NEVER;
578                 op.ors_slimit = 1;
579                 op.ors_filter = &generic_filter;
580
581                 op.o_bd->be_search( &op, &rs );
582         }
583         if ( ci.rc != SASL_OK ) {
584                 sasl_seterror( sconn, 0,
585                         ldap_err2string( LDAP_INVALID_CREDENTIALS ) );
586         }
587
588         ch_free( op.o_req_ndn.bv_val );
589
590         return ci.rc;
591 }
592
593 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
594  * auxiliary property, so that we can refer to it in sasl_authorize
595  * without interfering with anything else. Also, the SASL username
596  * buffer is constrained to 256 characters, and our DNs could be
597  * much longer (totally arbitrary length)...
598  */
599 static int
600 slap_sasl_canonicalize(
601         sasl_conn_t *sconn,
602         void *context,
603         const char *in,
604         unsigned inlen,
605         unsigned flags,
606         const char *user_realm,
607         char *out,
608         unsigned out_max,
609         unsigned *out_len)
610 {
611         Connection *conn = (Connection *)context;
612         struct propctx *props = sasl_auxprop_getctx( sconn );
613         struct propval auxvals[3];
614         struct berval dn;
615         int rc, which;
616         const char *names[2];
617
618         *out_len = 0;
619
620 #ifdef NEW_LOGGING
621         LDAP_LOG( TRANSPORT, ENTRY, 
622                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
623                 conn ? conn->c_connid : -1,
624                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
625                 in ? in : "<empty>");
626 #else
627         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
628                 conn ? conn->c_connid : -1,
629                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
630                 in ? in : "<empty>");
631 #endif
632
633         /* If name is too big, just truncate. We don't care, we're
634          * using DNs, not the usernames.
635          */
636         if ( inlen > out_max )
637                 inlen = out_max-1;
638
639         /* See if we need to add request, can only do it once */
640         prop_getnames( props, slap_propnames, auxvals );
641         if ( !auxvals[0].name )
642                 prop_request( props, slap_propnames );
643
644         if ( flags & SASL_CU_AUTHID )
645                 which = PROP_AUTHC;
646         else
647                 which = PROP_AUTHZ;
648
649         /* Need to store the Connection for auxprop_lookup */
650         if ( !auxvals[PROP_CONN].values ) {
651                 names[0] = slap_propnames[PROP_CONN];
652                 names[1] = NULL;
653                 prop_set( props, names[0], (char *)&conn, sizeof( conn ) );
654         }
655                 
656         /* Already been here? */
657         if ( auxvals[which].values )
658                 goto done;
659
660         /* Normally we require an authzID to have a u: or dn: prefix.
661          * However, SASL frequently gives us an authzID that is just
662          * an exact copy of the authcID, without a prefix. We need to
663          * detect and allow this condition. If SASL calls canonicalize
664          * with SASL_CU_AUTHID|SASL_CU_AUTHZID this is a no-brainer.
665          * But if it's broken into two calls, we need to remember the
666          * authcID so that we can compare the authzID later. We store
667          * the authcID temporarily in conn->c_sasl_dn. We necessarily
668          * finish Canonicalizing before Authorizing, so there is no
669          * conflict with slap_sasl_authorize's use of this temp var.
670          *
671          * The SASL EXTERNAL mech is backwards from all the other mechs,
672          * it does authzID before the authcID. If we see that authzID
673          * has already been done, don't do anything special with authcID.
674          */
675         if ( flags == SASL_CU_AUTHID && !auxvals[PROP_AUTHZ].values ) {
676                 conn->c_sasl_dn.bv_val = (char *) in;
677         } else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
678                 rc = strcmp( in, conn->c_sasl_dn.bv_val );
679                 conn->c_sasl_dn.bv_val = NULL;
680                 /* They were equal, no work needed */
681                 if ( !rc ) goto done;
682         }
683
684         rc = slap_sasl_getdn( conn, NULL, (char *)in, inlen, (char *)user_realm, &dn,
685                 (flags & SASL_CU_AUTHID) ? SLAP_GETDN_AUTHCID : SLAP_GETDN_AUTHZID );
686         if ( rc != LDAP_SUCCESS ) {
687                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
688                 return SASL_NOAUTHZ;
689         }               
690
691         names[0] = slap_propnames[which];
692         names[1] = NULL;
693
694         prop_set( props, names[0], (char *)&dn, sizeof( dn ) );
695                 
696 #ifdef NEW_LOGGING
697         LDAP_LOG( TRANSPORT, ENTRY, 
698                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
699                 conn ? conn->c_connid : -1, names[0]+1,
700                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
701 #else
702         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
703                 conn ? conn->c_connid : -1, names[0]+1,
704                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
705 #endif
706
707 done:
708         AC_MEMCPY( out, in, inlen );
709         out[inlen] = '\0';
710
711         *out_len = inlen;
712
713         return SASL_OK;
714 }
715
716 static int
717 slap_sasl_authorize(
718         sasl_conn_t *sconn,
719         void *context,
720         char *requested_user,
721         unsigned rlen,
722         char *auth_identity,
723         unsigned alen,
724         const char *def_realm,
725         unsigned urlen,
726         struct propctx *props)
727 {
728         Connection *conn = (Connection *)context;
729         struct propval auxvals[3];
730         struct berval authcDN, authzDN;
731         int rc;
732
733 #ifdef NEW_LOGGING
734         LDAP_LOG( TRANSPORT, ENTRY, 
735                 "slap_sasl_authorize: conn %d authcid=\"%s\" authzid=\"%s\"\n",
736                 conn ? conn->c_connid : -1, auth_identity, requested_user);
737 #else
738         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
739                 "authcid=\"%s\" authzid=\"%s\"\n",
740                 conn ? conn->c_connid : -1, auth_identity, requested_user );
741 #endif
742         if ( conn->c_sasl_dn.bv_val ) {
743                 ch_free( conn->c_sasl_dn.bv_val );
744                 conn->c_sasl_dn.bv_val = NULL;
745                 conn->c_sasl_dn.bv_len = 0;
746         }
747
748         /* Skip PROP_CONN */
749         prop_getnames( props, slap_propnames+1, auxvals );
750         
751         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
752
753         /* Nothing to do if no authzID was given */
754         if ( !auxvals[1].name || !auxvals[1].values ) {
755                 conn->c_sasl_dn = authcDN;
756                 goto ok;
757         }
758         
759         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
760
761         rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
762         ch_free( authcDN.bv_val );
763         if ( rc != LDAP_SUCCESS ) {
764 #ifdef NEW_LOGGING
765                 LDAP_LOG( TRANSPORT, INFO, 
766                         "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
767                         (long)(conn ? conn->c_connid : -1), rc, 0 );
768 #else
769                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
770                         " authorization disallowed (%d)\n",
771                         (long) (conn ? conn->c_connid : -1), rc, 0 );
772 #endif
773
774                 sasl_seterror( sconn, 0, "not authorized" );
775                 ch_free( authzDN.bv_val );
776                 return SASL_NOAUTHZ;
777         }
778
779         conn->c_sasl_dn = authzDN;
780 ok:
781         if (conn->c_sasl_bindop) {
782                 Statslog( LDAP_DEBUG_STATS,
783                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
784                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
785                         auth_identity, 0, 0);
786         }
787
788 #ifdef NEW_LOGGING
789         LDAP_LOG( TRANSPORT, ENTRY, 
790                 "slap_sasl_authorize: conn %d authorization allowed\n",
791                 (long)(conn ? conn->c_connid : -1), 0, 0 );
792 #else
793         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
794                 " authorization allowed\n",
795                 (long) (conn ? conn->c_connid : -1), 0, 0 );
796 #endif
797         return SASL_OK;
798
799 #else
800 static int
801 slap_sasl_authorize(
802         void *context,
803         char *authcid,
804         char *authzid,
805         const char **user,
806         const char **errstr)
807 {
808         struct berval authcDN, authzDN;
809         int rc;
810         Connection *conn = context;
811         char *realm;
812
813         *user = NULL;
814         if ( conn->c_sasl_dn.bv_val ) {
815                 ch_free( conn->c_sasl_dn.bv_val );
816                 conn->c_sasl_dn.bv_val = NULL;
817                 conn->c_sasl_dn.bv_len = 0;
818         }
819
820 #ifdef NEW_LOGGING
821         LDAP_LOG( TRANSPORT, ENTRY, 
822                 "slap_sasl_authorize: conn %d    authcid=\"%s\" authzid=\"%s\"\n",
823                 conn ? conn->c_connid : -1, authcid ? authcid : "<empty>",
824                 authzid ? authzid : "<empty>" );
825 #else
826         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
827                 "authcid=\"%s\" authzid=\"%s\"\n",
828                 (long) (conn ? conn->c_connid : -1),
829                 authcid ? authcid : "<empty>",
830                 authzid ? authzid : "<empty>" );
831 #endif
832
833         /* Figure out how much data we have for the dn */
834         rc = sasl_getprop( conn->c_sasl_authctx, SASL_REALM, (void **)&realm );
835         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
836 #ifdef NEW_LOGGING
837                 LDAP_LOG( TRANSPORT, ERR,
838                         "slap_sasl_authorize: getprop(REALM) failed.\n", 0, 0, 0 );
839 #else
840                 Debug(LDAP_DEBUG_TRACE,
841                         "authorize: getprop(REALM) failed!\n", 0,0,0);
842 #endif
843                 *errstr = "Could not extract realm";
844                 return SASL_NOAUTHZ;
845         }
846
847         /* Convert the identities to DN's. If no authzid was given, client will
848            be bound as the DN matching their username */
849         rc = slap_sasl_getdn( conn, NULL, (char *)authcid, 0, realm,
850                 &authcDN, SLAP_GETDN_AUTHCID );
851         if( rc != LDAP_SUCCESS ) {
852                 *errstr = ldap_err2string( rc );
853                 return SASL_NOAUTHZ;
854         }
855         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
856 #ifdef NEW_LOGGING
857                 LDAP_LOG( TRANSPORT, ENTRY, 
858                         "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
859                         conn ? conn->c_connid : -1, authcDN.bv_val, 0 );
860 #else
861                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
862                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
863 #endif
864
865                 conn->c_sasl_dn = authcDN;
866                 goto ok;
867         }
868         rc = slap_sasl_getdn( conn, NULL, (char *)authzid, 0, realm,
869                 &authzDN, SLAP_GETDN_AUTHZID );
870         if( rc != LDAP_SUCCESS ) {
871                 ch_free( authcDN.bv_val );
872                 *errstr = ldap_err2string( rc );
873                 return SASL_NOAUTHZ;
874         }
875
876         rc = slap_sasl_authorized(conn->c_sasl_bindop, &authcDN, &authzDN );
877         ch_free( authcDN.bv_val );
878         if( rc ) {
879 #ifdef NEW_LOGGING
880                 LDAP_LOG( TRANSPORT, INFO, 
881                         "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
882                         (long)(conn ? conn->c_connid : -1), rc, 0 );
883 #else
884                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
885                         " authorization disallowed (%d)\n",
886                         (long) (conn ? conn->c_connid : -1), rc, 0 );
887 #endif
888
889                 *errstr = "not authorized";
890                 ch_free( authzDN.bv_val );
891                 return SASL_NOAUTHZ;
892         }
893         conn->c_sasl_dn = authzDN;
894
895 ok:
896 #ifdef NEW_LOGGING
897         LDAP_LOG( TRANSPORT, RESULTS, 
898                 "slap_sasl_authorize: conn %d authorization allowed\n",
899            (long)(conn ? conn->c_connid : -1 ), 0, 0 );
900 #else
901         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
902                 " authorization allowed\n",
903                 (long) (conn ? conn->c_connid : -1), 0, 0 );
904 #endif
905
906         if (conn->c_sasl_bindop) {
907                 Statslog( LDAP_DEBUG_STATS,
908                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
909                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
910                         authcid, 0, 0);
911         }
912
913         *errstr = NULL;
914         return SASL_OK;
915 }
916 #endif /* SASL_VERSION_MAJOR >= 2 */
917
918 static int
919 slap_sasl_err2ldap( int saslerr )
920 {
921         int rc;
922
923         switch (saslerr) {
924                 case SASL_OK:
925                         rc = LDAP_SUCCESS;
926                         break;
927                 case SASL_CONTINUE:
928                         rc = LDAP_SASL_BIND_IN_PROGRESS;
929                         break;
930                 case SASL_FAIL:
931                         rc = LDAP_OTHER;
932                         break;
933                 case SASL_NOMEM:
934                         rc = LDAP_OTHER;
935                         break;
936                 case SASL_NOMECH:
937                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
938                         break;
939                 case SASL_BADAUTH:
940                         rc = LDAP_INVALID_CREDENTIALS;
941                         break;
942                 case SASL_NOAUTHZ:
943                         rc = LDAP_INSUFFICIENT_ACCESS;
944                         break;
945                 case SASL_TOOWEAK:
946                 case SASL_ENCRYPT:
947                         rc = LDAP_INAPPROPRIATE_AUTH;
948                         break;
949                 default:
950                         rc = LDAP_OTHER;
951                         break;
952         }
953
954         return rc;
955 }
956 #endif
957
958 int slap_sasl_init( void )
959 {
960 #ifdef HAVE_CYRUS_SASL
961         int rc;
962         static sasl_callback_t server_callbacks[] = {
963                 { SASL_CB_LOG, &slap_sasl_log, NULL },
964                 { SASL_CB_LIST_END, NULL, NULL }
965         };
966
967 #ifdef HAVE_SASL_VERSION
968 #define SASL_BUILD_VERSION ((SASL_VERSION_MAJOR << 24) |\
969         (SASL_VERSION_MINOR << 16) | SASL_VERSION_STEP)
970
971         sasl_version( NULL, &rc );
972         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
973                 (rc & 0xffff) < SASL_VERSION_STEP) {
974
975 #ifdef NEW_LOGGING
976                 LDAP_LOG( TRANSPORT, INFO,
977                 "slap_sasl_init: SASL version mismatch, got %x, wanted %x.\n",
978                         rc, SASL_BUILD_VERSION, 0 );
979 #else
980                 Debug( LDAP_DEBUG_ANY,
981                 "slap_sasl_init: SASL version mismatch, got %x, wanted %x.\n",
982                         rc, SASL_BUILD_VERSION, 0 );
983 #endif
984                 return -1;
985         }
986 #endif
987
988         /* SASL 2 does its own memory management internally */
989 #if SASL_VERSION_MAJOR < 2
990         sasl_set_alloc(
991                 ber_memalloc,
992                 ber_memcalloc,
993                 ber_memrealloc,
994                 ber_memfree ); 
995 #endif
996
997         sasl_set_mutex(
998                 ldap_pvt_sasl_mutex_new,
999                 ldap_pvt_sasl_mutex_lock,
1000                 ldap_pvt_sasl_mutex_unlock,
1001                 ldap_pvt_sasl_mutex_dispose );
1002
1003 #if SASL_VERSION_MAJOR >= 2
1004         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1005
1006         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1007 #endif
1008         /* should provide callbacks for logging */
1009         /* server name should be configurable */
1010         rc = sasl_server_init( server_callbacks, "slapd" );
1011
1012         if( rc != SASL_OK ) {
1013 #ifdef NEW_LOGGING
1014                 LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: init failed.\n", 0, 0, 0 );
1015 #else
1016                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
1017                         0, 0, 0 );
1018 #endif
1019 #if SASL_VERSION_MAJOR < 2
1020                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1021                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1022 #endif
1023
1024                 return -1;
1025         }
1026
1027 #ifdef NEW_LOGGING
1028         LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: initialized!\n", 0, 0, 0 );
1029 #else
1030         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1031                 0, 0, 0 );
1032 #endif
1033
1034
1035         /* default security properties */
1036         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1037         sasl_secprops.max_ssf = INT_MAX;
1038         sasl_secprops.maxbufsize = 65536;
1039         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1040 #endif
1041
1042         return 0;
1043 }
1044
1045 int slap_sasl_destroy( void )
1046 {
1047 #ifdef HAVE_CYRUS_SASL
1048         sasl_done();
1049 #endif
1050         free( global_host );
1051         global_host = NULL;
1052
1053         return 0;
1054 }
1055
1056 int slap_sasl_open( Connection *conn, int reopen )
1057 {
1058         int cb, sc = LDAP_SUCCESS;
1059 #if SASL_VERSION_MAJOR >= 2
1060         char *ipremoteport = NULL, *iplocalport = NULL;
1061 #endif
1062
1063 #ifdef HAVE_CYRUS_SASL
1064         sasl_conn_t *ctx = NULL;
1065         sasl_callback_t *session_callbacks;
1066
1067         assert( conn->c_sasl_authctx == NULL );
1068
1069         if ( !reopen ) {
1070                 assert( conn->c_sasl_extra == NULL );
1071
1072                 session_callbacks =
1073 #if SASL_VERSION_MAJOR >= 2
1074                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1075 #else
1076                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1077 #endif
1078                 if( session_callbacks == NULL ) {
1079 #ifdef NEW_LOGGING
1080                         LDAP_LOG( TRANSPORT, ERR, 
1081                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1082 #else
1083                         Debug( LDAP_DEBUG_ANY, 
1084                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1085 #endif
1086                         return -1;
1087                 }
1088                 conn->c_sasl_extra = session_callbacks;
1089
1090                 session_callbacks[cb=0].id = SASL_CB_LOG;
1091                 session_callbacks[cb].proc = &slap_sasl_log;
1092                 session_callbacks[cb++].context = conn;
1093
1094                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1095                 session_callbacks[cb].proc = &slap_sasl_authorize;
1096                 session_callbacks[cb++].context = conn;
1097
1098 #if SASL_VERSION_MAJOR >= 2
1099                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1100                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1101                 session_callbacks[cb++].context = conn;
1102
1103                 /* XXXX: this should be conditional */
1104                 session_callbacks[cb].id = SASL_CB_SERVER_USERDB_CHECKPASS;
1105                 session_callbacks[cb].proc = &slap_sasl_checkpass;
1106                 session_callbacks[cb++].context = conn;
1107 #endif
1108
1109                 session_callbacks[cb].id = SASL_CB_LIST_END;
1110                 session_callbacks[cb].proc = NULL;
1111                 session_callbacks[cb++].context = NULL;
1112         } else {
1113                 session_callbacks = conn->c_sasl_extra;
1114         }
1115
1116         conn->c_sasl_layers = 0;
1117
1118         if( global_host == NULL ) {
1119                 global_host = ldap_pvt_get_fqdn( NULL );
1120         }
1121
1122         /* create new SASL context */
1123 #if SASL_VERSION_MAJOR >= 2
1124         if ( conn->c_sock_name.bv_len != 0 &&
1125              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1126                 char *p;
1127
1128                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1129                 /* Convert IPv6 addresses to address;port syntax. */
1130                 p = strrchr( iplocalport, ' ' );
1131                 /* Convert IPv4 addresses to address;port syntax. */
1132                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1133                 if ( p != NULL ) {
1134                         *p = ';';
1135                 }
1136         }
1137         if ( conn->c_peer_name.bv_len != 0 &&
1138              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1139                 char *p;
1140
1141                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1142                 /* Convert IPv6 addresses to address;port syntax. */
1143                 p = strrchr( ipremoteport, ' ' );
1144                 /* Convert IPv4 addresses to address;port syntax. */
1145                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1146                 if ( p != NULL ) {
1147                         *p = ';';
1148                 }
1149         }
1150         sc = sasl_server_new( "ldap", global_host, global_realm,
1151                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1152         if ( iplocalport != NULL ) {
1153                 ch_free( iplocalport );
1154         }
1155         if ( ipremoteport != NULL ) {
1156                 ch_free( ipremoteport );
1157         }
1158 #else
1159         sc = sasl_server_new( "ldap", global_host, global_realm,
1160                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1161 #endif
1162
1163         if( sc != SASL_OK ) {
1164 #ifdef NEW_LOGGING
1165                 LDAP_LOG( TRANSPORT, ERR, 
1166                         "slap_sasl_open: sasl_server_new failed: %d\n", sc, 0, 0 );
1167 #else
1168                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1169                         sc, 0, 0 );
1170 #endif
1171
1172                 return -1;
1173         }
1174
1175         conn->c_sasl_authctx = ctx;
1176
1177         if( sc == SASL_OK ) {
1178                 sc = sasl_setprop( ctx,
1179                         SASL_SEC_PROPS, &sasl_secprops );
1180
1181                 if( sc != SASL_OK ) {
1182 #ifdef NEW_LOGGING
1183                         LDAP_LOG( TRANSPORT, ERR, 
1184                                 "slap_sasl_open: sasl_setprop failed: %d \n", sc, 0, 0 );
1185 #else
1186                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1187                                 sc, 0, 0 );
1188 #endif
1189
1190                         slap_sasl_close( conn );
1191                         return -1;
1192                 }
1193         }
1194
1195         sc = slap_sasl_err2ldap( sc );
1196 #endif
1197         return sc;
1198 }
1199
1200 int slap_sasl_external(
1201         Connection *conn,
1202         slap_ssf_t ssf,
1203         const char *auth_id )
1204 {
1205 #if SASL_VERSION_MAJOR >= 2
1206         int sc;
1207         sasl_conn_t *ctx = conn->c_sasl_authctx;
1208
1209         if ( ctx == NULL ) {
1210                 return LDAP_UNAVAILABLE;
1211         }
1212
1213         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1214
1215         if ( sc != SASL_OK ) {
1216                 return LDAP_OTHER;
1217         }
1218
1219         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL, auth_id );
1220
1221         if ( sc != SASL_OK ) {
1222                 return LDAP_OTHER;
1223         }
1224
1225 #elif defined(HAVE_CYRUS_SASL)
1226         int sc;
1227         sasl_conn_t *ctx = conn->c_sasl_authctx;
1228         sasl_external_properties_t extprops;
1229
1230         if ( ctx == NULL ) {
1231                 return LDAP_UNAVAILABLE;
1232         }
1233
1234         memset( &extprops, '\0', sizeof(extprops) );
1235         extprops.ssf = ssf;
1236         extprops.auth_id = (char *) auth_id;
1237
1238         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1239                 (void *) &extprops );
1240
1241         if ( sc != SASL_OK ) {
1242                 return LDAP_OTHER;
1243         }
1244 #endif
1245
1246         return LDAP_SUCCESS;
1247 }
1248
1249 int slap_sasl_reset( Connection *conn )
1250 {
1251         return LDAP_SUCCESS;
1252 }
1253
1254 char ** slap_sasl_mechs( Connection *conn )
1255 {
1256         char **mechs = NULL;
1257
1258 #ifdef HAVE_CYRUS_SASL
1259         sasl_conn_t *ctx = conn->c_sasl_authctx;
1260
1261         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1262
1263         if( ctx != NULL ) {
1264                 int sc;
1265                 SASL_CONST char *mechstr;
1266
1267                 sc = sasl_listmech( ctx,
1268                         NULL, NULL, ",", NULL,
1269                         &mechstr, NULL, NULL );
1270
1271                 if( sc != SASL_OK ) {
1272 #ifdef NEW_LOGGING
1273                         LDAP_LOG( TRANSPORT, ERR, 
1274                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc, 0, 0 );
1275 #else
1276                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1277                                 sc, 0, 0 );
1278 #endif
1279
1280                         return NULL;
1281                 }
1282
1283                 mechs = ldap_str2charray( mechstr, "," );
1284
1285 #if SASL_VERSION_MAJOR < 2
1286                 ch_free( mechstr );
1287 #endif
1288         }
1289 #endif
1290
1291         return mechs;
1292 }
1293
1294 int slap_sasl_close( Connection *conn )
1295 {
1296 #ifdef HAVE_CYRUS_SASL
1297         sasl_conn_t *ctx = conn->c_sasl_authctx;
1298
1299         if( ctx != NULL ) {
1300                 sasl_dispose( &ctx );
1301         }
1302         if ( conn->c_sasl_sockctx && conn->c_sasl_authctx != conn->c_sasl_sockctx ) {
1303                 ctx = conn->c_sasl_sockctx;
1304                 sasl_dispose( &ctx );
1305         }
1306
1307         conn->c_sasl_authctx = NULL;
1308         conn->c_sasl_sockctx = NULL;
1309         conn->c_sasl_done = 0;
1310
1311         free( conn->c_sasl_extra );
1312         conn->c_sasl_extra = NULL;
1313 #endif
1314
1315         return LDAP_SUCCESS;
1316 }
1317
1318 int slap_sasl_bind( Operation *op, SlapReply *rs )
1319 {
1320 #ifdef HAVE_CYRUS_SASL
1321         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1322         struct berval response;
1323         unsigned reslen = 0;
1324         int sc;
1325
1326 #ifdef NEW_LOGGING
1327         LDAP_LOG( TRANSPORT, ENTRY, 
1328                 "sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1329                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1330                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1331                 op->o_conn->c_sasl_bind_mech.bv_val,
1332                 op->orb_cred.bv_len );
1333 #else
1334         Debug(LDAP_DEBUG_ARGS,
1335                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1336                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1337                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1338                 op->o_conn->c_sasl_bind_mech.bv_val,
1339                 op->orb_cred.bv_len );
1340 #endif
1341
1342
1343         if( ctx == NULL ) {
1344                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1345                         "SASL unavailable on this session" );
1346                 return rs->sr_err;
1347         }
1348
1349 #if SASL_VERSION_MAJOR >= 2
1350 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1351         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1352 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1353         sasl_server_step( ctx, cred, clen, resp, rlen )
1354 #else
1355 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1356         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1357 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1358         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1359 #endif
1360
1361         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1362                 /* If we already authenticated once, must use a new context */
1363                 if ( op->o_conn->c_sasl_done ) {
1364                         slap_ssf_t ssf = 0;
1365                         const char *authid = NULL;
1366 #if SASL_VERSION_MAJOR >= 2
1367                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1368                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1369                         if ( authid ) authid = ch_strdup( authid );
1370 #endif
1371                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1372                                 sasl_dispose( &ctx );
1373                         }
1374                         op->o_conn->c_sasl_authctx = NULL;
1375                                 
1376                         slap_sasl_open( op->o_conn, 1 );
1377                         ctx = op->o_conn->c_sasl_authctx;
1378 #if SASL_VERSION_MAJOR >= 2
1379                         if ( authid ) {
1380                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1381                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1382                                 ch_free( (char *)authid );
1383                         }
1384 #endif
1385                 }
1386                 sc = START( ctx,
1387                         op->o_conn->c_sasl_bind_mech.bv_val,
1388                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1389                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1390
1391         } else {
1392                 sc = STEP( ctx,
1393                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1394                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1395         }
1396
1397         response.bv_len = reslen;
1398
1399         if ( sc == SASL_OK ) {
1400                 sasl_ssf_t *ssf = NULL;
1401
1402                 op->orb_edn = op->o_conn->c_sasl_dn;
1403                 op->o_conn->c_sasl_dn.bv_val = NULL;
1404                 op->o_conn->c_sasl_dn.bv_len = 0;
1405                 op->o_conn->c_sasl_done = 1;
1406
1407                 rs->sr_err = LDAP_SUCCESS;
1408
1409                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1410                 op->orb_ssf = ssf ? *ssf : 0;
1411
1412                 ctx = NULL;
1413                 if( op->orb_ssf ) {
1414                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1415                         op->o_conn->c_sasl_layers++;
1416
1417                         /* If there's an old layer, set sockctx to NULL to
1418                          * tell connection_read() to wait for us to finish.
1419                          * Otherwise there is a race condition: we have to
1420                          * send the Bind response using the old security
1421                          * context and then remove it before reading any
1422                          * new messages.
1423                          */
1424                         if ( op->o_conn->c_sasl_sockctx ) {
1425                                 ctx = op->o_conn->c_sasl_sockctx;
1426                                 op->o_conn->c_sasl_sockctx = NULL;
1427                         } else {
1428                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1429                         }
1430                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1431                 }
1432
1433                 /* Must send response using old security layer */
1434                 if (response.bv_len) rs->sr_sasldata = &response;
1435                 send_ldap_sasl( op, rs );
1436                 
1437                 /* Now dispose of the old security layer.
1438                  */
1439                 if ( ctx ) {
1440                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1441                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1442                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1443                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1444                         sasl_dispose( &ctx );
1445                 }
1446         } else if ( sc == SASL_CONTINUE ) {
1447                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1448                 rs->sr_sasldata = &response;
1449                 send_ldap_sasl( op, rs );
1450
1451         } else {
1452 #if SASL_VERSION_MAJOR >= 2
1453                 rs->sr_text = sasl_errdetail( ctx );
1454 #endif
1455                 rs->sr_err = slap_sasl_err2ldap( sc ),
1456                 send_ldap_result( op, rs );
1457         }
1458
1459 #if SASL_VERSION_MAJOR < 2
1460         if( response.bv_len ) {
1461                 ch_free( response.bv_val );
1462         }
1463 #endif
1464
1465 #ifdef NEW_LOGGING
1466         LDAP_LOG( TRANSPORT, RESULTS, "slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0 );
1467 #else
1468         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1469 #endif
1470
1471
1472 #else
1473         send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1474                 "SASL not supported" );
1475 #endif
1476
1477         return rs->sr_err;
1478 }
1479
1480 char* slap_sasl_secprops( const char *in )
1481 {
1482 #ifdef HAVE_CYRUS_SASL
1483         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1484
1485         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1486 #else
1487         return "SASL not supported";
1488 #endif
1489 }
1490
1491 #ifdef HAVE_CYRUS_SASL
1492 int
1493 slap_sasl_setpass( Operation *op, SlapReply *rs )
1494 {
1495         struct berval id = { 0, NULL }; /* needs to come from connection */
1496         struct berval new = { 0, NULL };
1497         struct berval old = { 0, NULL };
1498
1499         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1500
1501         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1502                 (SASL_CONST void **)&id.bv_val );
1503
1504         if( rs->sr_err != SASL_OK ) {
1505                 rs->sr_text = "unable to retrieve SASL username";
1506                 rs->sr_err = LDAP_OTHER;
1507                 goto done;
1508         }
1509
1510 #ifdef NEW_LOGGING
1511         LDAP_LOG( BACKEND, ENTRY,
1512                 "slap_sasl_setpass: \"%s\"\n",
1513                 id.bv_val ? id.bv_val : "", 0, 0);
1514 #else
1515         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1516                 id.bv_val ? id.bv_val : "", 0, 0 );
1517 #endif
1518
1519         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1520                 NULL, &old, &new, &rs->sr_text );
1521
1522         if( rs->sr_err != LDAP_SUCCESS ) {
1523                 goto done;
1524         }
1525
1526         if( new.bv_len == 0 ) {
1527                 slap_passwd_generate(&new);
1528
1529                 if( new.bv_len == 0 ) {
1530                         rs->sr_text = "password generation failed.";
1531                         rs->sr_err = LDAP_OTHER;
1532                         goto done;
1533                 }
1534                 
1535                 rs->sr_rspdata = slap_passwd_return( &new );
1536         }
1537
1538 #if SASL_VERSION_MAJOR < 2
1539         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx,
1540                 id.bv_val, new.bv_val, new.bv_len, 0, &rs->sr_text );
1541 #else
1542         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1543                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1544         if( rs->sr_err != SASL_OK ) {
1545                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1546         }
1547 #endif
1548         switch(rs->sr_err) {
1549                 case SASL_OK:
1550                         rs->sr_err = LDAP_SUCCESS;
1551                         break;
1552
1553                 case SASL_NOCHANGE:
1554                 case SASL_NOMECH:
1555                 case SASL_DISABLED:
1556                 case SASL_PWLOCK:
1557                 case SASL_FAIL:
1558                 case SASL_BADPARAM:
1559                 default:
1560                         rs->sr_err = LDAP_OTHER;
1561         }
1562
1563 done:
1564         return rs->sr_err;
1565 }
1566 #endif /* HAVE_CYRUS_SASL */
1567
1568 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1569    string returned in *dn is in its own allocated memory, and must be free'd 
1570    by the calling process.
1571    -Mark Adamson, Carnegie Mellon
1572
1573    The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1574    on strings passed in directly from SASL.
1575    -Howard Chu, Symas Corp.
1576 */
1577
1578 #define SET_NONE        0
1579 #define SET_DN          1
1580 #define SET_U           2
1581
1582 static struct berval ext_bv = BER_BVC( "EXTERNAL" );
1583
1584 int slap_sasl_getdn( Connection *conn, Operation *op, char *id, int len,
1585         char *user_realm, struct berval *dn, int flags )
1586 {
1587         char *c1;
1588         int rc, is_dn = SET_NONE, do_norm = 1;
1589         struct berval dn2;
1590
1591 #ifdef NEW_LOGGING
1592         LDAP_LOG( TRANSPORT, ENTRY, 
1593                 "slap_sasl_getdn: conn %d id=%s [len=%d]\n",
1594                 conn ? conn->c_connid : -1, id ? (*id ? id : "<empty>") : "NULL", len );
1595 #else
1596         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: id=%s [len=%d]\n", 
1597                 id ? ( *id ? id : "<empty>" ) : "NULL", len, 0 );
1598 #endif
1599
1600         if ( !op ) {
1601                 op = conn->c_sasl_bindop;
1602         }
1603
1604         dn->bv_val = NULL;
1605         dn->bv_len = 0;
1606
1607         if ( id ) {
1608                 if ( len == 0 ) len = strlen( id );
1609
1610                 /* Blatantly anonymous ID */
1611                 if ( len == sizeof("anonymous") - 1 &&
1612                         !strcasecmp( id, "anonymous" ) ) {
1613                         return( LDAP_SUCCESS );
1614                 }
1615         } else {
1616                 len = 0;
1617         }
1618
1619         /* An authcID needs to be converted to authzID form. Set the
1620          * values directly into *dn; they will be normalized later. (and
1621          * normalizing always makes a new copy.) An ID from a TLS certificate
1622          * is already normalized, so copy it and skip normalization.
1623          */
1624         if( flags & SLAP_GETDN_AUTHCID ) {
1625                 if( conn->c_sasl_bind_mech.bv_len == ext_bv.bv_len &&
1626                         strcasecmp( ext_bv.bv_val, conn->c_sasl_bind_mech.bv_val ) == 0 )
1627                 {
1628                         /* EXTERNAL DNs are already normalized */
1629                         do_norm = 0;
1630                         is_dn = SET_DN;
1631                         ber_str2bv_x( id, len, 1, dn, op->o_tmpmemctx );
1632
1633                 } else {
1634                         /* convert to u:<username> form */
1635                         is_dn = SET_U;
1636                         dn->bv_val = id;
1637                         dn->bv_len = len;
1638                 }
1639         }
1640         if( is_dn == SET_NONE ) {
1641                 if( !strncasecmp( id, "u:", sizeof("u:")-1 )) {
1642                         is_dn = SET_U;
1643                         dn->bv_val = id+2;
1644                         dn->bv_len = len-2;
1645                 } else if ( !strncasecmp( id, "dn:", sizeof("dn:")-1) ) {
1646                         is_dn = SET_DN;
1647                         dn->bv_val = id+3;
1648                         dn->bv_len = len-3;
1649                 }
1650         }
1651
1652         /* No other possibilities from here */
1653         if( is_dn == SET_NONE ) {
1654                 dn->bv_val = NULL;
1655                 dn->bv_len = 0;
1656                 return( LDAP_INAPPROPRIATE_AUTH );
1657         }
1658
1659         /* Username strings */
1660         if( is_dn == SET_U ) {
1661                 char *p, *realm;
1662                 len = dn->bv_len + sizeof("uid=")-1 + sizeof(",cn=auth")-1;
1663
1664                 /* username may have embedded realm name */
1665                 if( ( realm = strchr( dn->bv_val, '@') ) ) {
1666                         *realm++ = '\0';
1667                         len += sizeof(",cn=")-2;
1668                 } else if( user_realm && *user_realm ) {
1669                         len += strlen( user_realm ) + sizeof(",cn=")-1;
1670                 }
1671
1672                 if( conn->c_sasl_bind_mech.bv_len ) {
1673                         len += conn->c_sasl_bind_mech.bv_len + sizeof(",cn=")-1;
1674                 }
1675
1676                 /* Build the new dn */
1677                 c1 = dn->bv_val;
1678                 dn->bv_val = sl_malloc( len+1, op->o_tmpmemctx );
1679                 if( dn->bv_val == NULL ) {
1680 #ifdef NEW_LOGGING
1681                         LDAP_LOG( TRANSPORT, ERR, 
1682                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1683 #else
1684                         Debug( LDAP_DEBUG_ANY, 
1685                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1686 #endif
1687                         return LDAP_OTHER;
1688                 }
1689                 p = lutil_strcopy( dn->bv_val, "uid=" );
1690                 p = lutil_strncopy( p, c1, dn->bv_len );
1691
1692                 if( realm ) {
1693                         int rlen = dn->bv_len - ( realm - c1 );
1694                         p = lutil_strcopy( p, ",cn=" );
1695                         p = lutil_strncopy( p, realm, rlen );
1696                         realm[-1] = '@';
1697                 } else if( user_realm && *user_realm ) {
1698                         p = lutil_strcopy( p, ",cn=" );
1699                         p = lutil_strcopy( p, user_realm );
1700                 }
1701
1702                 if( conn->c_sasl_bind_mech.bv_len ) {
1703                         p = lutil_strcopy( p, ",cn=" );
1704                         p = lutil_strcopy( p, conn->c_sasl_bind_mech.bv_val );
1705                 }
1706                 p = lutil_strcopy( p, ",cn=auth" );
1707                 dn->bv_len = p - dn->bv_val;
1708
1709 #ifdef NEW_LOGGING
1710                 LDAP_LOG( TRANSPORT, ENTRY, 
1711                         "slap_sasl_getdn: u:id converted to %s.\n", dn->bv_val, 0, 0 );
1712 #else
1713                 Debug( LDAP_DEBUG_TRACE, "getdn: u:id converted to %s\n", dn->bv_val,0,0 );
1714 #endif
1715         } else {
1716                 
1717                 /* Dup the DN in any case, so we don't risk 
1718                  * leaks or dangling pointers later,
1719                  * and the DN value is '\0' terminated */
1720                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1721                 dn->bv_val = dn2.bv_val;
1722         }
1723
1724         /* All strings are in DN form now. Normalize if needed. */
1725         if ( do_norm ) {
1726                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1727
1728                 /* User DNs were constructed above and must be freed now */
1729                 sl_free( dn->bv_val, op->o_tmpmemctx );
1730
1731                 if ( rc != LDAP_SUCCESS ) {
1732                         dn->bv_val = NULL;
1733                         dn->bv_len = 0;
1734                         return rc;
1735                 }
1736                 *dn = dn2;
1737         }
1738
1739         /* Run thru regexp */
1740         slap_sasl2dn( op, dn, &dn2 );
1741         if( dn2.bv_val ) {
1742                 sl_free( dn->bv_val, op->o_tmpmemctx );
1743                 *dn = dn2;
1744 #ifdef NEW_LOGGING
1745                 LDAP_LOG( TRANSPORT, ENTRY, 
1746                         "slap_sasl_getdn: dn:id converted to %s.\n", dn->bv_val, 0, 0 );
1747 #else
1748                 Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
1749                         dn->bv_val, 0, 0 );
1750 #endif
1751         }
1752
1753         return( LDAP_SUCCESS );
1754 }