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