]> git.sur5r.net Git - openldap/blob - libraries/libldap/cyrus.c
plug potential ld_error leak (ITS#4064)
[openldap] / libraries / libldap / cyrus.c
1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2005 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15
16 #include "portable.h"
17
18 #include <stdio.h>
19
20 #include <ac/socket.h>
21 #include <ac/stdlib.h>
22 #include <ac/string.h>
23 #include <ac/time.h>
24 #include <ac/errno.h>
25 #include <ac/ctype.h>
26 #include <ac/unistd.h>
27
28 #include "ldap-int.h"
29
30 #ifdef HAVE_CYRUS_SASL
31
32 #ifdef LDAP_R_COMPILE
33 ldap_pvt_thread_mutex_t ldap_int_sasl_mutex;
34 #endif
35
36 #ifdef HAVE_SASL_SASL_H
37 #include <sasl/sasl.h>
38 #else
39 #include <sasl.h>
40 #endif
41
42 #if SASL_VERSION_MAJOR >= 2
43 #define SASL_CONST const
44 #else
45 #define SASL_CONST
46 #endif
47
48 /*
49 * Various Cyrus SASL related stuff.
50 */
51
52 static const sasl_callback_t client_callbacks[] = {
53 #ifdef SASL_CB_GETREALM
54         { SASL_CB_GETREALM, NULL, NULL },
55 #endif
56         { SASL_CB_USER, NULL, NULL },
57         { SASL_CB_AUTHNAME, NULL, NULL },
58         { SASL_CB_PASS, NULL, NULL },
59         { SASL_CB_ECHOPROMPT, NULL, NULL },
60         { SASL_CB_NOECHOPROMPT, NULL, NULL },
61         { SASL_CB_LIST_END, NULL, NULL }
62 };
63
64 int ldap_int_sasl_init( void )
65 {
66         /* XXX not threadsafe */
67         static int sasl_initialized = 0;
68
69 #ifdef HAVE_SASL_VERSION
70         /* stringify the version number, sasl.h doesn't do it for us */
71 #define VSTR0(maj, min, pat)    #maj "." #min "." #pat
72 #define VSTR(maj, min, pat)     VSTR0(maj, min, pat)
73 #define SASL_VERSION_STRING     VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
74                                 SASL_VERSION_STEP)
75         { int rc;
76         sasl_version( NULL, &rc );
77         if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
78                 (rc & 0xffff) < SASL_VERSION_STEP) {
79                 char version[sizeof("xxx.xxx.xxxxx")];
80                 sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
81                         rc & 0xffff );
82
83 #ifdef NEW_LOGGING
84                 LDAP_LOG( TRANSPORT, INFO,
85                 "ldap_int_sasl_init: SASL library version mismatch:"
86                 " expected " SASL_VERSION_STRING ","
87                 " got %s\n", version, 0, 0 );
88 #else
89                 Debug( LDAP_DEBUG_ANY,
90                 "ldap_int_sasl_init: SASL library version mismatch:"
91                 " expected " SASL_VERSION_STRING ","
92                 " got %s\n", version, 0, 0 );
93 #endif
94                 return -1;
95         }
96         }
97 #endif
98         if ( sasl_initialized ) {
99                 return 0;
100         }
101
102 /* SASL 2 takes care of its own memory completely internally */
103 #if SASL_VERSION_MAJOR < 2 && !defined(CSRIMALLOC)
104         sasl_set_alloc(
105                 ber_memalloc,
106                 ber_memcalloc,
107                 ber_memrealloc,
108                 ber_memfree );
109 #endif /* CSRIMALLOC */
110
111 #ifdef LDAP_R_COMPILE
112         sasl_set_mutex(
113                 ldap_pvt_sasl_mutex_new,
114                 ldap_pvt_sasl_mutex_lock,
115                 ldap_pvt_sasl_mutex_unlock,    
116                 ldap_pvt_sasl_mutex_dispose );    
117 #endif
118
119         if ( sasl_client_init( NULL ) == SASL_OK ) {
120                 sasl_initialized = 1;
121                 return 0;
122         }
123
124 #if SASL_VERSION_MAJOR < 2
125         /* A no-op to make sure we link with Cyrus 1.5 */
126         sasl_client_auth( NULL, NULL, NULL, 0, NULL, NULL );
127 #endif
128         return -1;
129 }
130
131 /*
132  * SASL encryption support for LBER Sockbufs
133  */
134
135 struct sb_sasl_data {
136         sasl_conn_t             *sasl_context;
137         unsigned                *sasl_maxbuf;
138         Sockbuf_Buf             sec_buf_in;
139         Sockbuf_Buf             buf_in;
140         Sockbuf_Buf             buf_out;
141 };
142
143 static int
144 sb_sasl_setup( Sockbuf_IO_Desc *sbiod, void *arg )
145 {
146         struct sb_sasl_data     *p;
147
148         assert( sbiod != NULL );
149
150         p = LBER_MALLOC( sizeof( *p ) );
151         if ( p == NULL )
152                 return -1;
153         p->sasl_context = (sasl_conn_t *)arg;
154         ber_pvt_sb_buf_init( &p->sec_buf_in );
155         ber_pvt_sb_buf_init( &p->buf_in );
156         ber_pvt_sb_buf_init( &p->buf_out );
157         if ( ber_pvt_sb_grow_buffer( &p->sec_buf_in, SASL_MIN_BUFF_SIZE ) < 0 ) {
158                 LBER_FREE( p );
159                 errno = ENOMEM;
160                 return -1;
161         }
162         sasl_getprop( p->sasl_context, SASL_MAXOUTBUF,
163                 (SASL_CONST void **) &p->sasl_maxbuf );
164             
165         sbiod->sbiod_pvt = p;
166
167         return 0;
168 }
169
170 static int
171 sb_sasl_remove( Sockbuf_IO_Desc *sbiod )
172 {
173         struct sb_sasl_data     *p;
174
175         assert( sbiod != NULL );
176         
177         p = (struct sb_sasl_data *)sbiod->sbiod_pvt;
178 #if SASL_VERSION_MAJOR >= 2
179         /*
180          * SASLv2 encode/decode buffers are managed by
181          * libsasl2. Ensure they are not freed by liblber.
182          */
183         p->buf_in.buf_base = NULL;
184         p->buf_out.buf_base = NULL;
185 #endif
186         ber_pvt_sb_buf_destroy( &p->sec_buf_in );
187         ber_pvt_sb_buf_destroy( &p->buf_in );
188         ber_pvt_sb_buf_destroy( &p->buf_out );
189         LBER_FREE( p );
190         sbiod->sbiod_pvt = NULL;
191         return 0;
192 }
193
194 static ber_len_t
195 sb_sasl_pkt_length( const unsigned char *buf, int debuglevel )
196 {
197         ber_len_t               size;
198
199         assert( buf != NULL );
200
201         size = buf[0] << 24
202                 | buf[1] << 16
203                 | buf[2] << 8
204                 | buf[3];
205    
206         if ( size > SASL_MAX_BUFF_SIZE ) {
207                 /* somebody is trying to mess me up. */
208                 ber_log_printf( LDAP_DEBUG_ANY, debuglevel,
209                         "sb_sasl_pkt_length: received illegal packet length "
210                         "of %lu bytes\n", (unsigned long)size );      
211                 size = 16; /* this should lead to an error. */
212         }
213
214         return size + 4; /* include the size !!! */
215 }
216
217 /* Drop a processed packet from the input buffer */
218 static void
219 sb_sasl_drop_packet ( Sockbuf_Buf *sec_buf_in, int debuglevel )
220 {
221         ber_slen_t                      len;
222
223         len = sec_buf_in->buf_ptr - sec_buf_in->buf_end;
224         if ( len > 0 )
225                 AC_MEMCPY( sec_buf_in->buf_base, sec_buf_in->buf_base +
226                         sec_buf_in->buf_end, len );
227    
228         if ( len >= 4 ) {
229                 sec_buf_in->buf_end = sb_sasl_pkt_length(
230                         (unsigned char *) sec_buf_in->buf_base, debuglevel);
231         }
232         else {
233                 sec_buf_in->buf_end = 0;
234         }
235         sec_buf_in->buf_ptr = len;
236 }
237
238 static ber_slen_t
239 sb_sasl_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
240 {
241         struct sb_sasl_data     *p;
242         ber_slen_t              ret, bufptr;
243    
244         assert( sbiod != NULL );
245         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
246
247         p = (struct sb_sasl_data *)sbiod->sbiod_pvt;
248
249         /* Are there anything left in the buffer? */
250         ret = ber_pvt_sb_copy_out( &p->buf_in, buf, len );
251         bufptr = ret;
252         len -= ret;
253
254         if ( len == 0 )
255                 return bufptr;
256
257 #if SASL_VERSION_MAJOR >= 2
258         ber_pvt_sb_buf_init( &p->buf_in );
259 #else
260         ber_pvt_sb_buf_destroy( &p->buf_in );
261 #endif
262
263         /* Read the length of the packet */
264         while ( p->sec_buf_in.buf_ptr < 4 ) {
265                 ret = LBER_SBIOD_READ_NEXT( sbiod, p->sec_buf_in.buf_base +
266                         p->sec_buf_in.buf_ptr,
267                         4 - p->sec_buf_in.buf_ptr );
268 #ifdef EINTR
269                 if ( ( ret < 0 ) && ( errno == EINTR ) )
270                         continue;
271 #endif
272                 if ( ret <= 0 )
273                         return bufptr ? bufptr : ret;
274
275                 p->sec_buf_in.buf_ptr += ret;
276         }
277
278         /* The new packet always starts at p->sec_buf_in.buf_base */
279         ret = sb_sasl_pkt_length( (unsigned char *) p->sec_buf_in.buf_base,
280                 sbiod->sbiod_sb->sb_debug );
281
282         /* Grow the packet buffer if neccessary */
283         if ( ( p->sec_buf_in.buf_size < (ber_len_t) ret ) && 
284                 ber_pvt_sb_grow_buffer( &p->sec_buf_in, ret ) < 0 )
285         {
286                 errno = ENOMEM;
287                 return -1;
288         }
289         p->sec_buf_in.buf_end = ret;
290
291         /* Did we read the whole encrypted packet? */
292         while ( p->sec_buf_in.buf_ptr < p->sec_buf_in.buf_end ) {
293                 /* No, we have got only a part of it */
294                 ret = p->sec_buf_in.buf_end - p->sec_buf_in.buf_ptr;
295
296                 ret = LBER_SBIOD_READ_NEXT( sbiod, p->sec_buf_in.buf_base +
297                         p->sec_buf_in.buf_ptr, ret );
298 #ifdef EINTR
299                 if ( ( ret < 0 ) && ( errno == EINTR ) )
300                         continue;
301 #endif
302                 if ( ret <= 0 )
303                         return bufptr ? bufptr : ret;
304
305                 p->sec_buf_in.buf_ptr += ret;
306         }
307
308         /* Decode the packet */
309         {
310                 unsigned tmpsize = p->buf_in.buf_end;
311                 ret = sasl_decode( p->sasl_context, p->sec_buf_in.buf_base,
312                         p->sec_buf_in.buf_end,
313                         (SASL_CONST char **)&p->buf_in.buf_base,
314                         (unsigned *)&tmpsize );
315                 p->buf_in.buf_end = tmpsize;
316         }
317
318         /* Drop the packet from the input buffer */
319         sb_sasl_drop_packet( &p->sec_buf_in, sbiod->sbiod_sb->sb_debug );
320
321         if ( ret != SASL_OK ) {
322                 ber_log_printf( LDAP_DEBUG_ANY, sbiod->sbiod_sb->sb_debug,
323                         "sb_sasl_read: failed to decode packet: %s\n",
324                         sasl_errstring( ret, NULL, NULL ) );
325                 errno = EIO;
326                 return -1;
327         }
328         
329         p->buf_in.buf_size = p->buf_in.buf_end;
330
331         bufptr += ber_pvt_sb_copy_out( &p->buf_in, (char*) buf + bufptr, len );
332
333         return bufptr;
334 }
335
336 static ber_slen_t
337 sb_sasl_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
338 {
339         struct sb_sasl_data     *p;
340         int                     ret;
341
342         assert( sbiod != NULL );
343         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
344
345         p = (struct sb_sasl_data *)sbiod->sbiod_pvt;
346
347         /* Are there anything left in the buffer? */
348         if ( p->buf_out.buf_ptr != p->buf_out.buf_end ) {
349                 ret = ber_pvt_sb_do_write( sbiod, &p->buf_out );
350                 if ( ret < 0 ) return ret;
351
352                 /* Still have something left?? */
353                 if ( p->buf_out.buf_ptr != p->buf_out.buf_end ) {
354                         errno = EAGAIN;
355                         return -1;
356                 }
357         }
358
359         /* now encode the next packet. */
360 #if SASL_VERSION_MAJOR >= 2
361         ber_pvt_sb_buf_init( &p->buf_out );
362 #else
363         ber_pvt_sb_buf_destroy( &p->buf_out );
364 #endif
365         if ( len > *p->sasl_maxbuf - 100 ) {
366                 len = *p->sasl_maxbuf - 100;    /* For safety margin */
367         }
368
369         {
370                 unsigned tmpsize = p->buf_out.buf_size;
371                 ret = sasl_encode( p->sasl_context, buf, len,
372                         (SASL_CONST char **)&p->buf_out.buf_base,
373                         &tmpsize );
374                 p->buf_out.buf_size = tmpsize;
375         }
376
377         if ( ret != SASL_OK ) {
378                 ber_log_printf( LDAP_DEBUG_ANY, sbiod->sbiod_sb->sb_debug,
379                         "sb_sasl_write: failed to encode packet: %s\n",
380                         sasl_errstring( ret, NULL, NULL ) );
381                 errno = EIO;
382                 return -1;
383         }
384         p->buf_out.buf_end = p->buf_out.buf_size;
385
386         ret = ber_pvt_sb_do_write( sbiod, &p->buf_out );
387
388         /* return number of bytes encoded, not written, to ensure
389          * no byte is encoded twice (even if only sent once).
390          */
391         return len;
392 }
393
394 static int
395 sb_sasl_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
396 {
397         struct sb_sasl_data     *p;
398
399         p = (struct sb_sasl_data *)sbiod->sbiod_pvt;
400
401         if ( opt == LBER_SB_OPT_DATA_READY ) {
402                 if ( p->buf_in.buf_ptr != p->buf_in.buf_end ) return 1;
403         }
404         
405         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
406 }
407
408 Sockbuf_IO ldap_pvt_sockbuf_io_sasl = {
409         sb_sasl_setup,          /* sbi_setup */
410         sb_sasl_remove,         /* sbi_remove */
411         sb_sasl_ctrl,           /* sbi_ctrl */
412         sb_sasl_read,           /* sbi_read */
413         sb_sasl_write,          /* sbi_write */
414         NULL                    /* sbi_close */
415 };
416
417 int ldap_pvt_sasl_install( Sockbuf *sb, void *ctx_arg )
418 {
419 #ifdef NEW_LOGGING
420         LDAP_LOG ( TRANSPORT, ENTRY, "ldap_pvt_sasl_install\n", 0, 0, 0 );
421 #else
422         Debug( LDAP_DEBUG_TRACE, "ldap_pvt_sasl_install\n",
423                 0, 0, 0 );
424 #endif
425
426         /* don't install the stuff unless security has been negotiated */
427
428         if ( !ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO,
429                         &ldap_pvt_sockbuf_io_sasl ) )
430         {
431 #ifdef LDAP_DEBUG
432                 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
433                         LBER_SBIOD_LEVEL_APPLICATION, (void *)"sasl_" );
434 #endif
435                 ber_sockbuf_add_io( sb, &ldap_pvt_sockbuf_io_sasl,
436                         LBER_SBIOD_LEVEL_APPLICATION, ctx_arg );
437         }
438
439         return LDAP_SUCCESS;
440 }
441
442 void ldap_pvt_sasl_remove( Sockbuf *sb )
443 {
444         ber_sockbuf_remove_io( sb, &ldap_pvt_sockbuf_io_sasl,
445                 LBER_SBIOD_LEVEL_APPLICATION );
446 #ifdef LDAP_DEBUG
447         ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
448                 LBER_SBIOD_LEVEL_APPLICATION );
449 #endif
450 }
451
452 static int
453 sasl_err2ldap( int saslerr )
454 {
455         int rc;
456
457         switch (saslerr) {
458                 case SASL_CONTINUE:
459                         rc = LDAP_MORE_RESULTS_TO_RETURN;
460                         break;
461                 case SASL_INTERACT:
462                         rc = LDAP_LOCAL_ERROR;
463                         break;
464                 case SASL_OK:
465                         rc = LDAP_SUCCESS;
466                         break;
467                 case SASL_FAIL:
468                         rc = LDAP_LOCAL_ERROR;
469                         break;
470                 case SASL_NOMEM:
471                         rc = LDAP_NO_MEMORY;
472                         break;
473                 case SASL_NOMECH:
474                         rc = LDAP_AUTH_UNKNOWN;
475                         break;
476                 case SASL_BADAUTH:
477                         rc = LDAP_AUTH_UNKNOWN;
478                         break;
479                 case SASL_NOAUTHZ:
480                         rc = LDAP_PARAM_ERROR;
481                         break;
482                 case SASL_TOOWEAK:
483                 case SASL_ENCRYPT:
484                         rc = LDAP_AUTH_UNKNOWN;
485                         break;
486                 default:
487                         rc = LDAP_LOCAL_ERROR;
488                         break;
489         }
490
491         assert( rc == LDAP_SUCCESS || LDAP_API_ERROR( rc ) );
492         return rc;
493 }
494
495 int
496 ldap_int_sasl_open(
497         LDAP *ld, 
498         LDAPConn *lc,
499         const char * host )
500 {
501         int rc;
502         sasl_conn_t *ctx;
503
504         assert( lc->lconn_sasl_authctx == NULL );
505
506         if ( host == NULL ) {
507                 ld->ld_errno = LDAP_LOCAL_ERROR;
508                 return ld->ld_errno;
509         }
510
511         if ( ldap_int_sasl_init() ) {
512                 ld->ld_errno = LDAP_LOCAL_ERROR;
513                 return ld->ld_errno;
514         }
515
516 #if SASL_VERSION_MAJOR >= 2
517         rc = sasl_client_new( "ldap", host, NULL, NULL,
518                 client_callbacks, 0, &ctx );
519 #else
520         rc = sasl_client_new( "ldap", host, client_callbacks,
521                 SASL_SECURITY_LAYER, &ctx );
522 #endif
523
524         if ( rc != SASL_OK ) {
525                 ld->ld_errno = sasl_err2ldap( rc );
526                 return ld->ld_errno;
527         }
528
529 #ifdef NEW_LOGGING
530         LDAP_LOG ( TRANSPORT, DETAIL1, "ldap_int_sasl_open: host=%s\n", 
531                 host, 0, 0 );
532 #else
533         Debug( LDAP_DEBUG_TRACE, "ldap_int_sasl_open: host=%s\n",
534                 host, 0, 0 );
535 #endif
536
537         lc->lconn_sasl_authctx = ctx;
538
539         return LDAP_SUCCESS;
540 }
541
542 int ldap_int_sasl_close( LDAP *ld, LDAPConn *lc )
543 {
544         sasl_conn_t *ctx = lc->lconn_sasl_authctx;
545
546         if( ctx != NULL ) {
547                 sasl_dispose( &ctx );
548                 if ( lc->lconn_sasl_sockctx &&
549                         lc->lconn_sasl_authctx != lc->lconn_sasl_sockctx ) {
550                         ctx = lc->lconn_sasl_sockctx;
551                         sasl_dispose( &ctx );
552                 }
553                 lc->lconn_sasl_sockctx = NULL;
554                 lc->lconn_sasl_authctx = NULL;
555         }
556
557         return LDAP_SUCCESS;
558 }
559
560 int
561 ldap_int_sasl_bind(
562         LDAP                    *ld,
563         const char              *dn,
564         const char              *mechs,
565         LDAPControl             **sctrls,
566         LDAPControl             **cctrls,
567         unsigned                flags,
568         LDAP_SASL_INTERACT_PROC *interact,
569         void * defaults )
570 {
571         char *data;
572         const char *mech = NULL;
573         const char *pmech = NULL;
574         int                     saslrc, rc;
575         sasl_ssf_t              *ssf = NULL;
576         sasl_conn_t     *ctx, *oldctx = NULL;
577         sasl_interact_t *prompts = NULL;
578         unsigned credlen;
579         struct berval ccred;
580         ber_socket_t            sd;
581         void    *ssl;
582
583 #ifdef NEW_LOGGING
584         LDAP_LOG ( TRANSPORT, ARGS, "ldap_int_sasl_bind: %s\n", 
585                 mechs ? mechs : "<null>", 0, 0 );
586 #else
587         Debug( LDAP_DEBUG_TRACE, "ldap_int_sasl_bind: %s\n",
588                 mechs ? mechs : "<null>", 0, 0 );
589 #endif
590
591         /* do a quick !LDAPv3 check... ldap_sasl_bind will do the rest. */
592         if (ld->ld_version < LDAP_VERSION3) {
593                 ld->ld_errno = LDAP_NOT_SUPPORTED;
594                 return ld->ld_errno;
595         }
596
597         ber_sockbuf_ctrl( ld->ld_sb, LBER_SB_OPT_GET_FD, &sd );
598
599         if ( sd == AC_SOCKET_INVALID ) {
600                 /* not connected yet */
601                 int rc;
602
603                 rc = ldap_open_defconn( ld );
604                 if( rc < 0 ) return ld->ld_errno;
605
606                 ber_sockbuf_ctrl( ld->ld_defconn->lconn_sb, LBER_SB_OPT_GET_FD, &sd );
607
608                 if( sd == AC_SOCKET_INVALID ) {
609                         ld->ld_errno = LDAP_LOCAL_ERROR;
610                         return ld->ld_errno;
611                 }
612         }   
613
614         oldctx = ld->ld_defconn->lconn_sasl_authctx;
615
616         /* If we already have an authentication context, clear it out */
617         if( oldctx ) {
618                 if ( oldctx != ld->ld_defconn->lconn_sasl_sockctx ) {
619                         sasl_dispose( &oldctx );
620                 }
621                 ld->ld_defconn->lconn_sasl_authctx = NULL;
622         }
623
624         { char *saslhost = ldap_host_connected_to( ld->ld_defconn->lconn_sb, "localhost" );
625         rc = ldap_int_sasl_open( ld, ld->ld_defconn, saslhost );
626         LDAP_FREE( saslhost );
627         }
628
629         if ( rc != LDAP_SUCCESS ) return rc;
630
631         ctx = ld->ld_defconn->lconn_sasl_authctx;
632
633         /* Check for TLS */
634         ssl = ldap_pvt_tls_sb_ctx( ld->ld_defconn->lconn_sb );
635         if ( ssl ) {
636                 struct berval authid = BER_BVNULL;
637                 ber_len_t fac;
638
639                 fac = ldap_pvt_tls_get_strength( ssl );
640                 /* failure is OK, we just can't use SASL EXTERNAL */
641                 (void) ldap_pvt_tls_get_my_dn( ssl, &authid, NULL, 0 );
642
643                 (void) ldap_int_sasl_external( ld, ld->ld_defconn, authid.bv_val, fac );
644                 LDAP_FREE( authid.bv_val );
645         }
646
647 #if !defined(_WIN32)
648         /* Check for local */
649         if ( ldap_pvt_url_scheme2proto( ld->ld_defconn->lconn_server->lud_scheme ) == LDAP_PROTO_IPC ) {
650                 char authid[sizeof("uidNumber=4294967295+gidNumber=4294967295,"
651                         "cn=peercred,cn=external,cn=auth")];
652                 sprintf( authid, "uidNumber=%d+gidNumber=%d,"
653                         "cn=peercred,cn=external,cn=auth",
654                         (int) geteuid(), (int) getegid() );
655                 (void) ldap_int_sasl_external( ld, ld->ld_defconn, authid, LDAP_PVT_SASL_LOCAL_SSF );
656         }
657 #endif
658
659         /* (re)set security properties */
660         sasl_setprop( ctx, SASL_SEC_PROPS,
661                 &ld->ld_options.ldo_sasl_secprops );
662
663         ccred.bv_val = NULL;
664         ccred.bv_len = 0;
665
666         do {
667                 saslrc = sasl_client_start( ctx,
668                         mechs,
669 #if SASL_VERSION_MAJOR < 2
670                         NULL,
671 #endif
672                         &prompts,
673                         (SASL_CONST char **)&ccred.bv_val,
674                         &credlen,
675                         &mech );
676
677                 if( pmech == NULL && mech != NULL ) {
678                         pmech = mech;
679
680                         if( flags != LDAP_SASL_QUIET ) {
681                                 fprintf(stderr,
682                                         "SASL/%s authentication started\n",
683                                         pmech );
684                         }
685                 }
686
687                 if( saslrc == SASL_INTERACT ) {
688                         int res;
689                         if( !interact ) break;
690                         res = (interact)( ld, flags, defaults, prompts );
691
692                         if( res != LDAP_SUCCESS ) break;
693                 }
694         } while ( saslrc == SASL_INTERACT );
695
696         ccred.bv_len = credlen;
697
698         if ( (saslrc != SASL_OK) && (saslrc != SASL_CONTINUE) ) {
699                 rc = ld->ld_errno = sasl_err2ldap( saslrc );
700 #if SASL_VERSION_MAJOR >= 2
701                 if (ld->ld_error ) {
702                         LDAP_FREE( ld->ld_error );
703                 }
704                 ld->ld_error = LDAP_STRDUP( sasl_errdetail( ctx ) );
705 #endif
706                 goto done;
707         }
708
709         do {
710                 struct berval *scred;
711                 unsigned credlen;
712
713                 scred = NULL;
714
715                 rc = ldap_sasl_bind_s( ld, dn, mech, &ccred, sctrls, cctrls, &scred );
716
717                 if ( ccred.bv_val != NULL ) {
718 #if SASL_VERSION_MAJOR < 2
719                         LDAP_FREE( ccred.bv_val );
720 #endif
721                         ccred.bv_val = NULL;
722                 }
723
724                 if ( rc != LDAP_SUCCESS && rc != LDAP_SASL_BIND_IN_PROGRESS ) {
725                         if( scred ) {
726                                 if ( scred->bv_len ) {
727                                         /* and server provided us with data? */
728 #ifdef NEW_LOGGING
729                                         LDAP_LOG ( TRANSPORT, DETAIL1, 
730                                                 "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n", 
731                                                 rc, saslrc, scred->bv_len );
732 #else
733                                         Debug( LDAP_DEBUG_TRACE,
734                                                 "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n",
735                                                 rc, saslrc, scred->bv_len );
736 #endif
737                                 }
738                                 ber_bvfree( scred );
739                         }
740                         rc = ld->ld_errno;
741                         goto done;
742                 }
743
744                 if( rc == LDAP_SUCCESS && saslrc == SASL_OK ) {
745                         /* we're done, no need to step */
746                         if( scred ) {
747                                 if ( scred->bv_len ) {
748                                 /* but server provided us with data! */
749 #ifdef NEW_LOGGING
750                                         LDAP_LOG ( TRANSPORT, DETAIL1, 
751                                                 "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n", 
752                                                 rc, saslrc, scred->bv_len );
753 #else
754                                         Debug( LDAP_DEBUG_TRACE,
755                                                 "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n",
756                                                 rc, saslrc, scred->bv_len );
757 #endif
758                                 }
759                                 ber_bvfree( scred );
760                                 rc = ld->ld_errno = LDAP_LOCAL_ERROR;
761                                 goto done;
762                         }
763                         break;
764                 }
765
766                 do {
767                         saslrc = sasl_client_step( ctx,
768                                 (scred == NULL) ? NULL : scred->bv_val,
769                                 (scred == NULL) ? 0 : scred->bv_len,
770                                 &prompts,
771                                 (SASL_CONST char **)&ccred.bv_val,
772                                 &credlen );
773
774 #ifdef NEW_LOGGING
775                                 LDAP_LOG ( TRANSPORT, DETAIL1, 
776                                         "ldap_int_sasl_bind: sasl_client_step: %d\n", saslrc,0,0 );
777 #else
778                         Debug( LDAP_DEBUG_TRACE, "sasl_client_step: %d\n",
779                                 saslrc, 0, 0 );
780 #endif
781
782                         if( saslrc == SASL_INTERACT ) {
783                                 int res;
784                                 if( !interact ) break;
785                                 res = (interact)( ld, flags, defaults, prompts );
786                                 if( res != LDAP_SUCCESS ) break;
787                         }
788                 } while ( saslrc == SASL_INTERACT );
789
790                 ccred.bv_len = credlen;
791                 ber_bvfree( scred );
792
793                 if ( (saslrc != SASL_OK) && (saslrc != SASL_CONTINUE) ) {
794                         ld->ld_errno = sasl_err2ldap( saslrc );
795 #if SASL_VERSION_MAJOR >= 2
796                         if (ld->ld_error ) {
797                                 LDAP_FREE( ld->ld_error );
798                         }
799                         ld->ld_error = LDAP_STRDUP( sasl_errdetail( ctx ) );
800 #endif
801                         rc = ld->ld_errno;
802                         goto done;
803                 }
804         } while ( rc == LDAP_SASL_BIND_IN_PROGRESS );
805
806         if ( rc != LDAP_SUCCESS ) goto done;
807
808         if ( saslrc != SASL_OK ) {
809 #if SASL_VERSION_MAJOR >= 2
810                 if (ld->ld_error ) {
811                         LDAP_FREE( ld->ld_error );
812                 }
813                 ld->ld_error = LDAP_STRDUP( sasl_errdetail( ctx ) );
814 #endif
815                 rc = ld->ld_errno = sasl_err2ldap( saslrc );
816                 goto done;
817         }
818
819         if( flags != LDAP_SASL_QUIET ) {
820                 saslrc = sasl_getprop( ctx, SASL_USERNAME, (SASL_CONST void **) &data );
821                 if( saslrc == SASL_OK && data && *data ) {
822                         fprintf( stderr, "SASL username: %s\n", data );
823                 }
824
825 #if SASL_VERSION_MAJOR < 2
826                 saslrc = sasl_getprop( ctx, SASL_REALM, (SASL_CONST void **) &data );
827                 if( saslrc == SASL_OK && data && *data ) {
828                         fprintf( stderr, "SASL realm: %s\n", data );
829                 }
830 #endif
831         }
832
833         saslrc = sasl_getprop( ctx, SASL_SSF, (SASL_CONST void **) &ssf );
834         if( saslrc == SASL_OK ) {
835                 if( flags != LDAP_SASL_QUIET ) {
836                         fprintf( stderr, "SASL SSF: %lu\n",
837                                 (unsigned long) *ssf );
838                 }
839
840                 if( ssf && *ssf ) {
841                         if( flags != LDAP_SASL_QUIET ) {
842                                 fprintf( stderr, "SASL installing layers\n" );
843                         }
844                         if ( ld->ld_defconn->lconn_sasl_sockctx ) {
845                                 oldctx = ld->ld_defconn->lconn_sasl_sockctx;
846                                 sasl_dispose( &oldctx );
847                                 ldap_pvt_sasl_remove( ld->ld_defconn->lconn_sb );
848                         }
849                         ldap_pvt_sasl_install( ld->ld_defconn->lconn_sb, ctx );
850                         ld->ld_defconn->lconn_sasl_sockctx = ctx;
851                 }
852         }
853         ld->ld_defconn->lconn_sasl_authctx = ctx;
854
855 done:
856         return rc;
857 }
858
859 int
860 ldap_int_sasl_external(
861         LDAP *ld,
862         LDAPConn *conn,
863         const char * authid,
864         ber_len_t ssf )
865 {
866         int sc;
867         sasl_conn_t *ctx;
868 #if SASL_VERSION_MAJOR < 2
869         sasl_external_properties_t extprops;
870 #endif
871
872         ctx = conn->lconn_sasl_authctx;
873
874         if ( ctx == NULL ) {
875                 return LDAP_LOCAL_ERROR;
876         }
877    
878 #if SASL_VERSION_MAJOR >= 2
879         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
880         if ( sc == SASL_OK )
881                 sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
882 #else
883         memset( &extprops, '\0', sizeof(extprops) );
884         extprops.ssf = ssf;
885         extprops.auth_id = (char *) authid;
886
887         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
888                 (void *) &extprops );
889 #endif
890
891         if ( sc != SASL_OK ) {
892                 return LDAP_LOCAL_ERROR;
893         }
894
895         return LDAP_SUCCESS;
896 }
897
898
899 int ldap_pvt_sasl_secprops(
900         const char *in,
901         sasl_security_properties_t *secprops )
902 {
903         int i;
904         char **props = ldap_str2charray( in, "," );
905         unsigned sflags = 0;
906         int got_sflags = 0;
907         sasl_ssf_t max_ssf = 0;
908         int got_max_ssf = 0;
909         sasl_ssf_t min_ssf = 0;
910         int got_min_ssf = 0;
911         unsigned maxbufsize = 0;
912         int got_maxbufsize = 0;
913
914         if( props == NULL || secprops == NULL ) {
915                 return LDAP_PARAM_ERROR;
916         }
917
918         for( i=0; props[i]; i++ ) {
919                 if( !strcasecmp(props[i], "none") ) {
920                         got_sflags++;
921
922                 } else if( !strcasecmp(props[i], "noplain") ) {
923                         got_sflags++;
924                         sflags |= SASL_SEC_NOPLAINTEXT;
925
926                 } else if( !strcasecmp(props[i], "noactive") ) {
927                         got_sflags++;
928                         sflags |= SASL_SEC_NOACTIVE;
929
930                 } else if( !strcasecmp(props[i], "nodict") ) {
931                         got_sflags++;
932                         sflags |= SASL_SEC_NODICTIONARY;
933
934                 } else if( !strcasecmp(props[i], "forwardsec") ) {
935                         got_sflags++;
936                         sflags |= SASL_SEC_FORWARD_SECRECY;
937
938                 } else if( !strcasecmp(props[i], "noanonymous")) {
939                         got_sflags++;
940                         sflags |= SASL_SEC_NOANONYMOUS;
941
942                 } else if( !strcasecmp(props[i], "passcred") ) {
943                         got_sflags++;
944                         sflags |= SASL_SEC_PASS_CREDENTIALS;
945
946                 } else if( !strncasecmp(props[i],
947                         "minssf=", sizeof("minssf")) )
948                 {
949                         if( isdigit( (unsigned char) props[i][sizeof("minssf")] ) ) {
950                                 got_min_ssf++;
951                                 min_ssf = atoi( &props[i][sizeof("minssf")] );
952                         } else {
953                                 return LDAP_NOT_SUPPORTED;
954                         }
955
956                 } else if( !strncasecmp(props[i],
957                         "maxssf=", sizeof("maxssf")) )
958                 {
959                         if( isdigit( (unsigned char) props[i][sizeof("maxssf")] ) ) {
960                                 got_max_ssf++;
961                                 max_ssf = atoi( &props[i][sizeof("maxssf")] );
962                         } else {
963                                 return LDAP_NOT_SUPPORTED;
964                         }
965
966                 } else if( !strncasecmp(props[i],
967                         "maxbufsize=", sizeof("maxbufsize")) )
968                 {
969                         if( isdigit( (unsigned char) props[i][sizeof("maxbufsize")] ) ) {
970                                 got_maxbufsize++;
971                                 maxbufsize = atoi( &props[i][sizeof("maxbufsize")] );
972                         } else {
973                                 return LDAP_NOT_SUPPORTED;
974                         }
975
976                         if( maxbufsize && (( maxbufsize < SASL_MIN_BUFF_SIZE )
977                                 || (maxbufsize > SASL_MAX_BUFF_SIZE )))
978                         {
979                                 /* bad maxbufsize */
980                                 return LDAP_PARAM_ERROR;
981                         }
982
983                 } else {
984                         return LDAP_NOT_SUPPORTED;
985                 }
986         }
987
988         if(got_sflags) {
989                 secprops->security_flags = sflags;
990         }
991         if(got_min_ssf) {
992                 secprops->min_ssf = min_ssf;
993         }
994         if(got_max_ssf) {
995                 secprops->max_ssf = max_ssf;
996         }
997         if(got_maxbufsize) {
998                 secprops->maxbufsize = maxbufsize;
999         }
1000
1001         ldap_charray_free( props );
1002         return LDAP_SUCCESS;
1003 }
1004
1005 int
1006 ldap_int_sasl_config( struct ldapoptions *lo, int option, const char *arg )
1007 {
1008         int rc;
1009
1010         switch( option ) {
1011         case LDAP_OPT_X_SASL_SECPROPS:
1012                 rc = ldap_pvt_sasl_secprops( arg, &lo->ldo_sasl_secprops );
1013                 if( rc == LDAP_SUCCESS ) return 0;
1014         }
1015
1016         return -1;
1017 }
1018
1019 int
1020 ldap_int_sasl_get_option( LDAP *ld, int option, void *arg )
1021 {
1022         if ( ld == NULL )
1023                 return -1;
1024
1025         switch ( option ) {
1026                 case LDAP_OPT_X_SASL_MECH: {
1027                         *(char **)arg = ld->ld_options.ldo_def_sasl_mech
1028                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_mech ) : NULL;
1029                 } break;
1030                 case LDAP_OPT_X_SASL_REALM: {
1031                         *(char **)arg = ld->ld_options.ldo_def_sasl_realm
1032                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_realm ) : NULL;
1033                 } break;
1034                 case LDAP_OPT_X_SASL_AUTHCID: {
1035                         *(char **)arg = ld->ld_options.ldo_def_sasl_authcid
1036                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_authcid ) : NULL;
1037                 } break;
1038                 case LDAP_OPT_X_SASL_AUTHZID: {
1039                         *(char **)arg = ld->ld_options.ldo_def_sasl_authzid
1040                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_authzid ) : NULL;
1041                 } break;
1042
1043                 case LDAP_OPT_X_SASL_SSF: {
1044                         int sc;
1045                         sasl_ssf_t      *ssf;
1046                         sasl_conn_t *ctx;
1047
1048                         if( ld->ld_defconn == NULL ) {
1049                                 return -1;
1050                         }
1051
1052                         ctx = ld->ld_defconn->lconn_sasl_sockctx;
1053
1054                         if ( ctx == NULL ) {
1055                                 return -1;
1056                         }
1057
1058                         sc = sasl_getprop( ctx, SASL_SSF,
1059                                 (SASL_CONST void **) &ssf );
1060
1061                         if ( sc != SASL_OK ) {
1062                                 return -1;
1063                         }
1064
1065                         *(ber_len_t *)arg = *ssf;
1066                 } break;
1067
1068                 case LDAP_OPT_X_SASL_SSF_EXTERNAL:
1069                         /* this option is write only */
1070                         return -1;
1071
1072                 case LDAP_OPT_X_SASL_SSF_MIN:
1073                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.min_ssf;
1074                         break;
1075                 case LDAP_OPT_X_SASL_SSF_MAX:
1076                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.max_ssf;
1077                         break;
1078                 case LDAP_OPT_X_SASL_MAXBUFSIZE:
1079                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.maxbufsize;
1080                         break;
1081
1082                 case LDAP_OPT_X_SASL_SECPROPS:
1083                         /* this option is write only */
1084                         return -1;
1085
1086                 default:
1087                         return -1;
1088         }
1089         return 0;
1090 }
1091
1092 int
1093 ldap_int_sasl_set_option( LDAP *ld, int option, void *arg )
1094 {
1095         if ( ld == NULL )
1096                 return -1;
1097
1098         switch ( option ) {
1099         case LDAP_OPT_X_SASL_SSF:
1100                 /* This option is read-only */
1101                 return -1;
1102
1103         case LDAP_OPT_X_SASL_SSF_EXTERNAL: {
1104                 int sc;
1105 #if SASL_VERSION_MAJOR < 2
1106                 sasl_external_properties_t extprops;
1107 #endif
1108                 sasl_conn_t *ctx;
1109
1110                 if( ld->ld_defconn == NULL ) {
1111                         return -1;
1112                 }
1113
1114                 ctx = ld->ld_defconn->lconn_sasl_authctx;
1115
1116                 if ( ctx == NULL ) {
1117                         return -1;
1118                 }
1119
1120 #if SASL_VERSION_MAJOR >= 2
1121                 sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, arg);
1122 #else
1123                 memset(&extprops, 0L, sizeof(extprops));
1124
1125                 extprops.ssf = * (ber_len_t *) arg;
1126
1127                 sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1128                         (void *) &extprops );
1129 #endif
1130
1131                 if ( sc != SASL_OK ) {
1132                         return -1;
1133                 }
1134                 } break;
1135
1136         case LDAP_OPT_X_SASL_SSF_MIN:
1137                 ld->ld_options.ldo_sasl_secprops.min_ssf = *(ber_len_t *)arg;
1138                 break;
1139         case LDAP_OPT_X_SASL_SSF_MAX:
1140                 ld->ld_options.ldo_sasl_secprops.max_ssf = *(ber_len_t *)arg;
1141                 break;
1142         case LDAP_OPT_X_SASL_MAXBUFSIZE:
1143                 ld->ld_options.ldo_sasl_secprops.maxbufsize = *(ber_len_t *)arg;
1144                 break;
1145
1146         case LDAP_OPT_X_SASL_SECPROPS: {
1147                 int sc;
1148                 sc = ldap_pvt_sasl_secprops( (char *) arg,
1149                         &ld->ld_options.ldo_sasl_secprops );
1150
1151                 return sc == LDAP_SUCCESS ? 0 : -1;
1152                 }
1153
1154         default:
1155                 return -1;
1156         }
1157         return 0;
1158 }
1159
1160 #ifdef LDAP_R_COMPILE
1161 #define LDAP_DEBUG_R_SASL
1162 void *ldap_pvt_sasl_mutex_new(void)
1163 {
1164         ldap_pvt_thread_mutex_t *mutex;
1165
1166         mutex = (ldap_pvt_thread_mutex_t *) LDAP_MALLOC(
1167                 sizeof(ldap_pvt_thread_mutex_t) );
1168
1169         if ( ldap_pvt_thread_mutex_init( mutex ) == 0 ) {
1170                 return mutex;
1171         }
1172 #ifndef LDAP_DEBUG_R_SASL
1173         assert( 0 );
1174 #endif /* !LDAP_DEBUG_R_SASL */
1175         return NULL;
1176 }
1177
1178 int ldap_pvt_sasl_mutex_lock(void *mutex)
1179 {
1180 #ifdef LDAP_DEBUG_R_SASL
1181         if ( mutex == NULL ) {
1182                 return SASL_OK;
1183         }
1184 #else /* !LDAP_DEBUG_R_SASL */
1185         assert( mutex );
1186 #endif /* !LDAP_DEBUG_R_SASL */
1187         return ldap_pvt_thread_mutex_lock( (ldap_pvt_thread_mutex_t *)mutex )
1188                 ? SASL_FAIL : SASL_OK;
1189 }
1190
1191 int ldap_pvt_sasl_mutex_unlock(void *mutex)
1192 {
1193 #ifdef LDAP_DEBUG_R_SASL
1194         if ( mutex == NULL ) {
1195                 return SASL_OK;
1196         }
1197 #else /* !LDAP_DEBUG_R_SASL */
1198         assert( mutex );
1199 #endif /* !LDAP_DEBUG_R_SASL */
1200         return ldap_pvt_thread_mutex_unlock( (ldap_pvt_thread_mutex_t *)mutex )
1201                 ? SASL_FAIL : SASL_OK;
1202 }
1203
1204 void ldap_pvt_sasl_mutex_dispose(void *mutex)
1205 {
1206 #ifdef LDAP_DEBUG_R_SASL
1207         if ( mutex == NULL ) {
1208                 return;
1209         }
1210 #else /* !LDAP_DEBUG_R_SASL */
1211         assert( mutex );
1212 #endif /* !LDAP_DEBUG_R_SASL */
1213         (void) ldap_pvt_thread_mutex_destroy( (ldap_pvt_thread_mutex_t *)mutex );
1214         LDAP_FREE( mutex );
1215 }
1216 #endif
1217
1218 #else
1219 int ldap_int_sasl_init( void )
1220 { return LDAP_SUCCESS; }
1221
1222 int ldap_int_sasl_close( LDAP *ld, LDAPConn *lc )
1223 { return LDAP_SUCCESS; }
1224
1225 int
1226 ldap_int_sasl_bind(
1227         LDAP                    *ld,
1228         const char              *dn,
1229         const char              *mechs,
1230         LDAPControl             **sctrls,
1231         LDAPControl             **cctrls,
1232         unsigned                flags,
1233         LDAP_SASL_INTERACT_PROC *interact,
1234         void * defaults )
1235 { return LDAP_NOT_SUPPORTED; }
1236
1237 int
1238 ldap_int_sasl_external(
1239         LDAP *ld,
1240         LDAPConn *conn,
1241         const char * authid,
1242         ber_len_t ssf )
1243 { return LDAP_SUCCESS; }
1244
1245 #endif /* HAVE_CYRUS_SASL */