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