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