]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
c67eb606401562f0bcb27128cf739781343f8821
[openldap] / servers / slapd / back-ldap / bind.c
1 /* bind.c - ldap backend bind function */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 1999-2005 The OpenLDAP Foundation.
6  * Portions Copyright 2000-2003 Pierangelo Masarati.
7  * Portions Copyright 1999-2003 Howard Chu.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted only as authorized by the OpenLDAP
12  * Public License.
13  *
14  * A copy of this license is available in the file LICENSE in the
15  * top-level directory of the distribution or, alternatively, at
16  * <http://www.OpenLDAP.org/license.html>.
17  */
18 /* ACKNOWLEDGEMENTS:
19  * This work was initially developed by Howard Chu for inclusion
20  * in OpenLDAP Software and subsequently enhanced by Pierangelo
21  * Masarati.
22  */
23
24 #include "portable.h"
25
26 #include <stdio.h>
27
28 #include <ac/errno.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
31
32 #define AVL_INTERNAL
33 #include "slap.h"
34 #include "back-ldap.h"
35
36 #include <lutil_ldap.h>
37
38 #define PRINT_CONNTREE 0
39
40 static LDAP_REBIND_PROC ldap_back_default_rebind;
41
42 LDAP_REBIND_PROC        *ldap_back_rebind_f = ldap_back_default_rebind;
43
44 static int
45 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs );
46
47 static int
48 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok );
49
50 int
51 ldap_back_bind( Operation *op, SlapReply *rs )
52 {
53         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
54         ldapconn_t      *lc;
55
56         int rc = 0;
57         ber_int_t msgid;
58
59         lc = ldap_back_getconn( op, rs, LDAP_BACK_SENDERR );
60         if ( !lc ) {
61                 return rs->sr_err;
62         }
63
64         if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
65                 ch_free( lc->lc_bound_ndn.bv_val );
66                 BER_BVZERO( &lc->lc_bound_ndn );
67         }
68         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
69
70         /* method is always LDAP_AUTH_SIMPLE if we got here */
71         rs->sr_err = ldap_sasl_bind( lc->lc_ld, op->o_req_dn.bv_val,
72                         LDAP_SASL_SIMPLE,
73                         &op->orb_cred, op->o_ctrls, NULL, &msgid );
74         rc = ldap_back_op_result( lc, op, rs, msgid, 0, LDAP_BACK_SENDERR );
75
76         if ( rc == LDAP_SUCCESS ) {
77                 /* If defined, proxyAuthz will be used also when
78                  * back-ldap is the authorizing backend; for this
79                  * purpose, a successful bind is followed by a
80                  * bind with the configured identity assertion */
81                 /* NOTE: use with care */
82                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
83                         ldap_back_proxy_authz_bind( lc, op, rs );
84                         if ( !LDAP_BACK_CONN_ISBOUND( lc ) ) {
85                                 rc = 1;
86                                 goto done;
87                         }
88                 }
89
90                 LDAP_BACK_CONN_ISBOUND_SET( lc );
91                 ber_dupbv( &lc->lc_bound_ndn, &op->o_req_ndn );
92
93                 if ( LDAP_BACK_SAVECRED( li ) ) {
94                         if ( !BER_BVISNULL( &lc->lc_cred ) ) {
95                                 memset( lc->lc_cred.bv_val, 0,
96                                                 lc->lc_cred.bv_len );
97                         }
98                         ber_bvreplace( &lc->lc_cred, &op->orb_cred );
99                         ldap_set_rebind_proc( lc->lc_ld, ldap_back_rebind_f, lc );
100                 }
101         }
102 done:;
103
104         /* must re-insert if local DN changed as result of bind */
105         if ( LDAP_BACK_CONN_ISBOUND( lc )
106                 && !dn_match( &op->o_req_ndn, &lc->lc_local_ndn ) )
107         {
108                 int             lerr;
109
110                 /* wait for all other ops to release the connection */
111 retry_lock:;
112                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
113                 if ( lc->lc_refcnt > 1 ) {
114                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
115                         ldap_pvt_thread_yield();
116                         goto retry_lock;
117                 }
118
119                 assert( lc->lc_refcnt == 1 );
120                 lc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
121                                 ldap_back_conn_cmp );
122                 assert( lc != NULL );
123
124                 ber_bvreplace( &lc->lc_local_ndn, &op->o_req_ndn );
125                 lerr = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
126                         ldap_back_conn_cmp, ldap_back_conn_dup );
127                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
128                 if ( lerr == -1 ) {
129                         /* we can do this because lc_refcnt == 1 */
130                         ldap_back_conn_free( lc );
131                         lc = NULL;
132                 }
133         }
134
135         if ( lc != NULL ) {
136                 ldap_back_release_conn( op, rs, lc );
137         }
138
139         return( rc );
140 }
141
142 /*
143  * ldap_back_conn_cmp
144  *
145  * compares two ldapconn_t based on the value of the conn pointer;
146  * used by avl stuff
147  */
148 int
149 ldap_back_conn_cmp( const void *c1, const void *c2 )
150 {
151         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
152         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
153         int rc;
154
155         /* If local DNs don't match, it is definitely not a match */
156         rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
157         if ( rc ) {
158                 return rc;
159         }
160
161         /* For shared sessions, conn is NULL. Only explicitly
162          * bound sessions will have non-NULL conn.
163          */
164         return SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
165 }
166
167 /*
168  * ldap_back_conn_dup
169  *
170  * returns -1 in case a duplicate ldapconn_t has been inserted;
171  * used by avl stuff
172  */
173 int
174 ldap_back_conn_dup( void *c1, void *c2 )
175 {
176         ldapconn_t      *lc1 = (ldapconn_t *)c1;
177         ldapconn_t      *lc2 = (ldapconn_t *)c2;
178
179         /* Cannot have more than one shared session with same DN */
180         if ( dn_match( &lc1->lc_local_ndn, &lc2->lc_local_ndn ) &&
181                         lc1->lc_conn == lc2->lc_conn )
182         {
183                 return -1;
184         }
185                 
186         return 0;
187 }
188
189 #if PRINT_CONNTREE > 0
190 static void
191 ravl_print( Avlnode *root, int depth )
192 {
193         int             i;
194         ldapconn_t      *lc;
195         
196         if ( root == 0 ) {
197                 return;
198         }
199         
200         ravl_print( root->avl_right, depth+1 );
201         
202         for ( i = 0; i < depth; i++ ) {
203                 printf( "   " );
204         }
205
206         lc = root->avl_data;
207         printf( "lc(%lx) local(%s) conn(%lx) %d\n",
208                         lc, lc->lc_local_ndn.bv_val, lc->lc_conn, root->avl_bf );
209         
210         ravl_print( root->avl_left, depth+1 );
211 }
212
213 static void
214 myprint( Avlnode *root )
215 {
216         printf( "********\n" );
217         
218         if ( root == 0 ) {
219                 printf( "\tNULL\n" );
220
221         } else {
222                 ravl_print( root, 0 );
223         }
224         
225         printf( "********\n" );
226 }
227 #endif /* PRINT_CONNTREE */
228
229 int
230 ldap_back_freeconn( Operation *op, ldapconn_t *lc, int dolock )
231 {
232         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
233
234         if ( dolock ) {
235                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
236         }
237
238         assert( lc->lc_refcnt > 0 );
239         if ( --lc->lc_refcnt == 0 ) {
240                 lc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
241                                 ldap_back_conn_cmp );
242                 assert( lc != NULL );
243
244                 ldap_back_conn_free( (void *)lc );
245         }
246
247         if ( dolock ) {
248                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
249         }
250
251         return 0;
252 }
253
254 #ifdef HAVE_TLS
255 static int
256 ldap_back_start_tls(
257         LDAP            *ld,
258         int             protocol,
259         int             *is_tls,
260         const char      *url,
261         unsigned        flags,
262         int             retries,
263         const char      **text )
264 {
265         int             rc = LDAP_SUCCESS;
266         ldapinfo_t      dummy;
267
268         /* this is ridiculous... */
269         dummy.li_flags = flags;
270
271         /* start TLS ("tls-[try-]{start,propagate}" statements) */
272         if ( ( LDAP_BACK_USE_TLS( &dummy ) || ( *is_tls && LDAP_BACK_PROPAGATE_TLS( &dummy ) ) )
273                                 && !ldap_is_ldaps_url( url ) )
274         {
275 #ifdef SLAP_STARTTLS_ASYNCHRONOUS
276                 /*
277                  * use asynchronous StartTLS
278                  * in case, chase referral (not implemented yet)
279                  */
280                 int             msgid;
281
282                 if ( protocol == 0 ) {
283                         ldap_get_option( ld, LDAP_OPT_PROTOCOL_VERSION,
284                                         (void *)&protocol );
285                 }
286
287                 if ( protocol < LDAP_VERSION3 ) {
288                         protocol = LDAP_VERSION3;
289                         /* Set LDAP version */
290                         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION,
291                                         (const void *)&protocol );
292                 }
293
294                 rc = ldap_start_tls( ld, NULL, NULL, &msgid );
295                 if ( rc == LDAP_SUCCESS ) {
296                         LDAPMessage     *res = NULL;
297                         struct timeval  tv;
298
299                         LDAP_BACK_TV_SET( &tv );
300
301 retry:;
302                         rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
303                         if ( rc < 0 ) {
304                                 rc = LDAP_UNAVAILABLE;
305
306                         } else if ( rc == 0 ) {
307                                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
308                                         ldap_pvt_thread_yield();
309                                         if ( retries > 0 ) {
310                                                 retries--;
311                                         }
312                                         LDAP_BACK_TV_SET( &tv );
313                                         goto retry;
314                                 }
315                                 rc = LDAP_UNAVAILABLE;
316
317                         } else if ( rc == LDAP_RES_EXTENDED ) {
318                                 struct berval   *data = NULL;
319
320                                 rc = ldap_parse_extended_result( ld, res,
321                                                 NULL, &data, 0 );
322                                 if ( rc == LDAP_SUCCESS ) {
323                                         int err;
324                                         rc = ldap_parse_result( ld, res, &err,
325                                                 NULL, NULL, NULL, NULL, 1 );
326                                         if ( rc == LDAP_SUCCESS ) {
327                                                 rc = err;
328                                         }
329                                         res = NULL;
330                                         
331                                         /* FIXME: in case a referral 
332                                          * is returned, should we try
333                                          * using it instead of the 
334                                          * configured URI? */
335                                         if ( rc == LDAP_SUCCESS ) {
336                                                 rc = ldap_install_tls( ld );
337
338                                         } else if ( rc == LDAP_REFERRAL ) {
339                                                 rc = LDAP_OTHER;
340                                                 *text = "unwilling to chase referral returned by Start TLS exop";
341                                         }
342
343                                         if ( data ) {
344                                                 if ( data->bv_val ) {
345                                                         ber_memfree( data->bv_val );
346                                                 }
347                                                 ber_memfree( data );
348                                         }
349                                 }
350
351                         } else {
352                                 rc = LDAP_OTHER;
353                         }
354
355                         if ( res != NULL ) {
356                                 ldap_msgfree( res );
357                         }
358                 }
359 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
360                 /*
361                  * use synchronous StartTLS
362                  */
363                 rc = ldap_start_tls_s( ld, NULL, NULL );
364 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
365
366                 /* if StartTLS is requested, only attempt it if the URL
367                  * is not "ldaps://"; this may occur not only in case
368                  * of misconfiguration, but also when used in the chain 
369                  * overlay, where the "uri" can be parsed out of a referral */
370                 switch ( rc ) {
371                 case LDAP_SUCCESS:
372                         *is_tls = 1;
373                         break;
374
375                 case LDAP_SERVER_DOWN:
376                         break;
377
378                 default:
379                         if ( LDAP_BACK_TLS_CRITICAL( &dummy ) ) {
380                                 *text = "could not start TLS";
381                                 break;
382                         }
383
384                         /* in case Start TLS is not critical */
385                         *is_tls = 0;
386                         rc = LDAP_SUCCESS;
387                         break;
388                 }
389
390         } else {
391                 *is_tls = 0;
392         }
393
394         return rc;
395 }
396 #endif /* HAVE_TLS */
397
398 static int
399 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
400 {
401         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
402         int             vers = op->o_protocol;
403         LDAP            *ld = NULL;
404 #ifdef HAVE_TLS
405         int             is_tls = op->o_conn->c_is_tls;
406 #endif /* HAVE_TLS */
407
408         assert( lcp != NULL );
409
410         rs->sr_err = ldap_initialize( &ld, li->li_uri );
411         if ( rs->sr_err != LDAP_SUCCESS ) {
412                 goto error_return;
413         }
414
415         /* Set LDAP version. This will always succeed: If the client
416          * bound with a particular version, then so can we.
417          */
418         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, (const void *)&vers );
419
420         /* automatically chase referrals ("[dont-]chase-referrals" statement) */
421         if ( LDAP_BACK_CHASE_REFERRALS( li ) ) {
422                 ldap_set_option( ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON );
423         }
424
425 #ifdef HAVE_TLS
426         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
427                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
428         if ( rs->sr_err != LDAP_SUCCESS ) {
429                 ldap_unbind_ext( ld, NULL, NULL );
430                 goto error_return;
431         }
432 #endif /* HAVE_TLS */
433
434         if ( *lcp == NULL ) {
435                 *lcp = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
436                 (*lcp)->lc_flags= li->li_flags;
437         }
438         (*lcp)->lc_ld = ld;
439         (*lcp)->lc_refcnt = 1;
440 #ifdef HAVE_TLS
441         if ( is_tls ) {
442                 LDAP_BACK_CONN_ISTLS_SET( *lcp );
443         } else {
444                 LDAP_BACK_CONN_ISTLS_CLEAR( *lcp );
445         }
446 #endif /* HAVE_TLS */
447
448 error_return:;
449         if ( rs->sr_err != LDAP_SUCCESS ) {
450                 rs->sr_err = slap_map_api2result( rs );
451                 if ( sendok & LDAP_BACK_SENDERR ) {
452                         if ( rs->sr_text == NULL ) {
453                                 rs->sr_text = "ldap_initialize() failed";
454                         }
455                         send_ldap_result( op, rs );
456                         rs->sr_text = NULL;
457                 }
458         }
459
460         return rs->sr_err;
461 }
462
463 ldapconn_t *
464 ldap_back_getconn( Operation *op, SlapReply *rs, ldap_back_send_t sendok )
465 {
466         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
467         ldapconn_t      *lc,
468                         lc_curr = { 0 };
469         int             refcnt = 1;
470
471         /* Internal searches are privileged and shared. So is root. */
472         if ( op->o_do_not_cache || be_isroot( op ) ) {
473                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
474                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
475                 lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
476
477         } else {
478                 lc_curr.lc_local_ndn = op->o_ndn;
479                 /* Explicit binds must not be shared */
480                 if ( op->o_tag == LDAP_REQ_BIND || SLAP_IS_AUTHZ_BACKEND( op ) ) {
481                         lc_curr.lc_conn = op->o_conn;
482         
483                 } else {
484                         lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
485                 }
486         }
487
488         /* Searches for a ldapconn in the avl tree */
489         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
490
491         lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
492                         (caddr_t)&lc_curr, ldap_back_conn_cmp );
493         if ( lc != NULL ) {
494                 refcnt = ++lc->lc_refcnt;
495         }
496         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
497
498         /* Looks like we didn't get a bind. Open a new session... */
499         if ( lc == NULL ) {
500                 if ( ldap_back_prepare_conn( &lc, op, rs, sendok ) != LDAP_SUCCESS ) {
501                         return NULL;
502                 }
503
504                 lc->lc_conn = lc_curr.lc_conn;
505                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
506
507                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
508                         ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
509                         ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
510                         LDAP_BACK_CONN_ISPRIV_SET( lc );
511
512                 } else {
513                         BER_BVZERO( &lc->lc_cred );
514                         BER_BVZERO( &lc->lc_bound_ndn );
515 #if 0
516                         /* FIXME: if we set lc_bound_ndn = o_ndn
517                          * we end up with a bind with DN but no password! */
518                         if ( !BER_BVISEMPTY( &op->o_ndn )
519                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
520                         {
521                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
522                         }
523 #endif
524                 }
525
526 #ifdef HAVE_TLS
527                 /* if start TLS failed but it was not mandatory,
528                  * check if the non-TLS connection was already
529                  * in cache; in case, destroy the newly created
530                  * connection and use the existing one */
531                 if ( lc->lc_conn == LDAP_BACK_PCONN_TLS
532                                 && !ldap_tls_inplace( lc->lc_ld ) )
533                 {
534                         ldapconn_t *tmplc;
535                         
536                         lc_curr.lc_conn = LDAP_BACK_PCONN;
537                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
538                         tmplc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
539                                         (caddr_t)&lc_curr, ldap_back_conn_cmp );
540                         if ( tmplc != NULL ) {
541                                 refcnt = ++tmplc->lc_refcnt;
542                                 ldap_back_conn_free( lc );
543                                 lc = tmplc;
544                         }
545                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
546
547                         if ( tmplc != NULL ) {
548                                 goto done;
549                         }
550                 }
551 #endif /* HAVE_TLS */
552
553                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
554
555                 /* Inserts the newly created ldapconn in the avl tree */
556                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
557
558                 assert( lc->lc_refcnt == 1 );
559                 rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
560                         ldap_back_conn_cmp, ldap_back_conn_dup );
561
562 #if PRINT_CONNTREE > 0
563                 myprint( li->li_conninfo.lai_tree );
564 #endif /* PRINT_CONNTREE */
565         
566                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
567
568                 Debug( LDAP_DEBUG_TRACE,
569                         "=>ldap_back_getconn: conn %p inserted (refcnt=%u)\n",
570                         (void *)lc, refcnt, 0 );
571         
572                 /* Err could be -1 in case a duplicate ldapconn is inserted */
573                 if ( rs->sr_err != 0 ) {
574                         ldap_back_conn_free( lc );
575                         rs->sr_err = LDAP_OTHER;
576                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
577                                 send_ldap_error( op, rs, LDAP_OTHER,
578                                         "internal server error" );
579                         }
580                         return NULL;
581                 }
582
583         } else {
584                 if ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout ) {
585                         /* in case of failure, it frees/taints lc and sets it to NULL */
586                         if ( ldap_back_retry( &lc, op, rs, sendok ) ) {
587                                 lc = NULL;
588                         }
589                 }
590
591                 if ( lc ) {
592                         Debug( LDAP_DEBUG_TRACE,
593                                 "=>ldap_back_getconn: conn %p fetched (refcnt=%u)\n",
594                                 (void *)lc, refcnt, 0 );
595                 }
596         }
597
598         if ( li->li_idle_timeout && lc ) {
599                 lc->lc_time = op->o_time;
600         }
601
602 done:;
603         return lc;
604 }
605
606 void
607 ldap_back_release_conn(
608         Operation               *op,
609         SlapReply               *rs,
610         ldapconn_t              *lc )
611 {
612         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
613
614         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
615         assert( lc->lc_refcnt > 0 );
616         lc->lc_refcnt--;
617         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
618 }
619
620 /*
621  * ldap_back_dobind
622  *
623  * Note: as the check for the value of lc->lc_bound was already here, I removed
624  * it from all the callers, and I made the function return the flag, so
625  * it can be used to simplify the check.
626  *
627  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
628  */
629 static int
630 ldap_back_dobind_int(
631         ldapconn_t              *lc,
632         Operation               *op,
633         SlapReply               *rs,
634         ldap_back_send_t        sendok,
635         int                     retries,
636         int                     dolock )
637 {       
638         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
639
640         int             rc = LDAP_BACK_CONN_ISBOUND( lc );
641         ber_int_t       msgid;
642
643         assert( retries >= 0 );
644
645         if ( rc ) {
646                 return rc;
647         }
648
649         /*
650          * FIXME: we need to let clients use proxyAuthz
651          * otherwise we cannot do symmetric pools of servers;
652          * we have to live with the fact that a user can
653          * authorize itself as any ID that is allowed
654          * by the authzTo directive of the "proxyauthzdn".
655          */
656         /*
657          * NOTE: current Proxy Authorization specification
658          * and implementation do not allow proxy authorization
659          * control to be provided with Bind requests
660          */
661         /*
662          * if no bind took place yet, but the connection is bound
663          * and the "idassert-authcDN" (or other ID) is set, 
664          * then bind as the asserting identity and explicitly 
665          * add the proxyAuthz control to every operation with the
666          * dn bound to the connection as control value.
667          * This is done also if this is the authrizing backend,
668          * but the "override" flag is given to idassert.
669          * It allows to use SASL bind and yet proxyAuthz users
670          */
671         if ( op->o_conn != NULL &&
672                         !op->o_do_not_cache &&
673                         ( BER_BVISNULL( &lc->lc_bound_ndn ) ||
674                           ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
675         {
676                 (void)ldap_back_proxy_authz_bind( lc, op, rs );
677                 goto done;
678         }
679
680 #ifdef HAVE_CYRUS_SASL
681         if ( LDAP_BACK_CONN_ISPRIV( lc )
682                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
683         {
684                 void            *defaults = NULL;
685
686                 if ( li->li_acl_secprops != NULL ) {
687                         rc = ldap_set_option( lc->lc_ld,
688                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops);
689
690                         if ( rc != LDAP_OPT_SUCCESS ) {
691                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
692                                         "(%s,SECPROPS,\"%s\") failed!\n",
693                                         li->li_uri, li->li_acl_secprops, 0 );
694                                 goto done;
695                         }
696                 }
697
698                 defaults = lutil_sasl_defaults( lc->lc_ld,
699                                 li->li_acl_sasl_mech.bv_val,
700                                 li->li_acl_sasl_realm.bv_val,
701                                 li->li_acl_authcID.bv_val,
702                                 li->li_acl_passwd.bv_val,
703                                 NULL );
704
705                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
706                                 li->li_acl_authcDN.bv_val,
707                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
708                                 LDAP_SASL_QUIET, lutil_sasl_interact,
709                                 defaults );
710
711                 lutil_sasl_freedefs( defaults );
712
713                 rs->sr_err = slap_map_api2result( rs );
714                 if ( rs->sr_err != LDAP_SUCCESS ) {
715                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
716                         send_ldap_result( op, rs );
717
718                 } else {
719                         LDAP_BACK_CONN_ISBOUND_SET( lc );
720                 }
721                 goto done;
722         }
723 #endif /* HAVE_CYRUS_SASL */
724
725 retry:;
726         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
727                         lc->lc_bound_ndn.bv_val,
728                         LDAP_SASL_SIMPLE, &lc->lc_cred,
729                         NULL, NULL, &msgid );
730
731         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
732                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
733                         if ( dolock ) {
734                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
735                         }
736
737                         assert( lc->lc_refcnt > 0 );
738                         if ( lc->lc_refcnt == 1 ) {
739                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
740                                 lc->lc_ld = NULL;
741
742                                 /* lc here must be the regular lc, reset and ready for init */
743                                 rs->sr_err = ldap_back_prepare_conn( &lc, op, rs, sendok );
744                         }
745                         if ( dolock ) {
746                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
747                         }
748                         if ( rs->sr_err == LDAP_SUCCESS ) {
749                                 if ( retries > 0 ) {
750                                         retries--;
751                                 }
752                                 goto retry;
753                         }
754                 }
755
756                 ldap_back_freeconn( op, lc, dolock );
757                 rs->sr_err = slap_map_api2result( rs );
758
759                 return 0;
760         }
761
762         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
763         if ( rc == LDAP_SUCCESS ) {
764                 LDAP_BACK_CONN_ISBOUND_SET( lc );
765
766         } else {
767                 ldap_back_release_conn( op, rs, lc );
768         }
769
770 done:;
771         rc = LDAP_BACK_CONN_ISBOUND( lc );
772
773         return rc;
774 }
775
776 int
777 ldap_back_dobind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
778 {
779         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
780
781         return ldap_back_dobind_int( lc, op, rs, sendok, li->li_nretries, 1 );
782 }
783
784 /*
785  * ldap_back_default_rebind
786  *
787  * This is a callback used for chasing referrals using the same
788  * credentials as the original user on this session.
789  */
790 static int 
791 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
792         ber_int_t msgid, void *params )
793 {
794         ldapconn_t      *lc = (ldapconn_t *)params;
795
796 #ifdef HAVE_TLS
797         /* ... otherwise we couldn't get here */
798         assert( lc != NULL );
799
800         if ( !ldap_tls_inplace( ld ) ) {
801                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
802                                 rc;
803                 const char      *text = NULL;
804
805                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
806                         LDAP_BACK_RETRY_DEFAULT, &text );
807                 if ( rc != LDAP_SUCCESS ) {
808                         return rc;
809                 }
810         }
811 #endif /* HAVE_TLS */
812
813         /* FIXME: add checks on the URL/identity? */
814
815         return ldap_sasl_bind_s( ld, lc->lc_bound_ndn.bv_val,
816                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
817 }
818
819 int
820 ldap_back_op_result(
821                 ldapconn_t              *lc,
822                 Operation               *op,
823                 SlapReply               *rs,
824                 ber_int_t               msgid,
825                 time_t                  timeout,
826                 ldap_back_send_t        sendok )
827 {
828         char            *match = NULL;
829         LDAPMessage     *res = NULL;
830         char            *text = NULL;
831
832 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
833
834         rs->sr_text = NULL;
835         rs->sr_matched = NULL;
836
837         /* if the error recorded in the reply corresponds
838          * to a successful state, get the error from the
839          * remote server response */
840         if ( ERR_OK( rs->sr_err ) ) {
841                 int             rc;
842                 struct timeval  tv;
843
844                 if ( timeout ) {
845                         tv.tv_sec = timeout;
846                         tv.tv_usec = 0;
847
848                 } else {
849                         LDAP_BACK_TV_SET( &tv );
850                 }
851
852 retry:;
853                 /* if result parsing fails, note the failure reason */
854                 rc = ldap_result( lc->lc_ld, msgid, 1, &tv, &res );
855                 switch ( rc ) {
856                 case 0:
857                         if ( timeout ) {
858                                 (void)ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
859                                 rs->sr_err = op->o_protocol >= LDAP_VERSION3 ?
860                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OPERATIONS_ERROR;
861                                 rs->sr_text = "Operation timed out";
862                                 break;
863                         }
864
865                         LDAP_BACK_TV_SET( &tv );
866                         ldap_pvt_thread_yield();
867                         goto retry;
868
869                 case -1:
870                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
871                                         &rs->sr_err );
872                         break;
873
874
875                 /* otherwise get the result; if it is not
876                  * LDAP_SUCCESS, record it in the reply
877                  * structure (this includes 
878                  * LDAP_COMPARE_{TRUE|FALSE}) */
879                 default:
880                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
881                                         &match, &text, NULL, NULL, 1 );
882 #ifndef LDAP_NULL_IS_NULL
883                         if ( match != NULL && match[ 0 ] == '\0' ) {
884                                 ldap_memfree( match );
885                                 match = NULL;
886                         }
887                         if ( text != NULL && text[ 0 ] == '\0' ) {
888                                 ldap_memfree( text );
889                                 text = NULL;
890                         }
891 #endif /* LDAP_NULL_IS_NULL */
892                         rs->sr_text = text;
893                         if ( rc != LDAP_SUCCESS ) {
894                                 rs->sr_err = rc;
895                         }
896                 }
897         }
898
899         /* if the error in the reply structure is not
900          * LDAP_SUCCESS, try to map it from client 
901          * to server error */
902         if ( !ERR_OK( rs->sr_err ) ) {
903                 rs->sr_err = slap_map_api2result( rs );
904
905                 /* internal ops ( op->o_conn == NULL ) 
906                  * must not reply to client */
907                 if ( op->o_conn && !op->o_do_not_cache && match ) {
908
909                         /* record the (massaged) matched
910                          * DN into the reply structure */
911                         rs->sr_matched = match;
912                 }
913         }
914         if ( op->o_conn &&
915                         ( ( sendok & LDAP_BACK_SENDOK ) 
916                           || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
917         {
918                 send_ldap_result( op, rs );
919         }
920         if ( match ) {
921                 if ( rs->sr_matched != match ) {
922                         free( (char *)rs->sr_matched );
923                 }
924                 rs->sr_matched = NULL;
925                 ldap_memfree( match );
926         }
927         if ( text ) {
928                 ldap_memfree( text );
929         }
930         rs->sr_text = NULL;
931         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
932 }
933
934 /* return true if bound, false if failed */
935 int
936 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
937 {
938         int             rc = 0;
939         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
940
941         assert( lcp != NULL );
942         assert( *lcp != NULL );
943
944         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
945
946         if ( (*lcp)->lc_refcnt == 1 ) {
947                 Debug( LDAP_DEBUG_ANY,
948                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
949                         op->o_log_prefix, li->li_uri,
950                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
951                                 "" : (*lcp)->lc_bound_ndn.bv_val );
952
953                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
954                 (*lcp)->lc_ld = NULL;
955                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
956
957                 /* lc here must be the regular lc, reset and ready for init */
958                 rc = ldap_back_prepare_conn( lcp, op, rs, sendok );
959                 if ( rc != LDAP_SUCCESS ) {
960                         rc = 0;
961                         *lcp = NULL;
962
963                 } else {
964                         rc = ldap_back_dobind_int( *lcp, op, rs, sendok, 0, 0 );
965                         if ( rc == 0 ) {
966                                 *lcp = NULL;
967                         }
968                 }
969         }
970
971         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
972
973         return rc;
974 }
975
976 static int
977 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs )
978 {
979         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
980         struct berval   binddn = slap_empty_bv;
981         struct berval   bindcred = slap_empty_bv;
982         int             dobind = 0;
983         int             msgid;
984         int             rc;
985
986         /*
987          * FIXME: we need to let clients use proxyAuthz
988          * otherwise we cannot do symmetric pools of servers;
989          * we have to live with the fact that a user can
990          * authorize itself as any ID that is allowed
991          * by the authzTo directive of the "proxyauthzdn".
992          */
993         /*
994          * NOTE: current Proxy Authorization specification
995          * and implementation do not allow proxy authorization
996          * control to be provided with Bind requests
997          */
998         /*
999          * if no bind took place yet, but the connection is bound
1000          * and the "proxyauthzdn" is set, then bind as 
1001          * "proxyauthzdn" and explicitly add the proxyAuthz 
1002          * control to every operation with the dn bound 
1003          * to the connection as control value.
1004          */
1005
1006         /* bind as proxyauthzdn only if no idassert mode
1007          * is requested, or if the client's identity
1008          * is authorized */
1009         switch ( li->li_idassert_mode ) {
1010         case LDAP_BACK_IDASSERT_LEGACY:
1011                 if ( !BER_BVISNULL( &op->o_conn->c_ndn ) && !BER_BVISEMPTY( &op->o_conn->c_ndn ) ) {
1012                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1013                         {
1014                                 binddn = li->li_idassert_authcDN;
1015                                 bindcred = li->li_idassert_passwd;
1016                                 dobind = 1;
1017                         }
1018                 }
1019                 break;
1020
1021         default:
1022                 /* NOTE: rootdn can always idassert */
1023                 if ( li->li_idassert_authz && !be_isroot( op ) ) {
1024                         struct berval authcDN;
1025
1026                         if ( BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1027                                 authcDN = slap_empty_bv;
1028
1029                         } else {
1030                                 authcDN = op->o_conn->c_ndn;
1031                         }       
1032                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1033                                         &authcDN, &authcDN );
1034                         if ( rs->sr_err != LDAP_SUCCESS ) {
1035                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1036                                         send_ldap_result( op, rs );
1037                                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1038
1039                                 } else {
1040                                         rs->sr_err = LDAP_SUCCESS;
1041                                         binddn = slap_empty_bv;
1042                                         bindcred = slap_empty_bv;
1043                                         break;
1044                                 }
1045
1046                                 goto done;
1047                         }
1048                 }
1049
1050                 binddn = li->li_idassert_authcDN;
1051                 bindcred = li->li_idassert_passwd;
1052                 dobind = 1;
1053                 break;
1054         }
1055
1056         if ( dobind && li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1057 #ifdef HAVE_CYRUS_SASL
1058                 void            *defaults = NULL;
1059                 struct berval   authzID = BER_BVNULL;
1060                 int             freeauthz = 0;
1061
1062                 /* if SASL supports native authz, prepare for it */
1063                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1064                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1065                 {
1066                         switch ( li->li_idassert_mode ) {
1067                         case LDAP_BACK_IDASSERT_OTHERID:
1068                         case LDAP_BACK_IDASSERT_OTHERDN:
1069                                 authzID = li->li_idassert_authzID;
1070                                 break;
1071
1072                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1073                                 BER_BVSTR( &authzID, "dn:" );
1074                                 break;
1075
1076                         case LDAP_BACK_IDASSERT_SELF:
1077                                 if ( BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1078                                         /* connection is not authc'd, so don't idassert */
1079                                         BER_BVSTR( &authzID, "dn:" );
1080                                         break;
1081                                 }
1082                                 authzID.bv_len = STRLENOF( "dn:" ) + op->o_conn->c_ndn.bv_len;
1083                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1084                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1085                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1086                                                 op->o_conn->c_ndn.bv_val, op->o_conn->c_ndn.bv_len + 1 );
1087                                 freeauthz = 1;
1088                                 break;
1089
1090                         default:
1091                                 break;
1092                         }
1093                 }
1094
1095                 if ( li->li_idassert_secprops != NULL ) {
1096                         rs->sr_err = ldap_set_option( lc->lc_ld,
1097                                 LDAP_OPT_X_SASL_SECPROPS,
1098                                 (void *)li->li_idassert_secprops );
1099
1100                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1101                                 send_ldap_result( op, rs );
1102                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1103                                 goto done;
1104                         }
1105                 }
1106
1107                 defaults = lutil_sasl_defaults( lc->lc_ld,
1108                                 li->li_idassert_sasl_mech.bv_val,
1109                                 li->li_idassert_sasl_realm.bv_val,
1110                                 li->li_idassert_authcID.bv_val,
1111                                 li->li_idassert_passwd.bv_val,
1112                                 authzID.bv_val );
1113
1114                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn.bv_val,
1115                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
1116                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1117                                 defaults );
1118
1119                 rs->sr_err = slap_map_api2result( rs );
1120                 if ( rs->sr_err != LDAP_SUCCESS ) {
1121                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1122                         send_ldap_result( op, rs );
1123
1124                 } else {
1125                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1126                 }
1127
1128                 lutil_sasl_freedefs( defaults );
1129                 if ( freeauthz ) {
1130                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1131                 }
1132
1133                 goto done;
1134 #endif /* HAVE_CYRUS_SASL */
1135         }
1136
1137         switch ( li->li_idassert_authmethod ) {
1138         case LDAP_AUTH_NONE:
1139                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1140                 goto done;
1141
1142         case LDAP_AUTH_SIMPLE:
1143                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1144                                 binddn.bv_val, LDAP_SASL_SIMPLE,
1145                                 &bindcred, NULL, NULL, &msgid );
1146                 break;
1147
1148         default:
1149                 /* unsupported! */
1150                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1151                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1152                 send_ldap_result( op, rs );
1153                 goto done;
1154         }
1155
1156         rc = ldap_back_op_result( lc, op, rs, msgid, 0, LDAP_BACK_SENDERR );
1157         if ( rc == LDAP_SUCCESS ) {
1158                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1159         }
1160 done:;
1161         return LDAP_BACK_CONN_ISBOUND( lc );
1162 }
1163
1164 /*
1165  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
1166  * to existing server-side controls if required; if not,
1167  * the existing server-side controls are placed in *pctrls.
1168  * The caller, after using the controls in client API 
1169  * operations, if ( *pctrls != op->o_ctrls ), should
1170  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
1171  * The function returns success if the control could
1172  * be added if required, or if it did nothing; in the future,
1173  * it might return some error if it failed.
1174  * 
1175  * if no bind took place yet, but the connection is bound
1176  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
1177  * and explicitly add proxyAuthz the control to every operation
1178  * with the dn bound to the connection as control value.
1179  *
1180  * If no server-side controls are defined for the operation,
1181  * simply add the proxyAuthz control; otherwise, if the
1182  * proxyAuthz control is not already set, add it as
1183  * the first one
1184  *
1185  * FIXME: is controls order significant for security?
1186  * ANSWER: controls ordering and interoperability
1187  * must be indicated by the specs of each control; if none
1188  * is specified, the order is irrelevant.
1189  */
1190 int
1191 ldap_back_proxy_authz_ctrl(
1192                 ldapconn_t      *lc,
1193                 Operation       *op,
1194                 SlapReply       *rs,
1195                 LDAPControl     ***pctrls )
1196 {
1197         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
1198         LDAPControl     **ctrls = NULL;
1199         int             i = 0,
1200                         mode;
1201         struct berval   assertedID;
1202
1203         *pctrls = NULL;
1204
1205         rs->sr_err = LDAP_SUCCESS;
1206
1207         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
1208          * but if it is not set this test fails.  We need a different
1209          * means to detect if idassert is enabled */
1210         if ( ( BER_BVISNULL( &li->li_idassert_authcID ) || BER_BVISEMPTY( &li->li_idassert_authcID ) )
1211                         && ( BER_BVISNULL( &li->li_idassert_authcDN ) || BER_BVISEMPTY( &li->li_idassert_authcDN ) ) )
1212         {
1213                 goto done;
1214         }
1215
1216         if ( !op->o_conn || op->o_do_not_cache || be_isroot( op ) ) {
1217                 goto done;
1218         }
1219
1220         if ( li->li_idassert_mode == LDAP_BACK_IDASSERT_LEGACY ) {
1221                 if ( op->o_proxy_authz ) {
1222                         /*
1223                          * FIXME: we do not want to perform proxyAuthz
1224                          * on behalf of the client, because this would
1225                          * be performed with "proxyauthzdn" privileges.
1226                          *
1227                          * This might actually be too strict, since
1228                          * the "proxyauthzdn" authzTo, and each entry's
1229                          * authzFrom attributes may be crafted
1230                          * to avoid unwanted proxyAuthz to take place.
1231                          */
1232 #if 0
1233                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1234                         rs->sr_text = "proxyAuthz not allowed within namingContext";
1235 #endif
1236                         goto done;
1237                 }
1238
1239                 if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
1240                         goto done;
1241                 }
1242
1243                 if ( BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1244                         goto done;
1245                 }
1246
1247                 if ( BER_BVISNULL( &li->li_idassert_authcDN ) ) {
1248                         goto done;
1249                 }
1250
1251         } else if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1252                 if ( ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ )
1253                                 /* && ( !BER_BVISNULL( &op->o_conn->c_ndn )
1254                                         || LDAP_BACK_CONN_ISBOUND( lc ) ) */ )
1255                 {
1256                         /* already asserted in SASL via native authz */
1257                         /* NOTE: the test on lc->lc_bound is used to trap
1258                          * native authorization of anonymous users,
1259                          * since in that case op->o_conn->c_ndn is NULL */
1260                         goto done;
1261                 }
1262
1263         } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1264                 int             rc;
1265                 struct berval authcDN;
1266
1267                 if ( BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1268                         authcDN = slap_empty_bv;
1269                 } else {
1270                         authcDN = op->o_conn->c_ndn;
1271                 }
1272                 rc = slap_sasl_matches( op, li->li_idassert_authz,
1273                                 &authcDN, & authcDN );
1274                 if ( rc != LDAP_SUCCESS ) {
1275                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE )
1276                         {
1277                                 /* op->o_conn->c_ndn is not authorized
1278                                  * to use idassert */
1279                                 return rc;
1280                         }
1281                         return rs->sr_err;
1282                 }
1283         }
1284
1285         if ( op->o_proxy_authz ) {
1286                 /*
1287                  * FIXME: we can:
1288                  * 1) ignore the already set proxyAuthz control
1289                  * 2) leave it in place, and don't set ours
1290                  * 3) add both
1291                  * 4) reject the operation
1292                  *
1293                  * option (4) is very drastic
1294                  * option (3) will make the remote server reject
1295                  * the operation, thus being equivalent to (4)
1296                  * option (2) will likely break the idassert
1297                  * assumptions, so we cannot accept it;
1298                  * option (1) means that we are contradicting
1299                  * the client's reques.
1300                  *
1301                  * I think (4) is the only correct choice.
1302                  */
1303                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1304                 rs->sr_text = "proxyAuthz not allowed within namingContext";
1305         }
1306
1307         if ( op->o_is_auth_check ) {
1308                 mode = LDAP_BACK_IDASSERT_NOASSERT;
1309
1310         } else {
1311                 mode = li->li_idassert_mode;
1312         }
1313
1314         switch ( mode ) {
1315         case LDAP_BACK_IDASSERT_LEGACY:
1316         case LDAP_BACK_IDASSERT_SELF:
1317                 /* original behavior:
1318                  * assert the client's identity */
1319                 if ( BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1320                         assertedID = slap_empty_bv;
1321                 } else {
1322                         assertedID = op->o_conn->c_ndn;
1323                 }
1324                 break;
1325
1326         case LDAP_BACK_IDASSERT_ANONYMOUS:
1327                 /* assert "anonymous" */
1328                 assertedID = slap_empty_bv;
1329                 break;
1330
1331         case LDAP_BACK_IDASSERT_NOASSERT:
1332                 /* don't assert; bind as proxyauthzdn */
1333                 goto done;
1334
1335         case LDAP_BACK_IDASSERT_OTHERID:
1336         case LDAP_BACK_IDASSERT_OTHERDN:
1337                 /* assert idassert DN */
1338                 assertedID = li->li_idassert_authzID;
1339                 break;
1340
1341         default:
1342                 assert( 0 );
1343         }
1344
1345         if ( BER_BVISNULL( &assertedID ) ) {
1346                 assertedID = slap_empty_bv;
1347         }
1348
1349         if ( op->o_ctrls ) {
1350                 for ( i = 0; op->o_ctrls[ i ]; i++ )
1351                         /* just count ctrls */ ;
1352         }
1353
1354         ctrls = ch_malloc( sizeof( LDAPControl * ) * (i + 2) );
1355         ctrls[ 0 ] = ch_malloc( sizeof( LDAPControl ) );
1356         
1357         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1358         ctrls[ 0 ]->ldctl_iscritical = 1;
1359
1360         switch ( li->li_idassert_mode ) {
1361         /* already in u:ID or dn:DN form */
1362         case LDAP_BACK_IDASSERT_OTHERID:
1363         case LDAP_BACK_IDASSERT_OTHERDN:
1364                 ber_dupbv( &ctrls[ 0 ]->ldctl_value, &assertedID );
1365                 break;
1366
1367         /* needs the dn: prefix */
1368         default:
1369                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
1370                 ctrls[ 0 ]->ldctl_value.bv_val = ch_malloc( ctrls[ 0 ]->ldctl_value.bv_len + 1 );
1371                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
1372                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
1373                                 assertedID.bv_val, assertedID.bv_len + 1 );
1374                 break;
1375         }
1376
1377         if ( op->o_ctrls ) {
1378                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1379                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
1380                 }
1381         }
1382         ctrls[ i + 1 ] = NULL;
1383
1384 done:;
1385         if ( ctrls == NULL ) {
1386                 ctrls = op->o_ctrls;
1387         }
1388
1389         *pctrls = ctrls;
1390         
1391         return rs->sr_err;
1392 }
1393
1394 int
1395 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
1396 {
1397         LDAPControl     **ctrls = *pctrls;
1398
1399         /* we assume that the first control is the proxyAuthz
1400          * added by back-ldap, so it's the only one we explicitly 
1401          * free */
1402         if ( ctrls && ctrls != op->o_ctrls ) {
1403                 assert( ctrls[ 0 ] != NULL );
1404
1405                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
1406                         free( ctrls[ 0 ]->ldctl_value.bv_val );
1407                 }
1408
1409                 free( ctrls[ 0 ] );
1410                 free( ctrls );
1411         } 
1412
1413         *pctrls = NULL;
1414
1415         return 0;
1416 }