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