]> git.sur5r.net Git - openldap/blob - libraries/libldap/cyrus.c
Sync with HEAD
[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 #define GOT_MINSSF      1
849 #define GOT_MAXSSF      2
850 #define GOT_MAXBUF      4
851
852 static struct {
853         struct berval key;
854         int sflag;
855         int ival;
856         int idef;
857 } sprops[] = {
858         { BER_BVC("none"), 0, 0, 0 },
859         { BER_BVC("nodict"), SASL_SEC_NODICTIONARY, 0, 0 },
860         { BER_BVC("noplain"), SASL_SEC_NOPLAINTEXT, 0, 0 },
861         { BER_BVC("noactive"), SASL_SEC_NOACTIVE, 0, 0 },
862         { BER_BVC("passcred"), SASL_SEC_PASS_CREDENTIALS, 0, 0 },
863         { BER_BVC("forwardsec"), SASL_SEC_FORWARD_SECRECY, 0, 0 },
864         { BER_BVC("noanonymous"), SASL_SEC_NOANONYMOUS, 0, 0 },
865         { BER_BVC("minssf="), 0, GOT_MINSSF, 0 },
866         { BER_BVC("maxssf="), 0, GOT_MAXSSF, INT_MAX },
867         { BER_BVC("maxbufsize="), 0, GOT_MAXBUF, 65536 },
868         { BER_BVNULL, 0, 0 }
869 };
870
871 void ldap_pvt_sasl_secprops_unparse(
872         sasl_security_properties_t *secprops,
873         struct berval *out )
874 {
875         int i, l = 0;
876         int comma;
877         char *ptr;
878
879         if ( secprops == NULL || out == NULL ) {
880                 return;
881         }
882
883         comma = 0;
884         for ( i=0; !BER_BVISNULL( &sprops[i].key ); i++ ) {
885                 if ( sprops[i].ival ) {
886                         int v;
887
888                         switch( sprops[i].ival ) {
889                         case GOT_MINSSF: v = secprops->min_ssf; break;
890                         case GOT_MAXSSF: v = secprops->max_ssf; break;
891                         case GOT_MAXBUF: v = secprops->maxbufsize; break;
892                         }
893                         /* It is the default, ignore it */
894                         if ( v == sprops[i].idef ) continue;
895
896                         l += sprops[i].key.bv_len + 24;
897                 } else if ( sprops[i].sflag ) {
898                         if ( sprops[i].sflag & secprops->security_flags ) {
899                                 l += sprops[i].key.bv_len;
900                         }
901                 } else if ( secprops->security_flags == 0 ) {
902                         l += sprops[i].key.bv_len;
903                 }
904                 if ( comma ) l++;
905                 comma = 1;
906         }
907         l++;
908
909         out->bv_val = LDAP_MALLOC( l );
910         if ( out->bv_val == NULL ) {
911                 out->bv_len = 0;
912                 return;
913         }
914
915         ptr = out->bv_val;
916         comma = 0;
917         for ( i=0; !BER_BVISNULL( &sprops[i].key ); i++ ) {
918                 if ( sprops[i].ival ) {
919                         int v;
920
921                         switch( sprops[i].ival ) {
922                         case GOT_MINSSF: v = secprops->min_ssf; break;
923                         case GOT_MAXSSF: v = secprops->max_ssf; break;
924                         case GOT_MAXBUF: v = secprops->maxbufsize; break;
925                         }
926                         /* It is the default, ignore it */
927                         if ( v == sprops[i].idef ) continue;
928
929                         if ( comma ) *ptr++ = ',';
930                         ptr += sprintf(ptr, "%s%d", sprops[i].key.bv_val, v );
931                         comma = 1;
932                 } else if ( sprops[i].sflag ) {
933                         if ( sprops[i].sflag & secprops->security_flags ) {
934                                 if ( comma ) *ptr++ = ',';
935                                 ptr += sprintf(ptr, "%s", sprops[i].key.bv_val );
936                                 comma = 1;
937                         }
938                 } else if ( secprops->security_flags == 0 ) {
939                         if ( comma ) *ptr++ = ',';
940                         ptr += sprintf(ptr, "%s", sprops[i].key.bv_val );
941                         comma = 1;
942                 }
943         }
944         out->bv_len = ptr - out->bv_val;
945 }
946
947 int ldap_pvt_sasl_secprops(
948         const char *in,
949         sasl_security_properties_t *secprops )
950 {
951         int i, j, l;
952         char **props = ldap_str2charray( in, "," );
953         unsigned sflags = 0;
954         int got_sflags = 0;
955         sasl_ssf_t max_ssf = 0;
956         int got_max_ssf = 0;
957         sasl_ssf_t min_ssf = 0;
958         int got_min_ssf = 0;
959         unsigned maxbufsize = 0;
960         int got_maxbufsize = 0;
961
962         if( props == NULL || secprops == NULL ) {
963                 return LDAP_PARAM_ERROR;
964         }
965
966         for( i=0; props[i]; i++ ) {
967                 l = strlen( props[i] );
968                 for ( j=0; !BER_BVISNULL( &sprops[j].key ); j++ ) {
969                         if ( l < sprops[j].key.bv_len ) continue;
970                         if ( strncasecmp( props[i], sprops[j].key.bv_val,
971                                 sprops[j].key.bv_len )) continue;
972                         if ( sprops[j].ival ) {
973                                 int v;
974                                 if ( props[i][sprops[j].key.bv_len] != '=' ) continue;
975                                 if ( !isdigit( props[i][sprops[j].key.bv_len+1] )) continue;
976                                 v = atoi( props[i]+sprops[j].key.bv_len+1 );
977                                 switch( sprops[j].ival ) {
978                                 case GOT_MINSSF:
979                                         min_ssf = v; got_min_ssf++; break;
980                                 case GOT_MAXSSF:
981                                         max_ssf = v; got_max_ssf++; break;
982                                 case GOT_MAXBUF:
983                                         maxbufsize = v; got_maxbufsize++; break;
984                                 }
985                         } else {
986                                 if ( props[i][sprops[j].key.bv_len] ) continue;
987                                 if ( sprops[j].sflag )
988                                         sflags |= sprops[j].sflag;
989                                 else
990                                         sflags = 0;
991                                 got_sflags++;
992                         }
993                         break;
994                 }
995                 if ( BER_BVISNULL( &sprops[j].key )) {
996                         return LDAP_NOT_SUPPORTED;
997                 }
998         }
999
1000         if(got_sflags) {
1001                 secprops->security_flags = sflags;
1002         }
1003         if(got_min_ssf) {
1004                 secprops->min_ssf = min_ssf;
1005         }
1006         if(got_max_ssf) {
1007                 secprops->max_ssf = max_ssf;
1008         }
1009         if(got_maxbufsize) {
1010                 secprops->maxbufsize = maxbufsize;
1011         }
1012
1013         ldap_charray_free( props );
1014         return LDAP_SUCCESS;
1015 }
1016
1017 int
1018 ldap_int_sasl_config( struct ldapoptions *lo, int option, const char *arg )
1019 {
1020         int rc;
1021
1022         switch( option ) {
1023         case LDAP_OPT_X_SASL_SECPROPS:
1024                 rc = ldap_pvt_sasl_secprops( arg, &lo->ldo_sasl_secprops );
1025                 if( rc == LDAP_SUCCESS ) return 0;
1026         }
1027
1028         return -1;
1029 }
1030
1031 int
1032 ldap_int_sasl_get_option( LDAP *ld, int option, void *arg )
1033 {
1034         if ( ld == NULL )
1035                 return -1;
1036
1037         switch ( option ) {
1038                 case LDAP_OPT_X_SASL_MECH: {
1039                         *(char **)arg = ld->ld_options.ldo_def_sasl_mech
1040                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_mech ) : NULL;
1041                 } break;
1042                 case LDAP_OPT_X_SASL_REALM: {
1043                         *(char **)arg = ld->ld_options.ldo_def_sasl_realm
1044                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_realm ) : NULL;
1045                 } break;
1046                 case LDAP_OPT_X_SASL_AUTHCID: {
1047                         *(char **)arg = ld->ld_options.ldo_def_sasl_authcid
1048                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_authcid ) : NULL;
1049                 } break;
1050                 case LDAP_OPT_X_SASL_AUTHZID: {
1051                         *(char **)arg = ld->ld_options.ldo_def_sasl_authzid
1052                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_authzid ) : NULL;
1053                 } break;
1054
1055                 case LDAP_OPT_X_SASL_SSF: {
1056                         int sc;
1057                         sasl_ssf_t      *ssf;
1058                         sasl_conn_t *ctx;
1059
1060                         if( ld->ld_defconn == NULL ) {
1061                                 return -1;
1062                         }
1063
1064                         ctx = ld->ld_defconn->lconn_sasl_sockctx;
1065
1066                         if ( ctx == NULL ) {
1067                                 return -1;
1068                         }
1069
1070                         sc = sasl_getprop( ctx, SASL_SSF,
1071                                 (SASL_CONST void **) &ssf );
1072
1073                         if ( sc != SASL_OK ) {
1074                                 return -1;
1075                         }
1076
1077                         *(ber_len_t *)arg = *ssf;
1078                 } break;
1079
1080                 case LDAP_OPT_X_SASL_SSF_EXTERNAL:
1081                         /* this option is write only */
1082                         return -1;
1083
1084                 case LDAP_OPT_X_SASL_SSF_MIN:
1085                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.min_ssf;
1086                         break;
1087                 case LDAP_OPT_X_SASL_SSF_MAX:
1088                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.max_ssf;
1089                         break;
1090                 case LDAP_OPT_X_SASL_MAXBUFSIZE:
1091                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.maxbufsize;
1092                         break;
1093
1094                 case LDAP_OPT_X_SASL_SECPROPS:
1095                         /* this option is write only */
1096                         return -1;
1097
1098                 default:
1099                         return -1;
1100         }
1101         return 0;
1102 }
1103
1104 int
1105 ldap_int_sasl_set_option( LDAP *ld, int option, void *arg )
1106 {
1107         if ( ld == NULL )
1108                 return -1;
1109
1110         switch ( option ) {
1111         case LDAP_OPT_X_SASL_SSF:
1112                 /* This option is read-only */
1113                 return -1;
1114
1115         case LDAP_OPT_X_SASL_SSF_EXTERNAL: {
1116                 int sc;
1117 #if SASL_VERSION_MAJOR < 2
1118                 sasl_external_properties_t extprops;
1119 #endif
1120                 sasl_conn_t *ctx;
1121
1122                 if( ld->ld_defconn == NULL ) {
1123                         return -1;
1124                 }
1125
1126                 ctx = ld->ld_defconn->lconn_sasl_authctx;
1127
1128                 if ( ctx == NULL ) {
1129                         return -1;
1130                 }
1131
1132 #if SASL_VERSION_MAJOR >= 2
1133                 sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, arg);
1134 #else
1135                 memset(&extprops, 0L, sizeof(extprops));
1136
1137                 extprops.ssf = * (ber_len_t *) arg;
1138
1139                 sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1140                         (void *) &extprops );
1141 #endif
1142
1143                 if ( sc != SASL_OK ) {
1144                         return -1;
1145                 }
1146                 } break;
1147
1148         case LDAP_OPT_X_SASL_SSF_MIN:
1149                 ld->ld_options.ldo_sasl_secprops.min_ssf = *(ber_len_t *)arg;
1150                 break;
1151         case LDAP_OPT_X_SASL_SSF_MAX:
1152                 ld->ld_options.ldo_sasl_secprops.max_ssf = *(ber_len_t *)arg;
1153                 break;
1154         case LDAP_OPT_X_SASL_MAXBUFSIZE:
1155                 ld->ld_options.ldo_sasl_secprops.maxbufsize = *(ber_len_t *)arg;
1156                 break;
1157
1158         case LDAP_OPT_X_SASL_SECPROPS: {
1159                 int sc;
1160                 sc = ldap_pvt_sasl_secprops( (char *) arg,
1161                         &ld->ld_options.ldo_sasl_secprops );
1162
1163                 return sc == LDAP_SUCCESS ? 0 : -1;
1164                 }
1165
1166         default:
1167                 return -1;
1168         }
1169         return 0;
1170 }
1171
1172 #ifdef LDAP_R_COMPILE
1173 #define LDAP_DEBUG_R_SASL
1174 void *ldap_pvt_sasl_mutex_new(void)
1175 {
1176         ldap_pvt_thread_mutex_t *mutex;
1177
1178         mutex = (ldap_pvt_thread_mutex_t *) LDAP_MALLOC(
1179                 sizeof(ldap_pvt_thread_mutex_t) );
1180
1181         if ( ldap_pvt_thread_mutex_init( mutex ) == 0 ) {
1182                 return mutex;
1183         }
1184 #ifndef LDAP_DEBUG_R_SASL
1185         assert( 0 );
1186 #endif /* !LDAP_DEBUG_R_SASL */
1187         return NULL;
1188 }
1189
1190 int ldap_pvt_sasl_mutex_lock(void *mutex)
1191 {
1192 #ifdef LDAP_DEBUG_R_SASL
1193         if ( mutex == NULL ) {
1194                 return SASL_OK;
1195         }
1196 #else /* !LDAP_DEBUG_R_SASL */
1197         assert( mutex );
1198 #endif /* !LDAP_DEBUG_R_SASL */
1199         return ldap_pvt_thread_mutex_lock( (ldap_pvt_thread_mutex_t *)mutex )
1200                 ? SASL_FAIL : SASL_OK;
1201 }
1202
1203 int ldap_pvt_sasl_mutex_unlock(void *mutex)
1204 {
1205 #ifdef LDAP_DEBUG_R_SASL
1206         if ( mutex == NULL ) {
1207                 return SASL_OK;
1208         }
1209 #else /* !LDAP_DEBUG_R_SASL */
1210         assert( mutex );
1211 #endif /* !LDAP_DEBUG_R_SASL */
1212         return ldap_pvt_thread_mutex_unlock( (ldap_pvt_thread_mutex_t *)mutex )
1213                 ? SASL_FAIL : SASL_OK;
1214 }
1215
1216 void ldap_pvt_sasl_mutex_dispose(void *mutex)
1217 {
1218 #ifdef LDAP_DEBUG_R_SASL
1219         if ( mutex == NULL ) {
1220                 return;
1221         }
1222 #else /* !LDAP_DEBUG_R_SASL */
1223         assert( mutex );
1224 #endif /* !LDAP_DEBUG_R_SASL */
1225         (void) ldap_pvt_thread_mutex_destroy( (ldap_pvt_thread_mutex_t *)mutex );
1226         LDAP_FREE( mutex );
1227 }
1228 #endif
1229
1230 #else
1231 int ldap_int_sasl_init( void )
1232 { return LDAP_SUCCESS; }
1233
1234 int ldap_int_sasl_close( LDAP *ld, LDAPConn *lc )
1235 { return LDAP_SUCCESS; }
1236
1237 int
1238 ldap_int_sasl_bind(
1239         LDAP                    *ld,
1240         const char              *dn,
1241         const char              *mechs,
1242         LDAPControl             **sctrls,
1243         LDAPControl             **cctrls,
1244         unsigned                flags,
1245         LDAP_SASL_INTERACT_PROC *interact,
1246         void * defaults )
1247 { return LDAP_NOT_SUPPORTED; }
1248
1249 int
1250 ldap_int_sasl_external(
1251         LDAP *ld,
1252         LDAPConn *conn,
1253         const char * authid,
1254         ber_len_t ssf )
1255 { return LDAP_SUCCESS; }
1256
1257 #endif /* HAVE_CYRUS_SASL */