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