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