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