]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
correct fix
[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          * The SASL EXTERNAL mech is backwards from all the other mechs,
843          * it does authzID before the authcID. If we see that authzID
844          * has already been done, don't do anything special with authcID.
845          */
846         if ( flags == SASL_CU_AUTHID && !auxvals[PROP_AUTHZ].values ) {
847                 conn->c_sasl_dn.bv_val = (char *) in;
848         } else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
849                 rc = strcmp( in, conn->c_sasl_dn.bv_val );
850                 conn->c_sasl_dn.bv_val = NULL;
851                 /* They were equal, no work needed */
852                 if ( !rc ) goto done;
853         }
854
855         rc = slap_sasl_getdn( conn, (char *)in, inlen, (char *)user_realm, &dn,
856                 (flags & SASL_CU_AUTHID) ? FLAG_GETDN_AUTHCID : FLAG_GETDN_AUTHZID );
857         if ( rc != LDAP_SUCCESS ) {
858                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
859                 return SASL_NOAUTHZ;
860         }               
861
862         names[0] = slap_propnames[which];
863         names[1] = NULL;
864
865         prop_set( props, names[0], (char *)&dn, sizeof( dn ) );
866                 
867 #ifdef NEW_LOGGING
868         LDAP_LOG( TRANSPORT, ENTRY, 
869                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
870                 conn ? conn->c_connid : -1, names[0]+1, dn.bv_val );
871 #else
872         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: "
873                 "%s=\"%s\"\n",
874                         conn ? conn->c_connid : -1,
875                         names[0]+1, dn.bv_val );
876 #endif
877 done:   AC_MEMCPY( out, in, inlen );
878         out[inlen] = '\0';
879
880         *out_len = inlen;
881
882         return SASL_OK;
883 }
884
885 static int
886 slap_sasl_authorize(
887         sasl_conn_t *sconn,
888         void *context,
889         char *requested_user,
890         unsigned rlen,
891         char *auth_identity,
892         unsigned alen,
893         const char *def_realm,
894         unsigned urlen,
895         struct propctx *props)
896 {
897         Connection *conn = (Connection *)context;
898         struct propval auxvals[3];
899         struct berval authcDN, authzDN;
900         int rc;
901
902 #ifdef NEW_LOGGING
903         LDAP_LOG( TRANSPORT, ENTRY, 
904                 "slap_sasl_authorize: conn %d authcid=\"%s\" authzid=\"%s\"\n",
905                 conn ? conn->c_connid : -1, auth_identity, requested_user);
906 #else
907         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
908                 "authcid=\"%s\" authzid=\"%s\"\n",
909                 conn ? conn->c_connid : -1, auth_identity, requested_user );
910 #endif
911         if ( conn->c_sasl_dn.bv_val ) {
912                 ch_free( conn->c_sasl_dn.bv_val );
913                 conn->c_sasl_dn.bv_val = NULL;
914                 conn->c_sasl_dn.bv_len = 0;
915         }
916
917         /* Skip PROP_CONN */
918         prop_getnames( props, slap_propnames+1, auxvals );
919         
920         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
921
922         /* Nothing to do if no authzID was given */
923         if ( !auxvals[1].name || !auxvals[1].values ) {
924                 conn->c_sasl_dn = authcDN;
925                 goto ok;
926         }
927         
928         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
929
930         rc = slap_sasl_authorized( conn, &authcDN, &authzDN );
931         ch_free( authcDN.bv_val );
932         if ( rc != LDAP_SUCCESS ) {
933 #ifdef NEW_LOGGING
934                 LDAP_LOG( TRANSPORT, INFO, 
935                         "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
936                         (long)(conn ? conn->c_connid : -1), rc, 0 );
937 #else
938                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
939                         " authorization disallowed (%d)\n",
940                         (long) (conn ? conn->c_connid : -1), rc, 0 );
941 #endif
942
943                 sasl_seterror( sconn, 0, "not authorized" );
944                 ch_free( authzDN.bv_val );
945                 return SASL_NOAUTHZ;
946         }
947
948         conn->c_sasl_dn = authzDN;
949 ok:
950         if (conn->c_sasl_bindop) {
951                 Statslog( LDAP_DEBUG_STATS,
952                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
953                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
954                         auth_identity, 0, 0);
955         }
956
957 #ifdef NEW_LOGGING
958         LDAP_LOG( TRANSPORT, ENTRY, 
959                 "slap_sasl_authorize: conn %d authorization allowed\n",
960                 (long)(conn ? conn->c_connid : -1), 0, 0 );
961 #else
962         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
963                 " authorization allowed\n",
964                 (long) (conn ? conn->c_connid : -1), 0, 0 );
965 #endif
966         return SASL_OK;
967
968 #else
969 static int
970 slap_sasl_authorize(
971         void *context,
972         char *authcid,
973         char *authzid,
974         const char **user,
975         const char **errstr)
976 {
977         struct berval authcDN, authzDN;
978         int rc;
979         Connection *conn = context;
980         char *realm;
981
982         *user = NULL;
983         if ( conn->c_sasl_dn.bv_val ) {
984                 ch_free( conn->c_sasl_dn.bv_val );
985                 conn->c_sasl_dn.bv_val = NULL;
986                 conn->c_sasl_dn.bv_len = 0;
987         }
988
989 #ifdef NEW_LOGGING
990         LDAP_LOG( TRANSPORT, ENTRY, 
991                 "slap_sasl_authorize: conn %d    authcid=\"%s\" authzid=\"%s\"\n",
992                 conn ? conn->c_connid : -1, authcid ? authcid : "<empty>",
993                 authzid ? authzid : "<empty>" );
994 #else
995         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
996                 "authcid=\"%s\" authzid=\"%s\"\n",
997                 (long) (conn ? conn->c_connid : -1),
998                 authcid ? authcid : "<empty>",
999                 authzid ? authzid : "<empty>" );
1000 #endif
1001
1002         /* Figure out how much data we have for the dn */
1003         rc = sasl_getprop( conn->c_sasl_context, SASL_REALM, (void **)&realm );
1004         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
1005 #ifdef NEW_LOGGING
1006                 LDAP_LOG( TRANSPORT, ERR,
1007                         "slap_sasl_authorize: getprop(REALM) failed.\n", 0, 0, 0 );
1008 #else
1009                 Debug(LDAP_DEBUG_TRACE,
1010                         "authorize: getprop(REALM) failed!\n", 0,0,0);
1011 #endif
1012                 *errstr = "Could not extract realm";
1013                 return SASL_NOAUTHZ;
1014         }
1015
1016         /* Convert the identities to DN's. If no authzid was given, client will
1017            be bound as the DN matching their username */
1018         rc = slap_sasl_getdn( conn, (char *)authcid, 0, realm, &authcDN, FLAG_GETDN_AUTHCID );
1019         if( rc != LDAP_SUCCESS ) {
1020                 *errstr = ldap_err2string( rc );
1021                 return SASL_NOAUTHZ;
1022         }
1023         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
1024 #ifdef NEW_LOGGING
1025                 LDAP_LOG( TRANSPORT, ENTRY, 
1026                         "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
1027                         conn ? conn->c_connid : -1, authcDN.bv_val, 0 );
1028 #else
1029                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
1030                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
1031 #endif
1032
1033                 conn->c_sasl_dn = authcDN;
1034                 goto ok;
1035         }
1036         rc = slap_sasl_getdn( conn, (char *)authzid, 0, realm, &authzDN, FLAG_GETDN_AUTHZID );
1037         if( rc != LDAP_SUCCESS ) {
1038                 ch_free( authcDN.bv_val );
1039                 *errstr = ldap_err2string( rc );
1040                 return SASL_NOAUTHZ;
1041         }
1042
1043         rc = slap_sasl_authorized(conn, &authcDN, &authzDN );
1044         ch_free( authcDN.bv_val );
1045         if( rc ) {
1046 #ifdef NEW_LOGGING
1047                 LDAP_LOG( TRANSPORT, INFO, 
1048                         "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
1049                         (long)(conn ? conn->c_connid : -1), rc, 0 );
1050 #else
1051                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
1052                         " authorization disallowed (%d)\n",
1053                         (long) (conn ? conn->c_connid : -1), rc, 0 );
1054 #endif
1055
1056                 *errstr = "not authorized";
1057                 ch_free( authzDN.bv_val );
1058                 return SASL_NOAUTHZ;
1059         }
1060         conn->c_sasl_dn = authzDN;
1061
1062 ok:
1063 #ifdef NEW_LOGGING
1064         LDAP_LOG( TRANSPORT, RESULTS, 
1065                 "slap_sasl_authorize: conn %d authorization allowed\n",
1066            (long)(conn ? conn->c_connid : -1 ), 0, 0 );
1067 #else
1068         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
1069                 " authorization allowed\n",
1070                 (long) (conn ? conn->c_connid : -1), 0, 0 );
1071 #endif
1072
1073         if (conn->c_sasl_bindop) {
1074                 Statslog( LDAP_DEBUG_STATS,
1075                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
1076                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
1077                         authcid, 0, 0);
1078         }
1079
1080         *errstr = NULL;
1081         return SASL_OK;
1082 }
1083 #endif /* SASL_VERSION_MAJOR >= 2 */
1084
1085 static int
1086 slap_sasl_err2ldap( int saslerr )
1087 {
1088         int rc;
1089
1090         switch (saslerr) {
1091                 case SASL_CONTINUE:
1092                         rc = LDAP_SASL_BIND_IN_PROGRESS;
1093                         break;
1094                 case SASL_FAIL:
1095                         rc = LDAP_OTHER;
1096                         break;
1097                 case SASL_NOMEM:
1098                         rc = LDAP_OTHER;
1099                         break;
1100                 case SASL_NOMECH:
1101                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1102                         break;
1103                 case SASL_BADAUTH:
1104                         rc = LDAP_INVALID_CREDENTIALS;
1105                         break;
1106                 case SASL_NOAUTHZ:
1107                         rc = LDAP_INSUFFICIENT_ACCESS;
1108                         break;
1109                 case SASL_TOOWEAK:
1110                 case SASL_ENCRYPT:
1111                         rc = LDAP_INAPPROPRIATE_AUTH;
1112                         break;
1113                 default:
1114                         rc = LDAP_OTHER;
1115                         break;
1116         }
1117
1118         return rc;
1119 }
1120 #endif
1121
1122
1123 int slap_sasl_init( void )
1124 {
1125 #ifdef HAVE_CYRUS_SASL
1126         int rc;
1127         static sasl_callback_t server_callbacks[] = {
1128                 { SASL_CB_LOG, &slap_sasl_log, NULL },
1129                 { SASL_CB_LIST_END, NULL, NULL }
1130         };
1131
1132 #ifdef HAVE_SASL_VERSION
1133 #define SASL_BUILD_VERSION ((SASL_VERSION_MAJOR << 24) |\
1134         (SASL_VERSION_MINOR << 16) | SASL_VERSION_STEP)
1135
1136         sasl_version( NULL, &rc );
1137         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1138                 (rc & 0xffff) < SASL_VERSION_STEP) {
1139
1140 #ifdef NEW_LOGGING
1141                 LDAP_LOG( TRANSPORT, INFO,
1142                 "slap_sasl_init: SASL version mismatch, got %x, wanted %x.\n",
1143                         rc, SASL_BUILD_VERSION, 0 );
1144 #else
1145                 Debug( LDAP_DEBUG_ANY,
1146                 "slap_sasl_init: SASL version mismatch, got %x, wanted %x.\n",
1147                         rc, SASL_BUILD_VERSION, 0 );
1148 #endif
1149                 return -1;
1150         }
1151 #endif
1152
1153         /* SASL 2 does its own memory management internally */
1154 #if SASL_VERSION_MAJOR < 2
1155         sasl_set_alloc(
1156                 ber_memalloc,
1157                 ber_memcalloc,
1158                 ber_memrealloc,
1159                 ber_memfree ); 
1160 #endif
1161
1162         sasl_set_mutex(
1163                 ldap_pvt_sasl_mutex_new,
1164                 ldap_pvt_sasl_mutex_lock,
1165                 ldap_pvt_sasl_mutex_unlock,
1166                 ldap_pvt_sasl_mutex_dispose );
1167
1168 #if SASL_VERSION_MAJOR >= 2
1169         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1170 #endif
1171         /* should provide callbacks for logging */
1172         /* server name should be configurable */
1173         rc = sasl_server_init( server_callbacks, "slapd" );
1174
1175         if( rc != SASL_OK ) {
1176 #ifdef NEW_LOGGING
1177                 LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: init failed.\n", 0, 0, 0 );
1178 #else
1179                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
1180                         0, 0, 0 );
1181 #endif
1182 #if SASL_VERSION_MAJOR < 2
1183                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1184                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1185 #endif
1186
1187                 return -1;
1188         }
1189
1190 #ifdef NEW_LOGGING
1191         LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: initialized!\n", 0, 0, 0 );
1192 #else
1193         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1194                 0, 0, 0 );
1195 #endif
1196
1197
1198         /* default security properties */
1199         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1200         sasl_secprops.max_ssf = INT_MAX;
1201         sasl_secprops.maxbufsize = 65536;
1202         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1203 #endif
1204
1205         return 0;
1206 }
1207
1208 int slap_sasl_destroy( void )
1209 {
1210 #ifdef HAVE_CYRUS_SASL
1211         sasl_done();
1212 #endif
1213 #if SASL_VERSION_MAJOR >= 2
1214         filter_free( generic_filter );
1215 #endif
1216         free( global_host );
1217         global_host = NULL;
1218
1219         return 0;
1220 }
1221
1222 int slap_sasl_open( Connection *conn )
1223 {
1224         int cb, sc = LDAP_SUCCESS;
1225 #if SASL_VERSION_MAJOR >= 2
1226         char *ipremoteport = NULL, *iplocalport = NULL;
1227 #endif
1228
1229 #ifdef HAVE_CYRUS_SASL
1230         sasl_conn_t *ctx = NULL;
1231         sasl_callback_t *session_callbacks;
1232
1233         assert( conn->c_sasl_context == NULL );
1234         assert( conn->c_sasl_extra == NULL );
1235
1236         conn->c_sasl_layers = 0;
1237
1238         session_callbacks =
1239 #if SASL_VERSION_MAJOR >= 2
1240                 SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1241 #else
1242                 SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1243 #endif
1244         if( session_callbacks == NULL ) {
1245 #ifdef NEW_LOGGING
1246                         LDAP_LOG( TRANSPORT, ERR, 
1247                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1248 #else
1249                         Debug( LDAP_DEBUG_ANY, 
1250                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1251 #endif
1252                         return -1;
1253         }
1254         conn->c_sasl_extra = session_callbacks;
1255
1256         session_callbacks[cb=0].id = SASL_CB_LOG;
1257         session_callbacks[cb].proc = &slap_sasl_log;
1258         session_callbacks[cb++].context = conn;
1259
1260         session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1261         session_callbacks[cb].proc = &slap_sasl_authorize;
1262         session_callbacks[cb++].context = conn;
1263
1264 #if SASL_VERSION_MAJOR >= 2
1265         session_callbacks[cb].id = SASL_CB_CANON_USER;
1266         session_callbacks[cb].proc = &slap_sasl_canonicalize;
1267         session_callbacks[cb++].context = conn;
1268
1269         /* XXXX: this should be conditional */
1270         session_callbacks[cb].id = SASL_CB_SERVER_USERDB_CHECKPASS;
1271         session_callbacks[cb].proc = &slap_sasl_checkpass;
1272         session_callbacks[cb++].context = conn;
1273 #endif
1274
1275         session_callbacks[cb].id = SASL_CB_LIST_END;
1276         session_callbacks[cb].proc = NULL;
1277         session_callbacks[cb++].context = NULL;
1278
1279         if( global_host == NULL ) {
1280                 global_host = ldap_pvt_get_fqdn( NULL );
1281         }
1282
1283         /* create new SASL context */
1284 #if SASL_VERSION_MAJOR >= 2
1285         if ( generic_filter == NULL ) {
1286                 generic_filter = str2filter( "(objectclass=*)" );
1287         }
1288         if ( conn->c_sock_name.bv_len != 0 &&
1289              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1290                 char *p;
1291
1292                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1293                 /* Convert IPv6 addresses to address;port syntax. */
1294                 p = strrchr( iplocalport, ' ' );
1295                 /* Convert IPv4 addresses to address;port syntax. */
1296                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1297                 if ( p != NULL ) {
1298                         *p = ';';
1299                 }
1300         }
1301         if ( conn->c_peer_name.bv_len != 0 &&
1302              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1303                 char *p;
1304
1305                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1306                 /* Convert IPv6 addresses to address;port syntax. */
1307                 p = strrchr( ipremoteport, ' ' );
1308                 /* Convert IPv4 addresses to address;port syntax. */
1309                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1310                 if ( p != NULL ) {
1311                         *p = ';';
1312                 }
1313         }
1314         sc = sasl_server_new( "ldap", global_host, global_realm,
1315                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1316         if ( iplocalport != NULL ) {
1317                 ch_free( iplocalport );
1318         }
1319         if ( ipremoteport != NULL ) {
1320                 ch_free( ipremoteport );
1321         }
1322 #else
1323         sc = sasl_server_new( "ldap", global_host, global_realm,
1324                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1325 #endif
1326
1327         if( sc != SASL_OK ) {
1328 #ifdef NEW_LOGGING
1329                 LDAP_LOG( TRANSPORT, ERR, 
1330                         "slap_sasl_open: sasl_server_new failed: %d\n", sc, 0, 0 );
1331 #else
1332                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1333                         sc, 0, 0 );
1334 #endif
1335
1336                 return -1;
1337         }
1338
1339         conn->c_sasl_context = ctx;
1340
1341         if( sc == SASL_OK ) {
1342                 sc = sasl_setprop( ctx,
1343                         SASL_SEC_PROPS, &sasl_secprops );
1344
1345                 if( sc != SASL_OK ) {
1346 #ifdef NEW_LOGGING
1347                         LDAP_LOG( TRANSPORT, ERR, 
1348                                 "slap_sasl_open: sasl_setprop failed: %d \n", sc, 0, 0 );
1349 #else
1350                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1351                                 sc, 0, 0 );
1352 #endif
1353
1354                         slap_sasl_close( conn );
1355                         return -1;
1356                 }
1357         }
1358
1359         sc = slap_sasl_err2ldap( sc );
1360 #endif
1361         return sc;
1362 }
1363
1364 int slap_sasl_external(
1365         Connection *conn,
1366         slap_ssf_t ssf,
1367         const char *auth_id )
1368 {
1369 #if SASL_VERSION_MAJOR >= 2
1370         int sc;
1371         sasl_conn_t *ctx = conn->c_sasl_context;
1372
1373         if ( ctx == NULL ) {
1374                 return LDAP_UNAVAILABLE;
1375         }
1376
1377         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1378
1379         if ( sc != SASL_OK ) {
1380                 return LDAP_OTHER;
1381         }
1382
1383         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL, auth_id );
1384
1385         if ( sc != SASL_OK ) {
1386                 return LDAP_OTHER;
1387         }
1388
1389 #elif defined(HAVE_CYRUS_SASL)
1390         int sc;
1391         sasl_conn_t *ctx = conn->c_sasl_context;
1392         sasl_external_properties_t extprops;
1393
1394         if ( ctx == NULL ) {
1395                 return LDAP_UNAVAILABLE;
1396         }
1397
1398         memset( &extprops, '\0', sizeof(extprops) );
1399         extprops.ssf = ssf;
1400         extprops.auth_id = (char *) auth_id;
1401
1402         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1403                 (void *) &extprops );
1404
1405         if ( sc != SASL_OK ) {
1406                 return LDAP_OTHER;
1407         }
1408 #endif
1409
1410         return LDAP_SUCCESS;
1411 }
1412
1413 int slap_sasl_reset( Connection *conn )
1414 {
1415 #ifdef HAVE_CYRUS_SASL
1416         sasl_conn_t *ctx = conn->c_sasl_context;
1417
1418         if( ctx != NULL ) {
1419         }
1420 #endif
1421         /* must return "anonymous" */
1422         return LDAP_SUCCESS;
1423 }
1424
1425 char ** slap_sasl_mechs( Connection *conn )
1426 {
1427         char **mechs = NULL;
1428
1429 #ifdef HAVE_CYRUS_SASL
1430         sasl_conn_t *ctx = conn->c_sasl_context;
1431
1432         if( ctx != NULL ) {
1433                 int sc;
1434                 SASL_CONST char *mechstr;
1435
1436                 sc = sasl_listmech( ctx,
1437                         NULL, NULL, ",", NULL,
1438                         &mechstr, NULL, NULL );
1439
1440                 if( sc != SASL_OK ) {
1441 #ifdef NEW_LOGGING
1442                         LDAP_LOG( TRANSPORT, ERR, 
1443                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc, 0, 0 );
1444 #else
1445                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1446                                 sc, 0, 0 );
1447 #endif
1448
1449                         return NULL;
1450                 }
1451
1452                 mechs = ldap_str2charray( mechstr, "," );
1453
1454 #if SASL_VERSION_MAJOR < 2
1455                 ch_free( mechstr );
1456 #endif
1457         }
1458 #endif
1459
1460         return mechs;
1461 }
1462
1463 int slap_sasl_close( Connection *conn )
1464 {
1465 #ifdef HAVE_CYRUS_SASL
1466         sasl_conn_t *ctx = conn->c_sasl_context;
1467
1468         if( ctx != NULL ) {
1469                 sasl_dispose( &ctx );
1470         }
1471
1472         conn->c_sasl_context = NULL;
1473
1474         free( conn->c_sasl_extra );
1475         conn->c_sasl_extra = NULL;
1476 #endif
1477
1478         return LDAP_SUCCESS;
1479 }
1480
1481 int slap_sasl_bind(
1482     Connection          *conn,
1483     Operation           *op,  
1484     struct berval       *dn,  
1485     struct berval       *ndn,
1486     struct berval       *cred,
1487         struct berval                   *edn,
1488         slap_ssf_t              *ssfp )
1489 {
1490         int rc = 1;
1491
1492 #ifdef HAVE_CYRUS_SASL
1493         sasl_conn_t *ctx = conn->c_sasl_context;
1494         struct berval response;
1495         unsigned reslen = 0;
1496         const char *errstr = NULL;
1497         int sc;
1498
1499 #ifdef NEW_LOGGING
1500         LDAP_LOG( TRANSPORT, ENTRY, 
1501                 "sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1502                 dn->bv_len ? dn->bv_val : "",
1503                 conn->c_sasl_bind_in_progress ? "<continuing>" : 
1504                 conn->c_sasl_bind_mech.bv_val,
1505                 cred ? cred->bv_len : 0 );
1506 #else
1507         Debug(LDAP_DEBUG_ARGS,
1508                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1509                 dn->bv_len ? dn->bv_val : "",
1510                 conn->c_sasl_bind_in_progress ? "<continuing>":conn->c_sasl_bind_mech.bv_val,
1511                 cred ? cred->bv_len : 0 );
1512 #endif
1513
1514
1515         if( ctx == NULL ) {
1516                 send_ldap_result( conn, op, LDAP_UNAVAILABLE,
1517                         NULL, "SASL unavailable on this session", NULL, NULL );
1518                 return rc;
1519         }
1520
1521 #if SASL_VERSION_MAJOR >= 2
1522 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1523         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1524 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1525         sasl_server_step( ctx, cred, clen, resp, rlen )
1526 #else
1527 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1528         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1529 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1530         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1531 #endif
1532
1533         if ( !conn->c_sasl_bind_in_progress ) {
1534                 sc = START( ctx,
1535                         conn->c_sasl_bind_mech.bv_val,
1536                         cred->bv_val, cred->bv_len,
1537                         (SASL_CONST char **)&response.bv_val, &reslen, &errstr );
1538
1539         } else {
1540                 sc = STEP( ctx,
1541                         cred->bv_val, cred->bv_len,
1542                         (SASL_CONST char **)&response.bv_val, &reslen, &errstr );
1543         }
1544
1545         response.bv_len = reslen;
1546
1547         if ( sc == SASL_OK ) {
1548                 sasl_ssf_t *ssf = NULL;
1549
1550                 *edn = conn->c_sasl_dn;
1551                 conn->c_sasl_dn.bv_val = NULL;
1552                 conn->c_sasl_dn.bv_len = 0;
1553
1554                 rc = LDAP_SUCCESS;
1555
1556                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1557                 *ssfp = ssf ? *ssf : 0;
1558
1559                 if( *ssfp ) {
1560                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1561                         conn->c_sasl_layers++;
1562                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1563                 }
1564
1565                 send_ldap_sasl( conn, op, rc,
1566                         NULL, NULL, NULL, NULL,
1567                         response.bv_len ? &response : NULL );
1568
1569         } else if ( sc == SASL_CONTINUE ) {
1570                 send_ldap_sasl( conn, op, rc = LDAP_SASL_BIND_IN_PROGRESS,
1571                         NULL, NULL, NULL, NULL, &response );
1572
1573         } else {
1574 #if SASL_VERSION_MAJOR >= 2
1575                 errstr = sasl_errdetail( ctx );
1576 #endif
1577                 send_ldap_result( conn, op, rc = slap_sasl_err2ldap( sc ),
1578                         NULL, errstr, NULL, NULL );
1579         }
1580
1581 #if SASL_VERSION_MAJOR < 2
1582         if( response.bv_len ) {
1583                 ch_free( response.bv_val );
1584         }
1585 #endif
1586
1587 #ifdef NEW_LOGGING
1588         LDAP_LOG( TRANSPORT, RESULTS, "slap_sasl_bind: rc=%d\n", rc, 0, 0 );
1589 #else
1590         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rc, 0, 0);
1591 #endif
1592
1593
1594 #else
1595         send_ldap_result( conn, op, rc = LDAP_UNAVAILABLE,
1596                 NULL, "SASL not supported", NULL, NULL );
1597 #endif
1598
1599         return rc;
1600 }
1601
1602 char* slap_sasl_secprops( const char *in )
1603 {
1604 #ifdef HAVE_CYRUS_SASL
1605         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1606
1607         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1608 #else
1609         return "SASL not supported";
1610 #endif
1611 }
1612
1613 #ifdef HAVE_CYRUS_SASL
1614 int
1615 slap_sasl_setpass(
1616         Connection      *conn,
1617         Operation       *op,
1618         const char      *reqoid,
1619         struct berval   *reqdata,
1620         char            **rspoid,
1621         struct berval   **rspdata,
1622         LDAPControl     *** rspctrls,
1623         const char      **text )
1624 {
1625         int rc;
1626         struct berval id = { 0, NULL }; /* needs to come from connection */
1627         struct berval new = { 0, NULL };
1628         struct berval old = { 0, NULL };
1629
1630         assert( reqoid != NULL );
1631         assert( strcmp( LDAP_EXOP_MODIFY_PASSWD, reqoid ) == 0 );
1632
1633         rc = sasl_getprop( conn->c_sasl_context, SASL_USERNAME,
1634                 (SASL_CONST void **)&id.bv_val );
1635
1636         if( rc != SASL_OK ) {
1637                 *text = "unable to retrieve SASL username";
1638                 rc = LDAP_OTHER;
1639                 goto done;
1640         }
1641
1642 #ifdef NEW_LOGGING
1643         LDAP_LOG( BACKEND, ENTRY,
1644                 "slap_sasl_setpass: \"%s\"\n",
1645                 id.bv_val ? id.bv_val : "", 0, 0);
1646 #else
1647         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1648                 id.bv_val ? id.bv_val : "", 0, 0 );
1649 #endif
1650
1651         rc = slap_passwd_parse( reqdata,
1652                 NULL, &old, &new, text );
1653
1654         if( rc != LDAP_SUCCESS ) {
1655                 goto done;
1656         }
1657
1658         if( new.bv_len == 0 ) {
1659                 slap_passwd_generate(&new);
1660
1661                 if( new.bv_len == 0 ) {
1662                         *text = "password generation failed.";
1663                         rc = LDAP_OTHER;
1664                         goto done;
1665                 }
1666                 
1667                 *rspdata = slap_passwd_return( &new );
1668         }
1669
1670 #if SASL_VERSION_MAJOR < 2
1671         rc = sasl_setpass( conn->c_sasl_context,
1672                 id.bv_val, new.bv_val, new.bv_len, 0, text );
1673 #else
1674         rc = sasl_setpass( conn->c_sasl_context, id.bv_val,
1675                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1676         if( rc != SASL_OK ) {
1677                 *text = sasl_errdetail( conn->c_sasl_context );
1678         }
1679 #endif
1680         switch(rc) {
1681                 case SASL_OK:
1682                         rc = LDAP_SUCCESS;
1683                         break;
1684
1685                 case SASL_NOCHANGE:
1686                 case SASL_NOMECH:
1687                 case SASL_DISABLED:
1688                 case SASL_PWLOCK:
1689                 case SASL_FAIL:
1690                 case SASL_BADPARAM:
1691                 default:
1692                         rc = LDAP_OTHER;
1693         }
1694
1695 done:
1696         return rc;
1697 }
1698 #endif