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