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