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