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