]> git.sur5r.net Git - openldap/blob - libraries/libldap/cyrus.c
Fix for ITS#1181 from Mark Adamson @ CMU.edu
[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                 return ret;
379         return len;
380 }
381
382 static int
383 sb_sasl_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
384 {
385         struct sb_sasl_data     *p;
386
387         p = (struct sb_sasl_data *)sbiod->sbiod_pvt;
388
389         if ( opt == LBER_SB_OPT_DATA_READY ) {
390                 if ( p->buf_in.buf_ptr != p->buf_in.buf_end )
391                         return 1;
392         }
393         
394         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
395 }
396
397 Sockbuf_IO ldap_pvt_sockbuf_io_sasl = {
398         sb_sasl_setup,          /* sbi_setup */
399         sb_sasl_remove,         /* sbi_remove */
400         sb_sasl_ctrl,           /* sbi_ctrl */
401         sb_sasl_read,           /* sbi_read */
402         sb_sasl_write,          /* sbi_write */
403         NULL                    /* sbi_close */
404 };
405
406 int ldap_pvt_sasl_install( Sockbuf *sb, void *ctx_arg )
407 {
408 #ifdef NEW_LOGGING
409         LDAP_LOG ( TRANSPORT, ENTRY, "ldap_pvt_sasl_install\n", 0, 0, 0 );
410 #else
411         Debug( LDAP_DEBUG_TRACE, "ldap_pvt_sasl_install\n",
412                 0, 0, 0 );
413 #endif
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 #ifdef NEW_LOGGING
519         LDAP_LOG ( TRANSPORT, DETAIL1, "ldap_int_sasl_open: host=%s\n", 
520                 host, 0, 0 );
521 #else
522         Debug( LDAP_DEBUG_TRACE, "ldap_int_sasl_open: host=%s\n",
523                 host, 0, 0 );
524 #endif
525
526         lc->lconn_sasl_authctx = ctx;
527
528         return LDAP_SUCCESS;
529 }
530
531 int ldap_int_sasl_close( LDAP *ld, LDAPConn *lc )
532 {
533         sasl_conn_t *ctx = lc->lconn_sasl_authctx;
534
535         if( ctx != NULL ) {
536                 sasl_dispose( &ctx );
537                 if ( lc->lconn_sasl_sockctx &&
538                         lc->lconn_sasl_authctx != lc->lconn_sasl_sockctx ) {
539                         ctx = lc->lconn_sasl_sockctx;
540                         sasl_dispose( &ctx );
541                 }
542                 lc->lconn_sasl_sockctx = NULL;
543                 lc->lconn_sasl_authctx = NULL;
544         }
545
546         return LDAP_SUCCESS;
547 }
548
549 int
550 ldap_int_sasl_bind(
551         LDAP                    *ld,
552         const char              *dn,
553         const char              *mechs,
554         LDAPControl             **sctrls,
555         LDAPControl             **cctrls,
556         unsigned                flags,
557         LDAP_SASL_INTERACT_PROC *interact,
558         void * defaults )
559 {
560         char *data;
561         const char *mech = NULL;
562         const char *pmech = NULL;
563         int                     saslrc, rc;
564         sasl_ssf_t              *ssf = NULL;
565         sasl_conn_t     *ctx, *oldctx = NULL;
566         sasl_interact_t *prompts = NULL;
567         unsigned credlen;
568         struct berval ccred;
569         ber_socket_t            sd;
570         void    *ssl;
571
572 #ifdef NEW_LOGGING
573         LDAP_LOG ( TRANSPORT, ARGS, "ldap_int_sasl_bind: %s\n", 
574                 mechs ? mechs : "<null>", 0, 0 );
575 #else
576         Debug( LDAP_DEBUG_TRACE, "ldap_int_sasl_bind: %s\n",
577                 mechs ? mechs : "<null>", 0, 0 );
578 #endif
579
580         /* do a quick !LDAPv3 check... ldap_sasl_bind will do the rest. */
581         if (ld->ld_version < LDAP_VERSION3) {
582                 ld->ld_errno = LDAP_NOT_SUPPORTED;
583                 return ld->ld_errno;
584         }
585
586         ber_sockbuf_ctrl( ld->ld_sb, LBER_SB_OPT_GET_FD, &sd );
587
588         if ( sd == AC_SOCKET_INVALID ) {
589                 /* not connected yet */
590                 int rc;
591
592                 rc = ldap_open_defconn( ld );
593                 if( rc < 0 ) return ld->ld_errno;
594
595                 ber_sockbuf_ctrl( ld->ld_sb, LBER_SB_OPT_GET_FD, &sd );
596
597                 if( sd == AC_SOCKET_INVALID ) {
598                         ld->ld_errno = LDAP_LOCAL_ERROR;
599                         return ld->ld_errno;
600                 }
601         }   
602
603         oldctx = ld->ld_defconn->lconn_sasl_authctx;
604
605         /* If we already have an authentication context, clear it out */
606         if( oldctx ) {
607                 if ( oldctx != ld->ld_defconn->lconn_sasl_sockctx ) {
608                         sasl_dispose( &oldctx );
609                 }
610                 ld->ld_defconn->lconn_sasl_authctx = NULL;
611         }
612
613         { char *saslhost = ldap_host_connected_to( ld->ld_sb, "localhost" );
614         rc = ldap_int_sasl_open( ld, ld->ld_defconn, saslhost );
615         LDAP_FREE( saslhost );
616         }
617
618         if ( rc != LDAP_SUCCESS ) return rc;
619
620         ctx = ld->ld_defconn->lconn_sasl_authctx;
621
622         /* Check for TLS */
623         ssl = ldap_pvt_tls_sb_ctx( ld->ld_sb );
624         if ( ssl ) {
625                 struct berval authid = BER_BVNULL;
626                 ber_len_t fac;
627
628                 fac = ldap_pvt_tls_get_strength( ssl );
629                 /* failure is OK, we just can't use SASL EXTERNAL */
630                 (void) ldap_pvt_tls_get_my_dn( ssl, &authid, NULL, 0 );
631
632                 (void) ldap_int_sasl_external( ld, ld->ld_defconn, authid.bv_val, fac );
633                 LDAP_FREE( authid.bv_val );
634         }
635
636 #if !defined(_WIN32)
637         /* Check for local */
638         if ( ldap_pvt_url_scheme2proto( ld->ld_defconn->lconn_server->lud_scheme ) == LDAP_PROTO_IPC ) {
639                 char authid[sizeof("uidNumber=4294967295+gidNumber=4294967295,"
640                         "cn=peercred,cn=external,cn=auth")];
641                 sprintf( authid, "uidNumber=%d+gidNumber=%d,"
642                         "cn=peercred,cn=external,cn=auth",
643                         (int) geteuid(), (int) getegid() );
644                 (void) ldap_int_sasl_external( ld, ld->ld_defconn, authid, LDAP_PVT_SASL_LOCAL_SSF );
645         }
646 #endif
647
648         /* (re)set security properties */
649         sasl_setprop( ctx, SASL_SEC_PROPS,
650                 &ld->ld_options.ldo_sasl_secprops );
651
652         ccred.bv_val = NULL;
653         ccred.bv_len = 0;
654
655         do {
656                 saslrc = sasl_client_start( ctx,
657                         mechs,
658 #if SASL_VERSION_MAJOR < 2
659                         NULL,
660 #endif
661                         &prompts,
662                         (SASL_CONST char **)&ccred.bv_val,
663                         &credlen,
664                         &mech );
665
666                 if( pmech == NULL && mech != NULL ) {
667                         pmech = mech;
668
669                         if( flags != LDAP_SASL_QUIET ) {
670                                 fprintf(stderr,
671                                         "SASL/%s authentication started\n",
672                                         pmech );
673                         }
674                 }
675
676                 if( saslrc == SASL_INTERACT ) {
677                         int res;
678                         if( !interact ) break;
679                         res = (interact)( ld, flags, defaults, prompts );
680
681                         if( res != LDAP_SUCCESS ) break;
682                 }
683         } while ( saslrc == SASL_INTERACT );
684
685         ccred.bv_len = credlen;
686
687         if ( (saslrc != SASL_OK) && (saslrc != SASL_CONTINUE) ) {
688                 rc = ld->ld_errno = sasl_err2ldap( saslrc );
689 #if SASL_VERSION_MAJOR >= 2
690                 ld->ld_error = LDAP_STRDUP( sasl_errdetail( ctx ) );
691 #endif
692                 goto done;
693         }
694
695         do {
696                 struct berval *scred;
697                 unsigned credlen;
698
699                 scred = NULL;
700
701                 rc = ldap_sasl_bind_s( ld, dn, mech, &ccred, sctrls, cctrls, &scred );
702
703                 if ( ccred.bv_val != NULL ) {
704 #if SASL_VERSION_MAJOR < 2
705                         LDAP_FREE( ccred.bv_val );
706 #endif
707                         ccred.bv_val = NULL;
708                 }
709
710                 if ( rc != LDAP_SUCCESS && rc != LDAP_SASL_BIND_IN_PROGRESS ) {
711                         if( scred && scred->bv_len ) {
712                                 /* and server provided us with data? */
713 #ifdef NEW_LOGGING
714                                 LDAP_LOG ( TRANSPORT, DETAIL1, 
715                                         "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n", 
716                                         rc, saslrc, scred->bv_len );
717 #else
718                                 Debug( LDAP_DEBUG_TRACE,
719                                         "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n",
720                                         rc, saslrc, scred->bv_len );
721 #endif
722                                 ber_bvfree( scred );
723                         }
724                         rc = ld->ld_errno;
725                         goto done;
726                 }
727
728                 if( rc == LDAP_SUCCESS && saslrc == SASL_OK ) {
729                         /* we're done, no need to step */
730                         if( scred && scred->bv_len ) {
731                                 /* but server provided us with data! */
732 #ifdef NEW_LOGGING
733                                 LDAP_LOG ( TRANSPORT, DETAIL1, 
734                                         "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n", 
735                                         rc, saslrc, scred->bv_len );
736 #else
737                                 Debug( LDAP_DEBUG_TRACE,
738                                         "ldap_int_sasl_bind: rc=%d sasl=%d len=%ld\n",
739                                         rc, saslrc, scred->bv_len );
740 #endif
741                                 ber_bvfree( scred );
742                                 rc = ld->ld_errno = LDAP_LOCAL_ERROR;
743                                 goto done;
744                         }
745                         break;
746                 }
747
748                 do {
749                         saslrc = sasl_client_step( ctx,
750                                 (scred == NULL) ? NULL : scred->bv_val,
751                                 (scred == NULL) ? 0 : scred->bv_len,
752                                 &prompts,
753                                 (SASL_CONST char **)&ccred.bv_val,
754                                 &credlen );
755
756 #ifdef NEW_LOGGING
757                                 LDAP_LOG ( TRANSPORT, DETAIL1, 
758                                         "ldap_int_sasl_bind: sasl_client_step: %d\n", saslrc,0,0 );
759 #else
760                         Debug( LDAP_DEBUG_TRACE, "sasl_client_step: %d\n",
761                                 saslrc, 0, 0 );
762 #endif
763
764                         if( saslrc == SASL_INTERACT ) {
765                                 int res;
766                                 if( !interact ) break;
767                                 res = (interact)( ld, flags, defaults, prompts );
768                                 if( res != LDAP_SUCCESS ) break;
769                         }
770                 } while ( saslrc == SASL_INTERACT );
771
772                 ccred.bv_len = credlen;
773                 ber_bvfree( scred );
774
775                 if ( (saslrc != SASL_OK) && (saslrc != SASL_CONTINUE) ) {
776                         ld->ld_errno = sasl_err2ldap( saslrc );
777 #if SASL_VERSION_MAJOR >= 2
778                         ld->ld_error = LDAP_STRDUP( sasl_errdetail( ctx ) );
779 #endif
780                         rc = ld->ld_errno;
781                         goto done;
782                 }
783         } while ( rc == LDAP_SASL_BIND_IN_PROGRESS );
784
785         if ( rc != LDAP_SUCCESS ) goto done;
786
787         if ( saslrc != SASL_OK ) {
788 #if SASL_VERSION_MAJOR >= 2
789                 ld->ld_error = LDAP_STRDUP( sasl_errdetail( ctx ) );
790 #endif
791                 rc = ld->ld_errno = sasl_err2ldap( saslrc );
792                 goto done;
793         }
794
795         if( flags != LDAP_SASL_QUIET ) {
796                 saslrc = sasl_getprop( ctx, SASL_USERNAME, (SASL_CONST void **) &data );
797                 if( saslrc == SASL_OK && data && *data ) {
798                         fprintf( stderr, "SASL username: %s\n", data );
799                 }
800
801 #if SASL_VERSION_MAJOR < 2
802                 saslrc = sasl_getprop( ctx, SASL_REALM, (SASL_CONST void **) &data );
803                 if( saslrc == SASL_OK && data && *data ) {
804                         fprintf( stderr, "SASL realm: %s\n", data );
805                 }
806 #endif
807         }
808
809         saslrc = sasl_getprop( ctx, SASL_SSF, (SASL_CONST void **) &ssf );
810         if( saslrc == SASL_OK ) {
811                 if( flags != LDAP_SASL_QUIET ) {
812                         fprintf( stderr, "SASL SSF: %lu\n",
813                                 (unsigned long) *ssf );
814                 }
815
816                 if( ssf && *ssf ) {
817                         if( flags != LDAP_SASL_QUIET ) {
818                                 fprintf( stderr, "SASL installing layers\n" );
819                         }
820                         if ( ld->ld_defconn->lconn_sasl_sockctx ) {
821                                 oldctx = ld->ld_defconn->lconn_sasl_sockctx;
822                                 sasl_dispose( &oldctx );
823                                 ldap_pvt_sasl_remove( ld->ld_sb );
824                         }
825                         ldap_pvt_sasl_install( ld->ld_conns->lconn_sb, ctx );
826                         ld->ld_defconn->lconn_sasl_sockctx = ctx;
827                 }
828         }
829         ld->ld_defconn->lconn_sasl_authctx = ctx;
830
831 done:
832         return rc;
833 }
834
835 int
836 ldap_int_sasl_external(
837         LDAP *ld,
838         LDAPConn *conn,
839         const char * authid,
840         ber_len_t ssf )
841 {
842         int sc;
843         sasl_conn_t *ctx;
844 #if SASL_VERSION_MAJOR < 2
845         sasl_external_properties_t extprops;
846 #endif
847
848         ctx = conn->lconn_sasl_authctx;
849
850         if ( ctx == NULL ) {
851                 return LDAP_LOCAL_ERROR;
852         }
853    
854 #if SASL_VERSION_MAJOR >= 2
855         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
856         if ( sc == SASL_OK )
857                 sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
858 #else
859         memset( &extprops, '\0', sizeof(extprops) );
860         extprops.ssf = ssf;
861         extprops.auth_id = (char *) authid;
862
863         sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
864                 (void *) &extprops );
865 #endif
866
867         if ( sc != SASL_OK ) {
868                 return LDAP_LOCAL_ERROR;
869         }
870
871         return LDAP_SUCCESS;
872 }
873
874
875 int ldap_pvt_sasl_secprops(
876         const char *in,
877         sasl_security_properties_t *secprops )
878 {
879         int i;
880         char **props = ldap_str2charray( in, "," );
881         unsigned sflags = 0;
882         int got_sflags = 0;
883         sasl_ssf_t max_ssf = 0;
884         int got_max_ssf = 0;
885         sasl_ssf_t min_ssf = 0;
886         int got_min_ssf = 0;
887         unsigned maxbufsize = 0;
888         int got_maxbufsize = 0;
889
890         if( props == NULL || secprops == NULL ) {
891                 return LDAP_PARAM_ERROR;
892         }
893
894         for( i=0; props[i]; i++ ) {
895                 if( !strcasecmp(props[i], "none") ) {
896                         got_sflags++;
897
898                 } else if( !strcasecmp(props[i], "noplain") ) {
899                         got_sflags++;
900                         sflags |= SASL_SEC_NOPLAINTEXT;
901
902                 } else if( !strcasecmp(props[i], "noactive") ) {
903                         got_sflags++;
904                         sflags |= SASL_SEC_NOACTIVE;
905
906                 } else if( !strcasecmp(props[i], "nodict") ) {
907                         got_sflags++;
908                         sflags |= SASL_SEC_NODICTIONARY;
909
910                 } else if( !strcasecmp(props[i], "forwardsec") ) {
911                         got_sflags++;
912                         sflags |= SASL_SEC_FORWARD_SECRECY;
913
914                 } else if( !strcasecmp(props[i], "noanonymous")) {
915                         got_sflags++;
916                         sflags |= SASL_SEC_NOANONYMOUS;
917
918                 } else if( !strcasecmp(props[i], "passcred") ) {
919                         got_sflags++;
920                         sflags |= SASL_SEC_PASS_CREDENTIALS;
921
922                 } else if( !strncasecmp(props[i],
923                         "minssf=", sizeof("minssf")) )
924                 {
925                         if( isdigit( (unsigned char) props[i][sizeof("minssf")] ) ) {
926                                 got_min_ssf++;
927                                 min_ssf = atoi( &props[i][sizeof("minssf")] );
928                         } else {
929                                 return LDAP_NOT_SUPPORTED;
930                         }
931
932                 } else if( !strncasecmp(props[i],
933                         "maxssf=", sizeof("maxssf")) )
934                 {
935                         if( isdigit( (unsigned char) props[i][sizeof("maxssf")] ) ) {
936                                 got_max_ssf++;
937                                 max_ssf = atoi( &props[i][sizeof("maxssf")] );
938                         } else {
939                                 return LDAP_NOT_SUPPORTED;
940                         }
941
942                 } else if( !strncasecmp(props[i],
943                         "maxbufsize=", sizeof("maxbufsize")) )
944                 {
945                         if( isdigit( (unsigned char) props[i][sizeof("maxbufsize")] ) ) {
946                                 got_maxbufsize++;
947                                 maxbufsize = atoi( &props[i][sizeof("maxbufsize")] );
948                         } else {
949                                 return LDAP_NOT_SUPPORTED;
950                         }
951
952                         if( maxbufsize && (( maxbufsize < SASL_MIN_BUFF_SIZE )
953                                 || (maxbufsize > SASL_MAX_BUFF_SIZE )))
954                         {
955                                 /* bad maxbufsize */
956                                 return LDAP_PARAM_ERROR;
957                         }
958
959                 } else {
960                         return LDAP_NOT_SUPPORTED;
961                 }
962         }
963
964         if(got_sflags) {
965                 secprops->security_flags = sflags;
966         }
967         if(got_min_ssf) {
968                 secprops->min_ssf = min_ssf;
969         }
970         if(got_max_ssf) {
971                 secprops->max_ssf = max_ssf;
972         }
973         if(got_maxbufsize) {
974                 secprops->maxbufsize = maxbufsize;
975         }
976
977         ldap_charray_free( props );
978         return LDAP_SUCCESS;
979 }
980
981 int
982 ldap_int_sasl_config( struct ldapoptions *lo, int option, const char *arg )
983 {
984         int rc;
985
986         switch( option ) {
987         case LDAP_OPT_X_SASL_SECPROPS:
988                 rc = ldap_pvt_sasl_secprops( arg, &lo->ldo_sasl_secprops );
989                 if( rc == LDAP_SUCCESS ) return 0;
990         }
991
992         return -1;
993 }
994
995 int
996 ldap_int_sasl_get_option( LDAP *ld, int option, void *arg )
997 {
998         if ( ld == NULL )
999                 return -1;
1000
1001         switch ( option ) {
1002                 case LDAP_OPT_X_SASL_MECH: {
1003                         *(char **)arg = ld->ld_options.ldo_def_sasl_mech
1004                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_mech ) : NULL;
1005                 } break;
1006                 case LDAP_OPT_X_SASL_REALM: {
1007                         *(char **)arg = ld->ld_options.ldo_def_sasl_realm
1008                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_realm ) : NULL;
1009                 } break;
1010                 case LDAP_OPT_X_SASL_AUTHCID: {
1011                         *(char **)arg = ld->ld_options.ldo_def_sasl_authcid
1012                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_authcid ) : NULL;
1013                 } break;
1014                 case LDAP_OPT_X_SASL_AUTHZID: {
1015                         *(char **)arg = ld->ld_options.ldo_def_sasl_authzid
1016                                 ? LDAP_STRDUP( ld->ld_options.ldo_def_sasl_authzid ) : NULL;
1017                 } break;
1018
1019                 case LDAP_OPT_X_SASL_SSF: {
1020                         int sc;
1021                         sasl_ssf_t      *ssf;
1022                         sasl_conn_t *ctx;
1023
1024                         if( ld->ld_defconn == NULL ) {
1025                                 return -1;
1026                         }
1027
1028                         ctx = ld->ld_defconn->lconn_sasl_sockctx;
1029
1030                         if ( ctx == NULL ) {
1031                                 return -1;
1032                         }
1033
1034                         sc = sasl_getprop( ctx, SASL_SSF,
1035                                 (SASL_CONST void **) &ssf );
1036
1037                         if ( sc != SASL_OK ) {
1038                                 return -1;
1039                         }
1040
1041                         *(ber_len_t *)arg = *ssf;
1042                 } break;
1043
1044                 case LDAP_OPT_X_SASL_SSF_EXTERNAL:
1045                         /* this option is write only */
1046                         return -1;
1047
1048                 case LDAP_OPT_X_SASL_SSF_MIN:
1049                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.min_ssf;
1050                         break;
1051                 case LDAP_OPT_X_SASL_SSF_MAX:
1052                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.max_ssf;
1053                         break;
1054                 case LDAP_OPT_X_SASL_MAXBUFSIZE:
1055                         *(ber_len_t *)arg = ld->ld_options.ldo_sasl_secprops.maxbufsize;
1056                         break;
1057
1058                 case LDAP_OPT_X_SASL_SECPROPS:
1059                         /* this option is write only */
1060                         return -1;
1061
1062                 default:
1063                         return -1;
1064         }
1065         return 0;
1066 }
1067
1068 int
1069 ldap_int_sasl_set_option( LDAP *ld, int option, void *arg )
1070 {
1071         if ( ld == NULL )
1072                 return -1;
1073
1074         switch ( option ) {
1075         case LDAP_OPT_X_SASL_SSF:
1076                 /* This option is read-only */
1077                 return -1;
1078
1079         case LDAP_OPT_X_SASL_SSF_EXTERNAL: {
1080                 int sc;
1081 #if SASL_VERSION_MAJOR < 2
1082                 sasl_external_properties_t extprops;
1083 #endif
1084                 sasl_conn_t *ctx;
1085
1086                 if( ld->ld_defconn == NULL ) {
1087                         return -1;
1088                 }
1089
1090                 ctx = ld->ld_defconn->lconn_sasl_authctx;
1091
1092                 if ( ctx == NULL ) {
1093                         return -1;
1094                 }
1095
1096 #if SASL_VERSION_MAJOR >= 2
1097                 sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, arg);
1098 #else
1099                 memset(&extprops, 0L, sizeof(extprops));
1100
1101                 extprops.ssf = * (ber_len_t *) arg;
1102
1103                 sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL,
1104                         (void *) &extprops );
1105 #endif
1106
1107                 if ( sc != SASL_OK ) {
1108                         return -1;
1109                 }
1110                 } break;
1111
1112         case LDAP_OPT_X_SASL_SSF_MIN:
1113                 ld->ld_options.ldo_sasl_secprops.min_ssf = *(ber_len_t *)arg;
1114                 break;
1115         case LDAP_OPT_X_SASL_SSF_MAX:
1116                 ld->ld_options.ldo_sasl_secprops.max_ssf = *(ber_len_t *)arg;
1117                 break;
1118         case LDAP_OPT_X_SASL_MAXBUFSIZE:
1119                 ld->ld_options.ldo_sasl_secprops.maxbufsize = *(ber_len_t *)arg;
1120                 break;
1121
1122         case LDAP_OPT_X_SASL_SECPROPS: {
1123                 int sc;
1124                 sc = ldap_pvt_sasl_secprops( (char *) arg,
1125                         &ld->ld_options.ldo_sasl_secprops );
1126
1127                 return sc == LDAP_SUCCESS ? 0 : -1;
1128                 }
1129
1130         default:
1131                 return -1;
1132         }
1133         return 0;
1134 }
1135
1136 #ifdef LDAP_R_COMPILE
1137 #define LDAP_DEBUG_R_SASL
1138 void *ldap_pvt_sasl_mutex_new(void)
1139 {
1140         ldap_pvt_thread_mutex_t *mutex;
1141
1142         mutex = (ldap_pvt_thread_mutex_t *) LDAP_MALLOC(
1143                 sizeof(ldap_pvt_thread_mutex_t) );
1144
1145         if ( ldap_pvt_thread_mutex_init( mutex ) == 0 ) {
1146                 return mutex;
1147         }
1148 #ifndef LDAP_DEBUG_R_SASL
1149         assert( 0 );
1150 #endif /* !LDAP_DEBUG_R_SASL */
1151         return NULL;
1152 }
1153
1154 int ldap_pvt_sasl_mutex_lock(void *mutex)
1155 {
1156 #ifdef LDAP_DEBUG_R_SASL
1157         if ( mutex == NULL ) {
1158                 return SASL_OK;
1159         }
1160 #else /* !LDAP_DEBUG_R_SASL */
1161         assert( mutex );
1162 #endif /* !LDAP_DEBUG_R_SASL */
1163         return ldap_pvt_thread_mutex_lock( (ldap_pvt_thread_mutex_t *)mutex )
1164                 ? SASL_FAIL : SASL_OK;
1165 }
1166
1167 int ldap_pvt_sasl_mutex_unlock(void *mutex)
1168 {
1169 #ifdef LDAP_DEBUG_R_SASL
1170         if ( mutex == NULL ) {
1171                 return SASL_OK;
1172         }
1173 #else /* !LDAP_DEBUG_R_SASL */
1174         assert( mutex );
1175 #endif /* !LDAP_DEBUG_R_SASL */
1176         return ldap_pvt_thread_mutex_unlock( (ldap_pvt_thread_mutex_t *)mutex )
1177                 ? SASL_FAIL : SASL_OK;
1178 }
1179
1180 void ldap_pvt_sasl_mutex_dispose(void *mutex)
1181 {
1182 #ifdef LDAP_DEBUG_R_SASL
1183         if ( mutex == NULL ) {
1184                 return;
1185         }
1186 #else /* !LDAP_DEBUG_R_SASL */
1187         assert( mutex );
1188 #endif /* !LDAP_DEBUG_R_SASL */
1189         (void) ldap_pvt_thread_mutex_destroy( (ldap_pvt_thread_mutex_t *)mutex );
1190         LDAP_FREE( mutex );
1191 }
1192 #endif
1193
1194 #else
1195 int ldap_int_sasl_init( void )
1196 { return LDAP_SUCCESS; }
1197
1198 int ldap_int_sasl_close( LDAP *ld, LDAPConn *lc )
1199 { return LDAP_SUCCESS; }
1200
1201 int
1202 ldap_int_sasl_bind(
1203         LDAP                    *ld,
1204         const char              *dn,
1205         const char              *mechs,
1206         LDAPControl             **sctrls,
1207         LDAPControl             **cctrls,
1208         unsigned                flags,
1209         LDAP_SASL_INTERACT_PROC *interact,
1210         void * defaults )
1211 { return LDAP_NOT_SUPPORTED; }
1212
1213 int
1214 ldap_int_sasl_external(
1215         LDAP *ld,
1216         LDAPConn *conn,
1217         const char * authid,
1218         ber_len_t ssf )
1219 { return LDAP_SUCCESS; }
1220
1221 #endif /* HAVE_CYRUS_SASL */