]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
Don't use slap_empty_bv in structures that are expected to be free'able.
[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 #if SASL_VERSION_MAJOR >= 2
28 #include <lutil.h>
29 #include <sasl/saslplug.h>
30 #define SASL_CONST const
31 #else
32 #define SASL_CONST
33 #endif
34
35 #include <ldap_pvt.h>
36
37 #ifdef SLAPD_SPASSWD
38 #include <lutil.h>
39 #endif
40
41 /* Flags for telling slap_sasl_getdn() what type of identity is being passed */
42 #define FLAG_GETDN_AUTHCID 2
43 #define FLAG_GETDN_AUTHZID 4
44
45 static sasl_security_properties_t sasl_secprops;
46
47 static int
48 slap_sasl_log(
49         void *context,
50         int priority,
51         const char *message) 
52 {
53         Connection *conn = context;
54         int level;
55         const char * label;
56
57         if ( message == NULL ) {
58                 return SASL_BADPARAM;
59         }
60
61         switch (priority) {
62 #if SASL_VERSION_MAJOR >= 2
63         case SASL_LOG_NONE:
64                 level = LDAP_DEBUG_NONE;
65                 label = "None";
66                 break;
67         case SASL_LOG_ERR:
68                 level = LDAP_DEBUG_ANY;
69                 label = "Error";
70                 break;
71         case SASL_LOG_FAIL:
72                 level = LDAP_DEBUG_ANY;
73                 label = "Failure";
74                 break;
75         case SASL_LOG_WARN:
76                 level = LDAP_DEBUG_TRACE;
77                 label = "Warning";
78                 break;
79         case SASL_LOG_NOTE:
80                 level = LDAP_DEBUG_TRACE;
81                 label = "Notice";
82                 break;
83         case SASL_LOG_DEBUG:
84                 level = LDAP_DEBUG_TRACE;
85                 label = "Debug";
86                 break;
87         case SASL_LOG_TRACE:
88                 level = LDAP_DEBUG_TRACE;
89                 label = "Trace";
90                 break;
91         case SASL_LOG_PASS:
92                 level = LDAP_DEBUG_TRACE;
93                 label = "Password Trace";
94                 break;
95 #else
96         case SASL_LOG_ERR:
97                 level = LDAP_DEBUG_ANY;
98                 label = "Error";
99                 break;
100         case SASL_LOG_WARNING:
101                 level = LDAP_DEBUG_TRACE;
102                 label = "Warning";
103                 break;
104         case SASL_LOG_INFO:
105                 level = LDAP_DEBUG_TRACE;
106                 label = "Info";
107                 break;
108 #endif
109         default:
110                 return SASL_BADPARAM;
111         }
112
113 #ifdef NEW_LOGGING
114         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
115                 "SASL [conn=%ld] %s: %s\n",
116                 conn ? conn->c_connid : -1,
117                 label, message ));
118 #else
119         Debug( level, "SASL [conn=%ld] %s: %s\n",
120                 conn ? conn->c_connid: -1,
121                 label, message );
122 #endif
123
124
125         return SASL_OK;
126 }
127
128
129 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
130    string returned in *dn is in its own allocated memory, and must be free'd 
131    by the calling process.
132    -Mark Adamson, Carnegie Mellon
133
134    The "dn:" prefix is no longer used anywhere inside slapd. It is only used
135    on strings passed in directly from SASL.
136    -Howard Chu, Symas Corp.
137 */
138
139 #define SET_DN  1
140 #define SET_U   2
141
142 static struct berval ext_bv = { sizeof("EXTERNAL")-1, "EXTERNAL" };
143
144 int slap_sasl_getdn( Connection *conn, char *id, int len,
145         char *user_realm, struct berval *dn, int flags )
146 {
147         char *c1;
148         int rc, is_dn = 0, do_norm = 1;
149         sasl_conn_t *ctx;
150         struct berval dn2;
151
152 #ifdef NEW_LOGGING
153         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
154                 "slap_sasl_getdn: conn %d id=%s\n",
155                 conn ? conn->c_connid : -1,
156                 id ? (*id ? id : "<empty>") : "NULL" ));
157 #else
158         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: id=%s\n", 
159       id?(*id?id:"<empty>"):"NULL",0,0 );
160 #endif
161
162         dn->bv_val = NULL;
163         dn->bv_len = 0;
164
165         if ( id ) {
166                 if ( len == 0 ) len = strlen( id );
167
168                 /* Blatantly anonymous ID */
169                 if ( len == sizeof("anonymous") - 1 &&
170                         !strcasecmp( id, "anonymous" ) ) {
171                         return( LDAP_SUCCESS );
172                 }
173         } else {
174                 len = 0;
175         }
176
177         ctx = conn->c_sasl_context;
178
179         /* An authcID needs to be converted to authzID form */
180         if( flags & FLAG_GETDN_AUTHCID ) {
181                 if( conn->c_is_tls && conn->c_sasl_bind_mech.bv_len == ext_bv.bv_len
182                         && ( strcasecmp( ext_bv.bv_val, conn->c_sasl_bind_mech.bv_val ) == 0 ) ) {
183                         /* X.509 DN is already normalized */
184                         do_norm = 0;
185                         is_dn = SET_DN;
186
187                 } else {
188                         /* convert to u:<username> form */
189                         is_dn = SET_U;
190                 }
191                 ber_str2bv( id, len, 1, dn );
192         }
193         if( !is_dn ) {
194                 if( !strncasecmp( id, "u:", sizeof("u:")-1 )) {
195                         is_dn = SET_U;
196                         ber_str2bv( id+2, len-2, 1, dn );
197                 } else if ( !strncasecmp( id, "dn:", sizeof("dn:")-1) ) {
198                         is_dn = SET_DN;
199                         ber_str2bv( id+3, len-3, 1, dn );
200                 }
201         }
202
203         /* An authzID must be properly prefixed */
204         if( (flags & FLAG_GETDN_AUTHZID) && !is_dn ) {
205                 free( dn->bv_val );
206                 dn->bv_val = NULL;
207                 dn->bv_len = 0;
208                 return( LDAP_INAPPROPRIATE_AUTH );
209         }
210
211         /* Username strings */
212         if( is_dn == SET_U ) {
213                 char *p;
214                 len = dn->bv_len + sizeof("uid=")-1 + sizeof(",cn=auth")-1;
215
216                 if( user_realm && *user_realm ) {
217                         len += strlen( user_realm ) + sizeof(",cn=")-1;
218                 }
219
220                 if( conn->c_sasl_bind_mech.bv_len ) {
221                         len += conn->c_sasl_bind_mech.bv_len + sizeof(",cn=")-1;
222                 }
223
224                 /* Build the new dn */
225                 c1 = dn->bv_val;
226                 dn->bv_val = ch_malloc( len+1 );
227                 p = slap_strcopy( dn->bv_val, "uid=" );
228                 p = slap_strcopy( p, c1 );
229                 ch_free( c1 );
230
231                 if( user_realm && *user_realm ) {
232                         p = slap_strcopy( p, ",cn=" );
233                         p = slap_strcopy( p, user_realm );
234                 }
235                 if( conn->c_sasl_bind_mech.bv_len ) {
236                         p = slap_strcopy( p, ",cn=" );
237                         p = slap_strcopy( p, conn->c_sasl_bind_mech.bv_val );
238                 }
239                 p = slap_strcopy( p, ",cn=auth" );
240                 dn->bv_len = p - dn->bv_val;
241                 is_dn = SET_DN;
242
243 #ifdef NEW_LOGGING
244                 LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
245                         "slap_sasl_getdn: u:id converted to %s.\n", dn->bv_val ));
246 #else
247                 Debug( LDAP_DEBUG_TRACE, "getdn: u:id converted to %s\n", dn->bv_val,0,0 );
248 #endif
249         }
250
251         /* DN strings that are a cn=auth identity to run through regexp */
252         if( is_dn == SET_DN )
253         {
254                 slap_sasl2dn( conn, dn, &dn2 );
255                 if( dn2.bv_val ) {
256                         ch_free( dn->bv_val );
257                         *dn = dn2;
258                         do_norm = 0;    /* slap_sasl2dn normalizes */
259 #ifdef NEW_LOGGING
260                         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
261                                 "slap_sasl_getdn: dn:id converted to %s.\n", dn->bv_val ));
262 #else
263                         Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
264                                 dn->bv_val, 0, 0 );
265 #endif
266                 }
267         }
268
269         if ( do_norm ) {
270                 rc = dnNormalize2( NULL, dn, &dn2 );
271                 free(dn->bv_val);
272                 if ( rc != LDAP_SUCCESS ) {
273                         dn->bv_val = NULL;
274                         dn->bv_len = 0;
275                         return rc;
276                 }
277                 *dn = dn2;
278         }
279
280         return( LDAP_SUCCESS );
281 }
282
283 #if SASL_VERSION_MAJOR >= 2
284 static const char *slap_propnames[] = { "*authcDN", "*authzDN", NULL };
285
286 static void
287 slap_auxprop_lookup(
288         void *glob_context,
289         sasl_server_params_t *sparams,
290         unsigned flags,
291         const char *user,
292         unsigned ulen)
293 {
294         int rc;
295         struct berval dn;
296         const struct propval *list, *cur;
297         BerVarray vals, bv;
298         AttributeDescription *ad;
299         const char *text;
300
301         list = sparams->utils->prop_get( sparams->propctx );
302
303         /* Find our DN first */
304         for( cur = list; cur->name; cur++ ) {
305                 if ( cur->name[0] == '*' ) {
306                         if ( (flags & SASL_AUXPROP_AUTHZID) &&
307                                 !strcmp( cur->name, slap_propnames[1] ) ) {
308                                 if ( cur->values && cur->values[0] )
309                                         AC_MEMCPY( &dn, cur->values[0], sizeof( dn ) );
310                                 break;
311                         }
312                         if ( !strcmp( cur->name, slap_propnames[0] ) ) {
313                                 AC_MEMCPY( &dn, cur->values[0], sizeof( dn ) );
314                                 if ( !(flags & SASL_AUXPROP_AUTHZID) )
315                                         break;
316                         }
317                 }
318         }
319
320         /* Now fetch the rest */
321         for( cur = list; cur->name; cur++ ) {
322                 const char *name = cur->name;
323
324                 if ( name[0] == '*' ) {
325                         if ( flags & SASL_AUXPROP_AUTHZID ) continue;
326                         name++;
327                 } else if ( !(flags & SASL_AUXPROP_AUTHZID ) )
328                         continue;
329
330                 if ( cur->values ) {
331                         if ( !(flags & SASL_AUXPROP_OVERRIDE) ) continue;
332                         sparams->utils->prop_erase( sparams->propctx, cur->name );
333                 }
334                 ad = NULL;
335                 rc = slap_str2ad( name, &ad, &text );
336                 if ( rc != LDAP_SUCCESS ) {
337 #ifdef NEW_LOGGING
338                         LDAP_LOG(( "sasl", LDAP_LEVEL_DETAIL1,
339                                 "slap_auxprop: str2ad(%s): %s\n", name, text ));
340 #else
341                         Debug( LDAP_DEBUG_TRACE,
342                                 "slap_auxprop: str2ad(%s): %s\n", name, text, 0 );
343 #endif
344                         rc = slap_str2undef_ad( name, &ad, &text );
345                         if ( rc != LDAP_SUCCESS ) continue;
346                 }
347                 rc = backend_attribute( NULL,NULL,NULL,NULL, &dn, ad, &vals );
348                 if ( rc != LDAP_SUCCESS ) continue;
349                 for ( bv = vals; bv->bv_val; bv++ ) {
350                         sparams->utils->prop_set( sparams->propctx, cur->name,
351                                 bv->bv_val, bv->bv_len );
352                 }
353                 ber_bvarray_free( vals );
354         }
355 }
356
357 static sasl_auxprop_plug_t slap_auxprop_plugin = {
358         0,      /* Features */
359         0,      /* spare */
360         NULL,   /* glob_context */
361         NULL,   /* auxprop_free */
362         slap_auxprop_lookup,
363         "slapd",        /* name */
364         NULL    /* spare */
365 };
366
367 static int
368 slap_auxprop_init(
369         const sasl_utils_t *utils,
370         int max_version,
371         int *out_version,
372         sasl_auxprop_plug_t **plug,
373         const char *plugname)
374 {
375         if ( !out_version | !plug ) return SASL_BADPARAM;
376
377         if ( max_version < SASL_AUXPROP_PLUG_VERSION ) return SASL_BADVERS;
378
379         *out_version = SASL_AUXPROP_PLUG_VERSION;
380         *plug = &slap_auxprop_plugin;
381         return SASL_OK;
382 }
383
384 static int
385 slap_sasl_checkpass(
386         sasl_conn_t *sconn,
387         void *context,
388         const char *username,
389         const char *pass,
390         unsigned passlen,
391         struct propctx *propctx)
392 {
393         Connection *conn = (Connection *)context;
394         struct berval dn, cred;
395         int rc;
396         BerVarray vals, bv;
397
398         cred.bv_val = (char *)pass;
399         cred.bv_len = passlen;
400
401         /* SASL will fallback to its own mechanisms if we don't
402          * find an answer here.
403          */
404
405         rc = slap_sasl_getdn( conn, (char *)username, 0, NULL, &dn,
406                 FLAG_GETDN_AUTHCID );
407         if ( rc != LDAP_SUCCESS ) {
408                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
409                 return SASL_NOUSER;
410         }
411
412         if ( dn.bv_len == 0 ) {
413                 sasl_seterror( sconn, 0,
414                         "No password is associated with the Root DSE" );
415                 if ( dn.bv_val != NULL ) {
416                         ch_free( dn.bv_val );
417                 }
418                 return SASL_NOUSER;
419         }
420
421         rc = backend_attribute( NULL, NULL, NULL, NULL, &dn,
422                 slap_schema.si_ad_userPassword, &vals);
423         if ( rc != LDAP_SUCCESS ) {
424                 ch_free( dn.bv_val );
425                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
426                 return SASL_NOVERIFY;
427         }
428
429         rc = SASL_NOVERIFY;
430
431         if ( vals != NULL ) {
432                 for ( bv = vals; bv->bv_val != NULL; bv++ ) {
433                         if ( !lutil_passwd( bv, &cred, NULL ) ) {
434                                 rc = SASL_OK;
435                                 break;
436                         }
437                 }
438                 ber_bvarray_free( vals );
439         }
440
441         if ( rc != SASL_OK ) {
442                 sasl_seterror( sconn, 0,
443                         ldap_err2string( LDAP_INVALID_CREDENTIALS ) );
444         }
445
446         ch_free( dn.bv_val );
447
448         return rc;
449 }
450
451 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
452  * auxiliary property, so that we can refer to it in sasl_authorize
453  * without interfering with anything else. Also, the SASL username
454  * buffer is constrained to 256 characters, and our DNs could be
455  * much longer (totally arbitrary length)...
456  */
457 static int
458 slap_sasl_canonicalize(
459         sasl_conn_t *sconn,
460         void *context,
461         const char *in,
462         unsigned inlen,
463         unsigned flags,
464         const char *user_realm,
465         char *out,
466         unsigned out_max,
467         unsigned *out_len)
468 {
469         Connection *conn = (Connection *)context;
470         struct propctx *props = sasl_auxprop_getctx( sconn );
471         struct berval dn;
472         int rc, ext = 0;
473         char *realm;
474         const char *names[2];
475
476         *out_len = 0;
477
478 #ifdef NEW_LOGGING
479         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
480                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
481                         conn ? conn->c_connid : -1,
482                         (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
483                         in ? in : "<empty>" ));
484 #else
485         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: "
486                 "%s=\"%s\"\n",
487                         conn ? conn->c_connid : -1,
488                         (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
489                         in ? in : "<empty>" );
490 #endif
491
492         if ( inlen > out_max )
493                 return SASL_BUFOVER;
494
495         if ( flags == SASL_CU_AUTHZID ) {
496         /* If we got unqualified authzid's, they probably came from SASL
497          * itself just passing the authcid to us. Ignore it.
498          */
499                 if (strncasecmp(in, "u:", 2) && strncasecmp(in, "dn:", 3)) {
500                         AC_MEMCPY( out, in, inlen );
501                         out[inlen] = '\0';
502                         *out_len = inlen;
503
504                         return SASL_OK;
505                 }
506         }
507
508         /* If using SASL-EXTERNAL, don't modify the ID in any way */
509         if ( conn->c_is_tls && conn->c_sasl_bind_mech.bv_len == ext_bv.bv_len
510                 && ( strcasecmp( ext_bv.bv_val, conn->c_sasl_bind_mech.bv_val ) == 0 ) ) {
511                 ext = 1;
512                 realm = NULL;
513         } else {
514         /* Else look for an embedded realm in the name */
515                 realm = strchr( in, '@' );
516                 if ( realm ) *realm++ = '\0';
517         }
518         rc = slap_sasl_getdn( conn, (char *)in, inlen, realm ? realm : (char *)user_realm, &dn,
519                 (flags & SASL_CU_AUTHID) ? FLAG_GETDN_AUTHCID : FLAG_GETDN_AUTHZID );
520         if ( realm )
521                 realm[-1] = '@';
522         if ( rc != LDAP_SUCCESS ) {
523                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
524                 return SASL_NOAUTHZ;
525         }               
526
527         AC_MEMCPY( out, in, inlen );
528         out[inlen] = '\0';
529
530         *out_len = inlen;
531
532         if ( flags & SASL_CU_AUTHID )
533                 names[0] = slap_propnames[0];
534         else
535                 names[0] = slap_propnames[1];
536         names[1] = NULL;
537
538         sasl_auxprop_request( sconn, names );
539         prop_set( props, names[0], (char *)&dn, sizeof( dn ) );
540                 
541 #ifdef NEW_LOGGING
542         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
543                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
544                         conn ? conn->c_connid : -1,
545                         (flags & SASL_CU_AUTHID) ? "authcDN" : "authzDN",
546                         dn.bv_val ));
547 #else
548         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: "
549                 "%s=\"%s\"\n",
550                         conn ? conn->c_connid : -1,
551                         (flags & SASL_CU_AUTHID) ? "authcDN" : "authzDN",
552                         dn.bv_val );
553 #endif
554
555         return SASL_OK;
556 }
557
558 static int
559 slap_sasl_authorize(
560         sasl_conn_t *sconn,
561         void *context,
562         char *requested_user,
563         unsigned rlen,
564         char *auth_identity,
565         unsigned alen,
566         const char *def_realm,
567         unsigned urlen,
568         struct propctx *props)
569 {
570         Connection *conn = (Connection *)context;
571         struct propval auxvals[3];
572         struct berval authcDN, authzDN;
573         int rc;
574
575 #ifdef NEW_LOGGING
576         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
577                 "slap_sasl_authorize: conn %d authcid=\"%s\" authzid=\"%s\"\n",
578                         conn ? conn->c_connid : -1, auth_identity, requested_user));
579 #else
580         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
581                 "authcid=\"%s\" authzid=\"%s\"\n",
582                 conn ? conn->c_connid : -1, auth_identity, requested_user );
583 #endif
584
585         prop_getnames( props, slap_propnames, auxvals );
586         
587         /* Nothing to do if no authzID was given */
588         if ( !auxvals[1].name )
589                 return SASL_OK;
590         
591         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
592         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
593
594         rc = slap_sasl_authorized( &authcDN, &authzDN );
595         if ( rc != LDAP_SUCCESS ) {
596 #ifdef NEW_LOGGING
597                 LDAP_LOG(( "sasl", LDAP_LEVEL_INFO,
598                            "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
599                            (long)(conn ? conn->c_connid : -1), rc ));
600 #else
601                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
602                         " authorization disallowed (%d)\n",
603                         (long) (conn ? conn->c_connid : -1), rc, 0 );
604 #endif
605
606                 sasl_seterror( sconn, 0, "not authorized" );
607                 return SASL_NOAUTHZ;
608         }
609
610 #ifdef NEW_LOGGING
611         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
612                    "slap_sasl_authorize: conn %d authorization allowed\n",
613                    (long)(conn ? conn->c_connid : -1 ) ));
614 #else
615         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
616                 " authorization allowed\n",
617                 (long) (conn ? conn->c_connid : -1), 0, 0 );
618 #endif
619         return SASL_OK;
620
621 #else
622 static int
623 slap_sasl_authorize(
624         void *context,
625         char *authcid,
626         char *authzid,
627         const char **user,
628         const char **errstr)
629 {
630         struct berval authcDN, authzDN;
631         int rc, ext = 0;
632         Connection *conn = context;
633         char *realm, *xrealm;
634
635         *user = NULL;
636
637 #ifdef NEW_LOGGING
638         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
639                    "slap_sasl_authorize: conn %d         authcid=\"%s\" authzid=\"%s\"\n",
640                    conn ? conn->c_connid : -1,
641                    authcid ? authcid : "<empty>",
642                    authzid ? authzid : "<empty>" ));
643 #else
644         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
645                 "authcid=\"%s\" authzid=\"%s\"\n",
646                 (long) (conn ? conn->c_connid : -1),
647                 authcid ? authcid : "<empty>",
648                 authzid ? authzid : "<empty>" );
649 #endif
650
651         /* Figure out how much data we have for the dn */
652         rc = sasl_getprop( conn->c_sasl_context, SASL_REALM, (void **)&realm );
653         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
654 #ifdef NEW_LOGGING
655                 LDAP_LOG(( "sasl", LDAP_LEVEL_ERR,
656                         "slap_sasl_authorize: getprop(REALM) failed.\n" ));
657 #else
658                 Debug(LDAP_DEBUG_TRACE,
659                         "authorize: getprop(REALM) failed!\n", 0,0,0);
660 #endif
661                 *errstr = "Could not extract realm";
662                 return SASL_NOAUTHZ;
663         }
664
665         /* Convert the identities to DN's. If no authzid was given, client will
666            be bound as the DN matching their username */
667         if ( conn->c_is_tls && conn->c_sasl_bind_mech.bv_len == ext_bv.bv_len
668                 && ( strcasecmp( ext_bv.bv_val, conn->c_sasl_bind_mech.bv_val ) == 0 ) ) {
669                 ext = 1;
670                 xrealm = NULL;
671         } else {
672                 xrealm = strchr( authcid, '@' );
673                 if ( xrealm ) *xrealm++ = '\0';
674         }
675         rc = slap_sasl_getdn( conn, (char *)authcid, 0, xrealm ? xrealm : realm, &authcDN, FLAG_GETDN_AUTHCID );
676         if ( xrealm ) xrealm[-1] = '@';
677         if( rc != LDAP_SUCCESS ) {
678                 *errstr = ldap_err2string( rc );
679                 return SASL_NOAUTHZ;
680         }
681         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
682 #ifdef NEW_LOGGING
683                 LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
684                            "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
685                            conn ? conn->c_connid : -1, authcDN.bv_val ));
686 #else
687                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
688                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
689 #endif
690
691                 *user = authcDN.bv_val;
692                 *errstr = NULL;
693                 return SASL_OK;
694         }
695         if ( ext ) {
696                 xrealm = NULL;
697         } else {
698                 xrealm = strchr( authzid, '@' );
699                 if ( xrealm ) *xrealm++ = '\0';
700         }
701         rc = slap_sasl_getdn( conn, (char *)authzid, 0, xrealm ? xrealm : realm, &authzDN, FLAG_GETDN_AUTHZID );
702         if ( xrealm ) xrealm[-1] = '@';
703         if( rc != LDAP_SUCCESS ) {
704                 ch_free( authcDN.bv_val );
705                 *errstr = ldap_err2string( rc );
706                 return SASL_NOAUTHZ;
707         }
708
709         rc = slap_sasl_authorized( &authcDN, &authzDN );
710         if( rc ) {
711 #ifdef NEW_LOGGING
712                 LDAP_LOG(( "sasl", LDAP_LEVEL_INFO,
713                            "slap_sasl_authorize: conn %ld  authorization disallowed (%d)\n",
714                            (long)(conn ? conn->c_connid : -1), rc ));
715 #else
716                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
717                         " authorization disallowed (%d)\n",
718                         (long) (conn ? conn->c_connid : -1), rc, 0 );
719 #endif
720
721                 *errstr = "not authorized";
722                 ch_free( authcDN.bv_val );
723                 ch_free( authzDN.bv_val );
724                 return SASL_NOAUTHZ;
725         }
726
727 #ifdef NEW_LOGGING
728         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
729                    "slap_sasl_authorize: conn %d authorization allowed\n",
730                    (long)(conn ? conn->c_connid : -1 ) ));
731 #else
732         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
733                 " authorization allowed\n",
734                 (long) (conn ? conn->c_connid : -1), 0, 0 );
735 #endif
736
737
738         ch_free( authcDN.bv_val );
739         *user = authzDN.bv_val;
740         *errstr = NULL;
741         return SASL_OK;
742 }
743 #endif /* SASL_VERSION_MAJOR >= 2 */
744
745 static int
746 slap_sasl_err2ldap( int saslerr )
747 {
748         int rc;
749
750         switch (saslerr) {
751                 case SASL_CONTINUE:
752                         rc = LDAP_SASL_BIND_IN_PROGRESS;
753                         break;
754                 case SASL_FAIL:
755                         rc = LDAP_OTHER;
756                         break;
757                 case SASL_NOMEM:
758                         rc = LDAP_OTHER;
759                         break;
760                 case SASL_NOMECH:
761                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
762                         break;
763                 case SASL_BADAUTH:
764                         rc = LDAP_INVALID_CREDENTIALS;
765                         break;
766                 case SASL_NOAUTHZ:
767                         rc = LDAP_INSUFFICIENT_ACCESS;
768                         break;
769                 case SASL_TOOWEAK:
770                 case SASL_ENCRYPT:
771                         rc = LDAP_INAPPROPRIATE_AUTH;
772                         break;
773                 default:
774                         rc = LDAP_OTHER;
775                         break;
776         }
777
778         return rc;
779 }
780 #endif
781
782
783 int slap_sasl_init( void )
784 {
785 #ifdef HAVE_CYRUS_SASL
786         int rc;
787         static sasl_callback_t server_callbacks[] = {
788                 { SASL_CB_LOG, &slap_sasl_log, NULL },
789                 { SASL_CB_LIST_END, NULL, NULL }
790         };
791
792         sasl_set_alloc(
793                 ch_malloc,
794                 ch_calloc,
795                 ch_realloc,
796                 ch_free ); 
797
798         sasl_set_mutex(
799                 ldap_pvt_sasl_mutex_new,
800                 ldap_pvt_sasl_mutex_lock,
801                 ldap_pvt_sasl_mutex_unlock,
802                 ldap_pvt_sasl_mutex_dispose );
803
804 #if SASL_VERSION_MAJOR >= 2
805         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
806 #endif
807         /* should provide callbacks for logging */
808         /* server name should be configurable */
809         rc = sasl_server_init( server_callbacks, "slapd" );
810
811         if( rc != SASL_OK ) {
812 #ifdef NEW_LOGGING
813                 LDAP_LOG(( "sasl", LDAP_LEVEL_INFO,
814                            "slap_sasl_init: init failed.\n" ));
815 #else
816                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
817                         0, 0, 0 );
818 #endif
819
820                 return -1;
821         }
822
823 #ifdef NEW_LOGGING
824         LDAP_LOG(( "sasl", LDAP_LEVEL_INFO,
825                    "slap_sasl_init: initialized!\n"));
826 #else
827         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
828                 0, 0, 0 );
829 #endif
830
831
832         /* default security properties */
833         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
834         sasl_secprops.max_ssf = INT_MAX;
835         sasl_secprops.maxbufsize = 65536;
836         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
837 #endif
838
839         return 0;
840 }
841
842 int slap_sasl_destroy( void )
843 {
844 #ifdef HAVE_CYRUS_SASL
845         sasl_done();
846 #endif
847         free( global_host );
848         global_host = NULL;
849
850         return 0;
851 }
852
853 int slap_sasl_open( Connection *conn )
854 {
855         int cb, sc = LDAP_SUCCESS;
856 #if SASL_VERSION_MAJOR >= 2
857         char *ipremoteport = NULL, *iplocalport = NULL;
858 #endif
859
860 #ifdef HAVE_CYRUS_SASL
861         sasl_conn_t *ctx = NULL;
862         sasl_callback_t *session_callbacks;
863
864         assert( conn->c_sasl_context == NULL );
865         assert( conn->c_sasl_extra == NULL );
866
867         conn->c_sasl_layers = 0;
868
869         session_callbacks =
870 #if SASL_VERSION_MAJOR >= 2
871                 ch_calloc( 5, sizeof(sasl_callback_t));
872 #else
873                 ch_calloc( 3, sizeof(sasl_callback_t));
874 #endif
875         conn->c_sasl_extra = session_callbacks;
876
877         session_callbacks[cb=0].id = SASL_CB_LOG;
878         session_callbacks[cb].proc = &slap_sasl_log;
879         session_callbacks[cb++].context = conn;
880
881         session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
882         session_callbacks[cb].proc = &slap_sasl_authorize;
883         session_callbacks[cb++].context = conn;
884
885 #if SASL_VERSION_MAJOR >= 2
886         session_callbacks[cb].id = SASL_CB_CANON_USER;
887         session_callbacks[cb].proc = &slap_sasl_canonicalize;
888         session_callbacks[cb++].context = conn;
889
890         /* XXXX: this should be conditional */
891         session_callbacks[cb].id = SASL_CB_SERVER_USERDB_CHECKPASS;
892         session_callbacks[cb].proc = &slap_sasl_checkpass;
893         session_callbacks[cb++].context = conn;
894 #endif
895
896         session_callbacks[cb].id = SASL_CB_LIST_END;
897         session_callbacks[cb].proc = NULL;
898         session_callbacks[cb++].context = NULL;
899
900         if( global_host == NULL ) {
901                 global_host = ldap_pvt_get_fqdn( NULL );
902         }
903
904         /* create new SASL context */
905 #if SASL_VERSION_MAJOR >= 2
906         if ( conn->c_sock_name.bv_len != 0 &&
907              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
908                 char *p;
909
910                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
911                 /* Convert IPv6 addresses to address;port syntax. */
912                 p = strrchr( iplocalport, ' ' );
913                 /* Convert IPv4 addresses to address;port syntax. */
914                 if ( p == NULL ) p = strchr( iplocalport, ':' );
915                 if ( p != NULL ) {
916                         *p = ';';
917                 }
918         }
919         if ( conn->c_peer_name.bv_len != 0 &&
920              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
921                 char *p;
922
923                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
924                 /* Convert IPv6 addresses to address;port syntax. */
925                 p = strrchr( ipremoteport, ' ' );
926                 /* Convert IPv4 addresses to address;port syntax. */
927                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
928                 if ( p != NULL ) {
929                         *p = ';';
930                 }
931         }
932         sc = sasl_server_new( "ldap", global_host, global_realm,
933                 iplocalport, ipremoteport, session_callbacks, 0, &ctx );
934         if ( iplocalport != NULL ) {
935                 ch_free( iplocalport );
936         }
937         if ( ipremoteport != NULL ) {
938                 ch_free( ipremoteport );
939         }
940 #else
941         sc = sasl_server_new( "ldap", global_host, global_realm,
942                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
943 #endif
944
945         if( sc != SASL_OK ) {
946 #ifdef NEW_LOGGING
947                 LDAP_LOG(( "sasl", LDAP_LEVEL_ERR,
948                            "slap_sasl_open: sasl_server_new failed: %d\n", sc ));
949 #else
950                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
951                         sc, 0, 0 );
952 #endif
953
954                 return -1;
955         }
956
957         conn->c_sasl_context = ctx;
958
959         if( sc == SASL_OK ) {
960                 sc = sasl_setprop( ctx,
961                         SASL_SEC_PROPS, &sasl_secprops );
962
963                 if( sc != SASL_OK ) {
964 #ifdef NEW_LOGGING
965                         LDAP_LOG(( "sasl", LDAP_LEVEL_ERR,
966                                    "slap_sasl_open: sasl_setprop failed: %d \n", sc ));
967 #else
968                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
969                                 sc, 0, 0 );
970 #endif
971
972                         slap_sasl_close( conn );
973                         return -1;
974                 }
975         }
976
977         sc = slap_sasl_err2ldap( sc );
978 #endif
979         return sc;
980 }
981
982 int slap_sasl_external(
983         Connection *conn,
984         slap_ssf_t ssf,
985         const char *auth_id )
986 {
987 #if SASL_VERSION_MAJOR >= 2
988         int sc;
989         sasl_conn_t *ctx = conn->c_sasl_context;
990
991         if ( ctx == NULL ) {
992                 return LDAP_UNAVAILABLE;
993         }
994
995         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
996
997         if ( sc != SASL_OK ) {
998                 return LDAP_OTHER;
999         }
1000
1001         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL, auth_id );
1002
1003         if ( sc != SASL_OK ) {
1004                 return LDAP_OTHER;
1005         }
1006
1007 #elif defined(HAVE_CYRUS_SASL)
1008         int sc;
1009         sasl_conn_t *ctx = conn->c_sasl_context;
1010         sasl_external_properties_t extprops;
1011
1012         if ( ctx == NULL ) {
1013                 return LDAP_UNAVAILABLE;
1014         }
1015
1016         memset( &extprops, '\0', sizeof(extprops) );
1017         extprops.ssf = ssf;
1018         extprops.auth_id = (char *) auth_id;
1019
1020         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1021                 (void *) &extprops );
1022
1023         if ( sc != SASL_OK ) {
1024                 return LDAP_OTHER;
1025         }
1026 #endif
1027
1028         return LDAP_SUCCESS;
1029 }
1030
1031 int slap_sasl_reset( Connection *conn )
1032 {
1033 #ifdef HAVE_CYRUS_SASL
1034         sasl_conn_t *ctx = conn->c_sasl_context;
1035
1036         if( ctx != NULL ) {
1037         }
1038 #endif
1039         /* must return "anonymous" */
1040         return LDAP_SUCCESS;
1041 }
1042
1043 char ** slap_sasl_mechs( Connection *conn )
1044 {
1045         char **mechs = NULL;
1046
1047 #ifdef HAVE_CYRUS_SASL
1048         sasl_conn_t *ctx = conn->c_sasl_context;
1049
1050         if( ctx != NULL ) {
1051                 int sc;
1052                 SASL_CONST char *mechstr;
1053
1054                 sc = sasl_listmech( ctx,
1055                         NULL, NULL, ",", NULL,
1056                         &mechstr, NULL, NULL );
1057
1058                 if( sc != SASL_OK ) {
1059 #ifdef NEW_LOGGING
1060                         LDAP_LOG(( "sasl", LDAP_LEVEL_ERR,
1061                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc ));
1062 #else
1063                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1064                                 sc, 0, 0 );
1065 #endif
1066
1067                         return NULL;
1068                 }
1069
1070                 mechs = str2charray( mechstr, "," );
1071
1072 #if SASL_VERSION_MAJOR < 2
1073                 ch_free( mechstr );
1074 #endif
1075         }
1076 #endif
1077
1078         return mechs;
1079 }
1080
1081 int slap_sasl_close( Connection *conn )
1082 {
1083 #ifdef HAVE_CYRUS_SASL
1084         sasl_conn_t *ctx = conn->c_sasl_context;
1085
1086         if( ctx != NULL ) {
1087                 sasl_dispose( &ctx );
1088         }
1089
1090         conn->c_sasl_context = NULL;
1091
1092         free( conn->c_sasl_extra );
1093         conn->c_sasl_extra = NULL;
1094 #endif
1095
1096         return LDAP_SUCCESS;
1097 }
1098
1099 int slap_sasl_bind(
1100     Connection          *conn,
1101     Operation           *op,  
1102     struct berval       *dn,  
1103     struct berval       *ndn,
1104     struct berval       *cred,
1105         struct berval                   *edn,
1106         slap_ssf_t              *ssfp )
1107 {
1108         int rc = 1;
1109
1110 #ifdef HAVE_CYRUS_SASL
1111         sasl_conn_t *ctx = conn->c_sasl_context;
1112         struct berval response;
1113         unsigned reslen = 0;
1114         const char *errstr = NULL;
1115         int sc;
1116
1117 #ifdef NEW_LOGGING
1118         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
1119                 "sasl_bind: conn %ld dn=\"%s\" mech=%s datalen=%ld\n",
1120                 conn->c_connid,
1121                 dn->bv_len ? dn->bv_val : "",
1122                 conn->c_sasl_bind_in_progress ? "<continuing>" : conn->c_sasl_bind_mech.bv_val,
1123                 cred ? cred->bv_len : 0 ));
1124 #else
1125         Debug(LDAP_DEBUG_ARGS,
1126                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1127                 dn->bv_len ? dn->bv_val : "",
1128                 conn->c_sasl_bind_in_progress ? "<continuing>":conn->c_sasl_bind_mech.bv_val,
1129                 cred ? cred->bv_len : 0 );
1130 #endif
1131
1132
1133         if( ctx == NULL ) {
1134                 send_ldap_result( conn, op, LDAP_UNAVAILABLE,
1135                         NULL, "SASL unavailable on this session", NULL, NULL );
1136                 return rc;
1137         }
1138
1139 #if SASL_VERSION_MAJOR >= 2
1140 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1141         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1142 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1143         sasl_server_step( ctx, cred, clen, resp, rlen )
1144 #else
1145 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1146         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1147 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1148         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1149 #endif
1150
1151         if ( !conn->c_sasl_bind_in_progress ) {
1152                 sc = START( ctx,
1153                         conn->c_sasl_bind_mech.bv_val,
1154                         cred->bv_len ? cred->bv_val : "",
1155                         cred->bv_len,
1156                         (SASL_CONST char **)&response.bv_val, &reslen, &errstr );
1157
1158         } else {
1159                 sc = STEP( ctx,
1160                         cred->bv_val, cred->bv_len,
1161                         (SASL_CONST char **)&response.bv_val, &reslen, &errstr );
1162         }
1163
1164         response.bv_len = reslen;
1165
1166         if ( sc == SASL_OK ) {
1167 #if SASL_VERSION_MAJOR >= 2
1168                 struct propctx *props = sasl_auxprop_getctx( ctx );
1169                 struct propval vals[3];
1170                 sasl_ssf_t *ssf = NULL;
1171
1172                 prop_getnames( props, slap_propnames, vals );
1173
1174                 AC_MEMCPY( edn, vals[0].values[0], sizeof(*edn) );
1175                 if ( vals[1].name ) {
1176                         ch_free( edn->bv_val );
1177                         AC_MEMCPY( edn, vals[1].values[0], sizeof(*edn) );
1178                 }
1179
1180                 rc = LDAP_SUCCESS;
1181
1182                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1183                 *ssfp = ssf ? *ssf : 0;
1184
1185                 if( *ssfp ) {
1186                         ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1187                         conn->c_sasl_layers++;
1188                         ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1189                 }
1190
1191                 send_ldap_sasl( conn, op, rc,
1192                         NULL, NULL, NULL, NULL,
1193                         response.bv_len ? &response : NULL );
1194 #else
1195                 char *username = NULL;
1196
1197                 sc = sasl_getprop( ctx,
1198                         SASL_USERNAME, (SASL_CONST void **)&username );
1199
1200                 if ( sc != SASL_OK ) {
1201 #ifdef NEW_LOGGING
1202                         LDAP_LOG(( "sasl", LDAP_LEVEL_ERR,
1203                                 "slap_sasl_bind: getprop(USERNAME) failed: %d\n", sc ));
1204 #else
1205                         Debug(LDAP_DEBUG_TRACE,
1206                                 "slap_sasl_bind: getprop(USERNAME) failed!\n",
1207                                 0, 0, 0);
1208 #endif
1209
1210
1211                         send_ldap_result( conn, op, rc = slap_sasl_err2ldap( sc ),
1212                                 NULL, "no SASL username", NULL, NULL );
1213
1214                 } else {
1215                         sasl_ssf_t *ssf = NULL;
1216
1217                         rc = LDAP_SUCCESS;
1218                         ber_str2bv( username, 0, 1, edn );
1219
1220                         (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1221                         *ssfp = ssf ? *ssf : 0;
1222
1223                         if( *ssfp ) {
1224                                 ldap_pvt_thread_mutex_lock( &conn->c_mutex );
1225                                 conn->c_sasl_layers++;
1226                                 ldap_pvt_thread_mutex_unlock( &conn->c_mutex );
1227                         }
1228
1229                         send_ldap_sasl( conn, op, rc,
1230                                 NULL, NULL, NULL, NULL,
1231                                 response.bv_len ? &response : NULL );
1232                 }
1233 #endif
1234
1235         } else if ( sc == SASL_CONTINUE ) {
1236                 send_ldap_sasl( conn, op, rc = LDAP_SASL_BIND_IN_PROGRESS,
1237                         NULL, NULL, NULL, NULL, &response );
1238
1239         } else {
1240 #if SASL_VERSION_MAJOR >= 2
1241                 errstr = sasl_errdetail( ctx );
1242 #endif
1243                 send_ldap_result( conn, op, rc = slap_sasl_err2ldap( sc ),
1244                         NULL, errstr, NULL, NULL );
1245         }
1246
1247 #if SASL_VERSION_MAJOR < 2
1248         if( response.bv_len ) {
1249                 ch_free( response.bv_val );
1250         }
1251 #endif
1252
1253 #ifdef NEW_LOGGING
1254         LDAP_LOG(( "sasl", LDAP_LEVEL_ENTRY,
1255                 "slap_sasl_bind: rc=%d\n", rc ));
1256 #else
1257         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rc, 0, 0);
1258 #endif
1259
1260
1261 #else
1262         send_ldap_result( conn, op, rc = LDAP_UNAVAILABLE,
1263                 NULL, "SASL not supported", NULL, NULL );
1264 #endif
1265
1266         return rc;
1267 }
1268
1269 char* slap_sasl_secprops( const char *in )
1270 {
1271 #ifdef HAVE_CYRUS_SASL
1272         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1273
1274         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1275 #else
1276         return "SASL not supported";
1277 #endif
1278 }