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