]> git.sur5r.net Git - openldap/blob - servers/slapd/sasl.c
f186eb7c0c95003c9363d7f5b67d5ce52f4ae799
[openldap] / servers / slapd / sasl.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2003 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 ) ) return 0;
641
642         for ( bv = a->a_vals; bv->bv_val != NULL; bv++ ) {
643                 if ( !lutil_passwd( bv, &ci->cred, NULL, &rs->sr_text ) ) {
644                         ci->rc = SASL_OK;
645                         break;
646                 }
647         }
648         return 0;
649 }
650
651 static int
652 slap_sasl_checkpass(
653         sasl_conn_t *sconn,
654         void *context,
655         const char *username,
656         const char *pass,
657         unsigned passlen,
658         struct propctx *propctx)
659 {
660         Connection *conn = (Connection *)context;
661         Operation op = {0};
662         int rc;
663         checkpass_info ci;
664
665         ci.rc = SASL_NOUSER;
666
667         /* SASL will fallback to its own mechanisms if we don't
668          * find an answer here.
669          */
670
671         rc = slap_sasl_getdn( conn, NULL, (char *)username, 0, NULL, &op.o_req_ndn,
672                 SLAP_GETDN_AUTHCID );
673         if ( rc != LDAP_SUCCESS ) {
674                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
675                 return SASL_NOUSER;
676         }
677
678         if ( op.o_req_ndn.bv_len == 0 ) {
679                 sasl_seterror( sconn, 0,
680                         "No password is associated with the Root DSE" );
681                 if ( op.o_req_ndn.bv_val != NULL ) {
682                         ch_free( op.o_req_ndn.bv_val );
683                 }
684                 return SASL_NOUSER;
685         }
686
687         op.o_bd = select_backend( &op.o_req_ndn, 0, 1 );
688         if ( op.o_bd && op.o_bd->be_search ) {
689                 slap_callback cb = { NULL, sasl_cb_checkpass, NULL, NULL };
690                 SlapReply rs = {REP_RESULT};
691
692                 ci.cred.bv_val = (char *)pass;
693                 ci.cred.bv_len = passlen;
694
695                 cb.sc_private = &ci;
696                 op.o_tag = LDAP_REQ_SEARCH;
697                 op.o_protocol = LDAP_VERSION3;
698                 op.o_ndn = conn->c_ndn;
699                 op.o_callback = &cb;
700                 op.o_time = slap_get_time();
701                 op.o_do_not_cache = 1;
702                 op.o_is_auth_check = 1;
703                 op.o_threadctx = conn->c_sasl_bindop->o_threadctx;
704                 op.o_tmpmemctx = conn->c_sasl_bindop->o_tmpmemctx;
705                 op.o_tmpmfuncs = conn->c_sasl_bindop->o_tmpmfuncs;
706                 op.o_conn = conn;
707                 op.o_connid = conn->c_connid;
708                 op.o_req_dn = op.o_req_ndn;
709                 op.ors_scope = LDAP_SCOPE_BASE;
710                 op.ors_deref = LDAP_DEREF_NEVER;
711                 op.ors_slimit = 1;
712                 op.ors_filter = &generic_filter;
713                 op.ors_filterstr = generic_filterstr;
714
715                 op.o_bd->be_search( &op, &rs );
716         }
717         if ( ci.rc != SASL_OK ) {
718                 sasl_seterror( sconn, 0,
719                         ldap_err2string( LDAP_INVALID_CREDENTIALS ) );
720         }
721
722         ch_free( op.o_req_ndn.bv_val );
723
724         return ci.rc;
725 }
726
727 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
728  * auxiliary property, so that we can refer to it in sasl_authorize
729  * without interfering with anything else. Also, the SASL username
730  * buffer is constrained to 256 characters, and our DNs could be
731  * much longer (SLAP_LDAPDN_MAXLEN, currently set to 8192)
732  */
733 static int
734 slap_sasl_canonicalize(
735         sasl_conn_t *sconn,
736         void *context,
737         const char *in,
738         unsigned inlen,
739         unsigned flags,
740         const char *user_realm,
741         char *out,
742         unsigned out_max,
743         unsigned *out_len)
744 {
745         Connection *conn = (Connection *)context;
746         struct propctx *props = sasl_auxprop_getctx( sconn );
747         struct propval auxvals[3];
748         struct berval dn;
749         int rc, which;
750         const char *names[2];
751
752         *out_len = 0;
753
754 #ifdef NEW_LOGGING
755         LDAP_LOG( TRANSPORT, ENTRY, 
756                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
757                 conn ? conn->c_connid : -1,
758                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
759                 in ? in : "<empty>");
760 #else
761         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
762                 conn ? conn->c_connid : -1,
763                 (flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
764                 in ? in : "<empty>");
765 #endif
766
767         /* If name is too big, just truncate. We don't care, we're
768          * using DNs, not the usernames.
769          */
770         if ( inlen > out_max )
771                 inlen = out_max-1;
772
773         /* See if we need to add request, can only do it once */
774         prop_getnames( props, slap_propnames, auxvals );
775         if ( !auxvals[0].name )
776                 prop_request( props, slap_propnames );
777
778         if ( flags & SASL_CU_AUTHID )
779                 which = PROP_AUTHC;
780         else
781                 which = PROP_AUTHZ;
782
783         /* Need to store the Connection for auxprop_lookup */
784         if ( !auxvals[PROP_CONN].values ) {
785                 names[0] = slap_propnames[PROP_CONN];
786                 names[1] = NULL;
787                 prop_set( props, names[0], (char *)&conn, sizeof( conn ) );
788         }
789                 
790         /* Already been here? */
791         if ( auxvals[which].values )
792                 goto done;
793
794         /* Normally we require an authzID to have a u: or dn: prefix.
795          * However, SASL frequently gives us an authzID that is just
796          * an exact copy of the authcID, without a prefix. We need to
797          * detect and allow this condition. If SASL calls canonicalize
798          * with SASL_CU_AUTHID|SASL_CU_AUTHZID this is a no-brainer.
799          * But if it's broken into two calls, we need to remember the
800          * authcID so that we can compare the authzID later. We store
801          * the authcID temporarily in conn->c_sasl_dn. We necessarily
802          * finish Canonicalizing before Authorizing, so there is no
803          * conflict with slap_sasl_authorize's use of this temp var.
804          *
805          * The SASL EXTERNAL mech is backwards from all the other mechs,
806          * it does authzID before the authcID. If we see that authzID
807          * has already been done, don't do anything special with authcID.
808          */
809         if ( flags == SASL_CU_AUTHID && !auxvals[PROP_AUTHZ].values ) {
810                 conn->c_sasl_dn.bv_val = (char *) in;
811         } else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
812                 rc = strcmp( in, conn->c_sasl_dn.bv_val );
813                 conn->c_sasl_dn.bv_val = NULL;
814                 /* They were equal, no work needed */
815                 if ( !rc ) goto done;
816         }
817
818         rc = slap_sasl_getdn( conn, NULL, (char *)in, inlen, (char *)user_realm, &dn,
819                 (flags & SASL_CU_AUTHID) ? SLAP_GETDN_AUTHCID : SLAP_GETDN_AUTHZID );
820         if ( rc != LDAP_SUCCESS ) {
821                 sasl_seterror( sconn, 0, ldap_err2string( rc ) );
822                 return SASL_NOAUTHZ;
823         }               
824
825         names[0] = slap_propnames[which];
826         names[1] = NULL;
827
828         prop_set( props, names[0], (char *)&dn, sizeof( dn ) );
829                 
830 #ifdef NEW_LOGGING
831         LDAP_LOG( TRANSPORT, ENTRY, 
832                 "slap_sasl_canonicalize: conn %d %s=\"%s\"\n",
833                 conn ? conn->c_connid : -1, names[0]+1,
834                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
835 #else
836         Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
837                 conn ? conn->c_connid : -1, names[0]+1,
838                 dn.bv_val ? dn.bv_val : "<EMPTY>" );
839 #endif
840
841 done:
842         AC_MEMCPY( out, in, inlen );
843         out[inlen] = '\0';
844
845         *out_len = inlen;
846
847         return SASL_OK;
848 }
849
850 static int
851 slap_sasl_authorize(
852         sasl_conn_t *sconn,
853         void *context,
854         char *requested_user,
855         unsigned rlen,
856         char *auth_identity,
857         unsigned alen,
858         const char *def_realm,
859         unsigned urlen,
860         struct propctx *props)
861 {
862         Connection *conn = (Connection *)context;
863         struct propval auxvals[3];
864         struct berval authcDN, authzDN;
865         int rc;
866
867 #ifdef NEW_LOGGING
868         LDAP_LOG( TRANSPORT, ENTRY, 
869                 "slap_sasl_authorize: conn %d authcid=\"%s\" authzid=\"%s\"\n",
870                 conn ? conn->c_connid : -1, auth_identity, requested_user);
871 #else
872         Debug( LDAP_DEBUG_ARGS, "SASL proxy authorize [conn=%ld]: "
873                 "authcid=\"%s\" authzid=\"%s\"\n",
874                 conn ? conn->c_connid : -1, auth_identity, requested_user );
875 #endif
876         if ( conn->c_sasl_dn.bv_val ) {
877                 ch_free( conn->c_sasl_dn.bv_val );
878                 conn->c_sasl_dn.bv_val = NULL;
879                 conn->c_sasl_dn.bv_len = 0;
880         }
881
882         /* Skip PROP_CONN */
883         prop_getnames( props, slap_propnames+1, auxvals );
884         
885         AC_MEMCPY( &authcDN, auxvals[0].values[0], sizeof(authcDN) );
886
887         /* Nothing to do if no authzID was given */
888         if ( !auxvals[1].name || !auxvals[1].values ) {
889                 conn->c_sasl_dn = authcDN;
890                 goto ok;
891         }
892         
893         AC_MEMCPY( &authzDN, auxvals[1].values[0], sizeof(authzDN) );
894
895         rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
896         ch_free( authcDN.bv_val );
897         if ( rc != LDAP_SUCCESS ) {
898 #ifdef NEW_LOGGING
899                 LDAP_LOG( TRANSPORT, INFO, 
900                         "slap_sasl_authorize: conn %ld "
901                         "proxy authorization disallowed (%d)\n",
902                         (long)(conn ? conn->c_connid : -1), rc, 0 );
903 #else
904                 Debug( LDAP_DEBUG_TRACE, "SASL Proxy Authorize [conn=%ld]: "
905                         "proxy authorization disallowed (%d)\n",
906                         (long) (conn ? conn->c_connid : -1), rc, 0 );
907 #endif
908
909                 sasl_seterror( sconn, 0, "not authorized" );
910                 ch_free( authzDN.bv_val );
911                 return SASL_NOAUTHZ;
912         }
913
914         conn->c_sasl_dn = authzDN;
915 ok:
916         if (conn->c_sasl_bindop) {
917                 Statslog( LDAP_DEBUG_STATS,
918                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
919                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
920                         auth_identity, 0, 0);
921         }
922
923 #ifdef NEW_LOGGING
924         LDAP_LOG( TRANSPORT, ENTRY, 
925                 "slap_sasl_authorize: conn %d proxy authorization allowed\n",
926                 (long)(conn ? conn->c_connid : -1), 0, 0 );
927 #else
928         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
929                 " proxy authorization allowed\n",
930                 (long) (conn ? conn->c_connid : -1), 0, 0 );
931 #endif
932         return SASL_OK;
933
934 #else
935 static int
936 slap_sasl_authorize(
937         void *context,
938         char *authcid,
939         char *authzid,
940         const char **user,
941         const char **errstr)
942 {
943         struct berval authcDN, authzDN;
944         int rc;
945         Connection *conn = context;
946         char *realm;
947
948         *user = NULL;
949         if ( conn->c_sasl_dn.bv_val ) {
950                 ch_free( conn->c_sasl_dn.bv_val );
951                 conn->c_sasl_dn.bv_val = NULL;
952                 conn->c_sasl_dn.bv_len = 0;
953         }
954
955 #ifdef NEW_LOGGING
956         LDAP_LOG( TRANSPORT, ENTRY, 
957                 "slap_sasl_authorize: conn %d    authcid=\"%s\" authzid=\"%s\"\n",
958                 conn ? conn->c_connid : -1, authcid ? authcid : "<empty>",
959                 authzid ? authzid : "<empty>" );
960 #else
961         Debug( LDAP_DEBUG_ARGS, "SASL Authorize [conn=%ld]: "
962                 "authcid=\"%s\" authzid=\"%s\"\n",
963                 (long) (conn ? conn->c_connid : -1),
964                 authcid ? authcid : "<empty>",
965                 authzid ? authzid : "<empty>" );
966 #endif
967
968         /* Figure out how much data we have for the dn */
969         rc = sasl_getprop( conn->c_sasl_authctx, SASL_REALM, (void **)&realm );
970         if( rc != SASL_OK && rc != SASL_NOTDONE ) {
971 #ifdef NEW_LOGGING
972                 LDAP_LOG( TRANSPORT, ERR,
973                         "slap_sasl_authorize: getprop(REALM) failed.\n", 0, 0, 0 );
974 #else
975                 Debug(LDAP_DEBUG_TRACE,
976                         "authorize: getprop(REALM) failed!\n", 0,0,0);
977 #endif
978                 *errstr = "Could not extract realm";
979                 return SASL_NOAUTHZ;
980         }
981
982         /* Convert the identities to DN's. If no authzid was given, client will
983            be bound as the DN matching their username */
984         rc = slap_sasl_getdn( conn, NULL, (char *)authcid, 0, realm,
985                 &authcDN, SLAP_GETDN_AUTHCID );
986         if( rc != LDAP_SUCCESS ) {
987                 *errstr = ldap_err2string( rc );
988                 return SASL_NOAUTHZ;
989         }
990         if( ( authzid == NULL ) || !strcmp( authcid,authzid ) ) {
991 #ifdef NEW_LOGGING
992                 LDAP_LOG( TRANSPORT, ENTRY, 
993                         "slap_sasl_authorize: conn %d  Using authcDN=%s\n",
994                         conn ? conn->c_connid : -1, authcDN.bv_val, 0 );
995 #else
996                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
997                  "Using authcDN=%s\n", (long) (conn ? conn->c_connid : -1), authcDN.bv_val,0 );
998 #endif
999
1000                 conn->c_sasl_dn = authcDN;
1001                 goto ok;
1002         }
1003         rc = slap_sasl_getdn( conn, NULL, (char *)authzid, 0, realm,
1004                 &authzDN, SLAP_GETDN_AUTHZID );
1005         if( rc != LDAP_SUCCESS ) {
1006                 ch_free( authcDN.bv_val );
1007                 *errstr = ldap_err2string( rc );
1008                 return SASL_NOAUTHZ;
1009         }
1010
1011         rc = slap_sasl_authorized(conn->c_sasl_bindop, &authcDN, &authzDN );
1012         ch_free( authcDN.bv_val );
1013         if( rc ) {
1014 #ifdef NEW_LOGGING
1015                 LDAP_LOG( TRANSPORT, INFO, 
1016                         "slap_sasl_authorize: conn %ld "
1017                         "proxy authorization disallowed (%d)\n",
1018                         (long)(conn ? conn->c_connid : -1), rc, 0 );
1019 #else
1020                 Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
1021                         "proxy authorization disallowed (%d)\n",
1022                         (long) (conn ? conn->c_connid : -1), rc, 0 );
1023 #endif
1024
1025                 *errstr = "not authorized";
1026                 ch_free( authzDN.bv_val );
1027                 return SASL_NOAUTHZ;
1028         }
1029         conn->c_sasl_dn = authzDN;
1030
1031 ok:
1032 #ifdef NEW_LOGGING
1033         LDAP_LOG( TRANSPORT, RESULTS, 
1034                 "slap_sasl_authorize: conn %d proxy authorization allowed\n",
1035            (long)(conn ? conn->c_connid : -1 ), 0, 0 );
1036 #else
1037         Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
1038                 " authorization allowed\n",
1039                 (long) (conn ? conn->c_connid : -1), 0, 0 );
1040 #endif
1041
1042         if (conn->c_sasl_bindop) {
1043                 Statslog( LDAP_DEBUG_STATS,
1044                         "conn=%lu op=%lu BIND authcid=\"%s\"\n",
1045                         conn->c_connid, conn->c_sasl_bindop->o_opid, 
1046                         authcid, 0, 0);
1047         }
1048
1049         *errstr = NULL;
1050         return SASL_OK;
1051 }
1052 #endif /* SASL_VERSION_MAJOR >= 2 */
1053
1054 static int
1055 slap_sasl_err2ldap( int saslerr )
1056 {
1057         int rc;
1058
1059         switch (saslerr) {
1060                 case SASL_OK:
1061                         rc = LDAP_SUCCESS;
1062                         break;
1063                 case SASL_CONTINUE:
1064                         rc = LDAP_SASL_BIND_IN_PROGRESS;
1065                         break;
1066                 case SASL_FAIL:
1067                         rc = LDAP_OTHER;
1068                         break;
1069                 case SASL_NOMEM:
1070                         rc = LDAP_OTHER;
1071                         break;
1072                 case SASL_NOMECH:
1073                         rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1074                         break;
1075                 case SASL_BADAUTH:
1076                         rc = LDAP_INVALID_CREDENTIALS;
1077                         break;
1078                 case SASL_NOAUTHZ:
1079                         rc = LDAP_INSUFFICIENT_ACCESS;
1080                         break;
1081                 case SASL_TOOWEAK:
1082                 case SASL_ENCRYPT:
1083                         rc = LDAP_INAPPROPRIATE_AUTH;
1084                         break;
1085                 default:
1086                         rc = LDAP_OTHER;
1087                         break;
1088         }
1089
1090         return rc;
1091 }
1092 #endif
1093
1094 int slap_sasl_init( void )
1095 {
1096 #ifdef HAVE_CYRUS_SASL
1097         int rc;
1098         static sasl_callback_t server_callbacks[] = {
1099                 { SASL_CB_LOG, &slap_sasl_log, NULL },
1100                 { SASL_CB_LIST_END, NULL, NULL }
1101         };
1102
1103 #ifdef HAVE_SASL_VERSION
1104         /* stringify the version number, sasl.h doesn't do it for us */
1105 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
1106 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
1107 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
1108                                 SASL_VERSION_STEP)
1109
1110         sasl_version( NULL, &rc );
1111         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1112                 (rc & 0xffff) < SASL_VERSION_STEP)
1113         {
1114                 char version[sizeof("xxx.xxx.xxxxx")];
1115                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
1116                         rc & 0xffff );
1117 #ifdef NEW_LOGGING
1118                 LDAP_LOG( TRANSPORT, INFO,
1119                 "slap_sasl_init: SASL library version mismatch:"
1120                 " expected " SASL_VERSION_STRING ","
1121                 " got %s\n", version, 0, 0 );
1122 #else
1123                 Debug( LDAP_DEBUG_ANY,
1124                 "slap_sasl_init: SASL library version mismatch:"
1125                 " expected " SASL_VERSION_STRING ","
1126                 " got %s\n", version, 0, 0 );
1127 #endif
1128                 return -1;
1129         }
1130 #endif
1131
1132         /* SASL 2 does its own memory management internally */
1133 #if SASL_VERSION_MAJOR < 2
1134         sasl_set_alloc(
1135                 ber_memalloc,
1136                 ber_memcalloc,
1137                 ber_memrealloc,
1138                 ber_memfree ); 
1139 #endif
1140
1141         sasl_set_mutex(
1142                 ldap_pvt_sasl_mutex_new,
1143                 ldap_pvt_sasl_mutex_lock,
1144                 ldap_pvt_sasl_mutex_unlock,
1145                 ldap_pvt_sasl_mutex_dispose );
1146
1147 #if SASL_VERSION_MAJOR >= 2
1148         generic_filter.f_desc = slap_schema.si_ad_objectClass;
1149
1150         sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1151 #endif
1152         /* should provide callbacks for logging */
1153         /* server name should be configurable */
1154         rc = sasl_server_init( server_callbacks, "slapd" );
1155
1156         if( rc != SASL_OK ) {
1157 #ifdef NEW_LOGGING
1158                 LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: init failed.\n", 0, 0, 0 );
1159 #else
1160                 Debug( LDAP_DEBUG_ANY, "sasl_server_init failed\n",
1161                         0, 0, 0 );
1162 #endif
1163 #if SASL_VERSION_MAJOR < 2
1164                 /* A no-op used to make sure we linked with Cyrus 1.5 */
1165                 sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
1166 #endif
1167
1168                 return -1;
1169         }
1170
1171 #ifdef NEW_LOGGING
1172         LDAP_LOG( TRANSPORT, INFO, "slap_sasl_init: initialized!\n", 0, 0, 0 );
1173 #else
1174         Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1175                 0, 0, 0 );
1176 #endif
1177
1178         /* default security properties */
1179         memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1180         sasl_secprops.max_ssf = INT_MAX;
1181         sasl_secprops.maxbufsize = 65536;
1182         sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1183 #endif
1184
1185         return 0;
1186 }
1187
1188 int slap_sasl_destroy( void )
1189 {
1190 #ifdef HAVE_CYRUS_SASL
1191         sasl_done();
1192 #endif
1193         free( global_host );
1194         global_host = NULL;
1195
1196         return 0;
1197 }
1198
1199 int slap_sasl_open( Connection *conn, int reopen )
1200 {
1201         int sc = LDAP_SUCCESS;
1202 #ifdef HAVE_CYRUS_SASL
1203         int cb;
1204
1205         sasl_conn_t *ctx = NULL;
1206         sasl_callback_t *session_callbacks;
1207
1208 #if SASL_VERSION_MAJOR >= 2
1209         char *ipremoteport = NULL, *iplocalport = NULL;
1210 #endif
1211
1212         assert( conn->c_sasl_authctx == NULL );
1213
1214         if ( !reopen ) {
1215                 assert( conn->c_sasl_extra == NULL );
1216
1217                 session_callbacks =
1218 #if SASL_VERSION_MAJOR >= 2
1219                         SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1220 #else
1221                         SLAP_CALLOC( 3, sizeof(sasl_callback_t));
1222 #endif
1223                 if( session_callbacks == NULL ) {
1224 #ifdef NEW_LOGGING
1225                         LDAP_LOG( TRANSPORT, ERR, 
1226                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1227 #else
1228                         Debug( LDAP_DEBUG_ANY, 
1229                                 "slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1230 #endif
1231                         return -1;
1232                 }
1233                 conn->c_sasl_extra = session_callbacks;
1234
1235                 session_callbacks[cb=0].id = SASL_CB_LOG;
1236                 session_callbacks[cb].proc = &slap_sasl_log;
1237                 session_callbacks[cb++].context = conn;
1238
1239                 session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1240                 session_callbacks[cb].proc = &slap_sasl_authorize;
1241                 session_callbacks[cb++].context = conn;
1242
1243 #if SASL_VERSION_MAJOR >= 2
1244                 session_callbacks[cb].id = SASL_CB_CANON_USER;
1245                 session_callbacks[cb].proc = &slap_sasl_canonicalize;
1246                 session_callbacks[cb++].context = conn;
1247
1248                 /* XXXX: this should be conditional */
1249                 session_callbacks[cb].id = SASL_CB_SERVER_USERDB_CHECKPASS;
1250                 session_callbacks[cb].proc = &slap_sasl_checkpass;
1251                 session_callbacks[cb++].context = conn;
1252 #endif
1253
1254                 session_callbacks[cb].id = SASL_CB_LIST_END;
1255                 session_callbacks[cb].proc = NULL;
1256                 session_callbacks[cb++].context = NULL;
1257         } else {
1258                 session_callbacks = conn->c_sasl_extra;
1259         }
1260
1261         conn->c_sasl_layers = 0;
1262
1263         if( global_host == NULL ) {
1264                 global_host = ldap_pvt_get_fqdn( NULL );
1265         }
1266
1267         /* create new SASL context */
1268 #if SASL_VERSION_MAJOR >= 2
1269         if ( conn->c_sock_name.bv_len != 0 &&
1270              strncmp( conn->c_sock_name.bv_val, "IP=", 3 ) == 0) {
1271                 char *p;
1272
1273                 iplocalport = ch_strdup( conn->c_sock_name.bv_val + 3 );
1274                 /* Convert IPv6 addresses to address;port syntax. */
1275                 p = strrchr( iplocalport, ' ' );
1276                 /* Convert IPv4 addresses to address;port syntax. */
1277                 if ( p == NULL ) p = strchr( iplocalport, ':' );
1278                 if ( p != NULL ) {
1279                         *p = ';';
1280                 }
1281         }
1282         if ( conn->c_peer_name.bv_len != 0 &&
1283              strncmp( conn->c_peer_name.bv_val, "IP=", 3 ) == 0) {
1284                 char *p;
1285
1286                 ipremoteport = ch_strdup( conn->c_peer_name.bv_val + 3 );
1287                 /* Convert IPv6 addresses to address;port syntax. */
1288                 p = strrchr( ipremoteport, ' ' );
1289                 /* Convert IPv4 addresses to address;port syntax. */
1290                 if ( p == NULL ) p = strchr( ipremoteport, ':' );
1291                 if ( p != NULL ) {
1292                         *p = ';';
1293                 }
1294         }
1295         sc = sasl_server_new( "ldap", global_host, global_realm,
1296                 iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1297         if ( iplocalport != NULL ) {
1298                 ch_free( iplocalport );
1299         }
1300         if ( ipremoteport != NULL ) {
1301                 ch_free( ipremoteport );
1302         }
1303 #else
1304         sc = sasl_server_new( "ldap", global_host, global_realm,
1305                 session_callbacks, SASL_SECURITY_LAYER, &ctx );
1306 #endif
1307
1308         if( sc != SASL_OK ) {
1309 #ifdef NEW_LOGGING
1310                 LDAP_LOG( TRANSPORT, ERR, 
1311                         "slap_sasl_open: sasl_server_new failed: %d\n", sc, 0, 0 );
1312 #else
1313                 Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1314                         sc, 0, 0 );
1315 #endif
1316
1317                 return -1;
1318         }
1319
1320         conn->c_sasl_authctx = ctx;
1321
1322         if( sc == SASL_OK ) {
1323                 sc = sasl_setprop( ctx,
1324                         SASL_SEC_PROPS, &sasl_secprops );
1325
1326                 if( sc != SASL_OK ) {
1327 #ifdef NEW_LOGGING
1328                         LDAP_LOG( TRANSPORT, ERR, 
1329                                 "slap_sasl_open: sasl_setprop failed: %d \n", sc, 0, 0 );
1330 #else
1331                         Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1332                                 sc, 0, 0 );
1333 #endif
1334
1335                         slap_sasl_close( conn );
1336                         return -1;
1337                 }
1338         }
1339
1340         sc = slap_sasl_err2ldap( sc );
1341
1342 #elif defined(SLAP_BUILTIN_SASL)
1343         /* built-in SASL implementation */
1344         SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1345         if( ctx == NULL ) return -1;
1346
1347         ctx->sc_external_ssf = 0;
1348         ctx->sc_external_id.bv_len = 0;
1349         ctx->sc_external_id.bv_val = NULL;
1350
1351         conn->c_sasl_authctx = ctx;
1352 #endif
1353
1354         return sc;
1355 }
1356
1357 int slap_sasl_external(
1358         Connection *conn,
1359         slap_ssf_t ssf,
1360         struct berval *auth_id )
1361 {
1362 #if SASL_VERSION_MAJOR >= 2
1363         int sc;
1364         sasl_conn_t *ctx = conn->c_sasl_authctx;
1365
1366         if ( ctx == NULL ) {
1367                 return LDAP_UNAVAILABLE;
1368         }
1369
1370         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1371
1372         if ( sc != SASL_OK ) {
1373                 return LDAP_OTHER;
1374         }
1375
1376         sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1377                 auth_id ? auth_id->bv_val : NULL );
1378
1379         if ( sc != SASL_OK ) {
1380                 return LDAP_OTHER;
1381         }
1382
1383 #elif defined(HAVE_CYRUS_SASL)
1384         int sc;
1385         sasl_conn_t *ctx = conn->c_sasl_authctx;
1386         sasl_external_properties_t extprops;
1387
1388         if ( ctx == NULL ) {
1389                 return LDAP_UNAVAILABLE;
1390         }
1391
1392         memset( &extprops, '\0', sizeof(extprops) );
1393         extprops.ssf = ssf;
1394         extprops.auth_id = auth_id ? auth_id->bv_val : NULL;
1395
1396         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1397                 (void *) &extprops );
1398
1399         if ( sc != SASL_OK ) {
1400                 return LDAP_OTHER;
1401         }
1402 #elif defined(SLAP_BUILTIN_SASL)
1403         /* built-in SASL implementation */
1404         SASL_CTX *ctx = conn->c_sasl_authctx;
1405         if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1406
1407         ctx->sc_external_ssf = ssf;
1408         if( auth_id ) {
1409                 ctx->sc_external_id = *auth_id;
1410                 auth_id->bv_len = 0;
1411                 auth_id->bv_val = NULL;
1412         } else {
1413                 ctx->sc_external_id.bv_len = 0;
1414                 ctx->sc_external_id.bv_val = NULL;
1415         }
1416 #endif
1417
1418         return LDAP_SUCCESS;
1419 }
1420
1421 int slap_sasl_reset( Connection *conn )
1422 {
1423         return LDAP_SUCCESS;
1424 }
1425
1426 char ** slap_sasl_mechs( Connection *conn )
1427 {
1428         char **mechs = NULL;
1429
1430 #ifdef HAVE_CYRUS_SASL
1431         sasl_conn_t *ctx = conn->c_sasl_authctx;
1432
1433         if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1434
1435         if( ctx != NULL ) {
1436                 int sc;
1437                 SASL_CONST char *mechstr;
1438
1439                 sc = sasl_listmech( ctx,
1440                         NULL, NULL, ",", NULL,
1441                         &mechstr, NULL, NULL );
1442
1443                 if( sc != SASL_OK ) {
1444 #ifdef NEW_LOGGING
1445                         LDAP_LOG( TRANSPORT, ERR, 
1446                                 "slap_sasl_mechs: sasl_listmech failed: %d\n", sc, 0, 0 );
1447 #else
1448                         Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1449                                 sc, 0, 0 );
1450 #endif
1451
1452                         return NULL;
1453                 }
1454
1455                 mechs = ldap_str2charray( mechstr, "," );
1456
1457 #if SASL_VERSION_MAJOR < 2
1458                 ch_free( mechstr );
1459 #endif
1460         }
1461 #elif defined(SLAP_BUILTIN_SASL)
1462         /* builtin SASL implementation */
1463         SASL_CTX *ctx = conn->c_sasl_authctx;
1464         if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1465                 /* should check ssf */
1466                 mechs = ldap_str2charray( "EXTERNAL", "," );
1467         }
1468 #endif
1469
1470         return mechs;
1471 }
1472
1473 int slap_sasl_close( Connection *conn )
1474 {
1475 #ifdef HAVE_CYRUS_SASL
1476         sasl_conn_t *ctx = conn->c_sasl_authctx;
1477
1478         if( ctx != NULL ) {
1479                 sasl_dispose( &ctx );
1480         }
1481         if ( conn->c_sasl_sockctx &&
1482                 conn->c_sasl_authctx != conn->c_sasl_sockctx )
1483         {
1484                 ctx = conn->c_sasl_sockctx;
1485                 sasl_dispose( &ctx );
1486         }
1487
1488         conn->c_sasl_authctx = NULL;
1489         conn->c_sasl_sockctx = NULL;
1490         conn->c_sasl_done = 0;
1491
1492         free( conn->c_sasl_extra );
1493         conn->c_sasl_extra = NULL;
1494
1495 #elif defined(SLAP_BUILTIN_SASL)
1496         SASL_CTX *ctx = conn->c_sasl_authctx;
1497         if( ctx ) {
1498                 if( ctx->sc_external_id.bv_val ) {
1499                         free( ctx->sc_external_id.bv_val );
1500                         ctx->sc_external_id.bv_val = NULL;
1501                 }
1502                 free( ctx );
1503                 conn->c_sasl_authctx = NULL;
1504         }
1505 #endif
1506
1507         return LDAP_SUCCESS;
1508 }
1509
1510 int slap_sasl_bind( Operation *op, SlapReply *rs )
1511 {
1512 #ifdef HAVE_CYRUS_SASL
1513         sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1514         struct berval response;
1515         unsigned reslen = 0;
1516         int sc;
1517
1518 #ifdef NEW_LOGGING
1519         LDAP_LOG( TRANSPORT, ENTRY, 
1520                 "sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1521                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1522                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1523                 op->o_conn->c_sasl_bind_mech.bv_val,
1524                 op->orb_cred.bv_len );
1525 #else
1526         Debug(LDAP_DEBUG_ARGS,
1527                 "==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1528                 op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1529                 op->o_conn->c_sasl_bind_in_progress ? "<continuing>" : 
1530                 op->o_conn->c_sasl_bind_mech.bv_val,
1531                 op->orb_cred.bv_len );
1532 #endif
1533
1534         if( ctx == NULL ) {
1535                 send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1536                         "SASL unavailable on this session" );
1537                 return rs->sr_err;
1538         }
1539
1540 #if SASL_VERSION_MAJOR >= 2
1541 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1542         sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1543 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1544         sasl_server_step( ctx, cred, clen, resp, rlen )
1545 #else
1546 #define START( ctx, mech, cred, clen, resp, rlen, err ) \
1547         sasl_server_start( ctx, mech, cred, clen, resp, rlen, err )
1548 #define STEP( ctx, cred, clen, resp, rlen, err ) \
1549         sasl_server_step( ctx, cred, clen, resp, rlen, err )
1550 #endif
1551
1552         if ( !op->o_conn->c_sasl_bind_in_progress ) {
1553                 /* If we already authenticated once, must use a new context */
1554                 if ( op->o_conn->c_sasl_done ) {
1555                         slap_ssf_t ssf = 0;
1556                         const char *authid = NULL;
1557 #if SASL_VERSION_MAJOR >= 2
1558                         sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssf );
1559                         sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1560                         if ( authid ) authid = ch_strdup( authid );
1561 #endif
1562                         if ( ctx != op->o_conn->c_sasl_sockctx ) {
1563                                 sasl_dispose( &ctx );
1564                         }
1565                         op->o_conn->c_sasl_authctx = NULL;
1566                                 
1567                         slap_sasl_open( op->o_conn, 1 );
1568                         ctx = op->o_conn->c_sasl_authctx;
1569 #if SASL_VERSION_MAJOR >= 2
1570                         if ( authid ) {
1571                                 sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1572                                 sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1573                                 ch_free( (char *)authid );
1574                         }
1575 #endif
1576                 }
1577                 sc = START( ctx,
1578                         op->o_conn->c_sasl_bind_mech.bv_val,
1579                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1580                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1581
1582         } else {
1583                 sc = STEP( ctx,
1584                         op->orb_cred.bv_val, op->orb_cred.bv_len,
1585                         (SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1586         }
1587
1588         response.bv_len = reslen;
1589
1590         if ( sc == SASL_OK ) {
1591                 sasl_ssf_t *ssf = NULL;
1592
1593                 op->orb_edn = op->o_conn->c_sasl_dn;
1594                 op->o_conn->c_sasl_dn.bv_val = NULL;
1595                 op->o_conn->c_sasl_dn.bv_len = 0;
1596                 op->o_conn->c_sasl_done = 1;
1597
1598                 rs->sr_err = LDAP_SUCCESS;
1599
1600                 (void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1601                 op->orb_ssf = ssf ? *ssf : 0;
1602
1603                 ctx = NULL;
1604                 if( op->orb_ssf ) {
1605                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1606                         op->o_conn->c_sasl_layers++;
1607
1608                         /* If there's an old layer, set sockctx to NULL to
1609                          * tell connection_read() to wait for us to finish.
1610                          * Otherwise there is a race condition: we have to
1611                          * send the Bind response using the old security
1612                          * context and then remove it before reading any
1613                          * new messages.
1614                          */
1615                         if ( op->o_conn->c_sasl_sockctx ) {
1616                                 ctx = op->o_conn->c_sasl_sockctx;
1617                                 op->o_conn->c_sasl_sockctx = NULL;
1618                         } else {
1619                                 op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1620                         }
1621                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1622                 }
1623
1624                 /* Must send response using old security layer */
1625                 if (response.bv_len) rs->sr_sasldata = &response;
1626                 send_ldap_sasl( op, rs );
1627                 
1628                 /* Now dispose of the old security layer.
1629                  */
1630                 if ( ctx ) {
1631                         ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1632                         ldap_pvt_sasl_remove( op->o_conn->c_sb );
1633                         op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1634                         ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1635                         sasl_dispose( &ctx );
1636                 }
1637         } else if ( sc == SASL_CONTINUE ) {
1638                 rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1639                 rs->sr_sasldata = &response;
1640                 send_ldap_sasl( op, rs );
1641
1642         } else {
1643 #if SASL_VERSION_MAJOR >= 2
1644                 rs->sr_text = sasl_errdetail( ctx );
1645 #endif
1646                 rs->sr_err = slap_sasl_err2ldap( sc ),
1647                 send_ldap_result( op, rs );
1648         }
1649
1650 #if SASL_VERSION_MAJOR < 2
1651         if( response.bv_len ) {
1652                 ch_free( response.bv_val );
1653         }
1654 #endif
1655
1656 #ifdef NEW_LOGGING
1657         LDAP_LOG( TRANSPORT, RESULTS, "slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0 );
1658 #else
1659         Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1660 #endif
1661
1662 #elif defined(SLAP_BUILTIN_SASL)
1663         /* built-in SASL implementation */
1664         SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1665
1666         if ( ctx == NULL ) {
1667                 send_ldap_error( op, rs, LDAP_OTHER,
1668                         "Internal SASL Error" );
1669
1670         } else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1671                 /* EXTERNAL */
1672
1673                 if( op->orb_cred.bv_len ) {
1674                         rs->sr_text = "proxy authorization not support";
1675                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1676                         send_ldap_result( op, rs );
1677
1678                 } else {
1679                         op->orb_edn = ctx->sc_external_id;
1680                         rs->sr_err = LDAP_SUCCESS;
1681                         rs->sr_sasldata = NULL;
1682                         send_ldap_sasl( op, rs );
1683                 }
1684
1685         } else {
1686                 send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1687                         "requested SASL mechanism not supported" );
1688         }
1689 #else
1690         send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1691                 "SASL not supported" );
1692 #endif
1693
1694         return rs->sr_err;
1695 }
1696
1697 char* slap_sasl_secprops( const char *in )
1698 {
1699 #ifdef HAVE_CYRUS_SASL
1700         int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1701
1702         return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1703 #else
1704         return "SASL not supported";
1705 #endif
1706 }
1707
1708 #ifdef HAVE_CYRUS_SASL
1709 int
1710 slap_sasl_setpass( Operation *op, SlapReply *rs )
1711 {
1712         struct berval id = { 0, NULL }; /* needs to come from connection */
1713         struct berval new = { 0, NULL };
1714         struct berval old = { 0, NULL };
1715
1716         assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1717
1718         rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1719                 (SASL_CONST void **)&id.bv_val );
1720
1721         if( rs->sr_err != SASL_OK ) {
1722                 rs->sr_text = "unable to retrieve SASL username";
1723                 rs->sr_err = LDAP_OTHER;
1724                 goto done;
1725         }
1726
1727 #ifdef NEW_LOGGING
1728         LDAP_LOG( BACKEND, ENTRY,
1729                 "slap_sasl_setpass: \"%s\"\n",
1730                 id.bv_val ? id.bv_val : "", 0, 0);
1731 #else
1732         Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1733                 id.bv_val ? id.bv_val : "", 0, 0 );
1734 #endif
1735
1736         rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1737                 NULL, &old, &new, &rs->sr_text );
1738
1739         if( rs->sr_err != LDAP_SUCCESS ) {
1740                 goto done;
1741         }
1742
1743         if( new.bv_len == 0 ) {
1744                 slap_passwd_generate(&new);
1745
1746                 if( new.bv_len == 0 ) {
1747                         rs->sr_text = "password generation failed.";
1748                         rs->sr_err = LDAP_OTHER;
1749                         goto done;
1750                 }
1751                 
1752                 rs->sr_rspdata = slap_passwd_return( &new );
1753         }
1754
1755 #if SASL_VERSION_MAJOR < 2
1756         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx,
1757                 id.bv_val, new.bv_val, new.bv_len, 0, &rs->sr_text );
1758 #else
1759         rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1760                 new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1761         if( rs->sr_err != SASL_OK ) {
1762                 rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1763         }
1764 #endif
1765         switch(rs->sr_err) {
1766                 case SASL_OK:
1767                         rs->sr_err = LDAP_SUCCESS;
1768                         break;
1769
1770                 case SASL_NOCHANGE:
1771                 case SASL_NOMECH:
1772                 case SASL_DISABLED:
1773                 case SASL_PWLOCK:
1774                 case SASL_FAIL:
1775                 case SASL_BADPARAM:
1776                 default:
1777                         rs->sr_err = LDAP_OTHER;
1778         }
1779
1780 done:
1781         return rs->sr_err;
1782 }
1783 #endif /* HAVE_CYRUS_SASL */
1784
1785 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1786  * string returned in *dn is in its own allocated memory, and must be free'd 
1787  * by the calling process.  -Mark Adamson, Carnegie Mellon
1788  *
1789  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1790  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1791  */
1792
1793 #define SET_NONE        0
1794 #define SET_DN          1
1795 #define SET_U           2
1796
1797 int slap_sasl_getdn( Connection *conn, Operation *op, char *id, int len,
1798         char *user_realm, struct berval *dn, int flags )
1799 {
1800         int rc, is_dn = SET_NONE, do_norm = 1;
1801         struct berval dn2, *mech;
1802
1803         assert( conn );
1804
1805 #ifdef NEW_LOGGING
1806         LDAP_LOG( TRANSPORT, ENTRY, 
1807                 "slap_sasl_getdn: conn %d id=%s [len=%d]\n",
1808                 conn->c_connid, id ? (*id ? id : "<empty>") : "NULL", len );
1809 #else
1810         Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: id=%s [len=%d]\n", 
1811                 id ? ( *id ? id : "<empty>" ) : "NULL", len, 0 );
1812 #endif
1813
1814         if ( !op ) {
1815                 op = conn->c_sasl_bindop;
1816         }
1817
1818         dn->bv_val = NULL;
1819         dn->bv_len = 0;
1820
1821         if ( id ) {
1822                 if ( len == 0 ) len = strlen( id );
1823
1824                 /* Blatantly anonymous ID */
1825                 if ( len == sizeof("anonymous") - 1 &&
1826                         !strcasecmp( id, "anonymous" ) ) {
1827                         return( LDAP_SUCCESS );
1828                 }
1829         } else {
1830                 len = 0;
1831         }
1832
1833         if ( conn->c_sasl_bind_mech.bv_len ) {
1834                 mech = &conn->c_sasl_bind_mech;
1835         } else {
1836                 mech = &conn->c_authmech;
1837         }
1838
1839         /* An authcID needs to be converted to authzID form. Set the
1840          * values directly into *dn; they will be normalized later. (and
1841          * normalizing always makes a new copy.) An ID from a TLS certificate
1842          * is already normalized, so copy it and skip normalization.
1843          */
1844         if( flags & SLAP_GETDN_AUTHCID ) {
1845                 if( bvmatch( mech, &ext_bv )) {
1846                         /* EXTERNAL DNs are already normalized */
1847                         do_norm = 0;
1848                         is_dn = SET_DN;
1849                         ber_str2bv_x( id, len, 1, dn, op->o_tmpmemctx );
1850
1851                 } else {
1852                         /* convert to u:<username> form */
1853                         is_dn = SET_U;
1854                         dn->bv_val = id;
1855                         dn->bv_len = len;
1856                 }
1857         }
1858         if( is_dn == SET_NONE ) {
1859                 if( !strncasecmp( id, "u:", sizeof("u:")-1 )) {
1860                         is_dn = SET_U;
1861                         dn->bv_val = id+2;
1862                         dn->bv_len = len-2;
1863                 } else if ( !strncasecmp( id, "dn:", sizeof("dn:")-1) ) {
1864                         is_dn = SET_DN;
1865                         dn->bv_val = id+3;
1866                         dn->bv_len = len-3;
1867                 }
1868         }
1869
1870         /* No other possibilities from here */
1871         if( is_dn == SET_NONE ) {
1872                 dn->bv_val = NULL;
1873                 dn->bv_len = 0;
1874                 return( LDAP_INAPPROPRIATE_AUTH );
1875         }
1876
1877         /* Username strings */
1878         if( is_dn == SET_U ) {
1879                 char            *p;
1880                 struct berval   realm = { 0, NULL }, c1 = *dn;
1881
1882                 len = dn->bv_len + sizeof("uid=")-1 + sizeof(",cn=auth")-1;
1883
1884                 if( user_realm && *user_realm ) {
1885                         realm.bv_val = user_realm;
1886                         realm.bv_len = strlen( user_realm );
1887                         len += realm.bv_len + sizeof(",cn=") - 1;
1888                 }
1889
1890                 if( mech->bv_len ) {
1891                         len += mech->bv_len + sizeof(",cn=")-1;
1892                 }
1893
1894                 /* Build the new dn */
1895                 dn->bv_val = sl_malloc( len+1, op->o_tmpmemctx );
1896                 if( dn->bv_val == NULL ) {
1897 #ifdef NEW_LOGGING
1898                         LDAP_LOG( TRANSPORT, ERR, 
1899                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1900 #else
1901                         Debug( LDAP_DEBUG_ANY, 
1902                                 "slap_sasl_getdn: SLAP_MALLOC failed", 0, 0, 0 );
1903 #endif
1904                         return LDAP_OTHER;
1905                 }
1906                 p = lutil_strcopy( dn->bv_val, "uid=" );
1907                 p = lutil_strncopy( p, c1.bv_val, c1.bv_len );
1908
1909                 if( realm.bv_len ) {
1910                         p = lutil_strcopy( p, ",cn=" );
1911                         p = lutil_strncopy( p, realm.bv_val, realm.bv_len );
1912                 }
1913
1914                 if( mech->bv_len ) {
1915                         p = lutil_strcopy( p, ",cn=" );
1916                         p = lutil_strcopy( p, mech->bv_val );
1917                 }
1918                 p = lutil_strcopy( p, ",cn=auth" );
1919                 dn->bv_len = p - dn->bv_val;
1920
1921 #ifdef NEW_LOGGING
1922                 LDAP_LOG( TRANSPORT, ENTRY, 
1923                         "slap_sasl_getdn: u:id converted to %s.\n", dn->bv_val, 0, 0 );
1924 #else
1925                 Debug( LDAP_DEBUG_TRACE, "slap_sasl_getdn: u:id converted to %s\n", dn->bv_val,0,0 );
1926 #endif
1927         } else {
1928                 
1929                 /* Dup the DN in any case, so we don't risk 
1930                  * leaks or dangling pointers later,
1931                  * and the DN value is '\0' terminated */
1932                 ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1933                 dn->bv_val = dn2.bv_val;
1934         }
1935
1936         /* All strings are in DN form now. Normalize if needed. */
1937         if ( do_norm ) {
1938                 rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1939
1940                 /* User DNs were constructed above and must be freed now */
1941                 sl_free( dn->bv_val, op->o_tmpmemctx );
1942
1943                 if ( rc != LDAP_SUCCESS ) {
1944                         dn->bv_val = NULL;
1945                         dn->bv_len = 0;
1946                         return rc;
1947                 }
1948                 *dn = dn2;
1949         }
1950
1951         /* Run thru regexp */
1952         slap_sasl2dn( op, dn, &dn2, flags );
1953         if( dn2.bv_val ) {
1954                 sl_free( dn->bv_val, op->o_tmpmemctx );
1955                 *dn = dn2;
1956 #ifdef NEW_LOGGING
1957                 LDAP_LOG( TRANSPORT, ENTRY, 
1958                         "slap_sasl_getdn: dn:id converted to %s.\n", dn->bv_val, 0, 0 );
1959 #else
1960                 Debug( LDAP_DEBUG_TRACE, "getdn: dn:id converted to %s\n",
1961                         dn->bv_val, 0, 0 );
1962 #endif
1963         }
1964
1965         return( LDAP_SUCCESS );
1966 }