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