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