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