]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
Sync with HEAD
[openldap] / servers / slapd / sasl.c
1 /* $OpenLDAP$ */
2 /*
3  * Copyright 1998-2003 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 #include <limits.h>
19
20 #ifdef HAVE_CYRUS_SASL
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 # ifdef HAVE_SASL_SASL_H
29 #  include <sasl/saslplug.h>
30 # else
31 #  include <saslplug.h>
32 # endif
33 #  define       SASL_CONST const
34 # else
35 #  define       SASL_CONST
36 # endif
37
38 static sasl_security_properties_t sasl_secprops;
39 #endif /* HAVE_CYRUS_SASL */
40
41 #include "ldap_pvt.h"
42 #include "lber_pvt.h"
43 #include <lutil.h>
44
45 int slap_sasl_config( int cargc, char **cargv, char *line,
46         const char *fname, int lineno )
47 {
48                 /* set SASL proxy authorization policy */
49                 if ( strcasecmp( cargv[0], "sasl-authz-policy" ) == 0 ) {
50                         if ( cargc != 2 ) {
51 #ifdef NEW_LOGGING
52                                 LDAP_LOG( CONFIG, CRIT,
53                                         "%s: line %d: missing policy in"
54                                         " \"sasl-authz-policy <policy>\" line\n",
55                                         fname, lineno, 0 );
56 #else
57                                 Debug( LDAP_DEBUG_ANY,
58                                         "%s: line %d: missing policy in"
59                                         " \"sasl-authz-policy <policy>\" line\n",
60                                     fname, lineno, 0 );
61 #endif
62
63                                 return( 1 );
64                         }
65                         if ( slap_sasl_setpolicy( cargv[1] ) ) {
66 #ifdef NEW_LOGGING
67                                 LDAP_LOG( CONFIG, CRIT,
68                                            "%s: line %d: unable "
69                                            "to parse value \"%s\" "
70                                            "in \"sasl-authz-policy "
71                                            "<policy>\" line.\n",
72                                            fname, lineno, cargv[1] );
73 #else
74                                 Debug( LDAP_DEBUG_ANY,
75                                         "%s: line %d: unable "
76                                         "to parse value \"%s\" "
77                                         "in \"sasl-authz-policy "
78                                         "<policy>\" line\n",
79                                         fname, lineno, cargv[1] );
80 #endif
81                                 return( 1 );
82                         }
83
84                 } else if ( !strcasecmp( cargv[0], "sasl-regexp" ) 
85                         || !strcasecmp( cargv[0], "saslregexp" ) )
86                 {
87                         int rc;
88                         if ( cargc != 3 ) {
89 #ifdef NEW_LOGGING
90                                 LDAP_LOG( CONFIG, CRIT,
91                                         "%s: line %d: need 2 args in "
92                                         "\"saslregexp <match> <replace>\"\n",
93                                         fname, lineno, 0 );
94 #else
95                                 Debug( LDAP_DEBUG_ANY, 
96                                         "%s: line %d: need 2 args in "
97                                         "\"saslregexp <match> <replace>\"\n",
98                                         fname, lineno, 0 );
99 #endif
100
101                                 return( 1 );
102                         }
103                         rc = slap_sasl_regexp_config( cargv[1], cargv[2] );
104                         if ( rc ) {
105                                 return rc;
106                         }
107
108 #ifdef HAVE_CYRUS_SASL
109                 /* set SASL host */
110                 } else if ( strcasecmp( cargv[0], "sasl-host" ) == 0 ) {
111                         if ( cargc < 2 ) {
112 #ifdef NEW_LOGGING
113                                 LDAP_LOG( CONFIG, CRIT,
114                                         "%s: line %d: missing host in \"sasl-host <host>\" line\n",
115                                         fname, lineno, 0 );
116 #else
117                                 Debug( LDAP_DEBUG_ANY,
118                                 "%s: line %d: missing host in \"sasl-host <host>\" line\n",
119                                     fname, lineno, 0 );
120 #endif
121
122                                 return( 1 );
123                         }
124
125                         if ( global_host != NULL ) {
126 #ifdef NEW_LOGGING
127                                 LDAP_LOG( CONFIG, CRIT,
128                                         "%s: line %d: already set sasl-host!\n",
129                                         fname, lineno, 0 );
130 #else
131                                 Debug( LDAP_DEBUG_ANY,
132                                         "%s: line %d: already set sasl-host!\n",
133                                         fname, lineno, 0 );
134 #endif
135
136                                 return 1;
137
138                         } else {
139                                 global_host = ch_strdup( cargv[1] );
140                         }
141
142                 /* set SASL realm */
143                 } else if ( strcasecmp( cargv[0], "sasl-realm" ) == 0 ) {
144                         if ( cargc < 2 ) {
145 #ifdef NEW_LOGGING
146                                 LDAP_LOG( CONFIG, CRIT, "%s: line %d: "
147                                         "missing realm in \"sasl-realm <realm>\" line.\n",
148                                         fname, lineno, 0 );
149 #else
150                                 Debug( LDAP_DEBUG_ANY, "%s: line %d: "
151                                         "missing realm in \"sasl-realm <realm>\" line.\n",
152                                     fname, lineno, 0 );
153 #endif
154
155                                 return( 1 );
156                         }
157
158                         if ( global_realm != NULL ) {
159 #ifdef NEW_LOGGING
160                                 LDAP_LOG( CONFIG, CRIT,
161                                         "%s: line %d: already set sasl-realm!\n",
162                                         fname, lineno, 0 );
163 #else
164                                 Debug( LDAP_DEBUG_ANY,
165                                         "%s: line %d: already set sasl-realm!\n",
166                                         fname, lineno, 0 );
167 #endif
168
169                                 return 1;
170
171                         } else {
172                                 global_realm = ch_strdup( cargv[1] );
173                         }
174
175                 /* SASL security properties */
176                 } else if ( strcasecmp( cargv[0], "sasl-secprops" ) == 0 ) {
177                         char *txt;
178
179                         if ( cargc < 2 ) {
180 #ifdef NEW_LOGGING
181                                 LDAP_LOG( CONFIG, CRIT, "%s: line %d: "
182                                         "missing flags in \"sasl-secprops <properties>\" line\n",
183                                         fname, lineno, 0 );
184 #else
185                                 Debug( LDAP_DEBUG_ANY, "%s: line %d: "
186                                         "missing flags in \"sasl-secprops <properties>\" line\n",
187                                     fname, lineno, 0 );
188 #endif
189
190                                 return 1;
191                         }
192
193                         txt = slap_sasl_secprops( cargv[1] );
194                         if ( txt != NULL ) {
195 #ifdef NEW_LOGGING
196                                 LDAP_LOG( CONFIG, CRIT,
197                                         "%s: line %d sasl-secprops: %s\n",
198                                         fname, lineno, txt );
199 #else
200                                 Debug( LDAP_DEBUG_ANY,
201                                         "%s: line %d: sasl-secprops: %s\n",
202                                     fname, lineno, txt );
203 #endif
204
205                                 return 1;
206                         }
207 #endif /* HAVE_CYRUS_SASL */
208             }
209
210             return LDAP_SUCCESS;
211 }
212
213 #ifdef HAVE_CYRUS_SASL
214
215 int
216 slap_sasl_log(
217         void *context,
218         int priority,
219         const char *message) 
220 {
221         Connection *conn = context;
222         int level;
223         const char * label;
224
225         if ( message == NULL ) {
226                 return SASL_BADPARAM;
227         }
228
229         switch (priority) {
230 #if SASL_VERSION_MAJOR >= 2
231         case SASL_LOG_NONE:
232                 level = LDAP_DEBUG_NONE;
233                 label = "None";
234                 break;
235         case SASL_LOG_ERR:
236                 level = LDAP_DEBUG_ANY;
237                 label = "Error";
238                 break;
239         case SASL_LOG_FAIL:
240                 level = LDAP_DEBUG_ANY;
241                 label = "Failure";
242                 break;
243         case SASL_LOG_WARN:
244                 level = LDAP_DEBUG_TRACE;
245                 label = "Warning";
246                 break;
247         case SASL_LOG_NOTE:
248                 level = LDAP_DEBUG_TRACE;
249                 label = "Notice";
250                 break;
251         case SASL_LOG_DEBUG:
252                 level = LDAP_DEBUG_TRACE;
253                 label = "Debug";
254                 break;
255         case SASL_LOG_TRACE:
256                 level = LDAP_DEBUG_TRACE;
257                 label = "Trace";
258                 break;
259         case SASL_LOG_PASS:
260                 level = LDAP_DEBUG_TRACE;
261                 label = "Password Trace";
262                 break;
263 #else
264         case SASL_LOG_ERR:
265                 level = LDAP_DEBUG_ANY;
266                 label = "Error";
267                 break;
268         case SASL_LOG_WARNING:
269                 level = LDAP_DEBUG_TRACE;
270                 label = "Warning";
271                 break;
272         case SASL_LOG_INFO:
273                 level = LDAP_DEBUG_TRACE;
274                 label = "Info";
275                 break;
276 #endif
277         default:
278                 return SASL_BADPARAM;
279         }
280
281 #ifdef NEW_LOGGING
282         LDAP_LOG( TRANSPORT, ENTRY, 
283                 "SASL [conn=%ld] %s: %s\n", conn ? conn->c_connid : -1, label, message);
284 #else
285         Debug( level, "SASL [conn=%ld] %s: %s\n",
286                 conn ? conn->c_connid: -1,
287                 label, message );
288 #endif
289
290
291         return SASL_OK;
292 }
293
294
295 #if SASL_VERSION_MAJOR >= 2
296 static const char *slap_propnames[] = {
297         "*slapConn", "*authcDN", "*authzDN", NULL };
298
299 static Filter generic_filter = { LDAP_FILTER_PRESENT };
300
301 #define PROP_CONN       0
302 #define PROP_AUTHC      1
303 #define PROP_AUTHZ      2
304
305 typedef struct lookup_info {
306         int last;
307         int flags;
308         const struct propval *list;
309         sasl_server_params_t *sparams;
310 } lookup_info;
311
312 static slap_response sasl_ap_lookup, sasl_cb_checkpass;
313
314 static int
315 sasl_ap_lookup( Operation *op, SlapReply *rs )
316 {
317         BerVarray bv;
318         AttributeDescription *ad;
319         Attribute *a;
320         const char *text;
321         int rc, i;
322         slap_callback *tmp = op->o_callback;
323         lookup_info *sl = tmp->sc_private;
324
325         if (rs->sr_type != REP_SEARCH) return 0;
326
327         for( i = 0; i < sl->last; i++ ) {
328                 const char *name = sl->list[i].name;
329
330                 if ( name[0] == '*' ) {
331                         if ( sl->flags & SASL_AUXPROP_AUTHZID ) continue;
332                         name++;
333                 } else if ( !(sl->flags & SASL_AUXPROP_AUTHZID ) )
334                         continue;
335
336                 if ( sl->list[i].values ) {
337                         if ( !(sl->flags & SASL_AUXPROP_OVERRIDE) ) continue;
338                 }
339                 ad = NULL;
340                 rc = slap_str2ad( name, &ad, &text );
341                 if ( rc != LDAP_SUCCESS ) {
342 #ifdef NEW_LOGGING
343                         LDAP_LOG( TRANSPORT, DETAIL1, 
344                                 "slap_auxprop: str2ad(%s): %s\n", name, text, 0 );
345 #else
346                         Debug( LDAP_DEBUG_TRACE,
347                                 "slap_auxprop: str2ad(%s): %s\n", name, text, 0 );
348 #endif
349                         continue;
350                 }
351                 a = attr_find( rs->sr_entry->e_attrs, ad );
352                 if ( !a ) continue;
353                 if ( ! access_allowed( op, rs->sr_entry, ad, NULL, ACL_AUTH, NULL ) ) {
354                         continue;
355                 }
356                 if ( sl->list[i].values && ( sl->flags & SASL_AUXPROP_OVERRIDE ) ) {
357                         sl->sparams->utils->prop_erase( sl->sparams->propctx,
358                         sl->list[i].name );
359                 }
360                 for ( bv = a->a_vals; bv->bv_val; bv++ ) {
361                         sl->sparams->utils->prop_set( sl->sparams->propctx,
362                                 sl->list[i].name, bv->bv_val, bv->bv_len );
363                 }
364         }
365         return LDAP_SUCCESS;
366 }
367
368 static void
369 slap_auxprop_lookup(
370         void *glob_context,
371         sasl_server_params_t *sparams,
372         unsigned flags,
373         const char *user,
374         unsigned ulen)
375 {
376         Operation op = {0};
377         int rc, i, doit=0;
378         Connection *conn = NULL;
379         lookup_info sl;
380
381         sl.list = sparams->utils->prop_get( sparams->propctx );
382         sl.sparams = sparams;
383         sl.flags = flags;
384
385         /* Find our DN and conn first */
386         for( i = 0, sl.last = 0; sl.list[i].name; i++ ) {
387                 if ( sl.list[i].name[0] == '*' ) {
388                         if ( !strcmp( sl.list[i].name, slap_propnames[PROP_CONN] ) ) {
389                                 if ( sl.list[i].values && sl.list[i].values[0] )
390                                         AC_MEMCPY( &conn, sl.list[i].values[0], sizeof( conn ) );
391                                 if ( !sl.last ) sl.last = i;
392                         }
393                         if ( (flags & SASL_AUXPROP_AUTHZID) &&
394                                 !strcmp( sl.list[i].name, slap_propnames[PROP_AUTHZ] ) ) {
395
396                                 if ( sl.list[i].values && sl.list[i].values[0] )
397                                         AC_MEMCPY( &op.o_req_ndn, sl.list[i].values[0], sizeof( struct berval ) );
398                                 if ( !sl.last ) sl.last = i;
399                                 break;
400                         }
401                         if ( !strcmp( sl.list[i].name, slap_propnames[PROP_AUTHC] ) ) {
402                                 if ( !sl.last ) sl.last = i;
403                                 if ( sl.list[i].values && sl.list[i].values[0] ) {
404                                         AC_MEMCPY( &op.o_req_ndn, sl.list[i].values[0], sizeof( struct berval ) );
405                                         if ( !(flags & SASL_AUXPROP_AUTHZID) )
406                                                 break;
407                                 }
408                         }
409                 }
410         }
411
412         /* Now see what else needs to be fetched */
413         for( i = 0; i < sl.last; i++ ) {
414                 const char *name = sl.list[i].name;
415
416                 if ( name[0] == '*' ) {
417                         if ( flags & SASL_AUXPROP_AUTHZID ) continue;
418                         name++;
419                 } else if ( !(flags & SASL_AUXPROP_AUTHZID ) )
420                         continue;
421
422                 if ( sl.list[i].values ) {
423                         if ( !(flags & SASL_AUXPROP_OVERRIDE) ) continue;
424                 }
425                 doit = 1;
426         }
427
428         if (doit) {
429                 slap_callback cb = { sasl_ap_lookup, NULL };
430
431                 cb.sc_private = &sl;
432
433                 op.o_bd = select_backend( &op.o_req_ndn, 0, 1 );
434
435                 if ( op.o_bd && op.o_bd->be_search ) {
436                         SlapReply rs = {REP_RESULT};
437                         op.o_tag = LDAP_REQ_SEARCH;
438                         op.o_protocol = LDAP_VERSION3;
439                         op.o_ndn = conn->c_ndn;
440                         op.o_callback = &cb;
441                         op.o_time = slap_get_time();
442                         op.o_do_not_cache = 1;
443                         op.o_is_auth_check = 1;
444                         op.o_threadctx = conn->c_sasl_bindop->o_threadctx;
445                         op.o_tmpmemctx = conn->c_sasl_bindop->o_tmpmemctx;
446                         op.o_tmpmfuncs = conn->c_sasl_bindop->o_tmpmfuncs;
447 #ifdef LDAP_SLAPI
448                         op.o_pb = conn->c_sasl_bindop->o_pb;
449 #endif
450                         op.o_conn = conn;
451                         op.o_connid = conn->c_connid;
452                         op.ors_scope = LDAP_SCOPE_BASE;
453                         op.ors_deref = LDAP_DEREF_NEVER;
454                         op.ors_slimit = 1;
455                         op.ors_filter = &generic_filter;
456
457                         op.o_bd->be_search( &op, &rs );
458                 }
459         }
460 }
461
462 static sasl_auxprop_plug_t slap_auxprop_plugin = {
463         0,      /* Features */
464         0,      /* spare */
465         NULL,   /* glob_context */
466         NULL,   /* auxprop_free */
467         slap_auxprop_lookup,
468         "slapd",        /* name */
469         NULL    /* spare */
470 };
471
472 static int
473 slap_auxprop_init(
474         const sasl_utils_t *utils,
475         int max_version,
476         int *out_version,
477         sasl_auxprop_plug_t **plug,
478         const char *plugname)
479 {
480         if ( !out_version | !plug ) return SASL_BADPARAM;
481
482         if ( max_version < SASL_AUXPROP_PLUG_VERSION ) return SASL_BADVERS;
483
484         *out_version = SASL_AUXPROP_PLUG_VERSION;
485         *plug = &slap_auxprop_plugin;
486         return SASL_OK;
487 }
488
489 typedef struct checkpass_info {
490         int rc;
491         struct berval cred;
492 } checkpass_info;
493
494 static int
495 sasl_cb_checkpass( Operation *op, SlapReply *rs )
496 {
497         slap_callback *tmp = op->o_callback;
498         checkpass_info *ci = tmp->sc_private;
499         Attribute *a;
500         struct berval *bv;
501         
502         if (rs->sr_type != REP_SEARCH) return 0;
503
504         ci->rc = SASL_NOVERIFY;
505
506         a = attr_find( rs->sr_entry->e_attrs, slap_schema.si_ad_userPassword );
507         if ( !a ) return 0;
508         if ( ! access_allowed( op, rs->sr_entry, slap_schema.si_ad_userPassword,
509                 NULL, ACL_AUTH, NULL ) ) return 0;
510
511         for ( bv = a->a_vals; bv->bv_val != NULL; bv++ ) {
512                 if ( !lutil_passwd( bv, &ci->cred, NULL, &rs->sr_text ) ) {
513                         ci->rc = SASL_OK;
514                         break;
515                 }
516         }
517         return 0;
518 }
519
520 static int
521 slap_sasl_checkpass(
522         sasl_conn_t *sconn,
523         void *context,
524         const char *username,
525         const char *pass,
526         unsigned passlen,
527         struct propctx *propctx)
528 {
529         Connection *conn = (Connection *)context;
530         Operation op = {0};
531         int rc;
532         checkpass_info ci;
533
534         ci.rc = SASL_NOUSER;
535
536         /* SASL will fallback to its own mechanisms if we don't
537          * find an answer here.
538          */
539
540         rc = slap_sasl_getdn( conn, NULL, (char *)username, 0, NULL, &op.o_req_ndn,
541                 SLAP_GETDN_AUTHCID );
542         if ( rc != LDAP_SUCCESS ) {
543                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
544                 return SASL_NOUSER;
545         }
546
547         if ( op.o_req_ndn.bv_len == 0 ) {
548                 sasl_seterror( sconn, 0,
549                         "No password is associated with the Root DSE" );
550                 if ( op.o_req_ndn.bv_val != NULL ) {
551                         ch_free( op.o_req_ndn.bv_val );
552                 }
553                 return SASL_NOUSER;
554         }
555
556         op.o_bd = select_backend( &op.o_req_ndn, 0, 1 );
557         if ( op.o_bd && op.o_bd->be_search ) {
558                 slap_callback cb = { sasl_cb_checkpass, NULL };
559                 SlapReply rs = {REP_RESULT};
560
561                 ci.cred.bv_val = (char *)pass;
562                 ci.cred.bv_len = passlen;
563
564                 cb.sc_private = &ci;
565                 op.o_tag = LDAP_REQ_SEARCH;
566                 op.o_protocol = LDAP_VERSION3;
567                 op.o_ndn = conn->c_ndn;
568                 op.o_callback = &cb;
569                 op.o_time = slap_get_time();
570                 op.o_do_not_cache = 1;
571                 op.o_is_auth_check = 1;
572                 op.o_threadctx = conn->c_sasl_bindop->o_threadctx;
573                 op.o_tmpmemctx = conn->c_sasl_bindop->o_tmpmemctx;
574                 op.o_tmpmfuncs = conn->c_sasl_bindop->o_tmpmfuncs;
575 #ifdef LDAP_SLAPI
576                 op.o_pb = conn->c_sasl_bindop->o_pb;
577 #endif
578                 op.o_conn = conn;
579                 op.o_connid = conn->c_connid;
580                 op.ors_scope = LDAP_SCOPE_BASE;
581                 op.ors_deref = LDAP_DEREF_NEVER;
582                 op.ors_slimit = 1;
583                 op.ors_filter = &generic_filter;
584
585                 op.o_bd->be_search( &op, &rs );
586         }
587         if ( ci.rc != SASL_OK ) {
588                 sasl_seterror( sconn, 0,
589                         ldap_err2string( LDAP_INVALID_CREDENTIALS ) );
590         }
591
592         ch_free( op.o_req_ndn.bv_val );
593
594         return ci.rc;
595 }
596
597 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
598  * auxiliary property, so that we can refer to it in sasl_authorize
599  * without interfering with anything else. Also, the SASL username
600  * buffer is constrained to 256 characters, and our DNs could be
601  * much longer (totally arbitrary length)...
602  */
603 static int
604 slap_sasl_canonicalize(
605         sasl_conn_t *sconn,
606         void *context,
607         const char *in,
608         unsigned inlen,
609         unsigned flags,
610         const char *user_realm,
611         char *out,
612         unsigned out_max,
613         unsigned *out_len)
614 {
615         Connection *conn = (Connection *)context;
616         struct propctx *props = sasl_auxprop_getctx( sconn );
617         struct propval auxvals[3];
618         struct berval dn;
619         int rc, which;
620         const char *names[2];
621
622         *out_len = 0;
623
624 #ifdef NEW_LOGGING
625         LDAP_LOG( TRANSPORT, ENTRY, 
626                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
627                 conn ? conn->c_connid : -1,
628                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
629                 in ? in : "<empty>");
630 #else
631         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
632                 conn ? conn->c_connid : -1,
633                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
634                 in ? in : "<empty>");
635 #endif
636
637         /* If name is too big, just truncate. We don't care, we're
638          * using DNs, not the usernames.
639          */
640         if ( inlen > out_max )
641                 inlen = out_max-1;
642
643         /* See if we need to add request, can only do it once */
644         prop_getnames( props, slap_propnames, auxvals );
645         if ( !auxvals[0].name )
646                 prop_request( props, slap_propnames );
647
648         if ( flags & SASL_CU_AUTHID )
649                 which = PROP_AUTHC;
650         else
651                 which = PROP_AUTHZ;
652
653         /* Need to store the Connection for auxprop_lookup */
654         if ( !auxvals[PROP_CONN].values ) {
655                 names[0] = slap_propnames[PROP_CONN];
656                 names[1] = NULL;
657                 prop_set( props, names[0], (char *)&conn, sizeof( conn ) );
658         }
659                 
660         /* Already been here? */
661         if ( auxvals[which].values )
662                 goto done;
663
664         /* Normally we require an authzID to have a u: or dn: prefix.
665          * However, SASL frequently gives us an authzID that is just
666          * an exact copy of the authcID, without a prefix. We need to
667          * detect and allow this condition. If SASL calls canonicalize
668          * with SASL_CU_AUTHID|SASL_CU_AUTHZID this is a no-brainer.
669          * But if it's broken into two calls, we need to remember the
670          * authcID so that we can compare the authzID later. We store
671          * the authcID temporarily in conn->c_sasl_dn. We necessarily
672          * finish Canonicalizing before Authorizing, so there is no
673          * conflict with slap_sasl_authorize's use of this temp var.
674          *
675          * The SASL EXTERNAL mech is backwards from all the other mechs,
676          * it does authzID before the authcID. If we see that authzID
677          * has already been done, don't do anything special with authcID.
678          */
679         if ( flags == SASL_CU_AUTHID && !auxvals[PROP_AUTHZ].values ) {
680                 conn->c_sasl_dn.bv_val = (char *) in;
681         } else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
682                 rc = strcmp( in, conn->c_sasl_dn.bv_val );
683                 conn->c_sasl_dn.bv_val = NULL;
684                 /* They were equal, no work needed */
685                 if ( !rc ) goto done;
686         }
687
688         rc = slap_sasl_getdn( conn, NULL, (char *)in, inlen, (char *)user_realm, &dn,
689                 (flags & SASL_CU_AUTHID) ? SLAP_GETDN_AUTHCID : SLAP_GETDN_AUTHZID );
690         if ( rc != LDAP_SUCCESS ) {
691                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
692                 return SASL_NOAUTHZ;
693         }               
694
695         names[0] = slap_propnames[which];
696         names[1] = NULL;
697
698         prop_set( props, names[0], (char *)&dn, sizeof( dn ) );
699                 
700 #ifdef NEW_LOGGING
701         LDAP_LOG( TRANSPORT, ENTRY, 
702                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
703                 conn ? conn->c_connid : -1, names[0]+1,
704                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
705 #else
706         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
707                 conn ? conn->c_connid : -1, names[0]+1,
708                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
709 #endif
710
711 done:
712         AC_MEMCPY( out, in, inlen );
713         out[inlen] = '\0';
714
715         *out_len = inlen;
716
717         return SASL_OK;
718 }
719
720 static int
721 slap_sasl_authorize(
722         sasl_conn_t *sconn,
723         void *context,
724         char *requested_user,
725         unsigned rlen,
726         char *auth_identity,
727         unsigned alen,
728         const char *def_realm,
729         unsigned urlen,
730         struct propctx *props)
731 {
732         Connection *conn = (Connection *)context;
733         struct propval auxvals[3];
734         struct berval authcDN, authzDN;
735         int rc;
736
737 #ifdef NEW_LOGGING
738         LDAP_LOG( TRANSPORT, ENTRY, 
739                 "slap_sasl_authorize: conn %d authcid=\"%s\" authzid=\"%s\"\n",
740                 conn ? conn->c_connid : -1, auth_identity, requested_user);
741 #else
742         Debug( LDAP_DEBUG_ARGS, "SASL proxy authorize [conn=%ld]: "
743                 "authcid=\"%s\" authzid=\"%s\"\n",
744                 conn ? conn->c_connid : -1, auth_identity, requested_user );
745 #endif
746         if ( conn->c_sasl_dn.bv_val ) {
747                 ch_free( conn->c_sasl_dn.bv_val );
748                 conn->c_sasl_dn.bv_val = NULL;
749                 conn->c_sasl_dn.bv_len = 0;
750         }
751
752         /* Skip PROP_CONN */
753         prop_getnames( props, slap_propnames+1, auxvals );
754         
755         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
756
757         /* Nothing to do if no authzID was given */
758         if ( !auxvals[1].name || !auxvals[1].values ) {
759                 conn->c_sasl_dn = authcDN;
760                 goto ok;
761         }
762         
763         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
764
765         rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
766         ch_free( authcDN.bv_val );
767         if ( rc != LDAP_SUCCESS ) {
768 #ifdef NEW_LOGGING
769                 LDAP_LOG( TRANSPORT, INFO, 
770                         "slap_sasl_authorize: conn %ld "
771                         "proxy authorization disallowed (%d)\n",
772                         (long)(conn ? conn->c_connid : -1), rc, 0 );
773 #else
774                 Debug( LDAP_DEBUG_TRACE, "SASL Proxy Authorize [conn=%ld]: "
775                         "proxy authorization disallowed (%d)\n",
776                         (long) (conn ? conn->c_connid : -1), rc, 0 );
777 #endif
778
779                 sasl_seterror( sconn, 0, "not authorized" );
780                 ch_free( authzDN.bv_val );
781                 return SASL_NOAUTHZ;
782         }
783
784         conn->c_sasl_dn = authzDN;
785 ok:
786         if (conn->c_sasl_bindop) {
787                 Statslog( LDAP_DEBUG_STATS,
788                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
789                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
790                         auth_identity, 0, 0);
791         }
792
793 #ifdef NEW_LOGGING
794         LDAP_LOG( TRANSPORT, ENTRY, 
795                 "slap_sasl_authorize: conn %d proxy authorization allowed\n",
796                 (long)(conn ? conn->c_connid : -1), 0, 0 );
797 #else
798         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
799                 " proxy authorization allowed\n",
800                 (long) (conn ? conn->c_connid : -1), 0, 0 );
801 #endif
802         return SASL_OK;
803
804 #else
805 static int
806 slap_sasl_authorize(
807         void *context,
808         char *authcid,
809         char *authzid,
810         const char **user,
811         const char **errstr)
812 {
813         struct berval authcDN, authzDN;
814         int rc;
815         Connection *conn = context;
816         char *realm;
817
818         *user = NULL;
819         if ( conn->c_sasl_dn.bv_val ) {
820                 ch_free( conn->c_sasl_dn.bv_val );
821                 conn->c_sasl_dn.bv_val = NULL;
822                 conn->c_sasl_dn.bv_len = 0;
823         }
824
825 #ifdef NEW_LOGGING
826         LDAP_LOG( TRANSPORT, ENTRY, 
827                 "slap_sasl_authorize: conn %d    authcid=\"%s\" authzid=\"%s\"\n",
828                 conn ? conn->c_connid : -1, authcid ? authcid : "<empty>",
829                 authzid ? authzid : "<empty>" );
830 #else
831         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
832                 "authcid=\"%s\" authzid=\"%s\"\n",
833                 (long) (conn ? conn->c_connid : -1),
834                 authcid ? authcid : "<empty>",
835                 authzid ? authzid : "<empty>" );
836 #endif
837
838         /* Figure out how much data we have for the dn */
839         rc = sasl_getprop( conn->c_sasl_authctx, SASL_REALM, (void **)&realm );
840         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
841 #ifdef NEW_LOGGING
842                 LDAP_LOG( TRANSPORT, ERR,
843                         "slap_sasl_authorize: getprop(REALM) failed.\n", 0, 0, 0 );
844 #else
845                 Debug(LDAP_DEBUG_TRACE,
846                         "authorize: getprop(REALM) failed!\n", 0,0,0);
847 #endif
848                 *errstr = "Could not extract realm";
849                 return SASL_NOAUTHZ;
850         }
851
852         /* Convert the identities to DN's. If no authzid was given, client will
853            be bound as the DN matching their username */
854         rc = slap_sasl_getdn( conn, NULL, (char *)authcid, 0, realm,
855                 &authcDN, SLAP_GETDN_AUTHCID );
856         if( rc != LDAP_SUCCESS ) {
857                 *errstr = ldap_err2string( rc );
858                 return SASL_NOAUTHZ;
859         }
860         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
861 #ifdef NEW_LOGGING
862                 LDAP_LOG( TRANSPORT, ENTRY, 
863                         "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
864                         conn ? conn->c_connid : -1, authcDN.bv_val, 0 );
865 #else
866                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
867                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
868 #endif
869
870                 conn->c_sasl_dn = authcDN;
871                 goto ok;
872         }
873         rc = slap_sasl_getdn( conn, NULL, (char *)authzid, 0, realm,
874                 &authzDN, SLAP_GETDN_AUTHZID );
875         if( rc != LDAP_SUCCESS ) {
876                 ch_free( authcDN.bv_val );
877                 *errstr = ldap_err2string( rc );
878                 return SASL_NOAUTHZ;
879         }
880
881         rc = slap_sasl_authorized(conn->c_sasl_bindop, &authcDN, &authzDN );
882         ch_free( authcDN.bv_val );
883         if( rc ) {
884 #ifdef NEW_LOGGING
885                 LDAP_LOG( TRANSPORT, INFO, 
886                         "slap_sasl_authorize: conn %ld "
887                         "proxy authorization disallowed (%d)\n",
888                         (long)(conn ? conn->c_connid : -1), rc, 0 );
889 #else
890                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
891                         "proxy authorization disallowed (%d)\n",
892                         (long) (conn ? conn->c_connid : -1), rc, 0 );
893 #endif
894
895                 *errstr = "not authorized";
896                 ch_free( authzDN.bv_val );
897                 return SASL_NOAUTHZ;
898         }
899         conn->c_sasl_dn = authzDN;
900
901 ok:
902 #ifdef NEW_LOGGING
903         LDAP_LOG( TRANSPORT, RESULTS, 
904                 "slap_sasl_authorize: conn %d proxy authorization allowed\n",
905            (long)(conn ? conn->c_connid : -1 ), 0, 0 );
906 #else
907         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
908                 " authorization allowed\n",
909                 (long) (conn ? conn->c_connid : -1), 0, 0 );
910 #endif
911
912         if (conn->c_sasl_bindop) {
913                 Statslog( LDAP_DEBUG_STATS,
914                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
915                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
916                         authcid, 0, 0);
917         }
918
919         *errstr = NULL;
920         return SASL_OK;
921 }
922 #endif /* SASL_VERSION_MAJOR >= 2 */
923
924 static int
925 slap_sasl_err2ldap( int saslerr )
926 {
927         int rc;
928
929         switch (saslerr) {
930                 case SASL_OK:
931                         rc = LDAP_SUCCESS;
932                         break;
933                 case SASL_CONTINUE:
934                         rc = LDAP_SASL_BIND_IN_PROGRESS;
935                         break;
936                 case SASL_FAIL:
937                         rc = LDAP_OTHER;
938                         break;
939                 case SASL_NOMEM:
940                         rc = LDAP_OTHER;
941                         break;
942                 case SASL_NOMECH:
943                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
944                         break;
945                 case SASL_BADAUTH:
946                         rc = LDAP_INVALID_CREDENTIALS;
947                         break;
948                 case SASL_NOAUTHZ:
949                         rc = LDAP_INSUFFICIENT_ACCESS;
950                         break;
951                 case SASL_TOOWEAK:
952                 case SASL_ENCRYPT:
953                         rc = LDAP_INAPPROPRIATE_AUTH;
954                         break;
955                 default:
956                         rc = LDAP_OTHER;
957                         break;
958         }
959
960         return rc;
961 }
962 #endif
963
964 int slap_sasl_init( void )
965 {
966 #ifdef HAVE_CYRUS_SASL
967         int rc;
968         static sasl_callback_t server_callbacks[] = {
969                 { SASL_CB_LOG, &slap_sasl_log, NULL },
970                 { SASL_CB_LIST_END, NULL, NULL }
971         };
972
973 #ifdef HAVE_SASL_VERSION
974         /* stringify the version number, sasl.h doesn't do it for us */
975 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
976 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
977 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
978                                 SASL_VERSION_STEP)
979
980         sasl_version( NULL, &rc );
981         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
982                 (rc & 0xffff) < SASL_VERSION_STEP) {
983                 char version[sizeof("xxx.xxx.xxxxx")];
984                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
985                         rc & 0xffff );
986 #ifdef NEW_LOGGING
987                 LDAP_LOG( TRANSPORT, INFO,
988                 "slap_sasl_init: SASL library version mismatch:"
989                 " expected " SASL_VERSION_STRING ","
990                 " got %s\n", version, 0, 0 );
991 #else
992                 Debug( LDAP_DEBUG_ANY,
993                 "slap_sasl_init: SASL library version mismatch:"
994                 " expected " SASL_VERSION_STRING ","
995                 " got %s\n", version, 0, 0 );
996 #endif
997                 return -1;
998         }
999 #endif
1000
1001         /* SASL 2 does its own memory management internally */
1002 #if SASL_VERSION_MAJOR < 2
1003         sasl_set_alloc(
1004                 ber_memalloc,
1005                 ber_memcalloc,
1006                 ber_memrealloc,
1007                 ber_memfree ); 
1008 #endif
1009
1010         sasl_set_mutex(
1011                 ldap_pvt_sasl_mutex_new,
1012                 ldap_pvt_sasl_mutex_lock,
1013                 ldap_pvt_sasl_mutex_unlock,
1014                 ldap_pvt_sasl_mutex_dispose );
1015
1016 #if SASL_VERSION_MAJOR >= 2
1017         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1018
1019         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1020 #endif
1021         /* should provide callbacks for logging */
1022         /* server name should be configurable */
1023         rc = sasl_server_init( server_callbacks, "slapd" );
1024
1025         if( rc != SASL_OK ) {
1026 #ifdef NEW_LOGGING
1027                 LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: init failed.\n", 0, 0, 0 );
1028 #else
1029                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
1030                         0, 0, 0 );
1031 #endif
1032 #if SASL_VERSION_MAJOR < 2
1033                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1034                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1035 #endif
1036
1037                 return -1;
1038         }
1039
1040 #ifdef NEW_LOGGING
1041         LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: initialized!\n", 0, 0, 0 );
1042 #else
1043         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1044                 0, 0, 0 );
1045 #endif
1046
1047
1048         /* default security properties */
1049         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1050         sasl_secprops.max_ssf = INT_MAX;
1051         sasl_secprops.maxbufsize = 65536;
1052         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1053 #endif
1054
1055         return 0;
1056 }
1057
1058 int slap_sasl_destroy( void )
1059 {
1060 #ifdef HAVE_CYRUS_SASL
1061         sasl_done();
1062 #endif
1063         free( global_host );
1064         global_host = NULL;
1065
1066         return 0;
1067 }
1068
1069 int slap_sasl_open( Connection *conn, int reopen )
1070 {
1071         int cb, sc = LDAP_SUCCESS;
1072 #if SASL_VERSION_MAJOR >= 2
1073         char *ipremoteport = NULL, *iplocalport = NULL;
1074 #endif
1075
1076 #ifdef HAVE_CYRUS_SASL
1077         sasl_conn_t *ctx = NULL;
1078         sasl_callback_t *session_callbacks;
1079
1080         assert( conn->c_sasl_authctx == NULL );
1081
1082         if ( !reopen ) {
1083                 assert( conn->c_sasl_extra == NULL );
1084
1085                 session_callbacks =
1086 #if SASL_VERSION_MAJOR >= 2
1087                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1088 #else
1089                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1090 #endif
1091                 if( session_callbacks == NULL ) {
1092 #ifdef NEW_LOGGING
1093                         LDAP_LOG( TRANSPORT, ERR, 
1094                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1095 #else
1096                         Debug( LDAP_DEBUG_ANY, 
1097                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1098 #endif
1099                         return -1;
1100                 }
1101                 conn->c_sasl_extra = session_callbacks;
1102
1103                 session_callbacks[cb=0].id = SASL_CB_LOG;
1104                 session_callbacks[cb].proc = &slap_sasl_log;
1105                 session_callbacks[cb++].context = conn;
1106
1107                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1108                 session_callbacks[cb].proc = &slap_sasl_authorize;
1109                 session_callbacks[cb++].context = conn;
1110
1111 #if SASL_VERSION_MAJOR >= 2
1112                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1113                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1114                 session_callbacks[cb++].context = conn;
1115
1116                 /* XXXX: this should be conditional */
1117                 session_callbacks[cb].id = SASL_CB_SERVER_USERDB_CHECKPASS;
1118                 session_callbacks[cb].proc = &slap_sasl_checkpass;
1119                 session_callbacks[cb++].context = conn;
1120 #endif
1121
1122                 session_callbacks[cb].id = SASL_CB_LIST_END;
1123                 session_callbacks[cb].proc = NULL;
1124                 session_callbacks[cb++].context = NULL;
1125         } else {
1126                 session_callbacks = conn->c_sasl_extra;
1127         }
1128
1129         conn->c_sasl_layers = 0;
1130
1131         if( global_host == NULL ) {
1132                 global_host = ldap_pvt_get_fqdn( NULL );
1133         }
1134
1135         /* create new SASL context */
1136 #if SASL_VERSION_MAJOR >= 2
1137         if ( conn->c_sock_name.bv_len != 0 &&
1138              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1139                 char *p;
1140
1141                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1142                 /* Convert IPv6 addresses to address;port syntax. */
1143                 p = strrchr( iplocalport, ' ' );
1144                 /* Convert IPv4 addresses to address;port syntax. */
1145                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1146                 if ( p != NULL ) {
1147                         *p = ';';
1148                 }
1149         }
1150         if ( conn->c_peer_name.bv_len != 0 &&
1151              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1152                 char *p;
1153
1154                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1155                 /* Convert IPv6 addresses to address;port syntax. */
1156                 p = strrchr( ipremoteport, ' ' );
1157                 /* Convert IPv4 addresses to address;port syntax. */
1158                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1159                 if ( p != NULL ) {
1160                         *p = ';';
1161                 }
1162         }
1163         sc = sasl_server_new( "ldap", global_host, global_realm,
1164                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1165         if ( iplocalport != NULL ) {
1166                 ch_free( iplocalport );
1167         }
1168         if ( ipremoteport != NULL ) {
1169                 ch_free( ipremoteport );
1170         }
1171 #else
1172         sc = sasl_server_new( "ldap", global_host, global_realm,
1173                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1174 #endif
1175
1176         if( sc != SASL_OK ) {
1177 #ifdef NEW_LOGGING
1178                 LDAP_LOG( TRANSPORT, ERR, 
1179                         "slap_sasl_open: sasl_server_new failed: %d\n", sc, 0, 0 );
1180 #else
1181                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1182                         sc, 0, 0 );
1183 #endif
1184
1185                 return -1;
1186         }
1187
1188         conn->c_sasl_authctx = ctx;
1189
1190         if( sc == SASL_OK ) {
1191                 sc = sasl_setprop( ctx,
1192                         SASL_SEC_PROPS, &sasl_secprops );
1193
1194                 if( sc != SASL_OK ) {
1195 #ifdef NEW_LOGGING
1196                         LDAP_LOG( TRANSPORT, ERR, 
1197                                 "slap_sasl_open: sasl_setprop failed: %d \n", sc, 0, 0 );
1198 #else
1199                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1200                                 sc, 0, 0 );
1201 #endif
1202
1203                         slap_sasl_close( conn );
1204                         return -1;
1205                 }
1206         }
1207
1208         sc = slap_sasl_err2ldap( sc );
1209 #endif
1210         return sc;
1211 }
1212
1213 int slap_sasl_external(
1214         Connection *conn,
1215         slap_ssf_t ssf,
1216         const char *auth_id )
1217 {
1218 #if SASL_VERSION_MAJOR >= 2
1219         int sc;
1220         sasl_conn_t *ctx = conn->c_sasl_authctx;
1221
1222         if ( ctx == NULL ) {
1223                 return LDAP_UNAVAILABLE;
1224         }
1225
1226         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1227
1228         if ( sc != SASL_OK ) {
1229                 return LDAP_OTHER;
1230         }
1231
1232         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL, auth_id );
1233
1234         if ( sc != SASL_OK ) {
1235                 return LDAP_OTHER;
1236         }
1237
1238 #elif defined(HAVE_CYRUS_SASL)
1239         int sc;
1240         sasl_conn_t *ctx = conn->c_sasl_authctx;
1241         sasl_external_properties_t extprops;
1242
1243         if ( ctx == NULL ) {
1244                 return LDAP_UNAVAILABLE;
1245         }
1246
1247         memset( &extprops, '\0', sizeof(extprops) );
1248         extprops.ssf = ssf;
1249         extprops.auth_id = (char *) auth_id;
1250
1251         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1252                 (void *) &extprops );
1253
1254         if ( sc != SASL_OK ) {
1255                 return LDAP_OTHER;
1256         }
1257 #endif
1258
1259         return LDAP_SUCCESS;
1260 }
1261
1262 int slap_sasl_reset( Connection *conn )
1263 {
1264         return LDAP_SUCCESS;
1265 }
1266
1267 char ** slap_sasl_mechs( Connection *conn )
1268 {
1269         char **mechs = NULL;
1270
1271 #ifdef HAVE_CYRUS_SASL
1272         sasl_conn_t *ctx = conn->c_sasl_authctx;
1273
1274         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1275
1276         if( ctx != NULL ) {
1277                 int sc;
1278                 SASL_CONST char *mechstr;
1279
1280                 sc = sasl_listmech( ctx,
1281                         NULL, NULL, ",", NULL,
1282                         &mechstr, NULL, NULL );
1283
1284                 if( sc != SASL_OK ) {
1285 #ifdef NEW_LOGGING
1286                         LDAP_LOG( TRANSPORT, ERR, 
1287                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc, 0, 0 );
1288 #else
1289                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1290                                 sc, 0, 0 );
1291 #endif
1292
1293                         return NULL;
1294                 }
1295
1296                 mechs = ldap_str2charray( mechstr, "," );
1297
1298 #if SASL_VERSION_MAJOR < 2
1299                 ch_free( mechstr );
1300 #endif
1301         }
1302 #endif
1303
1304         return mechs;
1305 }
1306
1307 int slap_sasl_close( Connection *conn )
1308 {
1309 #ifdef HAVE_CYRUS_SASL
1310         sasl_conn_t *ctx = conn->c_sasl_authctx;
1311
1312         if( ctx != NULL ) {
1313                 sasl_dispose( &ctx );
1314         }
1315         if ( conn->c_sasl_sockctx && conn->c_sasl_authctx != conn->c_sasl_sockctx ) {
1316                 ctx = conn->c_sasl_sockctx;
1317                 sasl_dispose( &ctx );
1318         }
1319
1320         conn->c_sasl_authctx = NULL;
1321         conn->c_sasl_sockctx = NULL;
1322         conn->c_sasl_done = 0;
1323
1324         free( conn->c_sasl_extra );
1325         conn->c_sasl_extra = NULL;
1326 #endif
1327
1328         return LDAP_SUCCESS;
1329 }
1330
1331 int slap_sasl_bind( Operation *op, SlapReply *rs )
1332 {
1333 #ifdef HAVE_CYRUS_SASL
1334         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1335         struct berval response;
1336         unsigned reslen = 0;
1337         int sc;
1338
1339 #ifdef NEW_LOGGING
1340         LDAP_LOG( TRANSPORT, ENTRY, 
1341                 "sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1342                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1343                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1344                 op->o_conn->c_sasl_bind_mech.bv_val,
1345                 op->orb_cred.bv_len );
1346 #else
1347         Debug(LDAP_DEBUG_ARGS,
1348                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1349                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1350                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1351                 op->o_conn->c_sasl_bind_mech.bv_val,
1352                 op->orb_cred.bv_len );
1353 #endif
1354
1355
1356         if( ctx == NULL ) {
1357                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1358                         "SASL unavailable on this session" );
1359                 return rs->sr_err;
1360         }
1361
1362 #if SASL_VERSION_MAJOR >= 2
1363 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1364         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1365 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1366         sasl_server_step( ctx, cred, clen, resp, rlen )
1367 #else
1368 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1369         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1370 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1371         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1372 #endif
1373
1374         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1375                 /* If we already authenticated once, must use a new context */
1376                 if ( op->o_conn->c_sasl_done ) {
1377                         slap_ssf_t ssf = 0;
1378                         const char *authid = NULL;
1379 #if SASL_VERSION_MAJOR >= 2
1380                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1381                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1382                         if ( authid ) authid = ch_strdup( authid );
1383 #endif
1384                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1385                                 sasl_dispose( &ctx );
1386                         }
1387                         op->o_conn->c_sasl_authctx = NULL;
1388                                 
1389                         slap_sasl_open( op->o_conn, 1 );
1390                         ctx = op->o_conn->c_sasl_authctx;
1391 #if SASL_VERSION_MAJOR >= 2
1392                         if ( authid ) {
1393                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1394                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1395                                 ch_free( (char *)authid );
1396                         }
1397 #endif
1398                 }
1399                 sc = START( ctx,
1400                         op->o_conn->c_sasl_bind_mech.bv_val,
1401                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1402                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1403
1404         } else {
1405                 sc = STEP( ctx,
1406                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1407                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1408         }
1409
1410         response.bv_len = reslen;
1411
1412         if ( sc == SASL_OK ) {
1413                 sasl_ssf_t *ssf = NULL;
1414
1415                 op->orb_edn = op->o_conn->c_sasl_dn;
1416                 op->o_conn->c_sasl_dn.bv_val = NULL;
1417                 op->o_conn->c_sasl_dn.bv_len = 0;
1418                 op->o_conn->c_sasl_done = 1;
1419
1420                 rs->sr_err = LDAP_SUCCESS;
1421
1422                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1423                 op->orb_ssf = ssf ? *ssf : 0;
1424
1425                 ctx = NULL;
1426                 if( op->orb_ssf ) {
1427                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1428                         op->o_conn->c_sasl_layers++;
1429
1430                         /* If there's an old layer, set sockctx to NULL to
1431                          * tell connection_read() to wait for us to finish.
1432                          * Otherwise there is a race condition: we have to
1433                          * send the Bind response using the old security
1434                          * context and then remove it before reading any
1435                          * new messages.
1436                          */
1437                         if ( op->o_conn->c_sasl_sockctx ) {
1438                                 ctx = op->o_conn->c_sasl_sockctx;
1439                                 op->o_conn->c_sasl_sockctx = NULL;
1440                         } else {
1441                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1442                         }
1443                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1444                 }
1445
1446                 /* Must send response using old security layer */
1447                 if (response.bv_len) rs->sr_sasldata = &response;
1448                 send_ldap_sasl( op, rs );
1449                 
1450                 /* Now dispose of the old security layer.
1451                  */
1452                 if ( ctx ) {
1453                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1454                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1455                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1456                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1457                         sasl_dispose( &ctx );
1458                 }
1459         } else if ( sc == SASL_CONTINUE ) {
1460                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1461                 rs->sr_sasldata = &response;
1462                 send_ldap_sasl( op, rs );
1463
1464         } else {
1465 #if SASL_VERSION_MAJOR >= 2
1466                 rs->sr_text = sasl_errdetail( ctx );
1467 #endif
1468                 rs->sr_err = slap_sasl_err2ldap( sc ),
1469                 send_ldap_result( op, rs );
1470         }
1471
1472 #if SASL_VERSION_MAJOR < 2
1473         if( response.bv_len ) {
1474                 ch_free( response.bv_val );
1475         }
1476 #endif
1477
1478 #ifdef NEW_LOGGING
1479         LDAP_LOG( TRANSPORT, RESULTS, "slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0 );
1480 #else
1481         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1482 #endif
1483
1484
1485 #else
1486         send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1487                 "SASL not supported" );
1488 #endif
1489
1490         return rs->sr_err;
1491 }
1492
1493 char* slap_sasl_secprops( const char *in )
1494 {
1495 #ifdef HAVE_CYRUS_SASL
1496         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1497
1498         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1499 #else
1500         return "SASL not supported";
1501 #endif
1502 }
1503
1504 #ifdef HAVE_CYRUS_SASL
1505 int
1506 slap_sasl_setpass( Operation *op, SlapReply *rs )
1507 {
1508         struct berval id = { 0, NULL }; /* needs to come from connection */
1509         struct berval new = { 0, NULL };
1510         struct berval old = { 0, NULL };
1511
1512         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1513
1514         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1515                 (SASL_CONST void **)&id.bv_val );
1516
1517         if( rs->sr_err != SASL_OK ) {
1518                 rs->sr_text = "unable to retrieve SASL username";
1519                 rs->sr_err = LDAP_OTHER;
1520                 goto done;
1521         }
1522
1523 #ifdef NEW_LOGGING
1524         LDAP_LOG( BACKEND, ENTRY,
1525                 "slap_sasl_setpass: \"%s\"\n",
1526                 id.bv_val ? id.bv_val : "", 0, 0);
1527 #else
1528         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1529                 id.bv_val ? id.bv_val : "", 0, 0 );
1530 #endif
1531
1532         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1533                 NULL, &old, &new, &rs->sr_text );
1534
1535         if( rs->sr_err != LDAP_SUCCESS ) {
1536                 goto done;
1537         }
1538
1539         if( new.bv_len == 0 ) {
1540                 slap_passwd_generate(&new);
1541
1542                 if( new.bv_len == 0 ) {
1543                         rs->sr_text = "password generation failed.";
1544                         rs->sr_err = LDAP_OTHER;
1545                         goto done;
1546                 }
1547                 
1548                 rs->sr_rspdata = slap_passwd_return( &new );
1549         }
1550
1551 #if SASL_VERSION_MAJOR < 2
1552         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx,
1553                 id.bv_val, new.bv_val, new.bv_len, 0, &rs->sr_text );
1554 #else
1555         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1556                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1557         if( rs->sr_err != SASL_OK ) {
1558                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1559         }
1560 #endif
1561         switch(rs->sr_err) {
1562                 case SASL_OK:
1563                         rs->sr_err = LDAP_SUCCESS;
1564                         break;
1565
1566                 case SASL_NOCHANGE:
1567                 case SASL_NOMECH:
1568                 case SASL_DISABLED:
1569                 case SASL_PWLOCK:
1570                 case SASL_FAIL:
1571                 case SASL_BADPARAM:
1572                 default:
1573                         rs->sr_err = LDAP_OTHER;
1574         }
1575
1576 done:
1577         return rs->sr_err;
1578 }
1579 #endif /* HAVE_CYRUS_SASL */
1580
1581 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1582    string returned in *dn is in its own allocated memory, and must be free'd 
1583    by the calling process.
1584    -Mark Adamson, Carnegie Mellon
1585
1586    The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1587    on strings passed in directly from SASL.
1588    -Howard Chu, Symas Corp.
1589 */
1590
1591 #define SET_NONE        0
1592 #define SET_DN          1
1593 #define SET_U           2
1594
1595 static struct berval ext_bv = BER_BVC( "EXTERNAL" );
1596
1597 int slap_sasl_getdn( Connection *conn, Operation *op, char *id, int len,
1598         char *user_realm, struct berval *dn, int flags )
1599 {
1600         char *c1;
1601         int rc, is_dn = SET_NONE, do_norm = 1;
1602         struct berval dn2;
1603
1604 #ifdef NEW_LOGGING
1605         LDAP_LOG( TRANSPORT, ENTRY, 
1606                 "slap_sasl_getdn: conn %d id=%s [len=%d]\n",
1607                 conn ? conn->c_connid : -1, id ? (*id ? id : "<empty>") : "NULL", len );
1608 #else
1609         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: id=%s [len=%d]\n", 
1610                 id ? ( *id ? id : "<empty>" ) : "NULL", len, 0 );
1611 #endif
1612
1613         if ( !op ) {
1614                 op = conn->c_sasl_bindop;
1615         }
1616
1617         dn->bv_val = NULL;
1618         dn->bv_len = 0;
1619
1620         if ( id ) {
1621                 if ( len == 0 ) len = strlen( id );
1622
1623                 /* Blatantly anonymous ID */
1624                 if ( len == sizeof("anonymous") - 1 &&
1625                         !strcasecmp( id, "anonymous" ) ) {
1626                         return( LDAP_SUCCESS );
1627                 }
1628         } else {
1629                 len = 0;
1630         }
1631
1632         /* An authcID needs to be converted to authzID form. Set the
1633          * values directly into *dn; they will be normalized later. (and
1634          * normalizing always makes a new copy.) An ID from a TLS certificate
1635          * is already normalized, so copy it and skip normalization.
1636          */
1637         if( flags & SLAP_GETDN_AUTHCID ) {
1638                 if( conn->c_sasl_bind_mech.bv_len == ext_bv.bv_len &&
1639                         strcasecmp( ext_bv.bv_val, conn->c_sasl_bind_mech.bv_val ) == 0 )
1640                 {
1641                         /* EXTERNAL DNs are already normalized */
1642                         do_norm = 0;
1643                         is_dn = SET_DN;
1644                         ber_str2bv_x( id, len, 1, dn, op->o_tmpmemctx );
1645
1646                 } else {
1647                         /* convert to u:<username> form */
1648                         is_dn = SET_U;
1649                         dn->bv_val = id;
1650                         dn->bv_len = len;
1651                 }
1652         }
1653         if( is_dn == SET_NONE ) {
1654                 if( !strncasecmp( id, "u:", sizeof("u:")-1 )) {
1655                         is_dn = SET_U;
1656                         dn->bv_val = id+2;
1657                         dn->bv_len = len-2;
1658                 } else if ( !strncasecmp( id, "dn:", sizeof("dn:")-1) ) {
1659                         is_dn = SET_DN;
1660                         dn->bv_val = id+3;
1661                         dn->bv_len = len-3;
1662                 }
1663         }
1664
1665         /* No other possibilities from here */
1666         if( is_dn == SET_NONE ) {
1667                 dn->bv_val = NULL;
1668                 dn->bv_len = 0;
1669                 return( LDAP_INAPPROPRIATE_AUTH );
1670         }
1671
1672         /* Username strings */
1673         if( is_dn == SET_U ) {
1674                 char *p, *realm;
1675                 len = dn->bv_len + sizeof("uid=")-1 + sizeof(",cn=auth")-1;
1676
1677                 /* username may have embedded realm name */
1678                 if( ( realm = strchr( dn->bv_val, '@') ) ) {
1679                         *realm++ = '\0';
1680                         len += sizeof(",cn=")-2;
1681                 } else if( user_realm && *user_realm ) {
1682                         len += strlen( user_realm ) + sizeof(",cn=")-1;
1683                 }
1684
1685                 if( conn->c_sasl_bind_mech.bv_len ) {
1686                         len += conn->c_sasl_bind_mech.bv_len + sizeof(",cn=")-1;
1687                 }
1688
1689                 /* Build the new dn */
1690                 c1 = dn->bv_val;
1691                 dn->bv_val = sl_malloc( len+1, op->o_tmpmemctx );
1692                 if( dn->bv_val == NULL ) {
1693 #ifdef NEW_LOGGING
1694                         LDAP_LOG( TRANSPORT, ERR, 
1695                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1696 #else
1697                         Debug( LDAP_DEBUG_ANY, 
1698                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1699 #endif
1700                         return LDAP_OTHER;
1701                 }
1702                 p = lutil_strcopy( dn->bv_val, "uid=" );
1703                 p = lutil_strncopy( p, c1, dn->bv_len );
1704
1705                 if( realm ) {
1706                         int rlen = dn->bv_len - ( realm - c1 );
1707                         p = lutil_strcopy( p, ",cn=" );
1708                         p = lutil_strncopy( p, realm, rlen );
1709                         realm[-1] = '@';
1710                 } else if( user_realm && *user_realm ) {
1711                         p = lutil_strcopy( p, ",cn=" );
1712                         p = lutil_strcopy( p, user_realm );
1713                 }
1714
1715                 if( conn->c_sasl_bind_mech.bv_len ) {
1716                         p = lutil_strcopy( p, ",cn=" );
1717                         p = lutil_strcopy( p, conn->c_sasl_bind_mech.bv_val );
1718                 }
1719                 p = lutil_strcopy( p, ",cn=auth" );
1720                 dn->bv_len = p - dn->bv_val;
1721
1722 #ifdef NEW_LOGGING
1723                 LDAP_LOG( TRANSPORT, ENTRY, 
1724                         "slap_sasl_getdn: u:id converted to %s.\n", dn->bv_val, 0, 0 );
1725 #else
1726                 Debug( LDAP_DEBUG_TRACE, "getdn: u:id converted to %s\n", dn->bv_val,0,0 );
1727 #endif
1728         } else {
1729                 
1730                 /* Dup the DN in any case, so we don't risk 
1731                  * leaks or dangling pointers later,
1732                  * and the DN value is '\0' terminated */
1733                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1734                 dn->bv_val = dn2.bv_val;
1735         }
1736
1737         /* All strings are in DN form now. Normalize if needed. */
1738         if ( do_norm ) {
1739                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1740
1741                 /* User DNs were constructed above and must be freed now */
1742                 sl_free( dn->bv_val, op->o_tmpmemctx );
1743
1744                 if ( rc != LDAP_SUCCESS ) {
1745                         dn->bv_val = NULL;
1746                         dn->bv_len = 0;
1747                         return rc;
1748                 }
1749                 *dn = dn2;
1750         }
1751
1752         /* Run thru regexp */
1753         slap_sasl2dn( op, dn, &dn2 );
1754         if( dn2.bv_val ) {
1755                 sl_free( dn->bv_val, op->o_tmpmemctx );
1756                 *dn = dn2;
1757 #ifdef NEW_LOGGING
1758                 LDAP_LOG( TRANSPORT, ENTRY, 
1759                         "slap_sasl_getdn: dn:id converted to %s.\n", dn->bv_val, 0, 0 );
1760 #else
1761                 Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
1762                         dn->bv_val, 0, 0 );
1763 #endif
1764         }
1765
1766         return( LDAP_SUCCESS );
1767 }