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