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