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