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