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