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