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