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