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