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