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