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