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