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