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