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