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