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