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