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