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