]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
ed478507eff9bff3c01a0dd49beacc998b8be78d
[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 #ifndef LDAP_NULL_IS_NULL
953                         if ( match != NULL && match[ 0 ] == '\0' ) {
954                                 ldap_memfree( match );
955                                 match = NULL;
956                         }
957                         if ( text != NULL && text[ 0 ] == '\0' ) {
958                                 ldap_memfree( text );
959                                 text = NULL;
960                         }
961 #endif /* LDAP_NULL_IS_NULL */
962                         rs->sr_text = text;
963                         if ( rc != LDAP_SUCCESS ) {
964                                 rs->sr_err = rc;
965                         }
966                 }
967         }
968
969         /* if the error in the reply structure is not
970          * LDAP_SUCCESS, try to map it from client 
971          * to server error */
972         if ( !ERR_OK( rs->sr_err ) ) {
973                 rs->sr_err = slap_map_api2result( rs );
974
975                 /* internal ops ( op->o_conn == NULL ) 
976                  * must not reply to client */
977                 if ( op->o_conn && !op->o_do_not_cache && match ) {
978
979                         /* record the (massaged) matched
980                          * DN into the reply structure */
981                         rs->sr_matched = match;
982                 }
983         }
984         if ( op->o_conn &&
985                         ( ( sendok & LDAP_BACK_SENDOK ) 
986                           || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
987         {
988                 send_ldap_result( op, rs );
989         }
990         if ( match ) {
991                 if ( rs->sr_matched != match ) {
992                         free( (char *)rs->sr_matched );
993                 }
994                 rs->sr_matched = NULL;
995                 ldap_memfree( match );
996         }
997         if ( text ) {
998                 ldap_memfree( text );
999         }
1000         rs->sr_text = NULL;
1001         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
1002 }
1003
1004 /* return true if bound, false if failed */
1005 int
1006 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1007 {
1008         int             rc = 0;
1009         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1010
1011         assert( lcp != NULL );
1012         assert( *lcp != NULL );
1013
1014         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
1015
1016         if ( (*lcp)->lc_refcnt == 1 ) {
1017                 Debug( LDAP_DEBUG_ANY,
1018                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
1019                         op->o_log_prefix, li->li_uri,
1020                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
1021                                 "" : (*lcp)->lc_bound_ndn.bv_val );
1022
1023                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
1024                 (*lcp)->lc_ld = NULL;
1025                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
1026
1027                 /* lc here must be the regular lc, reset and ready for init */
1028                 rc = ldap_back_prepare_conn( lcp, op, rs, sendok );
1029                 if ( rc != LDAP_SUCCESS ) {
1030                         rc = 0;
1031                         *lcp = NULL;
1032
1033                 } else {
1034                         rc = ldap_back_dobind_int( *lcp, op, rs, sendok, 0, 0 );
1035                         if ( rc == 0 ) {
1036                                 *lcp = NULL;
1037                         }
1038                 }
1039         }
1040
1041         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1042
1043         return rc;
1044 }
1045
1046 static int
1047 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1048 {
1049         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1050         struct berval   binddn = slap_empty_bv;
1051         struct berval   bindcred = slap_empty_bv;
1052         struct berval   ndn;
1053         int             dobind = 0;
1054         int             msgid;
1055         int             rc;
1056
1057         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1058                 ndn = op->o_conn->c_ndn;
1059
1060         } else {
1061                 ndn = op->o_ndn;
1062         }
1063
1064         /*
1065          * FIXME: we need to let clients use proxyAuthz
1066          * otherwise we cannot do symmetric pools of servers;
1067          * we have to live with the fact that a user can
1068          * authorize itself as any ID that is allowed
1069          * by the authzTo directive of the "proxyauthzdn".
1070          */
1071         /*
1072          * NOTE: current Proxy Authorization specification
1073          * and implementation do not allow proxy authorization
1074          * control to be provided with Bind requests
1075          */
1076         /*
1077          * if no bind took place yet, but the connection is bound
1078          * and the "proxyauthzdn" is set, then bind as 
1079          * "proxyauthzdn" and explicitly add the proxyAuthz 
1080          * control to every operation with the dn bound 
1081          * to the connection as control value.
1082          */
1083
1084         /* bind as proxyauthzdn only if no idassert mode
1085          * is requested, or if the client's identity
1086          * is authorized */
1087         switch ( li->li_idassert_mode ) {
1088         case LDAP_BACK_IDASSERT_LEGACY:
1089                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1090                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1091                         {
1092                                 binddn = li->li_idassert_authcDN;
1093                                 bindcred = li->li_idassert_passwd;
1094                                 dobind = 1;
1095                         }
1096                 }
1097                 break;
1098
1099         default:
1100                 /* NOTE: rootdn can always idassert */
1101                 if ( BER_BVISNULL( &ndn ) && li->li_idassert_authz == NULL ) {
1102                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1103                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1104                                 if ( sendok & LDAP_BACK_SENDERR ) {
1105                                         send_ldap_result( op, rs );
1106                                 }
1107                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1108
1109                         } else {
1110                                 rs->sr_err = LDAP_SUCCESS;
1111                                 binddn = slap_empty_bv;
1112                                 bindcred = slap_empty_bv;
1113                                 break;
1114                         }
1115
1116                         goto done;
1117
1118                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1119                         struct berval authcDN;
1120
1121                         if ( BER_BVISNULL( &ndn ) ) {
1122                                 authcDN = slap_empty_bv;
1123
1124                         } else {
1125                                 authcDN = ndn;
1126                         }       
1127                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1128                                         &authcDN, &authcDN );
1129                         if ( rs->sr_err != LDAP_SUCCESS ) {
1130                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1131                                         if ( sendok & LDAP_BACK_SENDERR ) {
1132                                                 send_ldap_result( op, rs );
1133                                         }
1134                                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1135
1136                                 } else {
1137                                         rs->sr_err = LDAP_SUCCESS;
1138                                         binddn = slap_empty_bv;
1139                                         bindcred = slap_empty_bv;
1140                                         break;
1141                                 }
1142
1143                                 goto done;
1144                         }
1145                 }
1146
1147                 binddn = li->li_idassert_authcDN;
1148                 bindcred = li->li_idassert_passwd;
1149                 dobind = 1;
1150                 break;
1151         }
1152
1153         if ( dobind && li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1154 #ifdef HAVE_CYRUS_SASL
1155                 void            *defaults = NULL;
1156                 struct berval   authzID = BER_BVNULL;
1157                 int             freeauthz = 0;
1158
1159                 /* if SASL supports native authz, prepare for it */
1160                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1161                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1162                 {
1163                         switch ( li->li_idassert_mode ) {
1164                         case LDAP_BACK_IDASSERT_OTHERID:
1165                         case LDAP_BACK_IDASSERT_OTHERDN:
1166                                 authzID = li->li_idassert_authzID;
1167                                 break;
1168
1169                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1170                                 BER_BVSTR( &authzID, "dn:" );
1171                                 break;
1172
1173                         case LDAP_BACK_IDASSERT_SELF:
1174                                 if ( BER_BVISNULL( &ndn ) ) {
1175                                         /* connection is not authc'd, so don't idassert */
1176                                         BER_BVSTR( &authzID, "dn:" );
1177                                         break;
1178                                 }
1179                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1180                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1181                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1182                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1183                                                 ndn.bv_val, ndn.bv_len + 1 );
1184                                 freeauthz = 1;
1185                                 break;
1186
1187                         default:
1188                                 break;
1189                         }
1190                 }
1191
1192                 if ( li->li_idassert_secprops != NULL ) {
1193                         rs->sr_err = ldap_set_option( lc->lc_ld,
1194                                 LDAP_OPT_X_SASL_SECPROPS,
1195                                 (void *)li->li_idassert_secprops );
1196
1197                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1198                                 rs->sr_err = LDAP_OTHER;
1199                                 if ( sendok & LDAP_BACK_SENDERR ) {
1200                                         send_ldap_result( op, rs );
1201                                 }
1202                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1203                                 goto done;
1204                         }
1205                 }
1206
1207                 defaults = lutil_sasl_defaults( lc->lc_ld,
1208                                 li->li_idassert_sasl_mech.bv_val,
1209                                 li->li_idassert_sasl_realm.bv_val,
1210                                 li->li_idassert_authcID.bv_val,
1211                                 li->li_idassert_passwd.bv_val,
1212                                 authzID.bv_val );
1213
1214                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn.bv_val,
1215                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
1216                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1217                                 defaults );
1218
1219                 rs->sr_err = slap_map_api2result( rs );
1220                 if ( rs->sr_err != LDAP_SUCCESS ) {
1221                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1222                         if ( sendok & LDAP_BACK_SENDERR ) {
1223                                 send_ldap_result( op, rs );
1224                         }
1225
1226                 } else {
1227                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1228                 }
1229
1230                 lutil_sasl_freedefs( defaults );
1231                 if ( freeauthz ) {
1232                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1233                 }
1234
1235                 goto done;
1236 #endif /* HAVE_CYRUS_SASL */
1237         }
1238
1239         switch ( li->li_idassert_authmethod ) {
1240         case LDAP_AUTH_NONE:
1241                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1242                 goto done;
1243
1244         case LDAP_AUTH_SIMPLE:
1245                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1246                                 binddn.bv_val, LDAP_SASL_SIMPLE,
1247                                 &bindcred, NULL, NULL, &msgid );
1248                 break;
1249
1250         default:
1251                 /* unsupported! */
1252                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1253                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1254                 if ( sendok & LDAP_BACK_SENDERR ) {
1255                         send_ldap_result( op, rs );
1256                 }
1257                 goto done;
1258         }
1259
1260         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
1261         if ( rc == LDAP_SUCCESS ) {
1262                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1263         }
1264 done:;
1265         return LDAP_BACK_CONN_ISBOUND( lc );
1266 }
1267
1268 /*
1269  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
1270  * to existing server-side controls if required; if not,
1271  * the existing server-side controls are placed in *pctrls.
1272  * The caller, after using the controls in client API 
1273  * operations, if ( *pctrls != op->o_ctrls ), should
1274  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
1275  * The function returns success if the control could
1276  * be added if required, or if it did nothing; in the future,
1277  * it might return some error if it failed.
1278  * 
1279  * if no bind took place yet, but the connection is bound
1280  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
1281  * and explicitly add proxyAuthz the control to every operation
1282  * with the dn bound to the connection as control value.
1283  *
1284  * If no server-side controls are defined for the operation,
1285  * simply add the proxyAuthz control; otherwise, if the
1286  * proxyAuthz control is not already set, add it as
1287  * the first one
1288  *
1289  * FIXME: is controls order significant for security?
1290  * ANSWER: controls ordering and interoperability
1291  * must be indicated by the specs of each control; if none
1292  * is specified, the order is irrelevant.
1293  */
1294 int
1295 ldap_back_proxy_authz_ctrl(
1296                 ldapconn_t      *lc,
1297                 Operation       *op,
1298                 SlapReply       *rs,
1299                 LDAPControl     ***pctrls )
1300 {
1301         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
1302         LDAPControl     **ctrls = NULL;
1303         int             i = 0,
1304                         mode;
1305         struct berval   assertedID,
1306                         ndn;
1307
1308         *pctrls = NULL;
1309
1310         rs->sr_err = LDAP_SUCCESS;
1311
1312         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
1313          * but if it is not set this test fails.  We need a different
1314          * means to detect if idassert is enabled */
1315         if ( ( BER_BVISNULL( &li->li_idassert_authcID ) || BER_BVISEMPTY( &li->li_idassert_authcID ) )
1316                         && ( BER_BVISNULL( &li->li_idassert_authcDN ) || BER_BVISEMPTY( &li->li_idassert_authcDN ) ) )
1317         {
1318                 goto done;
1319         }
1320
1321         if ( !op->o_conn || op->o_do_not_cache || be_isroot( op ) ) {
1322                 goto done;
1323         }
1324
1325         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1326                 ndn = op->o_conn->c_ndn;
1327
1328         } else {
1329                 ndn = op->o_ndn;
1330         }
1331
1332         if ( li->li_idassert_mode == LDAP_BACK_IDASSERT_LEGACY ) {
1333                 if ( op->o_proxy_authz ) {
1334                         /*
1335                          * FIXME: we do not want to perform proxyAuthz
1336                          * on behalf of the client, because this would
1337                          * be performed with "proxyauthzdn" privileges.
1338                          *
1339                          * This might actually be too strict, since
1340                          * the "proxyauthzdn" authzTo, and each entry's
1341                          * authzFrom attributes may be crafted
1342                          * to avoid unwanted proxyAuthz to take place.
1343                          */
1344 #if 0
1345                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1346                         rs->sr_text = "proxyAuthz not allowed within namingContext";
1347 #endif
1348                         goto done;
1349                 }
1350
1351                 if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
1352                         goto done;
1353                 }
1354
1355                 if ( BER_BVISNULL( &ndn ) ) {
1356                         goto done;
1357                 }
1358
1359                 if ( BER_BVISNULL( &li->li_idassert_authcDN ) ) {
1360                         goto done;
1361                 }
1362
1363         } else if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1364                 if ( ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ )
1365                                 /* && ( !BER_BVISNULL( &ndn )
1366                                         || LDAP_BACK_CONN_ISBOUND( lc ) ) */ )
1367                 {
1368                         /* already asserted in SASL via native authz */
1369                         /* NOTE: the test on lc->lc_bound is used to trap
1370                          * native authorization of anonymous users,
1371                          * since in that case ndn is NULL */
1372                         goto done;
1373                 }
1374
1375         } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1376                 int             rc;
1377                 struct berval authcDN;
1378
1379                 if ( BER_BVISNULL( &ndn ) ) {
1380                         authcDN = slap_empty_bv;
1381                 } else {
1382                         authcDN = ndn;
1383                 }
1384                 rc = slap_sasl_matches( op, li->li_idassert_authz,
1385                                 &authcDN, & authcDN );
1386                 if ( rc != LDAP_SUCCESS ) {
1387                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE )
1388                         {
1389                                 /* ndn is not authorized
1390                                  * to use idassert */
1391                                 return rc;
1392                         }
1393                         return rs->sr_err;
1394                 }
1395         }
1396
1397         if ( op->o_proxy_authz ) {
1398                 /*
1399                  * FIXME: we can:
1400                  * 1) ignore the already set proxyAuthz control
1401                  * 2) leave it in place, and don't set ours
1402                  * 3) add both
1403                  * 4) reject the operation
1404                  *
1405                  * option (4) is very drastic
1406                  * option (3) will make the remote server reject
1407                  * the operation, thus being equivalent to (4)
1408                  * option (2) will likely break the idassert
1409                  * assumptions, so we cannot accept it;
1410                  * option (1) means that we are contradicting
1411                  * the client's reques.
1412                  *
1413                  * I think (4) is the only correct choice.
1414                  */
1415                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1416                 rs->sr_text = "proxyAuthz not allowed within namingContext";
1417         }
1418
1419         if ( op->o_is_auth_check ) {
1420                 mode = LDAP_BACK_IDASSERT_NOASSERT;
1421
1422         } else {
1423                 mode = li->li_idassert_mode;
1424         }
1425
1426         switch ( mode ) {
1427         case LDAP_BACK_IDASSERT_SELF:
1428                 if ( BER_BVISNULL( &ndn ) ) {
1429                         goto done;
1430                 }
1431                 assertedID = ndn;
1432                 break;
1433
1434         case LDAP_BACK_IDASSERT_LEGACY:
1435                 /* original behavior:
1436                  * assert the client's identity */
1437                 if ( BER_BVISNULL( &ndn ) ) {
1438                         assertedID = slap_empty_bv;
1439                 } else {
1440                         assertedID = ndn;
1441                 }
1442                 break;
1443
1444         case LDAP_BACK_IDASSERT_ANONYMOUS:
1445                 /* assert "anonymous" */
1446                 assertedID = slap_empty_bv;
1447                 break;
1448
1449         case LDAP_BACK_IDASSERT_NOASSERT:
1450                 /* don't assert; bind as proxyauthzdn */
1451                 goto done;
1452
1453         case LDAP_BACK_IDASSERT_OTHERID:
1454         case LDAP_BACK_IDASSERT_OTHERDN:
1455                 /* assert idassert DN */
1456                 assertedID = li->li_idassert_authzID;
1457                 break;
1458
1459         default:
1460                 assert( 0 );
1461         }
1462
1463         if ( BER_BVISNULL( &assertedID ) ) {
1464                 assertedID = slap_empty_bv;
1465         }
1466
1467         if ( op->o_ctrls ) {
1468                 for ( i = 0; op->o_ctrls[ i ]; i++ )
1469                         /* just count ctrls */ ;
1470         }
1471
1472         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
1473                         op->o_tmpmemctx );
1474         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
1475         
1476         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1477         ctrls[ 0 ]->ldctl_iscritical = 1;
1478
1479         switch ( li->li_idassert_mode ) {
1480         /* already in u:ID or dn:DN form */
1481         case LDAP_BACK_IDASSERT_OTHERID:
1482         case LDAP_BACK_IDASSERT_OTHERDN:
1483                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
1484                 break;
1485
1486         /* needs the dn: prefix */
1487         default:
1488                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
1489                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
1490                                 op->o_tmpmemctx );
1491                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
1492                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
1493                                 assertedID.bv_val, assertedID.bv_len + 1 );
1494                 break;
1495         }
1496
1497         if ( op->o_ctrls ) {
1498                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1499                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
1500                 }
1501         }
1502         ctrls[ i + 1 ] = NULL;
1503
1504 done:;
1505         if ( ctrls == NULL ) {
1506                 ctrls = op->o_ctrls;
1507         }
1508
1509         *pctrls = ctrls;
1510         
1511         return rs->sr_err;
1512 }
1513
1514 int
1515 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
1516 {
1517         LDAPControl     **ctrls = *pctrls;
1518
1519         /* we assume that the first control is the proxyAuthz
1520          * added by back-ldap, so it's the only one we explicitly 
1521          * free */
1522         if ( ctrls && ctrls != op->o_ctrls ) {
1523                 assert( ctrls[ 0 ] != NULL );
1524
1525                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
1526                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
1527                 }
1528
1529                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
1530         } 
1531
1532         *pctrls = NULL;
1533
1534         return 0;
1535 }