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