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