]> git.sur5r.net Git - openldap/blob - servers/slapd/back-ldap/bind.c
address ITS#4332; might remove dynamicObject counting
[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-2006 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/errno.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
31
32 #define AVL_INTERNAL
33 #include "slap.h"
34 #include "back-ldap.h"
35
36 #include <lutil_ldap.h>
37
38 #define PRINT_CONNTREE 0
39
40 static LDAP_REBIND_PROC ldap_back_default_rebind;
41
42 LDAP_REBIND_PROC        *ldap_back_rebind_f = ldap_back_default_rebind;
43
44 static int
45 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok );
46
47 static int
48 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok );
49
50 int
51 ldap_back_bind( Operation *op, SlapReply *rs )
52 {
53         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
54         ldapconn_t      *lc;
55
56         int rc = 0;
57         ber_int_t msgid;
58
59         lc = ldap_back_getconn( op, rs, LDAP_BACK_BIND_SERR );
60         if ( !lc ) {
61                 return rs->sr_err;
62         }
63
64         if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
65                 ch_free( lc->lc_bound_ndn.bv_val );
66                 BER_BVZERO( &lc->lc_bound_ndn );
67         }
68         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
69
70         /* method is always LDAP_AUTH_SIMPLE if we got here */
71         rs->sr_err = ldap_sasl_bind( lc->lc_ld, op->o_req_dn.bv_val,
72                         LDAP_SASL_SIMPLE,
73                         &op->orb_cred, op->o_ctrls, NULL, &msgid );
74         rc = ldap_back_op_result( lc, op, rs, msgid, 0, LDAP_BACK_SENDERR );
75
76         if ( rc == LDAP_SUCCESS ) {
77                 /* If defined, proxyAuthz will be used also when
78                  * back-ldap is the authorizing backend; for this
79                  * purpose, a successful bind is followed by a
80                  * bind with the configured identity assertion */
81                 /* NOTE: use with care */
82                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) {
83                         ldap_back_proxy_authz_bind( lc, op, rs, LDAP_BACK_SENDERR );
84                         if ( !LDAP_BACK_CONN_ISBOUND( lc ) ) {
85                                 rc = 1;
86                                 goto done;
87                         }
88                 }
89
90                 LDAP_BACK_CONN_ISBOUND_SET( lc );
91                 ber_dupbv( &lc->lc_bound_ndn, &op->o_req_ndn );
92
93                 if ( LDAP_BACK_SAVECRED( li ) ) {
94                         if ( !BER_BVISNULL( &lc->lc_cred ) ) {
95                                 memset( lc->lc_cred.bv_val, 0,
96                                                 lc->lc_cred.bv_len );
97                         }
98                         ber_bvreplace( &lc->lc_cred, &op->orb_cred );
99                         ldap_set_rebind_proc( lc->lc_ld, ldap_back_rebind_f, lc );
100                 }
101         }
102 done:;
103
104         /* must re-insert if local DN changed as result of bind */
105         if ( LDAP_BACK_CONN_ISBOUND( lc )
106                 && !dn_match( &op->o_req_ndn, &lc->lc_local_ndn ) )
107         {
108                 int             lerr;
109
110                 /* wait for all other ops to release the connection */
111 retry_lock:;
112                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
113                 if ( lc->lc_refcnt > 1 ) {
114                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
115                         ldap_pvt_thread_yield();
116                         goto retry_lock;
117                 }
118
119                 assert( lc->lc_refcnt == 1 );
120                 lc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
121                                 ldap_back_conn_cmp );
122                 assert( lc != NULL );
123
124                 ber_bvreplace( &lc->lc_local_ndn, &op->o_req_ndn );
125                 lerr = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
126                         ldap_back_conn_cmp, ldap_back_conn_dup );
127                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
128                 if ( lerr == -1 ) {
129                         /* we can do this because lc_refcnt == 1 */
130                         ldap_back_conn_free( lc );
131                         lc = NULL;
132                 }
133         }
134
135         if ( lc != NULL ) {
136                 ldap_back_release_conn( op, rs, lc );
137         }
138
139         return( rc );
140 }
141
142 /*
143  * ldap_back_conn_cmp
144  *
145  * compares two ldapconn_t based on the value of the conn pointer;
146  * used by avl stuff
147  */
148 int
149 ldap_back_conn_cmp( const void *c1, const void *c2 )
150 {
151         const ldapconn_t        *lc1 = (const ldapconn_t *)c1;
152         const ldapconn_t        *lc2 = (const ldapconn_t *)c2;
153         int rc;
154
155         /* If local DNs don't match, it is definitely not a match */
156         rc = ber_bvcmp( &lc1->lc_local_ndn, &lc2->lc_local_ndn );
157         if ( rc ) {
158                 return rc;
159         }
160
161         /* For shared sessions, conn is NULL. Only explicitly
162          * bound sessions will have non-NULL conn.
163          */
164         return SLAP_PTRCMP( lc1->lc_conn, lc2->lc_conn );
165 }
166
167 /*
168  * ldap_back_conn_dup
169  *
170  * returns -1 in case a duplicate ldapconn_t has been inserted;
171  * used by avl stuff
172  */
173 int
174 ldap_back_conn_dup( void *c1, void *c2 )
175 {
176         ldapconn_t      *lc1 = (ldapconn_t *)c1;
177         ldapconn_t      *lc2 = (ldapconn_t *)c2;
178
179         /* Cannot have more than one shared session with same DN */
180         if ( dn_match( &lc1->lc_local_ndn, &lc2->lc_local_ndn ) &&
181                         lc1->lc_conn == lc2->lc_conn )
182         {
183                 return -1;
184         }
185                 
186         return 0;
187 }
188
189 #if PRINT_CONNTREE > 0
190 static void
191 ravl_print( Avlnode *root, int depth )
192 {
193         int             i;
194         ldapconn_t      *lc;
195         
196         if ( root == 0 ) {
197                 return;
198         }
199         
200         ravl_print( root->avl_right, depth+1 );
201         
202         for ( i = 0; i < depth; i++ ) {
203                 printf( "   " );
204         }
205
206         lc = root->avl_data;
207         printf( "lc(%lx) local(%s) conn(%lx) %d\n",
208                         lc, lc->lc_local_ndn.bv_val, lc->lc_conn, root->avl_bf );
209         
210         ravl_print( root->avl_left, depth+1 );
211 }
212
213 static void
214 myprint( Avlnode *root )
215 {
216         printf( "********\n" );
217         
218         if ( root == 0 ) {
219                 printf( "\tNULL\n" );
220
221         } else {
222                 ravl_print( root, 0 );
223         }
224         
225         printf( "********\n" );
226 }
227 #endif /* PRINT_CONNTREE */
228
229 int
230 ldap_back_freeconn( Operation *op, ldapconn_t *lc, int dolock )
231 {
232         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
233
234         if ( dolock ) {
235                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
236         }
237
238         assert( lc->lc_refcnt > 0 );
239         if ( --lc->lc_refcnt == 0 ) {
240                 lc = avl_delete( &li->li_conninfo.lai_tree, (caddr_t)lc,
241                                 ldap_back_conn_cmp );
242                 assert( lc != NULL );
243
244                 ldap_back_conn_free( (void *)lc );
245         }
246
247         if ( dolock ) {
248                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
249         }
250
251         return 0;
252 }
253
254 #ifdef HAVE_TLS
255 static int
256 ldap_back_start_tls(
257         LDAP            *ld,
258         int             protocol,
259         int             *is_tls,
260         const char      *url,
261         unsigned        flags,
262         int             retries,
263         const char      **text )
264 {
265         int             rc = LDAP_SUCCESS;
266         ldapinfo_t      dummy;
267
268         /* this is ridiculous... */
269         dummy.li_flags = flags;
270
271         /* start TLS ("tls-[try-]{start,propagate}" statements) */
272         if ( ( LDAP_BACK_USE_TLS( &dummy ) || ( *is_tls && LDAP_BACK_PROPAGATE_TLS( &dummy ) ) )
273                                 && !ldap_is_ldaps_url( 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                 if ( protocol == 0 ) {
283                         ldap_get_option( ld, LDAP_OPT_PROTOCOL_VERSION,
284                                         (void *)&protocol );
285                 }
286
287                 if ( protocol < LDAP_VERSION3 ) {
288                         protocol = LDAP_VERSION3;
289                         /* Set LDAP version */
290                         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION,
291                                         (const void *)&protocol );
292                 }
293
294                 rc = ldap_start_tls( ld, NULL, NULL, &msgid );
295                 if ( rc == LDAP_SUCCESS ) {
296                         LDAPMessage     *res = NULL;
297                         struct timeval  tv;
298
299                         LDAP_BACK_TV_SET( &tv );
300
301 retry:;
302                         rc = ldap_result( ld, msgid, LDAP_MSG_ALL, &tv, &res );
303                         if ( rc < 0 ) {
304                                 rc = LDAP_UNAVAILABLE;
305
306                         } else if ( rc == 0 ) {
307                                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
308                                         ldap_pvt_thread_yield();
309                                         if ( retries > 0 ) {
310                                                 retries--;
311                                         }
312                                         LDAP_BACK_TV_SET( &tv );
313                                         goto retry;
314                                 }
315                                 rc = LDAP_UNAVAILABLE;
316
317                         } else if ( rc == LDAP_RES_EXTENDED ) {
318                                 struct berval   *data = NULL;
319
320                                 rc = ldap_parse_extended_result( ld, res,
321                                                 NULL, &data, 0 );
322                                 if ( rc == LDAP_SUCCESS ) {
323                                         int err;
324                                         rc = ldap_parse_result( ld, res, &err,
325                                                 NULL, NULL, NULL, NULL, 1 );
326                                         if ( rc == LDAP_SUCCESS ) {
327                                                 rc = err;
328                                         }
329                                         res = NULL;
330                                         
331                                         /* FIXME: in case a referral 
332                                          * is returned, should we try
333                                          * using it instead of the 
334                                          * configured URI? */
335                                         if ( rc == LDAP_SUCCESS ) {
336                                                 rc = ldap_install_tls( ld );
337
338                                         } else if ( rc == LDAP_REFERRAL ) {
339                                                 rc = LDAP_UNWILLING_TO_PERFORM;
340                                                 *text = "unwilling to chase referral returned by Start TLS exop";
341                                         }
342
343                                         if ( data ) {
344                                                 if ( data->bv_val ) {
345                                                         ber_memfree( data->bv_val );
346                                                 }
347                                                 ber_memfree( data );
348                                         }
349                                 }
350
351                         } else {
352                                 rc = LDAP_OTHER;
353                         }
354
355                         if ( res != NULL ) {
356                                 ldap_msgfree( res );
357                         }
358                 }
359 #else /* ! SLAP_STARTTLS_ASYNCHRONOUS */
360                 /*
361                  * use synchronous StartTLS
362                  */
363                 rc = ldap_start_tls_s( ld, NULL, NULL );
364 #endif /* ! SLAP_STARTTLS_ASYNCHRONOUS */
365
366                 /* if StartTLS is requested, only attempt it if the URL
367                  * is not "ldaps://"; this may occur not only in case
368                  * of misconfiguration, but also when used in the chain 
369                  * overlay, where the "uri" can be parsed out of a referral */
370                 switch ( rc ) {
371                 case LDAP_SUCCESS:
372                         *is_tls = 1;
373                         break;
374
375                 case LDAP_SERVER_DOWN:
376                         break;
377
378                 default:
379                         if ( LDAP_BACK_TLS_CRITICAL( &dummy ) ) {
380                                 *text = "could not start TLS";
381                                 break;
382                         }
383
384                         /* in case Start TLS is not critical */
385                         *is_tls = 0;
386                         rc = LDAP_SUCCESS;
387                         break;
388                 }
389
390         } else {
391                 *is_tls = 0;
392         }
393
394         return rc;
395 }
396 #endif /* HAVE_TLS */
397
398 static int
399 ldap_back_prepare_conn( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
400 {
401         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
402         int             vers = op->o_protocol;
403         LDAP            *ld = NULL;
404 #ifdef HAVE_TLS
405         int             is_tls = op->o_conn->c_is_tls;
406 #endif /* HAVE_TLS */
407
408         assert( lcp != NULL );
409
410         rs->sr_err = ldap_initialize( &ld, li->li_uri );
411         if ( rs->sr_err != LDAP_SUCCESS ) {
412                 goto error_return;
413         }
414
415         /* Set LDAP version. This will always succeed: If the client
416          * bound with a particular version, then so can we.
417          */
418         if ( vers == 0 ) {
419                 /* assume it's an internal op; set to LDAPv3 */
420                 vers = LDAP_VERSION3;
421         }
422         ldap_set_option( ld, LDAP_OPT_PROTOCOL_VERSION, (const void *)&vers );
423
424         /* automatically chase referrals ("[dont-]chase-referrals" statement) */
425         if ( LDAP_BACK_CHASE_REFERRALS( li ) ) {
426                 ldap_set_option( ld, LDAP_OPT_REFERRALS, LDAP_OPT_ON );
427         }
428
429 #ifdef HAVE_TLS
430         rs->sr_err = ldap_back_start_tls( ld, op->o_protocol, &is_tls,
431                         li->li_uri, li->li_flags, li->li_nretries, &rs->sr_text );
432         if ( rs->sr_err != LDAP_SUCCESS ) {
433                 ldap_unbind_ext( ld, NULL, NULL );
434                 goto error_return;
435         }
436 #endif /* HAVE_TLS */
437
438         if ( *lcp == NULL ) {
439                 *lcp = (ldapconn_t *)ch_calloc( 1, sizeof( ldapconn_t ) );
440                 (*lcp)->lc_flags= li->li_flags;
441         }
442         (*lcp)->lc_ld = ld;
443         (*lcp)->lc_refcnt = 1;
444 #ifdef HAVE_TLS
445         if ( is_tls ) {
446                 LDAP_BACK_CONN_ISTLS_SET( *lcp );
447         } else {
448                 LDAP_BACK_CONN_ISTLS_CLEAR( *lcp );
449         }
450 #endif /* HAVE_TLS */
451
452 error_return:;
453         if ( rs->sr_err != LDAP_SUCCESS ) {
454                 rs->sr_err = slap_map_api2result( rs );
455                 if ( sendok & LDAP_BACK_SENDERR ) {
456                         if ( rs->sr_text == NULL ) {
457                                 rs->sr_text = "ldap_initialize() failed";
458                         }
459                         send_ldap_result( op, rs );
460                         rs->sr_text = NULL;
461                 }
462         }
463
464         return rs->sr_err;
465 }
466
467 ldapconn_t *
468 ldap_back_getconn( Operation *op, SlapReply *rs, ldap_back_send_t sendok )
469 {
470         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
471         ldapconn_t      *lc = NULL,
472                         lc_curr = { 0 };
473         int             refcnt = 1;
474
475         /* Internal searches are privileged and shared. So is root. */
476         if ( op->o_do_not_cache || be_isroot( op ) ) {
477                 LDAP_BACK_CONN_ISPRIV_SET( &lc_curr );
478                 lc_curr.lc_local_ndn = op->o_bd->be_rootndn;
479                 lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
480
481         } else {
482                 lc_curr.lc_local_ndn = op->o_ndn;
483                 /* Explicit binds must not be shared */
484                 if ( op->o_tag == LDAP_REQ_BIND || SLAP_IS_AUTHZ_BACKEND( op ) ) {
485                         lc_curr.lc_conn = op->o_conn;
486         
487                 } else {
488                         lc_curr.lc_conn = LDAP_BACK_PCONN_SET( op );
489                 }
490         }
491
492         /* Explicit Bind requests always get their own conn */
493         if ( !( sendok & LDAP_BACK_BINDING ) ) {
494                 /* Searches for a ldapconn in the avl tree */
495 retry_lock:
496                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
497
498                 lc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
499                                 (caddr_t)&lc_curr, ldap_back_conn_cmp );
500                 if ( lc != NULL ) {
501                         /* Don't reuse connections while they're still binding */
502                         if ( LDAP_BACK_CONN_BINDING( lc ) ) {
503                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
504                                 ldap_pvt_thread_yield();
505                                 goto retry_lock;
506                         }
507                         refcnt = ++lc->lc_refcnt;
508                 }
509                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
510         }
511
512         /* Looks like we didn't get a bind. Open a new session... */
513         if ( lc == NULL ) {
514                 if ( ldap_back_prepare_conn( &lc, op, rs, sendok ) != LDAP_SUCCESS ) {
515                         return NULL;
516                 }
517                 if ( sendok & LDAP_BACK_BINDING ) {
518                         LDAP_BACK_CONN_BINDING_SET( lc );
519                 }
520                 lc->lc_conn = lc_curr.lc_conn;
521                 ber_dupbv( &lc->lc_local_ndn, &lc_curr.lc_local_ndn );
522
523                 if ( LDAP_BACK_CONN_ISPRIV( &lc_curr ) ) {
524                         ber_dupbv( &lc->lc_cred, &li->li_acl_passwd );
525                         ber_dupbv( &lc->lc_bound_ndn, &li->li_acl_authcDN );
526                         LDAP_BACK_CONN_ISPRIV_SET( lc );
527
528                 } else {
529                         BER_BVZERO( &lc->lc_cred );
530                         BER_BVZERO( &lc->lc_bound_ndn );
531 #if 0
532                         /* FIXME: if we set lc_bound_ndn = o_ndn
533                          * we end up with a bind with DN but no password! */
534                         if ( !BER_BVISEMPTY( &op->o_ndn )
535                                 && SLAP_IS_AUTHZ_BACKEND( op ) )
536                         {
537                                 ber_dupbv( &lc->lc_bound_ndn, &op->o_ndn );
538                         }
539 #endif
540                 }
541
542 #ifdef HAVE_TLS
543                 /* if start TLS failed but it was not mandatory,
544                  * check if the non-TLS connection was already
545                  * in cache; in case, destroy the newly created
546                  * connection and use the existing one */
547                 if ( lc->lc_conn == LDAP_BACK_PCONN_TLS
548                                 && !ldap_tls_inplace( lc->lc_ld ) )
549                 {
550                         ldapconn_t *tmplc;
551                         
552                         lc_curr.lc_conn = LDAP_BACK_PCONN;
553                         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
554                         tmplc = (ldapconn_t *)avl_find( li->li_conninfo.lai_tree, 
555                                         (caddr_t)&lc_curr, ldap_back_conn_cmp );
556                         if ( tmplc != NULL ) {
557                                 refcnt = ++tmplc->lc_refcnt;
558                                 ldap_back_conn_free( lc );
559                                 lc = tmplc;
560                         }
561                         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
562
563                         if ( tmplc != NULL ) {
564                                 goto done;
565                         }
566                 }
567 #endif /* HAVE_TLS */
568
569                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
570
571                 /* Inserts the newly created ldapconn in the avl tree */
572                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
573
574                 assert( lc->lc_refcnt == 1 );
575                 rs->sr_err = avl_insert( &li->li_conninfo.lai_tree, (caddr_t)lc,
576                         ldap_back_conn_cmp, ldap_back_conn_dup );
577
578 #if PRINT_CONNTREE > 0
579                 myprint( li->li_conninfo.lai_tree );
580 #endif /* PRINT_CONNTREE */
581         
582                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
583
584                 Debug( LDAP_DEBUG_TRACE,
585                         "=>ldap_back_getconn: conn %p inserted (refcnt=%u)\n",
586                         (void *)lc, refcnt, 0 );
587         
588                 /* Err could be -1 in case a duplicate ldapconn is inserted */
589                 if ( rs->sr_err != 0 ) {
590                         ldap_back_conn_free( lc );
591                         rs->sr_err = LDAP_OTHER;
592                         if ( op->o_conn && ( sendok & LDAP_BACK_SENDERR ) ) {
593                                 send_ldap_error( op, rs, LDAP_OTHER,
594                                         "internal server error" );
595                         }
596                         return NULL;
597                 }
598
599         } else {
600                 if ( li->li_idle_timeout != 0 && op->o_time > lc->lc_time + li->li_idle_timeout ) {
601                         /* in case of failure, it frees/taints lc and sets it to NULL */
602                         if ( ldap_back_retry( &lc, op, rs, sendok ) ) {
603                                 lc = NULL;
604                         }
605                 }
606
607                 if ( lc ) {
608                         Debug( LDAP_DEBUG_TRACE,
609                                 "=>ldap_back_getconn: conn %p fetched (refcnt=%u)\n",
610                                 (void *)lc, refcnt, 0 );
611                 }
612         }
613
614         if ( li->li_idle_timeout && lc ) {
615                 lc->lc_time = op->o_time;
616         }
617
618 done:;
619         return lc;
620 }
621
622 void
623 ldap_back_release_conn_lock(
624         Operation               *op,
625         SlapReply               *rs,
626         ldapconn_t              *lc,
627         int                     dolock )
628 {
629         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
630
631         if ( dolock ) {
632                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
633         }
634         assert( lc->lc_refcnt > 0 );
635         lc->lc_refcnt--;
636         LDAP_BACK_CONN_BINDING_CLEAR( lc );
637         if ( dolock ) {
638                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
639         }
640 }
641
642 /*
643  * ldap_back_dobind
644  *
645  * Note: as the check for the value of lc->lc_bound was already here, I removed
646  * it from all the callers, and I made the function return the flag, so
647  * it can be used to simplify the check.
648  *
649  * Note: dolock indicates whether li->li_conninfo.lai_mutex must be locked or not
650  */
651 static int
652 ldap_back_dobind_int(
653         ldapconn_t              *lc,
654         Operation               *op,
655         SlapReply               *rs,
656         ldap_back_send_t        sendok,
657         int                     retries,
658         int                     dolock )
659 {       
660         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
661
662         int             rc = LDAP_BACK_CONN_ISBOUND( lc );
663         ber_int_t       msgid;
664
665         assert( retries >= 0 );
666
667         if ( rc ) {
668                 return rc;
669         }
670
671         while ( lc->lc_refcnt > 1 ) {
672                 ldap_pvt_thread_yield();
673                 rc = LDAP_BACK_CONN_ISBOUND( lc );
674                 if ( rc ) {
675                         return rc;
676                 }
677         }
678
679         if ( dolock ) {
680                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
681         }
682         LDAP_BACK_CONN_BINDING_SET( lc );
683         if ( dolock ) {
684                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
685         }
686
687         /*
688          * FIXME: we need to let clients use proxyAuthz
689          * otherwise we cannot do symmetric pools of servers;
690          * we have to live with the fact that a user can
691          * authorize itself as any ID that is allowed
692          * by the authzTo directive of the "proxyauthzdn".
693          */
694         /*
695          * NOTE: current Proxy Authorization specification
696          * and implementation do not allow proxy authorization
697          * control to be provided with Bind requests
698          */
699         /*
700          * if no bind took place yet, but the connection is bound
701          * and the "idassert-authcDN" (or other ID) is set, 
702          * then bind as the asserting identity and explicitly 
703          * add the proxyAuthz control to every operation with the
704          * dn bound to the connection as control value.
705          * This is done also if this is the authrizing backend,
706          * but the "override" flag is given to idassert.
707          * It allows to use SASL bind and yet proxyAuthz users
708          */
709         if ( op->o_conn != NULL &&
710                         !op->o_do_not_cache &&
711                         ( BER_BVISNULL( &lc->lc_bound_ndn ) ||
712                           ( li->li_idassert_flags & LDAP_BACK_AUTH_OVERRIDE ) ) )
713         {
714                 (void)ldap_back_proxy_authz_bind( lc, op, rs, sendok );
715                 goto done;
716         }
717
718 #ifdef HAVE_CYRUS_SASL
719         if ( LDAP_BACK_CONN_ISPRIV( lc )
720                 && li->li_acl_authmethod == LDAP_AUTH_SASL )
721         {
722                 void            *defaults = NULL;
723
724                 if ( li->li_acl_secprops != NULL ) {
725                         rc = ldap_set_option( lc->lc_ld,
726                                 LDAP_OPT_X_SASL_SECPROPS, li->li_acl_secprops);
727
728                         if ( rc != LDAP_OPT_SUCCESS ) {
729                                 Debug( LDAP_DEBUG_ANY, "Error: ldap_set_option "
730                                         "(%s,SECPROPS,\"%s\") failed!\n",
731                                         li->li_uri, li->li_acl_secprops, 0 );
732                                 goto done;
733                         }
734                 }
735
736                 defaults = lutil_sasl_defaults( lc->lc_ld,
737                                 li->li_acl_sasl_mech.bv_val,
738                                 li->li_acl_sasl_realm.bv_val,
739                                 li->li_acl_authcID.bv_val,
740                                 li->li_acl_passwd.bv_val,
741                                 NULL );
742
743                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld,
744                                 li->li_acl_authcDN.bv_val,
745                                 li->li_acl_sasl_mech.bv_val, NULL, NULL,
746                                 LDAP_SASL_QUIET, lutil_sasl_interact,
747                                 defaults );
748
749                 lutil_sasl_freedefs( defaults );
750
751                 rs->sr_err = slap_map_api2result( rs );
752                 if ( rs->sr_err != LDAP_SUCCESS ) {
753                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
754                         send_ldap_result( op, rs );
755
756                 } else {
757                         LDAP_BACK_CONN_ISBOUND_SET( lc );
758                 }
759                 goto done;
760         }
761 #endif /* HAVE_CYRUS_SASL */
762
763 retry:;
764         rs->sr_err = ldap_sasl_bind( lc->lc_ld,
765                         lc->lc_bound_ndn.bv_val,
766                         LDAP_SASL_SIMPLE, &lc->lc_cred,
767                         NULL, NULL, &msgid );
768
769         if ( rs->sr_err == LDAP_SERVER_DOWN ) {
770                 if ( retries != LDAP_BACK_RETRY_NEVER ) {
771                         if ( dolock ) {
772                                 ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
773                         }
774
775                         assert( lc->lc_refcnt > 0 );
776                         if ( lc->lc_refcnt == 1 ) {
777                                 ldap_unbind_ext( lc->lc_ld, NULL, NULL );
778                                 lc->lc_ld = NULL;
779
780                                 /* lc here must be the regular lc, reset and ready for init */
781                                 rs->sr_err = ldap_back_prepare_conn( &lc, op, rs, sendok );
782                         }
783                         if ( dolock ) {
784                                 ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
785                         }
786                         if ( rs->sr_err == LDAP_SUCCESS ) {
787                                 if ( retries > 0 ) {
788                                         retries--;
789                                 }
790                                 goto retry;
791                         }
792                 }
793
794                 ldap_back_freeconn( op, lc, dolock );
795                 rs->sr_err = slap_map_api2result( rs );
796
797                 return 0;
798         }
799
800         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
801         if ( rc == LDAP_SUCCESS ) {
802                 LDAP_BACK_CONN_ISBOUND_SET( lc );
803         }
804
805 done:;
806         LDAP_BACK_CONN_BINDING_CLEAR( lc );
807         rc = LDAP_BACK_CONN_ISBOUND( lc );
808         if ( !rc ) {
809                 ldap_back_release_conn_lock( op, rs, lc, dolock );
810         }
811
812         return rc;
813 }
814
815 int
816 ldap_back_dobind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
817 {
818         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
819
820         return ldap_back_dobind_int( lc, op, rs, sendok, li->li_nretries, 1 );
821 }
822
823 /*
824  * ldap_back_default_rebind
825  *
826  * This is a callback used for chasing referrals using the same
827  * credentials as the original user on this session.
828  */
829 static int 
830 ldap_back_default_rebind( LDAP *ld, LDAP_CONST char *url, ber_tag_t request,
831         ber_int_t msgid, void *params )
832 {
833         ldapconn_t      *lc = (ldapconn_t *)params;
834
835 #ifdef HAVE_TLS
836         /* ... otherwise we couldn't get here */
837         assert( lc != NULL );
838
839         if ( !ldap_tls_inplace( ld ) ) {
840                 int             is_tls = LDAP_BACK_CONN_ISTLS( lc ),
841                                 rc;
842                 const char      *text = NULL;
843
844                 rc = ldap_back_start_tls( ld, 0, &is_tls, url, lc->lc_flags,
845                         LDAP_BACK_RETRY_DEFAULT, &text );
846                 if ( rc != LDAP_SUCCESS ) {
847                         return rc;
848                 }
849         }
850 #endif /* HAVE_TLS */
851
852         /* FIXME: add checks on the URL/identity? */
853
854         return ldap_sasl_bind_s( ld, lc->lc_bound_ndn.bv_val,
855                         LDAP_SASL_SIMPLE, &lc->lc_cred, NULL, NULL, NULL );
856 }
857
858 int
859 ldap_back_op_result(
860                 ldapconn_t              *lc,
861                 Operation               *op,
862                 SlapReply               *rs,
863                 ber_int_t               msgid,
864                 time_t                  timeout,
865                 ldap_back_send_t        sendok )
866 {
867         char            *match = NULL;
868         LDAPMessage     *res = NULL;
869         char            *text = NULL;
870
871 #define ERR_OK(err) ((err) == LDAP_SUCCESS || (err) == LDAP_COMPARE_FALSE || (err) == LDAP_COMPARE_TRUE)
872
873         rs->sr_text = NULL;
874         rs->sr_matched = NULL;
875
876         /* if the error recorded in the reply corresponds
877          * to a successful state, get the error from the
878          * remote server response */
879         if ( ERR_OK( rs->sr_err ) ) {
880                 int             rc;
881                 struct timeval  tv;
882
883                 if ( timeout ) {
884                         tv.tv_sec = timeout;
885                         tv.tv_usec = 0;
886
887                 } else {
888                         LDAP_BACK_TV_SET( &tv );
889                 }
890
891 retry:;
892                 /* if result parsing fails, note the failure reason */
893                 rc = ldap_result( lc->lc_ld, msgid, LDAP_MSG_ALL, &tv, &res );
894                 switch ( rc ) {
895                 case 0:
896                         if ( timeout ) {
897                                 (void)ldap_abandon_ext( lc->lc_ld, msgid, NULL, NULL );
898                                 rs->sr_err = op->o_protocol >= LDAP_VERSION3 ?
899                                         LDAP_ADMINLIMIT_EXCEEDED : LDAP_OPERATIONS_ERROR;
900                                 rs->sr_text = "Operation timed out";
901                                 break;
902                         }
903
904                         LDAP_BACK_TV_SET( &tv );
905                         ldap_pvt_thread_yield();
906                         goto retry;
907
908                 case -1:
909                         ldap_get_option( lc->lc_ld, LDAP_OPT_ERROR_NUMBER,
910                                         &rs->sr_err );
911                         break;
912
913
914                 /* otherwise get the result; if it is not
915                  * LDAP_SUCCESS, record it in the reply
916                  * structure (this includes 
917                  * LDAP_COMPARE_{TRUE|FALSE}) */
918                 default:
919                         rc = ldap_parse_result( lc->lc_ld, res, &rs->sr_err,
920                                         &match, &text, NULL, NULL, 1 );
921 #ifndef LDAP_NULL_IS_NULL
922                         if ( match != NULL && match[ 0 ] == '\0' ) {
923                                 ldap_memfree( match );
924                                 match = NULL;
925                         }
926                         if ( text != NULL && text[ 0 ] == '\0' ) {
927                                 ldap_memfree( text );
928                                 text = NULL;
929                         }
930 #endif /* LDAP_NULL_IS_NULL */
931                         rs->sr_text = text;
932                         if ( rc != LDAP_SUCCESS ) {
933                                 rs->sr_err = rc;
934                         }
935                 }
936         }
937
938         /* if the error in the reply structure is not
939          * LDAP_SUCCESS, try to map it from client 
940          * to server error */
941         if ( !ERR_OK( rs->sr_err ) ) {
942                 rs->sr_err = slap_map_api2result( rs );
943
944                 /* internal ops ( op->o_conn == NULL ) 
945                  * must not reply to client */
946                 if ( op->o_conn && !op->o_do_not_cache && match ) {
947
948                         /* record the (massaged) matched
949                          * DN into the reply structure */
950                         rs->sr_matched = match;
951                 }
952         }
953         if ( op->o_conn &&
954                         ( ( sendok & LDAP_BACK_SENDOK ) 
955                           || ( ( sendok & LDAP_BACK_SENDERR ) && rs->sr_err != LDAP_SUCCESS ) ) )
956         {
957                 send_ldap_result( op, rs );
958         }
959         if ( match ) {
960                 if ( rs->sr_matched != match ) {
961                         free( (char *)rs->sr_matched );
962                 }
963                 rs->sr_matched = NULL;
964                 ldap_memfree( match );
965         }
966         if ( text ) {
967                 ldap_memfree( text );
968         }
969         rs->sr_text = NULL;
970         return( ERR_OK( rs->sr_err ) ? LDAP_SUCCESS : rs->sr_err );
971 }
972
973 /* return true if bound, false if failed */
974 int
975 ldap_back_retry( ldapconn_t **lcp, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
976 {
977         int             rc = 0;
978         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
979
980         assert( lcp != NULL );
981         assert( *lcp != NULL );
982
983         ldap_pvt_thread_mutex_lock( &li->li_conninfo.lai_mutex );
984
985         if ( (*lcp)->lc_refcnt == 1 ) {
986                 Debug( LDAP_DEBUG_ANY,
987                         "%s ldap_back_retry: retrying URI=\"%s\" DN=\"%s\"\n",
988                         op->o_log_prefix, li->li_uri,
989                         BER_BVISNULL( &(*lcp)->lc_bound_ndn ) ?
990                                 "" : (*lcp)->lc_bound_ndn.bv_val );
991
992                 ldap_unbind_ext( (*lcp)->lc_ld, NULL, NULL );
993                 (*lcp)->lc_ld = NULL;
994                 LDAP_BACK_CONN_ISBOUND_CLEAR( (*lcp) );
995
996                 /* lc here must be the regular lc, reset and ready for init */
997                 rc = ldap_back_prepare_conn( lcp, op, rs, sendok );
998                 if ( rc != LDAP_SUCCESS ) {
999                         rc = 0;
1000                         *lcp = NULL;
1001
1002                 } else {
1003                         rc = ldap_back_dobind_int( *lcp, op, rs, sendok, 0, 0 );
1004                         if ( rc == 0 ) {
1005                                 *lcp = NULL;
1006                         }
1007                 }
1008         }
1009
1010         ldap_pvt_thread_mutex_unlock( &li->li_conninfo.lai_mutex );
1011
1012         return rc;
1013 }
1014
1015 static int
1016 ldap_back_proxy_authz_bind( ldapconn_t *lc, Operation *op, SlapReply *rs, ldap_back_send_t sendok )
1017 {
1018         ldapinfo_t      *li = (ldapinfo_t *)op->o_bd->be_private;
1019         struct berval   binddn = slap_empty_bv;
1020         struct berval   bindcred = slap_empty_bv;
1021         struct berval   ndn;
1022         int             dobind = 0;
1023         int             msgid;
1024         int             rc;
1025
1026         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1027                 ndn = op->o_conn->c_ndn;
1028
1029         } else {
1030                 ndn = op->o_ndn;
1031         }
1032
1033         /*
1034          * FIXME: we need to let clients use proxyAuthz
1035          * otherwise we cannot do symmetric pools of servers;
1036          * we have to live with the fact that a user can
1037          * authorize itself as any ID that is allowed
1038          * by the authzTo directive of the "proxyauthzdn".
1039          */
1040         /*
1041          * NOTE: current Proxy Authorization specification
1042          * and implementation do not allow proxy authorization
1043          * control to be provided with Bind requests
1044          */
1045         /*
1046          * if no bind took place yet, but the connection is bound
1047          * and the "proxyauthzdn" is set, then bind as 
1048          * "proxyauthzdn" and explicitly add the proxyAuthz 
1049          * control to every operation with the dn bound 
1050          * to the connection as control value.
1051          */
1052
1053         /* bind as proxyauthzdn only if no idassert mode
1054          * is requested, or if the client's identity
1055          * is authorized */
1056         switch ( li->li_idassert_mode ) {
1057         case LDAP_BACK_IDASSERT_LEGACY:
1058                 if ( !BER_BVISNULL( &ndn ) && !BER_BVISEMPTY( &ndn ) ) {
1059                         if ( !BER_BVISNULL( &li->li_idassert_authcDN ) && !BER_BVISEMPTY( &li->li_idassert_authcDN ) )
1060                         {
1061                                 binddn = li->li_idassert_authcDN;
1062                                 bindcred = li->li_idassert_passwd;
1063                                 dobind = 1;
1064                         }
1065                 }
1066                 break;
1067
1068         default:
1069                 /* NOTE: rootdn can always idassert */
1070                 if ( BER_BVISNULL( &ndn ) && li->li_idassert_authz == NULL ) {
1071                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1072                                 rs->sr_err = LDAP_INAPPROPRIATE_AUTH;
1073                                 if ( sendok & LDAP_BACK_SENDERR ) {
1074                                         send_ldap_result( op, rs );
1075                                 }
1076                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1077
1078                         } else {
1079                                 rs->sr_err = LDAP_SUCCESS;
1080                                 binddn = slap_empty_bv;
1081                                 bindcred = slap_empty_bv;
1082                                 break;
1083                         }
1084
1085                         goto done;
1086
1087                 } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1088                         struct berval authcDN;
1089
1090                         if ( BER_BVISNULL( &ndn ) ) {
1091                                 authcDN = slap_empty_bv;
1092
1093                         } else {
1094                                 authcDN = ndn;
1095                         }       
1096                         rs->sr_err = slap_sasl_matches( op, li->li_idassert_authz,
1097                                         &authcDN, &authcDN );
1098                         if ( rs->sr_err != LDAP_SUCCESS ) {
1099                                 if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE ) {
1100                                         if ( sendok & LDAP_BACK_SENDERR ) {
1101                                                 send_ldap_result( op, rs );
1102                                         }
1103                                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1104
1105                                 } else {
1106                                         rs->sr_err = LDAP_SUCCESS;
1107                                         binddn = slap_empty_bv;
1108                                         bindcred = slap_empty_bv;
1109                                         break;
1110                                 }
1111
1112                                 goto done;
1113                         }
1114                 }
1115
1116                 binddn = li->li_idassert_authcDN;
1117                 bindcred = li->li_idassert_passwd;
1118                 dobind = 1;
1119                 break;
1120         }
1121
1122         if ( dobind && li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1123 #ifdef HAVE_CYRUS_SASL
1124                 void            *defaults = NULL;
1125                 struct berval   authzID = BER_BVNULL;
1126                 int             freeauthz = 0;
1127
1128                 /* if SASL supports native authz, prepare for it */
1129                 if ( ( !op->o_do_not_cache || !op->o_is_auth_check ) &&
1130                                 ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ ) )
1131                 {
1132                         switch ( li->li_idassert_mode ) {
1133                         case LDAP_BACK_IDASSERT_OTHERID:
1134                         case LDAP_BACK_IDASSERT_OTHERDN:
1135                                 authzID = li->li_idassert_authzID;
1136                                 break;
1137
1138                         case LDAP_BACK_IDASSERT_ANONYMOUS:
1139                                 BER_BVSTR( &authzID, "dn:" );
1140                                 break;
1141
1142                         case LDAP_BACK_IDASSERT_SELF:
1143                                 if ( BER_BVISNULL( &ndn ) ) {
1144                                         /* connection is not authc'd, so don't idassert */
1145                                         BER_BVSTR( &authzID, "dn:" );
1146                                         break;
1147                                 }
1148                                 authzID.bv_len = STRLENOF( "dn:" ) + ndn.bv_len;
1149                                 authzID.bv_val = slap_sl_malloc( authzID.bv_len + 1, op->o_tmpmemctx );
1150                                 AC_MEMCPY( authzID.bv_val, "dn:", STRLENOF( "dn:" ) );
1151                                 AC_MEMCPY( authzID.bv_val + STRLENOF( "dn:" ),
1152                                                 ndn.bv_val, ndn.bv_len + 1 );
1153                                 freeauthz = 1;
1154                                 break;
1155
1156                         default:
1157                                 break;
1158                         }
1159                 }
1160
1161                 if ( li->li_idassert_secprops != NULL ) {
1162                         rs->sr_err = ldap_set_option( lc->lc_ld,
1163                                 LDAP_OPT_X_SASL_SECPROPS,
1164                                 (void *)li->li_idassert_secprops );
1165
1166                         if ( rs->sr_err != LDAP_OPT_SUCCESS ) {
1167                                 rs->sr_err = LDAP_OTHER;
1168                                 if ( sendok & LDAP_BACK_SENDERR ) {
1169                                         send_ldap_result( op, rs );
1170                                 }
1171                                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1172                                 goto done;
1173                         }
1174                 }
1175
1176                 defaults = lutil_sasl_defaults( lc->lc_ld,
1177                                 li->li_idassert_sasl_mech.bv_val,
1178                                 li->li_idassert_sasl_realm.bv_val,
1179                                 li->li_idassert_authcID.bv_val,
1180                                 li->li_idassert_passwd.bv_val,
1181                                 authzID.bv_val );
1182
1183                 rs->sr_err = ldap_sasl_interactive_bind_s( lc->lc_ld, binddn.bv_val,
1184                                 li->li_idassert_sasl_mech.bv_val, NULL, NULL,
1185                                 LDAP_SASL_QUIET, lutil_sasl_interact,
1186                                 defaults );
1187
1188                 rs->sr_err = slap_map_api2result( rs );
1189                 if ( rs->sr_err != LDAP_SUCCESS ) {
1190                         LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1191                         if ( sendok & LDAP_BACK_SENDERR ) {
1192                                 send_ldap_result( op, rs );
1193                         }
1194
1195                 } else {
1196                         LDAP_BACK_CONN_ISBOUND_SET( lc );
1197                 }
1198
1199                 lutil_sasl_freedefs( defaults );
1200                 if ( freeauthz ) {
1201                         slap_sl_free( authzID.bv_val, op->o_tmpmemctx );
1202                 }
1203
1204                 goto done;
1205 #endif /* HAVE_CYRUS_SASL */
1206         }
1207
1208         switch ( li->li_idassert_authmethod ) {
1209         case LDAP_AUTH_NONE:
1210                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1211                 goto done;
1212
1213         case LDAP_AUTH_SIMPLE:
1214                 rs->sr_err = ldap_sasl_bind( lc->lc_ld,
1215                                 binddn.bv_val, LDAP_SASL_SIMPLE,
1216                                 &bindcred, NULL, NULL, &msgid );
1217                 break;
1218
1219         default:
1220                 /* unsupported! */
1221                 LDAP_BACK_CONN_ISBOUND_CLEAR( lc );
1222                 rs->sr_err = LDAP_AUTH_METHOD_NOT_SUPPORTED;
1223                 if ( sendok & LDAP_BACK_SENDERR ) {
1224                         send_ldap_result( op, rs );
1225                 }
1226                 goto done;
1227         }
1228
1229         rc = ldap_back_op_result( lc, op, rs, msgid, 0, sendok );
1230         if ( rc == LDAP_SUCCESS ) {
1231                 LDAP_BACK_CONN_ISBOUND_SET( lc );
1232         }
1233 done:;
1234         return LDAP_BACK_CONN_ISBOUND( lc );
1235 }
1236
1237 /*
1238  * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
1239  * to existing server-side controls if required; if not,
1240  * the existing server-side controls are placed in *pctrls.
1241  * The caller, after using the controls in client API 
1242  * operations, if ( *pctrls != op->o_ctrls ), should
1243  * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
1244  * The function returns success if the control could
1245  * be added if required, or if it did nothing; in the future,
1246  * it might return some error if it failed.
1247  * 
1248  * if no bind took place yet, but the connection is bound
1249  * and the "proxyauthzdn" is set, then bind as "proxyauthzdn" 
1250  * and explicitly add proxyAuthz the control to every operation
1251  * with the dn bound to the connection as control value.
1252  *
1253  * If no server-side controls are defined for the operation,
1254  * simply add the proxyAuthz control; otherwise, if the
1255  * proxyAuthz control is not already set, add it as
1256  * the first one
1257  *
1258  * FIXME: is controls order significant for security?
1259  * ANSWER: controls ordering and interoperability
1260  * must be indicated by the specs of each control; if none
1261  * is specified, the order is irrelevant.
1262  */
1263 int
1264 ldap_back_proxy_authz_ctrl(
1265                 ldapconn_t      *lc,
1266                 Operation       *op,
1267                 SlapReply       *rs,
1268                 LDAPControl     ***pctrls )
1269 {
1270         ldapinfo_t      *li = (ldapinfo_t *) op->o_bd->be_private;
1271         LDAPControl     **ctrls = NULL;
1272         int             i = 0,
1273                         mode;
1274         struct berval   assertedID,
1275                         ndn;
1276
1277         *pctrls = NULL;
1278
1279         rs->sr_err = LDAP_SUCCESS;
1280
1281         /* FIXME: SASL/EXTERNAL over ldapi:// doesn't honor the authcID,
1282          * but if it is not set this test fails.  We need a different
1283          * means to detect if idassert is enabled */
1284         if ( ( BER_BVISNULL( &li->li_idassert_authcID ) || BER_BVISEMPTY( &li->li_idassert_authcID ) )
1285                         && ( BER_BVISNULL( &li->li_idassert_authcDN ) || BER_BVISEMPTY( &li->li_idassert_authcDN ) ) )
1286         {
1287                 goto done;
1288         }
1289
1290         if ( !op->o_conn || op->o_do_not_cache || be_isroot( op ) ) {
1291                 goto done;
1292         }
1293
1294         if ( !BER_BVISNULL( &op->o_conn->c_ndn ) ) {
1295                 ndn = op->o_conn->c_ndn;
1296
1297         } else {
1298                 ndn = op->o_ndn;
1299         }
1300
1301         if ( li->li_idassert_mode == LDAP_BACK_IDASSERT_LEGACY ) {
1302                 if ( op->o_proxy_authz ) {
1303                         /*
1304                          * FIXME: we do not want to perform proxyAuthz
1305                          * on behalf of the client, because this would
1306                          * be performed with "proxyauthzdn" privileges.
1307                          *
1308                          * This might actually be too strict, since
1309                          * the "proxyauthzdn" authzTo, and each entry's
1310                          * authzFrom attributes may be crafted
1311                          * to avoid unwanted proxyAuthz to take place.
1312                          */
1313 #if 0
1314                         rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1315                         rs->sr_text = "proxyAuthz not allowed within namingContext";
1316 #endif
1317                         goto done;
1318                 }
1319
1320                 if ( !BER_BVISNULL( &lc->lc_bound_ndn ) ) {
1321                         goto done;
1322                 }
1323
1324                 if ( BER_BVISNULL( &ndn ) ) {
1325                         goto done;
1326                 }
1327
1328                 if ( BER_BVISNULL( &li->li_idassert_authcDN ) ) {
1329                         goto done;
1330                 }
1331
1332         } else if ( li->li_idassert_authmethod == LDAP_AUTH_SASL ) {
1333                 if ( ( li->li_idassert_flags & LDAP_BACK_AUTH_NATIVE_AUTHZ )
1334                                 /* && ( !BER_BVISNULL( &ndn )
1335                                         || LDAP_BACK_CONN_ISBOUND( lc ) ) */ )
1336                 {
1337                         /* already asserted in SASL via native authz */
1338                         /* NOTE: the test on lc->lc_bound is used to trap
1339                          * native authorization of anonymous users,
1340                          * since in that case ndn is NULL */
1341                         goto done;
1342                 }
1343
1344         } else if ( li->li_idassert_authz && !be_isroot( op ) ) {
1345                 int             rc;
1346                 struct berval authcDN;
1347
1348                 if ( BER_BVISNULL( &ndn ) ) {
1349                         authcDN = slap_empty_bv;
1350                 } else {
1351                         authcDN = ndn;
1352                 }
1353                 rc = slap_sasl_matches( op, li->li_idassert_authz,
1354                                 &authcDN, & authcDN );
1355                 if ( rc != LDAP_SUCCESS ) {
1356                         if ( li->li_idassert_flags & LDAP_BACK_AUTH_PRESCRIPTIVE )
1357                         {
1358                                 /* ndn is not authorized
1359                                  * to use idassert */
1360                                 return rc;
1361                         }
1362                         return rs->sr_err;
1363                 }
1364         }
1365
1366         if ( op->o_proxy_authz ) {
1367                 /*
1368                  * FIXME: we can:
1369                  * 1) ignore the already set proxyAuthz control
1370                  * 2) leave it in place, and don't set ours
1371                  * 3) add both
1372                  * 4) reject the operation
1373                  *
1374                  * option (4) is very drastic
1375                  * option (3) will make the remote server reject
1376                  * the operation, thus being equivalent to (4)
1377                  * option (2) will likely break the idassert
1378                  * assumptions, so we cannot accept it;
1379                  * option (1) means that we are contradicting
1380                  * the client's reques.
1381                  *
1382                  * I think (4) is the only correct choice.
1383                  */
1384                 rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1385                 rs->sr_text = "proxyAuthz not allowed within namingContext";
1386         }
1387
1388         if ( op->o_is_auth_check ) {
1389                 mode = LDAP_BACK_IDASSERT_NOASSERT;
1390
1391         } else {
1392                 mode = li->li_idassert_mode;
1393         }
1394
1395         switch ( mode ) {
1396         case LDAP_BACK_IDASSERT_SELF:
1397                 if ( BER_BVISNULL( &ndn ) ) {
1398                         goto done;
1399                 }
1400                 assertedID = ndn;
1401                 break;
1402
1403         case LDAP_BACK_IDASSERT_LEGACY:
1404                 /* original behavior:
1405                  * assert the client's identity */
1406                 if ( BER_BVISNULL( &ndn ) ) {
1407                         assertedID = slap_empty_bv;
1408                 } else {
1409                         assertedID = ndn;
1410                 }
1411                 break;
1412
1413         case LDAP_BACK_IDASSERT_ANONYMOUS:
1414                 /* assert "anonymous" */
1415                 assertedID = slap_empty_bv;
1416                 break;
1417
1418         case LDAP_BACK_IDASSERT_NOASSERT:
1419                 /* don't assert; bind as proxyauthzdn */
1420                 goto done;
1421
1422         case LDAP_BACK_IDASSERT_OTHERID:
1423         case LDAP_BACK_IDASSERT_OTHERDN:
1424                 /* assert idassert DN */
1425                 assertedID = li->li_idassert_authzID;
1426                 break;
1427
1428         default:
1429                 assert( 0 );
1430         }
1431
1432         if ( BER_BVISNULL( &assertedID ) ) {
1433                 assertedID = slap_empty_bv;
1434         }
1435
1436         if ( op->o_ctrls ) {
1437                 for ( i = 0; op->o_ctrls[ i ]; i++ )
1438                         /* just count ctrls */ ;
1439         }
1440
1441         ctrls = op->o_tmpalloc( sizeof( LDAPControl * ) * (i + 2) + sizeof( LDAPControl ),
1442                         op->o_tmpmemctx );
1443         ctrls[ 0 ] = (LDAPControl *)&ctrls[ i + 2 ];
1444         
1445         ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
1446         ctrls[ 0 ]->ldctl_iscritical = 1;
1447
1448         switch ( li->li_idassert_mode ) {
1449         /* already in u:ID or dn:DN form */
1450         case LDAP_BACK_IDASSERT_OTHERID:
1451         case LDAP_BACK_IDASSERT_OTHERDN:
1452                 ber_dupbv_x( &ctrls[ 0 ]->ldctl_value, &assertedID, op->o_tmpmemctx );
1453                 break;
1454
1455         /* needs the dn: prefix */
1456         default:
1457                 ctrls[ 0 ]->ldctl_value.bv_len = assertedID.bv_len + STRLENOF( "dn:" );
1458                 ctrls[ 0 ]->ldctl_value.bv_val = op->o_tmpalloc( ctrls[ 0 ]->ldctl_value.bv_len + 1,
1459                                 op->o_tmpmemctx );
1460                 AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", STRLENOF( "dn:" ) );
1461                 AC_MEMCPY( &ctrls[ 0 ]->ldctl_value.bv_val[ STRLENOF( "dn:" ) ],
1462                                 assertedID.bv_val, assertedID.bv_len + 1 );
1463                 break;
1464         }
1465
1466         if ( op->o_ctrls ) {
1467                 for ( i = 0; op->o_ctrls[ i ]; i++ ) {
1468                         ctrls[ i + 1 ] = op->o_ctrls[ i ];
1469                 }
1470         }
1471         ctrls[ i + 1 ] = NULL;
1472
1473 done:;
1474         if ( ctrls == NULL ) {
1475                 ctrls = op->o_ctrls;
1476         }
1477
1478         *pctrls = ctrls;
1479         
1480         return rs->sr_err;
1481 }
1482
1483 int
1484 ldap_back_proxy_authz_ctrl_free( Operation *op, LDAPControl ***pctrls )
1485 {
1486         LDAPControl     **ctrls = *pctrls;
1487
1488         /* we assume that the first control is the proxyAuthz
1489          * added by back-ldap, so it's the only one we explicitly 
1490          * free */
1491         if ( ctrls && ctrls != op->o_ctrls ) {
1492                 assert( ctrls[ 0 ] != NULL );
1493
1494                 if ( !BER_BVISNULL( &ctrls[ 0 ]->ldctl_value ) ) {
1495                         op->o_tmpfree( ctrls[ 0 ]->ldctl_value.bv_val, op->o_tmpmemctx );
1496                 }
1497
1498                 op->o_tmpfree( ctrls, op->o_tmpmemctx );
1499         } 
1500
1501         *pctrls = NULL;
1502
1503         return 0;
1504 }