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