No empty .Rs/.Re
[netbsd-mini2440.git] / external / bsd / openldap / dist / libraries / libldap / tls.c
blob72961c20d9b057eebe753f78b14ba29e8c89f5c3
1 /* tls.c - Handle tls/ssl using SSLeay, OpenSSL or GNUTLS. */
2 /* $OpenLDAP: pkg/ldap/libraries/libldap/tls.c,v 1.133.2.11 2008/07/09 23:56:44 quanah Exp $ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2008 The OpenLDAP Foundation.
6 * All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted only as authorized by the OpenLDAP
10 * Public License.
12 * A copy of this license is available in the file LICENSE in the
13 * top-level directory of the distribution or, alternatively, at
14 * <http://www.OpenLDAP.org/license.html>.
16 /* ACKNOWLEDGEMENTS: GNUTLS support written by Howard Chu and
17 * Matt Backes; sponsored by The Written Word (thewrittenword.com)
18 * and Stanford University (stanford.edu).
21 #include "portable.h"
22 #include "ldap_config.h"
24 #include <stdio.h>
26 #include <ac/stdlib.h>
27 #include <ac/errno.h>
28 #include <ac/socket.h>
29 #include <ac/string.h>
30 #include <ac/ctype.h>
31 #include <ac/time.h>
32 #include <ac/unistd.h>
33 #include <ac/param.h>
34 #include <ac/dirent.h>
36 #include "ldap-int.h"
38 #ifdef HAVE_TLS
40 #ifdef LDAP_R_COMPILE
41 #include <ldap_pvt_thread.h>
42 #endif
44 #ifdef HAVE_GNUTLS
45 #include <gnutls/gnutls.h>
46 #include <gnutls/x509.h>
47 #include <gcrypt.h>
49 #define DH_BITS (1024)
51 #else
52 #ifdef HAVE_OPENSSL_SSL_H
53 #include <openssl/ssl.h>
54 #include <openssl/x509v3.h>
55 #include <openssl/err.h>
56 #include <openssl/rand.h>
57 #include <openssl/safestack.h>
58 #elif defined( HAVE_SSL_H )
59 #include <ssl.h>
60 #endif
61 #endif
63 #define HAS_TLS( sb ) ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO, \
64 (void *)&sb_tls_sbio )
66 #endif /* HAVE_TLS */
68 /* RFC2459 minimum required set of supported attribute types
69 * in a certificate DN
71 typedef struct oid_name {
72 struct berval oid;
73 struct berval name;
74 } oid_name;
76 #define CN_OID oids[0].oid.bv_val
78 static oid_name oids[] = {
79 { BER_BVC("2.5.4.3"), BER_BVC("cn") },
80 { BER_BVC("2.5.4.4"), BER_BVC("sn") },
81 { BER_BVC("2.5.4.6"), BER_BVC("c") },
82 { BER_BVC("2.5.4.7"), BER_BVC("l") },
83 { BER_BVC("2.5.4.8"), BER_BVC("st") },
84 { BER_BVC("2.5.4.10"), BER_BVC("o") },
85 { BER_BVC("2.5.4.11"), BER_BVC("ou") },
86 { BER_BVC("2.5.4.12"), BER_BVC("title") },
87 { BER_BVC("2.5.4.41"), BER_BVC("name") },
88 { BER_BVC("2.5.4.42"), BER_BVC("givenName") },
89 { BER_BVC("2.5.4.43"), BER_BVC("initials") },
90 { BER_BVC("2.5.4.44"), BER_BVC("generationQualifier") },
91 { BER_BVC("2.5.4.46"), BER_BVC("dnQualifier") },
92 { BER_BVC("1.2.840.113549.1.9.1"), BER_BVC("email") },
93 { BER_BVC("0.9.2342.19200300.100.1.25"), BER_BVC("dc") },
94 { BER_BVNULL, BER_BVNULL }
97 #ifdef HAVE_TLS
98 #ifdef HAVE_GNUTLS
100 typedef struct tls_cipher_suite {
101 const char *name;
102 gnutls_kx_algorithm_t kx;
103 gnutls_cipher_algorithm_t cipher;
104 gnutls_mac_algorithm_t mac;
105 gnutls_protocol_t version;
106 } tls_cipher_suite;
108 static tls_cipher_suite *ciphers;
109 static int n_ciphers;
111 /* sorta replacing SSL_CTX */
112 typedef struct tls_ctx {
113 struct ldapoptions *lo;
114 gnutls_certificate_credentials_t cred;
115 gnutls_dh_params_t dh_params;
116 unsigned long verify_depth;
117 int refcount;
118 int *kx_list;
119 int *cipher_list;
120 int *mac_list;
121 #ifdef LDAP_R_COMPILE
122 ldap_pvt_thread_mutex_t ref_mutex;
123 #endif
124 } tls_ctx;
126 /* sorta replacing SSL */
127 typedef struct tls_session {
128 tls_ctx *ctx;
129 gnutls_session_t session;
130 struct berval peer_der_dn;
131 } tls_session;
133 #ifdef LDAP_R_COMPILE
135 static int
136 ldap_pvt_gcry_mutex_init( void **priv )
138 int err = 0;
139 ldap_pvt_thread_mutex_t *lock = LDAP_MALLOC( sizeof( ldap_pvt_thread_mutex_t ));
141 if ( !lock )
142 err = ENOMEM;
143 if ( !err ) {
144 err = ldap_pvt_thread_mutex_init( lock );
145 if ( err )
146 LDAP_FREE( lock );
147 else
148 *priv = lock;
150 return err;
152 static int
153 ldap_pvt_gcry_mutex_destroy( void **lock )
155 int err = ldap_pvt_thread_mutex_destroy( *lock );
156 LDAP_FREE( *lock );
157 return err;
159 static int
160 ldap_pvt_gcry_mutex_lock( void **lock )
162 return ldap_pvt_thread_mutex_lock( *lock );
164 static int
165 ldap_pvt_gcry_mutex_unlock( void **lock )
167 return ldap_pvt_thread_mutex_unlock( *lock );
170 static struct gcry_thread_cbs ldap_generic_thread_cbs = {
171 GCRY_THREAD_OPTION_USER,
172 NULL,
173 ldap_pvt_gcry_mutex_init,
174 ldap_pvt_gcry_mutex_destroy,
175 ldap_pvt_gcry_mutex_lock,
176 ldap_pvt_gcry_mutex_unlock,
177 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
180 static void
181 tls_init_threads( void )
183 gcry_control (GCRYCTL_SET_THREAD_CBS, &ldap_generic_thread_cbs);
185 #endif /* LDAP_R_COMPILE */
187 void
188 ldap_pvt_tls_ctx_free ( void *c )
190 int refcount;
191 tls_ctx *ctx = c;
193 if ( !ctx ) return;
195 #ifdef LDAP_R_COMPILE
196 ldap_pvt_thread_mutex_lock( &ctx->ref_mutex );
197 #endif
198 refcount = --ctx->refcount;
199 #ifdef LDAP_R_COMPILE
200 ldap_pvt_thread_mutex_unlock( &ctx->ref_mutex );
201 #endif
202 if ( refcount )
203 return;
204 LDAP_FREE( ctx->kx_list );
205 gnutls_certificate_free_credentials( ctx->cred );
206 ber_memfree ( ctx );
209 static void *
210 tls_ctx_new ( struct ldapoptions *lo )
212 tls_ctx *ctx;
214 ctx = ber_memcalloc ( 1, sizeof (*ctx) );
215 if ( ctx ) {
216 ctx->lo = lo;
217 if ( gnutls_certificate_allocate_credentials( &ctx->cred )) {
218 ber_memfree( ctx );
219 return NULL;
221 ctx->refcount = 1;
222 #ifdef LDAP_R_COMPILE
223 ldap_pvt_thread_mutex_init( &ctx->ref_mutex );
224 #endif
226 return ctx;
229 static void
230 tls_ctx_ref( tls_ctx *ctx )
232 #ifdef LDAP_R_COMPILE
233 ldap_pvt_thread_mutex_lock( &ctx->ref_mutex );
234 #endif
235 ctx->refcount++;
236 #ifdef LDAP_R_COMPILE
237 ldap_pvt_thread_mutex_unlock( &ctx->ref_mutex );
238 #endif
241 tls_session *
242 tls_session_new ( tls_ctx * ctx, int is_server )
244 tls_session *session;
246 session = ber_memcalloc ( 1, sizeof (*session) );
247 if ( !session )
248 return NULL;
250 session->ctx = ctx;
251 gnutls_init( &session->session, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT );
252 gnutls_set_default_priority( session->session );
253 if ( ctx->kx_list ) {
254 gnutls_kx_set_priority( session->session, ctx->kx_list );
255 gnutls_cipher_set_priority( session->session, ctx->cipher_list );
256 gnutls_mac_set_priority( session->session, ctx->mac_list );
258 if ( ctx->cred )
259 gnutls_credentials_set( session->session, GNUTLS_CRD_CERTIFICATE, ctx->cred );
261 if ( is_server ) {
262 int flag = 0;
263 if ( ctx->lo->ldo_tls_require_cert ) {
264 flag = GNUTLS_CERT_REQUEST;
265 if ( ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
266 ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD )
267 flag = GNUTLS_CERT_REQUIRE;
268 gnutls_certificate_server_set_request( session->session, flag );
271 return session;
274 void
275 tls_session_free ( tls_session * session )
277 ber_memfree ( session );
280 #define tls_session_connect( ssl ) gnutls_handshake( ssl->session )
281 #define tls_session_accept( ssl ) gnutls_handshake( ssl->session )
283 /* suites is a string of colon-separated cipher suite names. */
284 static int
285 tls_parse_ciphers( tls_ctx *ctx, char *suites )
287 char *ptr, *end;
288 int i, j, len, num;
289 int *list, nkx = 0, ncipher = 0, nmac = 0;
290 int *kx, *cipher, *mac;
292 num = 0;
293 ptr = suites;
294 do {
295 end = strchr(ptr, ':');
296 if ( end )
297 len = end - ptr;
298 else
299 len = strlen(ptr);
300 for (i=0; i<n_ciphers; i++) {
301 if ( !strncasecmp( ciphers[i].name, ptr, len )) {
302 num++;
303 break;
306 if ( i == n_ciphers ) {
307 /* unrecognized cipher suite */
308 return -1;
310 ptr += len + 1;
311 } while (end);
313 /* Space for all 3 lists */
314 list = LDAP_MALLOC( (num+1) * sizeof(int) * 3 );
315 if ( !list )
316 return -1;
317 kx = list;
318 cipher = kx+num+1;
319 mac = cipher+num+1;
321 ptr = suites;
322 do {
323 end = strchr(ptr, ':');
324 if ( end )
325 len = end - ptr;
326 else
327 len = strlen(ptr);
328 for (i=0; i<n_ciphers; i++) {
329 /* For each cipher suite, insert its algorithms into
330 * their respective priority lists. Make sure they
331 * only appear once in each list.
333 if ( !strncasecmp( ciphers[i].name, ptr, len )) {
334 for (j=0; j<nkx; j++)
335 if ( kx[j] == ciphers[i].kx )
336 break;
337 if ( j == nkx )
338 kx[nkx++] = ciphers[i].kx;
339 for (j=0; j<ncipher; j++)
340 if ( cipher[j] == ciphers[i].cipher )
341 break;
342 if ( j == ncipher )
343 cipher[ncipher++] = ciphers[i].cipher;
344 for (j=0; j<nmac; j++)
345 if ( mac[j] == ciphers[i].mac )
346 break;
347 if ( j == nmac )
348 mac[nmac++] = ciphers[i].mac;
349 break;
352 ptr += len + 1;
353 } while (end);
354 kx[nkx] = 0;
355 cipher[ncipher] = 0;
356 mac[nmac] = 0;
357 ctx->kx_list = kx;
358 ctx->cipher_list = cipher;
359 ctx->mac_list = mac;
360 return 0;
363 #else /* OpenSSL */
365 typedef SSL_CTX tls_ctx;
366 typedef SSL tls_session;
368 static int tls_opt_trace = 1;
369 static char *tls_opt_randfile = NULL;
371 static void tls_report_error( void );
373 static void tls_info_cb( const SSL *ssl, int where, int ret );
374 static int tls_verify_cb( int ok, X509_STORE_CTX *ctx );
375 static int tls_verify_ok( int ok, X509_STORE_CTX *ctx );
376 static RSA * tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
378 static DH * tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
380 typedef struct dhplist {
381 struct dhplist *next;
382 int keylength;
383 DH *param;
384 } dhplist;
386 static dhplist *dhparams;
388 static int tls_seed_PRNG( const char *randfile );
390 #ifdef LDAP_R_COMPILE
392 * provide mutexes for the SSLeay library.
394 static ldap_pvt_thread_mutex_t tls_mutexes[CRYPTO_NUM_LOCKS];
396 static void tls_locking_cb( int mode, int type, const char *file, int line )
398 if ( mode & CRYPTO_LOCK ) {
399 ldap_pvt_thread_mutex_lock( &tls_mutexes[type] );
400 } else {
401 ldap_pvt_thread_mutex_unlock( &tls_mutexes[type] );
405 static unsigned long tls_thread_self( void )
407 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
408 * is an integral type that fits in an unsigned long
411 /* force an error if the ldap_pvt_thread_t type is too large */
412 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
413 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
415 return (unsigned long) ldap_pvt_thread_self();
418 static void tls_init_threads( void )
420 int i;
422 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
423 ldap_pvt_thread_mutex_init( &tls_mutexes[i] );
425 CRYPTO_set_locking_callback( tls_locking_cb );
426 CRYPTO_set_id_callback( tls_thread_self );
428 #endif /* LDAP_R_COMPILE */
430 void
431 ldap_pvt_tls_ctx_free ( void *c )
434 SSL_CTX_free( c );
437 static void *
438 tls_ctx_new( struct ldapoptions *lo )
440 return SSL_CTX_new( SSLv23_method() );
443 static void
444 tls_ctx_ref( void *c )
446 SSL_CTX *ctx = c;
447 CRYPTO_add( &ctx->references, 1, CRYPTO_LOCK_SSL_CTX );
450 static tls_session *
451 tls_session_new( tls_ctx *ctx, int is_server )
453 return SSL_new( ctx );
456 #define tls_session_connect( ssl ) SSL_connect( ssl )
457 #define tls_session_accept( ssl ) SSL_accept( ssl )
459 static STACK_OF(X509_NAME) *
460 get_ca_list( char * bundle, char * dir )
462 STACK_OF(X509_NAME) *ca_list = NULL;
464 if ( bundle ) {
465 ca_list = SSL_load_client_CA_file( bundle );
467 #if defined(HAVE_DIRENT_H) || defined(dirent)
468 if ( dir ) {
469 int freeit = 0;
471 if ( !ca_list ) {
472 ca_list = sk_X509_NAME_new_null();
473 freeit = 1;
475 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
476 freeit ) {
477 sk_X509_NAME_free( ca_list );
478 ca_list = NULL;
481 #endif
482 return ca_list;
485 #endif /* HAVE_GNUTLS */
487 #ifdef LDAP_R_COMPILE
489 * an extra mutex for the default ctx.
491 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex;
492 #endif
494 void
495 ldap_int_tls_destroy( struct ldapoptions *lo )
497 if ( lo->ldo_tls_ctx ) {
498 ldap_pvt_tls_ctx_free( lo->ldo_tls_ctx );
499 lo->ldo_tls_ctx = NULL;
502 if ( lo->ldo_tls_certfile ) {
503 LDAP_FREE( lo->ldo_tls_certfile );
504 lo->ldo_tls_certfile = NULL;
506 if ( lo->ldo_tls_keyfile ) {
507 LDAP_FREE( lo->ldo_tls_keyfile );
508 lo->ldo_tls_keyfile = NULL;
510 if ( lo->ldo_tls_dhfile ) {
511 LDAP_FREE( lo->ldo_tls_dhfile );
512 lo->ldo_tls_dhfile = NULL;
514 if ( lo->ldo_tls_cacertfile ) {
515 LDAP_FREE( lo->ldo_tls_cacertfile );
516 lo->ldo_tls_cacertfile = NULL;
518 if ( lo->ldo_tls_cacertdir ) {
519 LDAP_FREE( lo->ldo_tls_cacertdir );
520 lo->ldo_tls_cacertdir = NULL;
522 if ( lo->ldo_tls_ciphersuite ) {
523 LDAP_FREE( lo->ldo_tls_ciphersuite );
524 lo->ldo_tls_ciphersuite = NULL;
526 #ifdef HAVE_GNUTLS
527 if ( lo->ldo_tls_crlfile ) {
528 LDAP_FREE( lo->ldo_tls_crlfile );
529 lo->ldo_tls_crlfile = NULL;
531 #endif
535 * Tear down the TLS subsystem. Should only be called once.
537 void
538 ldap_pvt_tls_destroy( void )
540 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
542 ldap_int_tls_destroy( lo );
544 #ifdef HAVE_GNUTLS
545 LDAP_FREE( ciphers );
546 ciphers = NULL;
548 gnutls_global_deinit();
549 #else
550 EVP_cleanup();
551 ERR_remove_state(0);
552 ERR_free_strings();
554 if ( tls_opt_randfile ) {
555 LDAP_FREE( tls_opt_randfile );
556 tls_opt_randfile = NULL;
558 #endif
562 * Initialize TLS subsystem. Should be called only once.
565 ldap_pvt_tls_init( void )
567 static int tls_initialized = 0;
569 if ( tls_initialized++ ) return 0;
571 #ifdef LDAP_R_COMPILE
572 tls_init_threads();
573 ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex );
574 #endif
576 #ifdef HAVE_GNUTLS
577 gnutls_global_init ();
579 /* GNUtls cipher suite handling: The library ought to parse suite
580 * names for us, but it doesn't. It will return a list of suite names
581 * that it supports, so we can do parsing ourselves. It ought to tell
582 * us how long the list is, but it doesn't do that either, so we just
583 * have to count it manually...
586 int i = 0;
587 tls_cipher_suite *ptr, tmp;
588 char cs_id[2];
590 while ( gnutls_cipher_suite_info( i, cs_id, &tmp.kx, &tmp.cipher,
591 &tmp.mac, &tmp.version ))
592 i++;
593 n_ciphers = i;
595 /* Store a copy */
596 ciphers = LDAP_MALLOC(n_ciphers * sizeof(tls_cipher_suite));
597 if ( !ciphers )
598 return -1;
599 for ( i=0; i<n_ciphers; i++ ) {
600 ciphers[i].name = gnutls_cipher_suite_info( i, cs_id,
601 &ciphers[i].kx, &ciphers[i].cipher, &ciphers[i].mac,
602 &ciphers[i].version );
606 #else /* !HAVE_GNUTLS */
608 #ifdef HAVE_EBCDIC
610 char *file = LDAP_STRDUP( tls_opt_randfile );
611 if ( file ) __atoe( file );
612 (void) tls_seed_PRNG( file );
613 LDAP_FREE( file );
615 #else
616 (void) tls_seed_PRNG( tls_opt_randfile );
617 #endif
619 SSL_load_error_strings();
620 SSLeay_add_ssl_algorithms();
622 /* FIXME: mod_ssl does this */
623 X509V3_add_standard_extensions();
625 #endif /* HAVE_GNUTLS */
626 return 0;
630 * initialize a new TLS context
632 static int
633 ldap_int_tls_init_ctx( struct ldapoptions *lo, int is_server )
635 int i, rc = 0;
636 char *ciphersuite = lo->ldo_tls_ciphersuite;
637 char *cacertfile = lo->ldo_tls_cacertfile;
638 char *cacertdir = lo->ldo_tls_cacertdir;
639 char *certfile = lo->ldo_tls_certfile;
640 char *keyfile = lo->ldo_tls_keyfile;
641 #ifdef HAVE_GNUTLS
642 char *crlfile = lo->ldo_tls_crlfile;
643 #else
644 char *dhfile = lo->ldo_tls_dhfile;
645 #endif
647 if ( lo->ldo_tls_ctx )
648 return 0;
650 ldap_pvt_tls_init();
652 if ( is_server && !certfile && !keyfile && !cacertfile && !cacertdir ) {
653 /* minimum configuration not provided */
654 return LDAP_NOT_SUPPORTED;
657 #ifdef HAVE_EBCDIC
658 /* This ASCII/EBCDIC handling is a real pain! */
659 if ( ciphersuite ) {
660 ciphersuite = LDAP_STRDUP( ciphersuite );
661 __atoe( ciphersuite );
663 if ( cacertfile ) {
664 cacertfile = LDAP_STRDUP( cacertfile );
665 __atoe( cacertfile );
667 if ( certfile ) {
668 certfile = LDAP_STRDUP( certfile );
669 __atoe( certfile );
671 if ( keyfile ) {
672 keyfile = LDAP_STRDUP( keyfile );
673 __atoe( keyfile );
675 #ifdef HAVE_GNUTLS
676 if ( crlfile ) {
677 crlfile = LDAP_STRDUP( crlfile );
678 __atoe( crlfile );
680 #else
681 if ( cacertdir ) {
682 cacertdir = LDAP_STRDUP( cacertdir );
683 __atoe( cacertdir );
685 if ( dhfile ) {
686 dhfile = LDAP_STRDUP( dhfile );
687 __atoe( dhfile );
689 #endif
690 #endif
691 lo->ldo_tls_ctx = tls_ctx_new( lo );
692 if ( lo->ldo_tls_ctx == NULL ) {
693 #ifdef HAVE_GNUTLS
694 Debug( LDAP_DEBUG_ANY,
695 "TLS: could not allocate default ctx.\n",
696 0,0,0);
697 #else
698 Debug( LDAP_DEBUG_ANY,
699 "TLS: could not allocate default ctx (%lu).\n",
700 ERR_peek_error(),0,0);
701 #endif
702 rc = -1;
703 goto error_exit;
706 #ifdef HAVE_GNUTLS
707 if ( lo->ldo_tls_ciphersuite &&
708 tls_parse_ciphers( lo->ldo_tls_ctx,
709 ciphersuite )) {
710 Debug( LDAP_DEBUG_ANY,
711 "TLS: could not set cipher list %s.\n",
712 lo->ldo_tls_ciphersuite, 0, 0 );
713 rc = -1;
714 goto error_exit;
717 if (lo->ldo_tls_cacertdir != NULL) {
718 Debug( LDAP_DEBUG_ANY,
719 "TLS: warning: cacertdir not implemented for gnutls\n",
720 NULL, NULL, NULL );
723 if (lo->ldo_tls_cacertfile != NULL) {
724 rc = gnutls_certificate_set_x509_trust_file(
725 ((tls_ctx*) lo->ldo_tls_ctx)->cred,
726 cacertfile,
727 GNUTLS_X509_FMT_PEM );
728 if ( rc < 0 ) goto error_exit;
731 if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
732 rc = gnutls_certificate_set_x509_key_file(
733 ((tls_ctx*) lo->ldo_tls_ctx)->cred,
734 certfile,
735 keyfile,
736 GNUTLS_X509_FMT_PEM );
737 if ( rc ) goto error_exit;
738 } else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
739 Debug( LDAP_DEBUG_ANY,
740 "TLS: only one of certfile and keyfile specified\n",
741 NULL, NULL, NULL );
742 rc = 1;
743 goto error_exit;
746 if ( lo->ldo_tls_dhfile ) {
747 Debug( LDAP_DEBUG_ANY,
748 "TLS: warning: ignoring dhfile\n",
749 NULL, NULL, NULL );
752 if ( lo->ldo_tls_crlfile ) {
753 rc = gnutls_certificate_set_x509_crl_file(
754 ((tls_ctx*) lo->ldo_tls_ctx)->cred,
755 crlfile,
756 GNUTLS_X509_FMT_PEM );
757 if ( rc < 0 ) goto error_exit;
758 rc = 0;
760 if ( is_server ) {
761 gnutls_dh_params_init (&((tls_ctx*)
762 lo->ldo_tls_ctx)->dh_params);
763 gnutls_dh_params_generate2 (((tls_ctx*)
764 lo->ldo_tls_ctx)->dh_params,
765 DH_BITS);
768 #else /* !HAVE_GNUTLS */
770 if ( is_server ) {
771 SSL_CTX_set_session_id_context( lo->ldo_tls_ctx,
772 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
775 if ( lo->ldo_tls_ciphersuite &&
776 !SSL_CTX_set_cipher_list( lo->ldo_tls_ctx, ciphersuite ) )
778 Debug( LDAP_DEBUG_ANY,
779 "TLS: could not set cipher list %s.\n",
780 lo->ldo_tls_ciphersuite, 0, 0 );
781 tls_report_error();
782 rc = -1;
783 goto error_exit;
786 if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
787 if ( !SSL_CTX_load_verify_locations( lo->ldo_tls_ctx,
788 cacertfile, cacertdir ) ||
789 !SSL_CTX_set_default_verify_paths( lo->ldo_tls_ctx ) )
791 Debug( LDAP_DEBUG_ANY, "TLS: "
792 "could not load verify locations (file:`%s',dir:`%s').\n",
793 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
794 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
795 0 );
796 tls_report_error();
797 rc = -1;
798 goto error_exit;
801 if ( is_server ) {
802 STACK_OF(X509_NAME) *calist;
803 /* List of CA names to send to a client */
804 calist = get_ca_list( cacertfile, cacertdir );
805 if ( !calist ) {
806 Debug( LDAP_DEBUG_ANY, "TLS: "
807 "could not load client CA list (file:`%s',dir:`%s').\n",
808 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
809 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
810 0 );
811 tls_report_error();
812 rc = -1;
813 goto error_exit;
816 SSL_CTX_set_client_CA_list( lo->ldo_tls_ctx, calist );
820 if ( lo->ldo_tls_certfile &&
821 !SSL_CTX_use_certificate_file( lo->ldo_tls_ctx,
822 certfile, SSL_FILETYPE_PEM ) )
824 Debug( LDAP_DEBUG_ANY,
825 "TLS: could not use certificate `%s'.\n",
826 lo->ldo_tls_certfile,0,0);
827 tls_report_error();
828 rc = -1;
829 goto error_exit;
832 /* Key validity is checked automatically if cert has already been set */
833 if ( lo->ldo_tls_keyfile &&
834 !SSL_CTX_use_PrivateKey_file( lo->ldo_tls_ctx,
835 keyfile, SSL_FILETYPE_PEM ) )
837 Debug( LDAP_DEBUG_ANY,
838 "TLS: could not use key file `%s'.\n",
839 lo->ldo_tls_keyfile,0,0);
840 tls_report_error();
841 rc = -1;
842 goto error_exit;
845 if ( lo->ldo_tls_dhfile ) {
846 DH *dh = NULL;
847 BIO *bio;
848 dhplist *p;
850 if (( bio=BIO_new_file( dhfile,"r" )) == NULL ) {
851 Debug( LDAP_DEBUG_ANY,
852 "TLS: could not use DH parameters file `%s'.\n",
853 lo->ldo_tls_dhfile,0,0);
854 tls_report_error();
855 rc = -1;
856 goto error_exit;
858 while (( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
859 p = LDAP_MALLOC( sizeof(dhplist) );
860 if ( p != NULL ) {
861 p->keylength = DH_size( dh ) * 8;
862 p->param = dh;
863 p->next = dhparams;
864 dhparams = p;
867 BIO_free( bio );
870 if ( tls_opt_trace ) {
871 SSL_CTX_set_info_callback( (SSL_CTX *)lo->ldo_tls_ctx, tls_info_cb );
874 i = SSL_VERIFY_NONE;
875 if ( lo->ldo_tls_require_cert ) {
876 i = SSL_VERIFY_PEER;
877 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
878 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
879 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
883 SSL_CTX_set_verify( lo->ldo_tls_ctx, i,
884 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
885 tls_verify_ok : tls_verify_cb );
886 SSL_CTX_set_tmp_rsa_callback( lo->ldo_tls_ctx, tls_tmp_rsa_cb );
887 if ( lo->ldo_tls_dhfile ) {
888 SSL_CTX_set_tmp_dh_callback( lo->ldo_tls_ctx, tls_tmp_dh_cb );
890 #ifdef HAVE_OPENSSL_CRL
891 if ( lo->ldo_tls_crlcheck ) {
892 X509_STORE *x509_s = SSL_CTX_get_cert_store( lo->ldo_tls_ctx );
893 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
894 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
895 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
896 X509_STORE_set_flags( x509_s,
897 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
900 #endif
902 #endif /* HAVE_GNUTLS */
904 error_exit:
905 if ( rc == -1 && lo->ldo_tls_ctx != NULL ) {
906 ldap_pvt_tls_ctx_free( lo->ldo_tls_ctx );
907 lo->ldo_tls_ctx = NULL;
909 #ifdef HAVE_EBCDIC
910 LDAP_FREE( ciphersuite );
911 LDAP_FREE( cacertfile );
912 LDAP_FREE( certfile );
913 LDAP_FREE( keyfile );
914 #ifdef HAVE_GNUTLS
915 LDAP_FREE( crlfile );
916 #else
917 LDAP_FREE( cacertdir );
918 LDAP_FREE( dhfile );
919 #endif
920 #endif
921 return rc;
925 * initialize the default context
928 ldap_pvt_tls_init_def_ctx( int is_server )
930 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
931 int rc;
932 #ifdef LDAP_R_COMPILE
933 ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex );
934 #endif
935 rc = ldap_int_tls_init_ctx( lo, is_server );
936 #ifdef LDAP_R_COMPILE
937 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
938 #endif
939 return rc;
942 static tls_session *
943 alloc_handle( void *ctx_arg, int is_server )
945 tls_ctx *ctx;
946 tls_session *ssl;
948 if ( ctx_arg ) {
949 ctx = ctx_arg;
950 } else {
951 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
952 if ( ldap_pvt_tls_init_def_ctx( is_server ) < 0 ) return NULL;
953 ctx = lo->ldo_tls_ctx;
956 ssl = tls_session_new( ctx, is_server );
957 if ( ssl == NULL ) {
958 Debug( LDAP_DEBUG_ANY,"TLS: can't create ssl handle.\n",0,0,0);
959 return NULL;
961 return ssl;
964 static int
965 update_flags( Sockbuf *sb, tls_session * ssl, int rc )
967 sb->sb_trans_needs_read = 0;
968 sb->sb_trans_needs_write = 0;
970 #ifdef HAVE_GNUTLS
971 if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
972 return 0;
974 switch (gnutls_record_get_direction (ssl->session)) {
975 case 0:
976 sb->sb_trans_needs_read = 1;
977 return 1;
978 case 1:
979 sb->sb_trans_needs_write = 1;
980 return 1;
982 #else /* !HAVE_GNUTLS */
983 rc = SSL_get_error(ssl, rc);
984 if (rc == SSL_ERROR_WANT_READ) {
985 sb->sb_trans_needs_read = 1;
986 return 1;
988 } else if (rc == SSL_ERROR_WANT_WRITE) {
989 sb->sb_trans_needs_write = 1;
990 return 1;
992 } else if (rc == SSL_ERROR_WANT_CONNECT) {
993 return 1;
995 #endif /* HAVE_GNUTLS */
996 return 0;
1000 * TLS support for LBER Sockbufs
1003 struct tls_data {
1004 tls_session *ssl;
1005 Sockbuf_IO_Desc *sbiod;
1008 #ifdef HAVE_GNUTLS
1010 static ssize_t
1011 sb_gtls_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
1013 struct tls_data *p;
1015 if ( buf == NULL || len <= 0 ) return 0;
1017 p = (struct tls_data *)ptr;
1019 if ( p == NULL || p->sbiod == NULL ) {
1020 return 0;
1023 return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
1026 static ssize_t
1027 sb_gtls_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
1029 struct tls_data *p;
1031 if ( buf == NULL || len <= 0 ) return 0;
1033 p = (struct tls_data *)ptr;
1035 if ( p == NULL || p->sbiod == NULL ) {
1036 return 0;
1039 return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
1042 static int
1043 sb_tls_setup( Sockbuf_IO_Desc *sbiod, void *arg )
1045 struct tls_data *p;
1046 tls_session *session = arg;
1048 assert( sbiod != NULL );
1050 p = LBER_MALLOC( sizeof( *p ) );
1051 if ( p == NULL ) {
1052 return -1;
1055 gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
1056 gnutls_transport_set_pull_function( session->session, sb_gtls_recv );
1057 gnutls_transport_set_push_function( session->session, sb_gtls_send );
1058 p->ssl = arg;
1059 p->sbiod = sbiod;
1060 sbiod->sbiod_pvt = p;
1061 return 0;
1064 static int
1065 sb_tls_remove( Sockbuf_IO_Desc *sbiod )
1067 struct tls_data *p;
1069 assert( sbiod != NULL );
1070 assert( sbiod->sbiod_pvt != NULL );
1072 p = (struct tls_data *)sbiod->sbiod_pvt;
1073 gnutls_deinit ( p->ssl->session );
1074 LBER_FREE( p->ssl );
1075 LBER_FREE( sbiod->sbiod_pvt );
1076 sbiod->sbiod_pvt = NULL;
1077 return 0;
1080 static int
1081 sb_tls_close( Sockbuf_IO_Desc *sbiod )
1083 struct tls_data *p;
1085 assert( sbiod != NULL );
1086 assert( sbiod->sbiod_pvt != NULL );
1088 p = (struct tls_data *)sbiod->sbiod_pvt;
1089 gnutls_bye ( p->ssl->session, GNUTLS_SHUT_RDWR );
1090 return 0;
1093 static int
1094 sb_tls_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
1096 struct tls_data *p;
1098 assert( sbiod != NULL );
1099 assert( sbiod->sbiod_pvt != NULL );
1101 p = (struct tls_data *)sbiod->sbiod_pvt;
1103 if ( opt == LBER_SB_OPT_GET_SSL ) {
1104 *((tls_session **)arg) = p->ssl;
1105 return 1;
1107 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
1108 if( gnutls_record_check_pending( p->ssl->session ) > 0 ) {
1109 return 1;
1113 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1116 static ber_slen_t
1117 sb_tls_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1119 struct tls_data *p;
1120 ber_slen_t ret;
1121 int err;
1123 assert( sbiod != NULL );
1124 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1126 p = (struct tls_data *)sbiod->sbiod_pvt;
1128 ret = gnutls_record_recv ( p->ssl->session, buf, len );
1129 switch (ret) {
1130 case GNUTLS_E_INTERRUPTED:
1131 case GNUTLS_E_AGAIN:
1132 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1133 sock_errset(EWOULDBLOCK);
1134 ret = 0;
1135 break;
1136 case GNUTLS_E_REHANDSHAKE:
1137 for ( ret = gnutls_handshake ( p->ssl->session );
1138 ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
1139 ret = gnutls_handshake ( p->ssl->session ) );
1140 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1141 ret = 0;
1142 break;
1143 default:
1144 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1146 return ret;
1149 static ber_slen_t
1150 sb_tls_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1152 struct tls_data *p;
1153 ber_slen_t ret;
1154 int err;
1156 assert( sbiod != NULL );
1157 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1159 p = (struct tls_data *)sbiod->sbiod_pvt;
1161 ret = gnutls_record_send ( p->ssl->session, (char *)buf, len );
1163 if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
1164 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1165 sock_errset(EWOULDBLOCK);
1166 ret = 0;
1167 } else {
1168 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1170 return ret;
1173 #else /* !HAVE_GNUTLS */
1175 static int
1176 sb_tls_bio_create( BIO *b ) {
1177 b->init = 1;
1178 b->num = 0;
1179 b->ptr = NULL;
1180 b->flags = 0;
1181 return 1;
1184 static int
1185 sb_tls_bio_destroy( BIO *b )
1187 if ( b == NULL ) return 0;
1189 b->ptr = NULL; /* sb_tls_remove() will free it */
1190 b->init = 0;
1191 b->flags = 0;
1192 return 1;
1195 static int
1196 sb_tls_bio_read( BIO *b, char *buf, int len )
1198 struct tls_data *p;
1199 int ret;
1201 if ( buf == NULL || len <= 0 ) return 0;
1203 p = (struct tls_data *)b->ptr;
1205 if ( p == NULL || p->sbiod == NULL ) {
1206 return 0;
1209 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
1211 BIO_clear_retry_flags( b );
1212 if ( ret < 0 ) {
1213 int err = sock_errno();
1214 if ( err == EAGAIN || err == EWOULDBLOCK ) {
1215 BIO_set_retry_read( b );
1219 return ret;
1222 static int
1223 sb_tls_bio_write( BIO *b, const char *buf, int len )
1225 struct tls_data *p;
1226 int ret;
1228 if ( buf == NULL || len <= 0 ) return 0;
1230 p = (struct tls_data *)b->ptr;
1232 if ( p == NULL || p->sbiod == NULL ) {
1233 return 0;
1236 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
1238 BIO_clear_retry_flags( b );
1239 if ( ret < 0 ) {
1240 int err = sock_errno();
1241 if ( err == EAGAIN || err == EWOULDBLOCK ) {
1242 BIO_set_retry_write( b );
1246 return ret;
1249 static long
1250 sb_tls_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
1252 if ( cmd == BIO_CTRL_FLUSH ) {
1253 /* The OpenSSL library needs this */
1254 return 1;
1256 return 0;
1259 static int
1260 sb_tls_bio_gets( BIO *b, char *buf, int len )
1262 return -1;
1265 static int
1266 sb_tls_bio_puts( BIO *b, const char *str )
1268 return sb_tls_bio_write( b, str, strlen( str ) );
1271 static BIO_METHOD sb_tls_bio_method =
1273 ( 100 | 0x400 ), /* it's a source/sink BIO */
1274 "sockbuf glue",
1275 sb_tls_bio_write,
1276 sb_tls_bio_read,
1277 sb_tls_bio_puts,
1278 sb_tls_bio_gets,
1279 sb_tls_bio_ctrl,
1280 sb_tls_bio_create,
1281 sb_tls_bio_destroy
1284 static int
1285 sb_tls_setup( Sockbuf_IO_Desc *sbiod, void *arg )
1287 struct tls_data *p;
1288 BIO *bio;
1290 assert( sbiod != NULL );
1292 p = LBER_MALLOC( sizeof( *p ) );
1293 if ( p == NULL ) {
1294 return -1;
1297 p->ssl = (SSL *)arg;
1298 p->sbiod = sbiod;
1299 bio = BIO_new( &sb_tls_bio_method );
1300 bio->ptr = (void *)p;
1301 SSL_set_bio( p->ssl, bio, bio );
1302 sbiod->sbiod_pvt = p;
1303 return 0;
1306 static int
1307 sb_tls_remove( Sockbuf_IO_Desc *sbiod )
1309 struct tls_data *p;
1311 assert( sbiod != NULL );
1312 assert( sbiod->sbiod_pvt != NULL );
1314 p = (struct tls_data *)sbiod->sbiod_pvt;
1315 SSL_free( p->ssl );
1316 LBER_FREE( sbiod->sbiod_pvt );
1317 sbiod->sbiod_pvt = NULL;
1318 return 0;
1321 static int
1322 sb_tls_close( Sockbuf_IO_Desc *sbiod )
1324 struct tls_data *p;
1326 assert( sbiod != NULL );
1327 assert( sbiod->sbiod_pvt != NULL );
1329 p = (struct tls_data *)sbiod->sbiod_pvt;
1330 SSL_shutdown( p->ssl );
1331 return 0;
1334 static int
1335 sb_tls_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
1337 struct tls_data *p;
1339 assert( sbiod != NULL );
1340 assert( sbiod->sbiod_pvt != NULL );
1342 p = (struct tls_data *)sbiod->sbiod_pvt;
1344 if ( opt == LBER_SB_OPT_GET_SSL ) {
1345 *((SSL **)arg) = p->ssl;
1346 return 1;
1348 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
1349 if( SSL_pending( p->ssl ) > 0 ) {
1350 return 1;
1354 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1357 static ber_slen_t
1358 sb_tls_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1360 struct tls_data *p;
1361 ber_slen_t ret;
1362 int err;
1364 assert( sbiod != NULL );
1365 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1367 p = (struct tls_data *)sbiod->sbiod_pvt;
1369 ret = SSL_read( p->ssl, (char *)buf, len );
1370 #ifdef HAVE_WINSOCK
1371 errno = WSAGetLastError();
1372 #endif
1373 err = SSL_get_error( p->ssl, ret );
1374 if (err == SSL_ERROR_WANT_READ ) {
1375 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1376 sock_errset(EWOULDBLOCK);
1378 else
1379 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1380 return ret;
1383 static ber_slen_t
1384 sb_tls_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1386 struct tls_data *p;
1387 ber_slen_t ret;
1388 int err;
1390 assert( sbiod != NULL );
1391 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1393 p = (struct tls_data *)sbiod->sbiod_pvt;
1395 ret = SSL_write( p->ssl, (char *)buf, len );
1396 #ifdef HAVE_WINSOCK
1397 errno = WSAGetLastError();
1398 #endif
1399 err = SSL_get_error( p->ssl, ret );
1400 if (err == SSL_ERROR_WANT_WRITE ) {
1401 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1402 sock_errset(EWOULDBLOCK);
1404 } else {
1405 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1407 return ret;
1410 #endif
1412 static Sockbuf_IO sb_tls_sbio =
1414 sb_tls_setup, /* sbi_setup */
1415 sb_tls_remove, /* sbi_remove */
1416 sb_tls_ctrl, /* sbi_ctrl */
1417 sb_tls_read, /* sbi_read */
1418 sb_tls_write, /* sbi_write */
1419 sb_tls_close /* sbi_close */
1422 #ifdef HAVE_GNUTLS
1423 /* Certs are not automatically varified during the handshake */
1424 static int
1425 tls_cert_verify( tls_session *ssl )
1427 unsigned int status = 0;
1428 int err;
1429 time_t now = time(0);
1431 err = gnutls_certificate_verify_peers2( ssl->session, &status );
1432 if ( err < 0 ) {
1433 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
1434 err,0,0 );
1435 return -1;
1437 if ( status ) {
1438 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
1439 status, 0,0 );
1440 return -1;
1442 if ( gnutls_certificate_expiration_time_peers( ssl->session ) < now ) {
1443 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
1444 0, 0, 0 );
1445 return -1;
1447 if ( gnutls_certificate_activation_time_peers( ssl->session ) > now ) {
1448 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
1449 0, 0, 0 );
1450 return -1;
1452 return 0;
1454 #endif /* HAVE_GNUTLS */
1457 * Call this to do a TLS connect on a sockbuf. ctx_arg can be
1458 * a SSL_CTX * or NULL, in which case the default ctx is used.
1460 * Return value:
1462 * 0 - Success. Connection is ready for communication.
1463 * <0 - Error. Can't create a TLS stream.
1464 * >0 - Partial success.
1465 * Do a select (using information from lber_pvt_sb_needs_{read,write}
1466 * and call again.
1469 static int
1470 ldap_int_tls_connect( LDAP *ld, LDAPConn *conn )
1472 Sockbuf *sb = conn->lconn_sb;
1473 int err;
1474 tls_session *ssl;
1476 if ( HAS_TLS( sb ) ) {
1477 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
1479 } else {
1480 struct ldapoptions *lo;
1481 tls_ctx *ctx;
1483 ctx = ld->ld_options.ldo_tls_ctx;
1485 ssl = alloc_handle( ctx, 0 );
1487 if ( ssl == NULL ) return -1;
1489 #ifdef LDAP_DEBUG
1490 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
1491 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
1492 #endif
1493 ber_sockbuf_add_io( sb, &sb_tls_sbio,
1494 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
1496 lo = LDAP_INT_GLOBAL_OPT();
1497 if( ctx == NULL ) {
1498 ctx = lo->ldo_tls_ctx;
1499 ld->ld_options.ldo_tls_ctx = ctx;
1500 tls_ctx_ref( ctx );
1502 if ( ld->ld_options.ldo_tls_connect_cb )
1503 ld->ld_options.ldo_tls_connect_cb( ld, ssl, ctx,
1504 ld->ld_options.ldo_tls_connect_arg );
1505 if ( lo && lo->ldo_tls_connect_cb && lo->ldo_tls_connect_cb !=
1506 ld->ld_options.ldo_tls_connect_cb )
1507 lo->ldo_tls_connect_cb( ld, ssl, ctx, lo->ldo_tls_connect_arg );
1510 err = tls_session_connect( ssl );
1512 #ifdef HAVE_WINSOCK
1513 errno = WSAGetLastError();
1514 #endif
1516 #ifdef HAVE_GNUTLS
1517 if ( err < 0 )
1518 #else
1519 if ( err <= 0 )
1520 #endif
1522 if ( update_flags( sb, ssl, err )) {
1523 return 1;
1526 #ifndef HAVE_GNUTLS
1527 if ((err = ERR_peek_error()))
1528 #endif
1530 if ( ld->ld_error ) {
1531 LDAP_FREE( ld->ld_error );
1533 #ifdef HAVE_GNUTLS
1534 ld->ld_error = LDAP_STRDUP(gnutls_strerror( err ));
1535 #else
1537 char buf[256];
1538 ld->ld_error = LDAP_STRDUP(ERR_error_string(err, buf));
1540 #endif
1541 #ifdef HAVE_EBCDIC
1542 if ( ld->ld_error ) __etoa(ld->ld_error);
1543 #endif
1546 Debug( LDAP_DEBUG_ANY,"TLS: can't connect: %s.\n",
1547 ld->ld_error ? ld->ld_error : "" ,0,0);
1549 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
1550 LBER_SBIOD_LEVEL_TRANSPORT );
1551 #ifdef LDAP_DEBUG
1552 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
1553 LBER_SBIOD_LEVEL_TRANSPORT );
1554 #endif
1555 return -1;
1558 #ifdef HAVE_GNUTLS
1559 if ( ld->ld_options.ldo_tls_require_cert != LDAP_OPT_X_TLS_NEVER ) {
1560 err = tls_cert_verify( ssl );
1561 if ( err && ld->ld_options.ldo_tls_require_cert != LDAP_OPT_X_TLS_ALLOW )
1562 return err;
1564 #endif
1566 return 0;
1570 * Call this to do a TLS accept on a sockbuf.
1571 * Everything else is the same as with tls_connect.
1574 ldap_pvt_tls_accept( Sockbuf *sb, void *ctx_arg )
1576 int err;
1577 tls_session *ssl;
1579 if ( HAS_TLS( sb ) ) {
1580 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
1582 } else {
1583 ssl = alloc_handle( ctx_arg, 1 );
1584 if ( ssl == NULL ) return -1;
1586 #ifdef LDAP_DEBUG
1587 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
1588 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
1589 #endif
1590 ber_sockbuf_add_io( sb, &sb_tls_sbio,
1591 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
1594 err = tls_session_accept( ssl );
1596 #ifdef HAVE_WINSOCK
1597 errno = WSAGetLastError();
1598 #endif
1600 #ifdef HAVE_GNUTLS
1601 if ( err < 0 )
1602 #else
1603 if ( err <= 0 )
1604 #endif
1606 if ( update_flags( sb, ssl, err )) return 1;
1608 #ifdef HAVE_GNUTLS
1609 Debug( LDAP_DEBUG_ANY,"TLS: can't accept: %s.\n",
1610 gnutls_strerror( err ),0,0 );
1611 #else
1612 Debug( LDAP_DEBUG_ANY,"TLS: can't accept.\n",0,0,0 );
1613 tls_report_error();
1614 #endif
1615 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
1616 LBER_SBIOD_LEVEL_TRANSPORT );
1617 #ifdef LDAP_DEBUG
1618 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
1619 LBER_SBIOD_LEVEL_TRANSPORT );
1620 #endif
1621 return -1;
1624 #ifdef HAVE_GNUTLS
1625 if ( ssl->ctx->lo->ldo_tls_require_cert != LDAP_OPT_X_TLS_NEVER ) {
1626 err = tls_cert_verify( ssl );
1627 if ( err && ssl->ctx->lo->ldo_tls_require_cert != LDAP_OPT_X_TLS_ALLOW )
1628 return err;
1630 #endif
1631 return 0;
1635 ldap_pvt_tls_inplace ( Sockbuf *sb )
1637 return HAS_TLS( sb ) ? 1 : 0;
1641 ldap_tls_inplace( LDAP *ld )
1643 Sockbuf *sb = NULL;
1645 if ( ld->ld_defconn && ld->ld_defconn->lconn_sb ) {
1646 sb = ld->ld_defconn->lconn_sb;
1648 } else if ( ld->ld_sb ) {
1649 sb = ld->ld_sb;
1651 } else {
1652 return 0;
1655 return ldap_pvt_tls_inplace( sb );
1658 #ifdef HAVE_GNUTLS
1659 static void
1660 x509_cert_get_dn( struct berval *cert, struct berval *dn, int get_subject )
1662 BerElementBuffer berbuf;
1663 BerElement *ber = (BerElement *)&berbuf;
1664 ber_tag_t tag;
1665 ber_len_t len;
1666 ber_int_t i;
1668 ber_init2( ber, cert, LBER_USE_DER );
1669 tag = ber_skip_tag( ber, &len ); /* Sequence */
1670 tag = ber_skip_tag( ber, &len ); /* Sequence */
1671 tag = ber_skip_tag( ber, &len ); /* Context + Constructed (version) */
1672 if ( tag == 0xa0 ) /* Version is optional */
1673 tag = ber_get_int( ber, &i ); /* Int: Version */
1674 tag = ber_get_int( ber, &i ); /* Int: Serial */
1675 tag = ber_skip_tag( ber, &len ); /* Sequence: Signature */
1676 ber_skip_data( ber, len );
1677 if ( !get_subject ) {
1678 tag = ber_peek_tag( ber, &len ); /* Sequence: Issuer DN */
1679 } else {
1680 tag = ber_skip_tag( ber, &len );
1681 ber_skip_data( ber, len );
1682 tag = ber_skip_tag( ber, &len ); /* Sequence: Validity */
1683 ber_skip_data( ber, len );
1684 tag = ber_peek_tag( ber, &len ); /* Sequence: Subject DN */
1686 len = ber_ptrlen( ber );
1687 dn->bv_val = cert->bv_val + len;
1688 dn->bv_len = cert->bv_len - len;
1691 static int
1692 tls_get_cert_dn( tls_session *session, struct berval *dnbv )
1694 if ( !session->peer_der_dn.bv_val ) {
1695 const gnutls_datum_t *peer_cert_list;
1696 int list_size;
1697 struct berval bv;
1699 peer_cert_list = gnutls_certificate_get_peers( session->session,
1700 &list_size );
1701 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
1703 bv.bv_len = peer_cert_list->size;
1704 bv.bv_val = peer_cert_list->data;
1706 x509_cert_get_dn( &bv, &session->peer_der_dn, 1 );
1707 *dnbv = session->peer_der_dn;
1709 return 0;
1711 #else /* !HAVE_GNUTLS */
1712 static X509 *
1713 tls_get_cert( SSL *s )
1715 /* If peer cert was bad, treat as if no cert was given */
1716 if (SSL_get_verify_result(s)) {
1717 /* If we can send an alert, do so */
1718 if (SSL_version(s) != SSL2_VERSION) {
1719 ssl3_send_alert(s,SSL3_AL_WARNING,SSL3_AD_BAD_CERTIFICATE);
1721 return NULL;
1723 return SSL_get_peer_certificate(s);
1726 static int
1727 tls_get_cert_dn( tls_session *session, struct berval *dnbv )
1729 X509_NAME *xn;
1730 X509 *x = tls_get_cert( session );
1732 if ( !x )
1733 return LDAP_INVALID_CREDENTIALS;
1735 xn = X509_get_subject_name(x);
1736 dnbv->bv_len = i2d_X509_NAME( xn, NULL );
1737 dnbv->bv_val = xn->bytes->data;
1738 return 0;
1740 #endif /* HAVE_GNUTLS */
1743 ldap_pvt_tls_get_peer_dn( void *s, struct berval *dn,
1744 LDAPDN_rewrite_dummy *func, unsigned flags )
1746 tls_session *session = s;
1747 struct berval bvdn;
1748 int rc;
1750 rc = tls_get_cert_dn( session, &bvdn );
1751 if ( rc ) return rc;
1753 rc = ldap_X509dn2bv( &bvdn, dn,
1754 (LDAPDN_rewrite_func *)func, flags);
1755 return rc;
1758 /* what kind of hostname were we given? */
1759 #define IS_DNS 0
1760 #define IS_IP4 1
1761 #define IS_IP6 2
1763 #ifdef HAVE_GNUTLS
1766 ldap_pvt_tls_check_hostname( LDAP *ld, void *s, const char *name_in )
1768 tls_session *session = s;
1769 int i, ret;
1770 const gnutls_datum_t *peer_cert_list;
1771 int list_size;
1772 struct berval bv;
1773 char altname[NI_MAXHOST];
1774 size_t altnamesize;
1776 gnutls_x509_crt_t cert;
1777 gnutls_datum_t *x;
1778 const char *name;
1779 char *ptr;
1780 char *domain = NULL;
1781 #ifdef LDAP_PF_INET6
1782 struct in6_addr addr;
1783 #else
1784 struct in_addr addr;
1785 #endif
1786 int n, len1 = 0, len2 = 0;
1787 int ntype = IS_DNS;
1788 time_t now = time(0);
1790 if( ldap_int_hostname &&
1791 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
1793 name = ldap_int_hostname;
1794 } else {
1795 name = name_in;
1798 peer_cert_list = gnutls_certificate_get_peers( session->session,
1799 &list_size );
1800 if ( !peer_cert_list ) {
1801 Debug( LDAP_DEBUG_ANY,
1802 "TLS: unable to get peer certificate.\n",
1803 0, 0, 0 );
1804 /* If this was a fatal condition, things would have
1805 * aborted long before now.
1807 return LDAP_SUCCESS;
1809 ret = gnutls_x509_crt_init( &cert );
1810 if ( ret < 0 )
1811 return LDAP_LOCAL_ERROR;
1812 ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
1813 if ( ret ) {
1814 gnutls_x509_crt_deinit( cert );
1815 return LDAP_LOCAL_ERROR;
1818 #ifdef LDAP_PF_INET6
1819 if (name[0] == '[' && strchr(name, ']')) {
1820 char *n2 = ldap_strdup(name+1);
1821 *strchr(n2, ']') = 2;
1822 if (inet_pton(AF_INET6, n2, &addr))
1823 ntype = IS_IP6;
1824 LDAP_FREE(n2);
1825 } else
1826 #endif
1827 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
1828 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
1831 if (ntype == IS_DNS) {
1832 len1 = strlen(name);
1833 domain = strchr(name, '.');
1834 if (domain) {
1835 len2 = len1 - (domain-name);
1839 for ( i=0, ret=0; ret >= 0; i++ ) {
1840 altnamesize = sizeof(altname);
1841 ret = gnutls_x509_crt_get_subject_alt_name( cert, i,
1842 altname, &altnamesize, NULL );
1843 if ( ret < 0 ) break;
1845 /* ignore empty */
1846 if ( altnamesize == 0 ) continue;
1848 if ( ret == GNUTLS_SAN_DNSNAME ) {
1849 if (ntype != IS_DNS) continue;
1851 /* Is this an exact match? */
1852 if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
1853 break;
1856 /* Is this a wildcard match? */
1857 if (domain && (altname[0] == '*') && (altname[1] == '.') &&
1858 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
1860 break;
1862 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
1863 if (ntype == IS_DNS) continue;
1865 #ifdef LDAP_PF_INET6
1866 if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
1867 continue;
1868 } else
1869 #endif
1870 if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
1871 continue;
1873 if (!memcmp(altname, &addr, altnamesize)) {
1874 break;
1878 if ( ret >= 0 ) {
1879 ret = LDAP_SUCCESS;
1880 } else {
1881 altnamesize = sizeof(altname);
1882 ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
1883 0, 0, altname, &altnamesize );
1884 if ( ret < 0 ) {
1885 Debug( LDAP_DEBUG_ANY,
1886 "TLS: unable to get common name from peer certificate.\n",
1887 0, 0, 0 );
1888 ret = LDAP_CONNECT_ERROR;
1889 if ( ld->ld_error ) {
1890 LDAP_FREE( ld->ld_error );
1892 ld->ld_error = LDAP_STRDUP(
1893 _("TLS: unable to get CN from peer certificate"));
1895 } else {
1896 ret = LDAP_LOCAL_ERROR;
1897 if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
1898 ret = LDAP_SUCCESS;
1900 } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
1901 /* Is this a wildcard match? */
1902 if( domain &&
1903 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
1904 ret = LDAP_SUCCESS;
1909 if( ret == LDAP_LOCAL_ERROR ) {
1910 altname[altnamesize] = '\0';
1911 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
1912 "common name in certificate (%s).\n",
1913 name, altname, 0 );
1914 ret = LDAP_CONNECT_ERROR;
1915 if ( ld->ld_error ) {
1916 LDAP_FREE( ld->ld_error );
1918 ld->ld_error = LDAP_STRDUP(
1919 _("TLS: hostname does not match CN in peer certificate"));
1922 gnutls_x509_crt_deinit( cert );
1923 return ret;
1926 #else /* !HAVE_GNUTLS */
1929 ldap_pvt_tls_check_hostname( LDAP *ld, void *s, const char *name_in )
1931 int i, ret = LDAP_LOCAL_ERROR;
1932 X509 *x;
1933 const char *name;
1934 char *ptr;
1935 int ntype = IS_DNS;
1936 #ifdef LDAP_PF_INET6
1937 struct in6_addr addr;
1938 #else
1939 struct in_addr addr;
1940 #endif
1942 if( ldap_int_hostname &&
1943 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
1945 name = ldap_int_hostname;
1946 } else {
1947 name = name_in;
1950 x = tls_get_cert((SSL *)s);
1951 if (!x) {
1952 Debug( LDAP_DEBUG_ANY,
1953 "TLS: unable to get peer certificate.\n",
1954 0, 0, 0 );
1955 /* If this was a fatal condition, things would have
1956 * aborted long before now.
1958 return LDAP_SUCCESS;
1961 #ifdef LDAP_PF_INET6
1962 if (name[0] == '[' && strchr(name, ']')) {
1963 char *n2 = ldap_strdup(name+1);
1964 *strchr(n2, ']') = 2;
1965 if (inet_pton(AF_INET6, n2, &addr))
1966 ntype = IS_IP6;
1967 LDAP_FREE(n2);
1968 } else
1969 #endif
1970 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
1971 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
1974 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
1975 if (i >= 0) {
1976 X509_EXTENSION *ex;
1977 STACK_OF(GENERAL_NAME) *alt;
1979 ex = X509_get_ext(x, i);
1980 alt = X509V3_EXT_d2i(ex);
1981 if (alt) {
1982 int n, len1 = 0, len2 = 0;
1983 char *domain = NULL;
1984 GENERAL_NAME *gn;
1986 if (ntype == IS_DNS) {
1987 len1 = strlen(name);
1988 domain = strchr(name, '.');
1989 if (domain) {
1990 len2 = len1 - (domain-name);
1993 n = sk_GENERAL_NAME_num(alt);
1994 for (i=0; i<n; i++) {
1995 char *sn;
1996 int sl;
1997 gn = sk_GENERAL_NAME_value(alt, i);
1998 if (gn->type == GEN_DNS) {
1999 if (ntype != IS_DNS) continue;
2001 sn = (char *) ASN1_STRING_data(gn->d.ia5);
2002 sl = ASN1_STRING_length(gn->d.ia5);
2004 /* ignore empty */
2005 if (sl == 0) continue;
2007 /* Is this an exact match? */
2008 if ((len1 == sl) && !strncasecmp(name, sn, len1)) {
2009 break;
2012 /* Is this a wildcard match? */
2013 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
2014 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
2016 break;
2019 } else if (gn->type == GEN_IPADD) {
2020 if (ntype == IS_DNS) continue;
2022 sn = (char *) ASN1_STRING_data(gn->d.ia5);
2023 sl = ASN1_STRING_length(gn->d.ia5);
2025 #ifdef LDAP_PF_INET6
2026 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
2027 continue;
2028 } else
2029 #endif
2030 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
2031 continue;
2033 if (!memcmp(sn, &addr, sl)) {
2034 break;
2039 GENERAL_NAMES_free(alt);
2040 if (i < n) { /* Found a match */
2041 ret = LDAP_SUCCESS;
2046 if (ret != LDAP_SUCCESS) {
2047 X509_NAME *xn;
2048 char buf[2048];
2049 buf[0] = '\0';
2051 xn = X509_get_subject_name(x);
2052 if( X509_NAME_get_text_by_NID( xn, NID_commonName,
2053 buf, sizeof(buf)) == -1)
2055 Debug( LDAP_DEBUG_ANY,
2056 "TLS: unable to get common name from peer certificate.\n",
2057 0, 0, 0 );
2058 ret = LDAP_CONNECT_ERROR;
2059 if ( ld->ld_error ) {
2060 LDAP_FREE( ld->ld_error );
2062 ld->ld_error = LDAP_STRDUP(
2063 _("TLS: unable to get CN from peer certificate"));
2065 } else if (strcasecmp(name, buf) == 0 ) {
2066 ret = LDAP_SUCCESS;
2068 } else if (( buf[0] == '*' ) && ( buf[1] == '.' )) {
2069 char *domain = strchr(name, '.');
2070 if( domain ) {
2071 size_t dlen = 0;
2072 size_t sl;
2074 sl = strlen(name);
2075 dlen = sl - (domain-name);
2076 sl = strlen(buf);
2078 /* Is this a wildcard match? */
2079 if ((dlen == sl-1) && !strncasecmp(domain, &buf[1], dlen)) {
2080 ret = LDAP_SUCCESS;
2085 if( ret == LDAP_LOCAL_ERROR ) {
2086 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
2087 "common name in certificate (%s).\n",
2088 name, buf, 0 );
2089 ret = LDAP_CONNECT_ERROR;
2090 if ( ld->ld_error ) {
2091 LDAP_FREE( ld->ld_error );
2093 ld->ld_error = LDAP_STRDUP(
2094 _("TLS: hostname does not match CN in peer certificate"));
2097 X509_free(x);
2098 return ret;
2100 #endif
2103 ldap_int_tls_config( LDAP *ld, int option, const char *arg )
2105 int i;
2107 switch( option ) {
2108 case LDAP_OPT_X_TLS_CACERTFILE:
2109 case LDAP_OPT_X_TLS_CACERTDIR:
2110 case LDAP_OPT_X_TLS_CERTFILE:
2111 case LDAP_OPT_X_TLS_KEYFILE:
2112 case LDAP_OPT_X_TLS_RANDOM_FILE:
2113 case LDAP_OPT_X_TLS_CIPHER_SUITE:
2114 case LDAP_OPT_X_TLS_DHFILE:
2115 #ifdef HAVE_GNUTLS
2116 case LDAP_OPT_X_TLS_CRLFILE:
2117 #endif
2118 return ldap_pvt_tls_set_option( ld, option, (void *) arg );
2120 case LDAP_OPT_X_TLS_REQUIRE_CERT:
2121 case LDAP_OPT_X_TLS:
2122 i = -1;
2123 if ( strcasecmp( arg, "never" ) == 0 ) {
2124 i = LDAP_OPT_X_TLS_NEVER ;
2126 } else if ( strcasecmp( arg, "demand" ) == 0 ) {
2127 i = LDAP_OPT_X_TLS_DEMAND ;
2129 } else if ( strcasecmp( arg, "allow" ) == 0 ) {
2130 i = LDAP_OPT_X_TLS_ALLOW ;
2132 } else if ( strcasecmp( arg, "try" ) == 0 ) {
2133 i = LDAP_OPT_X_TLS_TRY ;
2135 } else if ( ( strcasecmp( arg, "hard" ) == 0 ) ||
2136 ( strcasecmp( arg, "on" ) == 0 ) ||
2137 ( strcasecmp( arg, "yes" ) == 0) ||
2138 ( strcasecmp( arg, "true" ) == 0 ) )
2140 i = LDAP_OPT_X_TLS_HARD ;
2143 if (i >= 0) {
2144 return ldap_pvt_tls_set_option( ld, option, &i );
2146 return -1;
2147 #ifdef HAVE_OPENSSL_CRL
2148 case LDAP_OPT_X_TLS_CRLCHECK:
2149 i = -1;
2150 if ( strcasecmp( arg, "none" ) == 0 ) {
2151 i = LDAP_OPT_X_TLS_CRL_NONE ;
2152 } else if ( strcasecmp( arg, "peer" ) == 0 ) {
2153 i = LDAP_OPT_X_TLS_CRL_PEER ;
2154 } else if ( strcasecmp( arg, "all" ) == 0 ) {
2155 i = LDAP_OPT_X_TLS_CRL_ALL ;
2157 if (i >= 0) {
2158 return ldap_pvt_tls_set_option( ld, option, &i );
2160 return -1;
2161 #endif
2163 return -1;
2167 ldap_pvt_tls_get_option( LDAP *ld, int option, void *arg )
2169 struct ldapoptions *lo;
2171 if( ld != NULL ) {
2172 assert( LDAP_VALID( ld ) );
2174 if( !LDAP_VALID( ld ) ) {
2175 return LDAP_OPT_ERROR;
2178 lo = &ld->ld_options;
2180 } else {
2181 /* Get pointer to global option structure */
2182 lo = LDAP_INT_GLOBAL_OPT();
2183 if ( lo == NULL ) {
2184 return LDAP_NO_MEMORY;
2188 switch( option ) {
2189 case LDAP_OPT_X_TLS:
2190 *(int *)arg = lo->ldo_tls_mode;
2191 break;
2192 case LDAP_OPT_X_TLS_CTX:
2193 *(void **)arg = lo->ldo_tls_ctx;
2194 if ( lo->ldo_tls_ctx ) {
2195 tls_ctx_ref( lo->ldo_tls_ctx );
2197 break;
2198 case LDAP_OPT_X_TLS_CACERTFILE:
2199 *(char **)arg = lo->ldo_tls_cacertfile ?
2200 LDAP_STRDUP( lo->ldo_tls_cacertfile ) : NULL;
2201 break;
2202 case LDAP_OPT_X_TLS_CACERTDIR:
2203 *(char **)arg = lo->ldo_tls_cacertdir ?
2204 LDAP_STRDUP( lo->ldo_tls_cacertdir ) : NULL;
2205 break;
2206 case LDAP_OPT_X_TLS_CERTFILE:
2207 *(char **)arg = lo->ldo_tls_certfile ?
2208 LDAP_STRDUP( lo->ldo_tls_certfile ) : NULL;
2209 break;
2210 case LDAP_OPT_X_TLS_KEYFILE:
2211 *(char **)arg = lo->ldo_tls_keyfile ?
2212 LDAP_STRDUP( lo->ldo_tls_keyfile ) : NULL;
2213 break;
2214 case LDAP_OPT_X_TLS_DHFILE:
2215 *(char **)arg = lo->ldo_tls_dhfile ?
2216 LDAP_STRDUP( lo->ldo_tls_dhfile ) : NULL;
2217 break;
2218 #ifdef HAVE_GNUTLS
2219 case LDAP_OPT_X_TLS_CRLFILE:
2220 *(char **)arg = lo->ldo_tls_crlfile ?
2221 LDAP_STRDUP( lo->ldo_tls_crlfile ) : NULL;
2222 break;
2223 #endif
2224 case LDAP_OPT_X_TLS_REQUIRE_CERT:
2225 *(int *)arg = lo->ldo_tls_require_cert;
2226 break;
2227 #ifdef HAVE_OPENSSL_CRL
2228 case LDAP_OPT_X_TLS_CRLCHECK:
2229 *(int *)arg = lo->ldo_tls_crlcheck;
2230 break;
2231 #endif
2232 case LDAP_OPT_X_TLS_CIPHER_SUITE:
2233 *(char **)arg = lo->ldo_tls_ciphersuite ?
2234 LDAP_STRDUP( lo->ldo_tls_ciphersuite ) : NULL;
2235 break;
2236 case LDAP_OPT_X_TLS_RANDOM_FILE:
2237 #ifdef HAVE_OPENSSL
2238 *(char **)arg = tls_opt_randfile ?
2239 LDAP_STRDUP( tls_opt_randfile ) : NULL;
2240 #else
2241 *(char **)arg = NULL;
2242 #endif
2243 break;
2244 case LDAP_OPT_X_TLS_SSL_CTX: {
2245 void *retval = 0;
2246 if ( ld != NULL ) {
2247 LDAPConn *conn = ld->ld_defconn;
2248 if ( conn != NULL ) {
2249 Sockbuf *sb = conn->lconn_sb;
2250 retval = ldap_pvt_tls_sb_ctx( sb );
2253 *(void **)arg = retval;
2254 break;
2256 case LDAP_OPT_X_TLS_CONNECT_CB:
2257 *(LDAP_TLS_CONNECT_CB **)arg = lo->ldo_tls_connect_cb;
2258 break;
2259 case LDAP_OPT_X_TLS_CONNECT_ARG:
2260 *(void **)arg = lo->ldo_tls_connect_arg;
2261 break;
2262 default:
2263 return -1;
2265 return 0;
2269 ldap_pvt_tls_set_option( LDAP *ld, int option, void *arg )
2271 struct ldapoptions *lo;
2273 if( ld != NULL ) {
2274 assert( LDAP_VALID( ld ) );
2276 if( !LDAP_VALID( ld ) ) {
2277 return LDAP_OPT_ERROR;
2280 lo = &ld->ld_options;
2282 } else {
2283 /* Get pointer to global option structure */
2284 lo = LDAP_INT_GLOBAL_OPT();
2285 if ( lo == NULL ) {
2286 return LDAP_NO_MEMORY;
2290 switch( option ) {
2291 case LDAP_OPT_X_TLS:
2292 if ( !arg ) return -1;
2294 switch( *(int *) arg ) {
2295 case LDAP_OPT_X_TLS_NEVER:
2296 case LDAP_OPT_X_TLS_DEMAND:
2297 case LDAP_OPT_X_TLS_ALLOW:
2298 case LDAP_OPT_X_TLS_TRY:
2299 case LDAP_OPT_X_TLS_HARD:
2300 if (lo != NULL) {
2301 lo->ldo_tls_mode = *(int *)arg;
2304 return 0;
2306 return -1;
2308 case LDAP_OPT_X_TLS_CTX:
2309 if ( lo->ldo_tls_ctx )
2310 ldap_pvt_tls_ctx_free( lo->ldo_tls_ctx );
2311 lo->ldo_tls_ctx = arg;
2312 tls_ctx_ref( lo->ldo_tls_ctx );
2313 return 0;
2314 case LDAP_OPT_X_TLS_CONNECT_CB:
2315 lo->ldo_tls_connect_cb = (LDAP_TLS_CONNECT_CB *)arg;
2316 return 0;
2317 case LDAP_OPT_X_TLS_CONNECT_ARG:
2318 lo->ldo_tls_connect_arg = arg;
2319 return 0;
2320 case LDAP_OPT_X_TLS_CACERTFILE:
2321 if ( lo->ldo_tls_cacertfile ) LDAP_FREE( lo->ldo_tls_cacertfile );
2322 lo->ldo_tls_cacertfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2323 return 0;
2324 case LDAP_OPT_X_TLS_CACERTDIR:
2325 if ( lo->ldo_tls_cacertdir ) LDAP_FREE( lo->ldo_tls_cacertdir );
2326 lo->ldo_tls_cacertdir = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2327 return 0;
2328 case LDAP_OPT_X_TLS_CERTFILE:
2329 if ( lo->ldo_tls_certfile ) LDAP_FREE( lo->ldo_tls_certfile );
2330 lo->ldo_tls_certfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2331 return 0;
2332 case LDAP_OPT_X_TLS_KEYFILE:
2333 if ( lo->ldo_tls_keyfile ) LDAP_FREE( lo->ldo_tls_keyfile );
2334 lo->ldo_tls_keyfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2335 return 0;
2336 case LDAP_OPT_X_TLS_DHFILE:
2337 if ( lo->ldo_tls_dhfile ) LDAP_FREE( lo->ldo_tls_dhfile );
2338 lo->ldo_tls_dhfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2339 return 0;
2340 #ifdef HAVE_GNUTLS
2341 case LDAP_OPT_X_TLS_CRLFILE:
2342 if ( lo->ldo_tls_crlfile ) LDAP_FREE( lo->ldo_tls_crlfile );
2343 lo->ldo_tls_crlfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2344 return 0;
2345 #endif
2346 case LDAP_OPT_X_TLS_REQUIRE_CERT:
2347 if ( !arg ) return -1;
2348 switch( *(int *) arg ) {
2349 case LDAP_OPT_X_TLS_NEVER:
2350 case LDAP_OPT_X_TLS_DEMAND:
2351 case LDAP_OPT_X_TLS_ALLOW:
2352 case LDAP_OPT_X_TLS_TRY:
2353 case LDAP_OPT_X_TLS_HARD:
2354 lo->ldo_tls_require_cert = * (int *) arg;
2355 return 0;
2357 return -1;
2358 #ifdef HAVE_OPENSSL_CRL
2359 case LDAP_OPT_X_TLS_CRLCHECK:
2360 if ( !arg ) return -1;
2361 switch( *(int *) arg ) {
2362 case LDAP_OPT_X_TLS_CRL_NONE:
2363 case LDAP_OPT_X_TLS_CRL_PEER:
2364 case LDAP_OPT_X_TLS_CRL_ALL:
2365 lo->ldo_tls_crlcheck = * (int *) arg;
2366 return 0;
2368 return -1;
2369 #endif
2370 case LDAP_OPT_X_TLS_CIPHER_SUITE:
2371 if ( lo->ldo_tls_ciphersuite ) LDAP_FREE( lo->ldo_tls_ciphersuite );
2372 lo->ldo_tls_ciphersuite = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2373 return 0;
2375 case LDAP_OPT_X_TLS_RANDOM_FILE:
2376 if ( ld != NULL )
2377 return -1;
2378 #ifdef HAVE_OPENSSL
2379 if (tls_opt_randfile ) LDAP_FREE (tls_opt_randfile );
2380 tls_opt_randfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
2381 #endif
2382 break;
2384 case LDAP_OPT_X_TLS_NEWCTX:
2385 if ( !arg ) return -1;
2386 if ( lo->ldo_tls_ctx )
2387 ldap_pvt_tls_ctx_free( lo->ldo_tls_ctx );
2388 lo->ldo_tls_ctx = NULL;
2389 return ldap_int_tls_init_ctx( lo, *(int *)arg );
2390 default:
2391 return -1;
2393 return 0;
2397 ldap_int_tls_start ( LDAP *ld, LDAPConn *conn, LDAPURLDesc *srv )
2399 Sockbuf *sb = conn->lconn_sb;
2400 char *host;
2401 void *ssl;
2403 if( srv ) {
2404 host = srv->lud_host;
2405 } else {
2406 host = conn->lconn_server->lud_host;
2409 /* avoid NULL host */
2410 if( host == NULL ) {
2411 host = "localhost";
2414 (void) ldap_pvt_tls_init();
2417 * Fortunately, the lib uses blocking io...
2419 if ( ldap_int_tls_connect( ld, conn ) < 0 ) {
2420 ld->ld_errno = LDAP_CONNECT_ERROR;
2421 return (ld->ld_errno);
2424 ssl = ldap_pvt_tls_sb_ctx( sb );
2425 assert( ssl != NULL );
2428 * compare host with name(s) in certificate
2430 if (ld->ld_options.ldo_tls_require_cert != LDAP_OPT_X_TLS_NEVER) {
2431 ld->ld_errno = ldap_pvt_tls_check_hostname( ld, ssl, host );
2432 if (ld->ld_errno != LDAP_SUCCESS) {
2433 return ld->ld_errno;
2437 return LDAP_SUCCESS;
2440 #ifdef HAVE_OPENSSL
2441 /* Derived from openssl/apps/s_cb.c */
2442 static void
2443 tls_info_cb( const SSL *ssl, int where, int ret )
2445 int w;
2446 char *op;
2447 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
2449 w = where & ~SSL_ST_MASK;
2450 if ( w & SSL_ST_CONNECT ) {
2451 op = "SSL_connect";
2452 } else if ( w & SSL_ST_ACCEPT ) {
2453 op = "SSL_accept";
2454 } else {
2455 op = "undefined";
2458 #ifdef HAVE_EBCDIC
2459 if ( state ) {
2460 state = LDAP_STRDUP( state );
2461 __etoa( state );
2463 #endif
2464 if ( where & SSL_CB_LOOP ) {
2465 Debug( LDAP_DEBUG_TRACE,
2466 "TLS trace: %s:%s\n",
2467 op, state, 0 );
2469 } else if ( where & SSL_CB_ALERT ) {
2470 char *atype = (char *) SSL_alert_type_string_long( ret );
2471 char *adesc = (char *) SSL_alert_desc_string_long( ret );
2472 op = ( where & SSL_CB_READ ) ? "read" : "write";
2473 #ifdef HAVE_EBCDIC
2474 if ( atype ) {
2475 atype = LDAP_STRDUP( atype );
2476 __etoa( atype );
2478 if ( adesc ) {
2479 adesc = LDAP_STRDUP( adesc );
2480 __etoa( adesc );
2482 #endif
2483 Debug( LDAP_DEBUG_TRACE,
2484 "TLS trace: SSL3 alert %s:%s:%s\n",
2485 op, atype, adesc );
2486 #ifdef HAVE_EBCDIC
2487 if ( atype ) LDAP_FREE( atype );
2488 if ( adesc ) LDAP_FREE( adesc );
2489 #endif
2490 } else if ( where & SSL_CB_EXIT ) {
2491 if ( ret == 0 ) {
2492 Debug( LDAP_DEBUG_TRACE,
2493 "TLS trace: %s:failed in %s\n",
2494 op, state, 0 );
2495 } else if ( ret < 0 ) {
2496 Debug( LDAP_DEBUG_TRACE,
2497 "TLS trace: %s:error in %s\n",
2498 op, state, 0 );
2501 #ifdef HAVE_EBCDIC
2502 if ( state ) LDAP_FREE( state );
2503 #endif
2506 static int
2507 tls_verify_cb( int ok, X509_STORE_CTX *ctx )
2509 X509 *cert;
2510 int errnum;
2511 int errdepth;
2512 X509_NAME *subject;
2513 X509_NAME *issuer;
2514 char *sname;
2515 char *iname;
2516 char *certerr = NULL;
2518 cert = X509_STORE_CTX_get_current_cert( ctx );
2519 errnum = X509_STORE_CTX_get_error( ctx );
2520 errdepth = X509_STORE_CTX_get_error_depth( ctx );
2523 * X509_get_*_name return pointers to the internal copies of
2524 * those things requested. So do not free them.
2526 subject = X509_get_subject_name( cert );
2527 issuer = X509_get_issuer_name( cert );
2528 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
2529 sname = X509_NAME_oneline( subject, NULL, 0 );
2530 iname = X509_NAME_oneline( issuer, NULL, 0 );
2531 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
2532 #ifdef HAVE_EBCDIC
2533 if ( sname ) __etoa( sname );
2534 if ( iname ) __etoa( iname );
2535 if ( certerr ) {
2536 certerr = LDAP_STRDUP( certerr );
2537 __etoa( certerr );
2539 #endif
2540 Debug( LDAP_DEBUG_TRACE,
2541 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
2542 errdepth, errnum,
2543 sname ? sname : "-unknown-" );
2544 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
2545 if ( !ok ) {
2546 Debug( LDAP_DEBUG_ANY,
2547 "TLS certificate verification: Error, %s\n",
2548 certerr, 0, 0 );
2550 if ( sname )
2551 CRYPTO_free ( sname );
2552 if ( iname )
2553 CRYPTO_free ( iname );
2554 #ifdef HAVE_EBCDIC
2555 if ( certerr ) LDAP_FREE( certerr );
2556 #endif
2557 return ok;
2560 static int
2561 tls_verify_ok( int ok, X509_STORE_CTX *ctx )
2563 (void) tls_verify_cb( ok, ctx );
2564 return 1;
2567 /* Inspired by ERR_print_errors in OpenSSL */
2568 static void
2569 tls_report_error( void )
2571 unsigned long l;
2572 char buf[200];
2573 const char *file;
2574 int line;
2576 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
2577 ERR_error_string_n( l, buf, sizeof( buf ) );
2578 #ifdef HAVE_EBCDIC
2579 if ( file ) {
2580 file = LDAP_STRDUP( file );
2581 __etoa( (char *)file );
2583 __etoa( buf );
2584 #endif
2585 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
2586 buf, file, line );
2587 #ifdef HAVE_EBCDIC
2588 if ( file ) LDAP_FREE( (void *)file );
2589 #endif
2593 static RSA *
2594 tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
2596 RSA *tmp_rsa;
2598 /* FIXME: Pregenerate the key on startup */
2599 /* FIXME: Who frees the key? */
2600 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
2602 if ( !tmp_rsa ) {
2603 Debug( LDAP_DEBUG_ANY,
2604 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
2605 key_length, is_export ? "export" : "domestic", 0 );
2606 return NULL;
2608 return tmp_rsa;
2611 static int
2612 tls_seed_PRNG( const char *randfile )
2614 #ifndef URANDOM_DEVICE
2615 /* no /dev/urandom (or equiv) */
2616 long total=0;
2617 char buffer[MAXPATHLEN];
2619 if (randfile == NULL) {
2620 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
2621 * If $HOME is not set or buffer too small to hold the pathname,
2622 * an error occurs. - From RAND_file_name() man page.
2623 * The fact is that when $HOME is NULL, .rnd is used.
2625 randfile = RAND_file_name( buffer, sizeof( buffer ) );
2627 } else if (RAND_egd(randfile) > 0) {
2628 /* EGD socket */
2629 return 0;
2632 if (randfile == NULL) {
2633 Debug( LDAP_DEBUG_ANY,
2634 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
2635 0, 0, 0);
2636 return -1;
2639 total = RAND_load_file(randfile, -1);
2641 if (RAND_status() == 0) {
2642 Debug( LDAP_DEBUG_ANY,
2643 "TLS: PRNG not been seeded with enough data\n",
2644 0, 0, 0);
2645 return -1;
2648 /* assume if there was enough bits to seed that it's okay
2649 * to write derived bits to the file
2651 RAND_write_file(randfile);
2653 #endif
2655 return 0;
2658 struct dhinfo {
2659 int keylength;
2660 const char *pem;
2661 size_t size;
2665 /* From the OpenSSL 0.9.7 distro */
2666 static const char dhpem512[] =
2667 "-----BEGIN DH PARAMETERS-----\n\
2668 MEYCQQDaWDwW2YUiidDkr3VvTMqS3UvlM7gE+w/tlO+cikQD7VdGUNNpmdsp13Yn\n\
2669 a6LT1BLiGPTdHghM9tgAPnxHdOgzAgEC\n\
2670 -----END DH PARAMETERS-----\n";
2672 static const char dhpem1024[] =
2673 "-----BEGIN DH PARAMETERS-----\n\
2674 MIGHAoGBAJf2QmHKtQXdKCjhPx1ottPb0PMTBH9A6FbaWMsTuKG/K3g6TG1Z1fkq\n\
2675 /Gz/PWk/eLI9TzFgqVAuPvr3q14a1aZeVUMTgo2oO5/y2UHe6VaJ+trqCTat3xlx\n\
2676 /mNbIK9HA2RgPC3gWfVLZQrY+gz3ASHHR5nXWHEyvpuZm7m3h+irAgEC\n\
2677 -----END DH PARAMETERS-----\n";
2679 static const char dhpem2048[] =
2680 "-----BEGIN DH PARAMETERS-----\n\
2681 MIIBCAKCAQEA7ZKJNYJFVcs7+6J2WmkEYb8h86tT0s0h2v94GRFS8Q7B4lW9aG9o\n\
2682 AFO5Imov5Jo0H2XMWTKKvbHbSe3fpxJmw/0hBHAY8H/W91hRGXKCeyKpNBgdL8sh\n\
2683 z22SrkO2qCnHJ6PLAMXy5fsKpFmFor2tRfCzrfnggTXu2YOzzK7q62bmqVdmufEo\n\
2684 pT8igNcLpvZxk5uBDvhakObMym9mX3rAEBoe8PwttggMYiiw7NuJKO4MqD1llGkW\n\
2685 aVM8U2ATsCun1IKHrRxynkE1/MJ86VHeYYX8GZt2YA8z+GuzylIOKcMH6JAWzMwA\n\
2686 Gbatw6QwizOhr9iMjZ0B26TE3X8LvW84wwIBAg==\n\
2687 -----END DH PARAMETERS-----\n";
2689 static const char dhpem4096[] =
2690 "-----BEGIN DH PARAMETERS-----\n\
2691 MIICCAKCAgEA/urRnb6vkPYc/KEGXWnbCIOaKitq7ySIq9dTH7s+Ri59zs77zty7\n\
2692 vfVlSe6VFTBWgYjD2XKUFmtqq6CqXMhVX5ElUDoYDpAyTH85xqNFLzFC7nKrff/H\n\
2693 TFKNttp22cZE9V0IPpzedPfnQkE7aUdmF9JnDyv21Z/818O93u1B4r0szdnmEvEF\n\
2694 bKuIxEHX+bp0ZR7RqE1AeifXGJX3d6tsd2PMAObxwwsv55RGkn50vHO4QxtTARr1\n\
2695 rRUV5j3B3oPMgC7Offxx+98Xn45B1/G0Prp11anDsR1PGwtaCYipqsvMwQUSJtyE\n\
2696 EOQWk+yFkeMe4vWv367eEi0Sd/wnC+TSXBE3pYvpYerJ8n1MceI5GQTdarJ77OW9\n\
2697 bGTHmxRsLSCM1jpLdPja5jjb4siAa6EHc4qN9c/iFKS3PQPJEnX7pXKBRs5f7AF3\n\
2698 W3RIGt+G9IVNZfXaS7Z/iCpgzgvKCs0VeqN38QsJGtC1aIkwOeyjPNy2G6jJ4yqH\n\
2699 ovXYt/0mc00vCWeSNS1wren0pR2EiLxX0ypjjgsU1mk/Z3b/+zVf7fZSIB+nDLjb\n\
2700 NPtUlJCVGnAeBK1J1nG3TQicqowOXoM6ISkdaXj5GPJdXHab2+S7cqhKGv5qC7rR\n\
2701 jT6sx7RUr0CNTxzLI7muV2/a4tGmj0PSdXQdsZ7tw7gbXlaWT1+MM2MCAQI=\n\
2702 -----END DH PARAMETERS-----\n";
2704 static const struct dhinfo dhpem[] = {
2705 { 512, dhpem512, sizeof(dhpem512) },
2706 { 1024, dhpem1024, sizeof(dhpem1024) },
2707 { 2048, dhpem2048, sizeof(dhpem2048) },
2708 { 4096, dhpem4096, sizeof(dhpem4096) },
2709 { 0, NULL, 0 }
2712 static DH *
2713 tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
2715 struct dhplist *p = NULL;
2716 BIO *b = NULL;
2717 DH *dh = NULL;
2718 int i;
2720 /* Do we have params of this length already? */
2721 #ifdef LDAP_R_COMPILE
2722 ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex );
2723 #endif
2724 for ( p = dhparams; p; p=p->next ) {
2725 if ( p->keylength == key_length ) {
2726 #ifdef LDAP_R_COMPILE
2727 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
2728 #endif
2729 return p->param;
2733 /* No - check for hardcoded params */
2735 for (i=0; dhpem[i].keylength; i++) {
2736 if ( dhpem[i].keylength == key_length ) {
2737 b = BIO_new_mem_buf( (char *)dhpem[i].pem, dhpem[i].size );
2738 break;
2742 if ( b ) {
2743 dh = PEM_read_bio_DHparams( b, NULL, NULL, NULL );
2744 BIO_free( b );
2747 /* Generating on the fly is expensive/slow... */
2748 if ( !dh ) {
2749 dh = DH_generate_parameters( key_length, DH_GENERATOR_2, NULL, NULL );
2751 if ( dh ) {
2752 p = LDAP_MALLOC( sizeof(struct dhplist) );
2753 if ( p != NULL ) {
2754 p->keylength = key_length;
2755 p->param = dh;
2756 p->next = dhparams;
2757 dhparams = p;
2761 #ifdef LDAP_R_COMPILE
2762 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
2763 #endif
2764 return dh;
2766 #endif
2768 #endif /* HAVE_OPENSSL */
2770 void *
2771 ldap_pvt_tls_sb_ctx( Sockbuf *sb )
2773 #ifdef HAVE_TLS
2774 void *p;
2776 if (HAS_TLS( sb )) {
2777 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&p );
2778 return p;
2780 #endif
2782 return NULL;
2786 ldap_pvt_tls_get_strength( void *s )
2788 #ifdef HAVE_OPENSSL
2789 const SSL_CIPHER *c;
2791 c = SSL_get_current_cipher((const SSL *)s);
2792 return SSL_CIPHER_get_bits(c, NULL);
2793 #elif defined(HAVE_GNUTLS)
2794 tls_session *session = s;
2795 gnutls_cipher_algorithm_t c;
2797 c = gnutls_cipher_get( session->session );
2798 return gnutls_cipher_get_key_size( c ) * 8;
2799 #else
2800 return 0;
2801 #endif
2806 ldap_pvt_tls_get_my_dn( void *s, struct berval *dn, LDAPDN_rewrite_dummy *func, unsigned flags )
2808 #ifdef HAVE_TLS
2809 struct berval der_dn;
2810 int rc;
2811 #ifdef HAVE_OPENSSL
2812 X509 *x;
2813 X509_NAME *xn;
2815 x = SSL_get_certificate((SSL *)s);
2817 if (!x) return LDAP_INVALID_CREDENTIALS;
2819 xn = X509_get_subject_name(x);
2820 der_dn.bv_len = i2d_X509_NAME( xn, NULL );
2821 der_dn.bv_val = xn->bytes->data;
2822 #elif defined(HAVE_GNUTLS)
2823 tls_session *session = s;
2824 const gnutls_datum_t *x;
2825 struct berval bv;
2827 x = gnutls_certificate_get_ours( session->session );
2829 if (!x) return LDAP_INVALID_CREDENTIALS;
2831 bv.bv_val = x->data;
2832 bv.bv_len = x->size;
2834 x509_cert_get_dn( &bv, &der_dn, 1 );
2835 #endif
2836 rc = ldap_X509dn2bv(&der_dn, dn, (LDAPDN_rewrite_func *)func, flags );
2837 return rc;
2838 #else /* !HAVE_TLS */
2839 return LDAP_NOT_SUPPORTED;
2840 #endif
2844 ldap_start_tls( LDAP *ld,
2845 LDAPControl **serverctrls,
2846 LDAPControl **clientctrls,
2847 int *msgidp )
2849 return ldap_extended_operation( ld, LDAP_EXOP_START_TLS,
2850 NULL, serverctrls, clientctrls, msgidp );
2854 ldap_install_tls( LDAP *ld )
2856 #ifndef HAVE_TLS
2857 return LDAP_NOT_SUPPORTED;
2858 #else
2859 if ( ldap_tls_inplace( ld ) ) {
2860 return LDAP_LOCAL_ERROR;
2863 return ldap_int_tls_start( ld, ld->ld_defconn, NULL );
2864 #endif
2868 ldap_start_tls_s ( LDAP *ld,
2869 LDAPControl **serverctrls,
2870 LDAPControl **clientctrls )
2872 #ifndef HAVE_TLS
2873 return LDAP_NOT_SUPPORTED;
2874 #else
2875 int rc;
2876 char *rspoid = NULL;
2877 struct berval *rspdata = NULL;
2879 /* XXYYZ: this initiates operation only on default connection! */
2881 if ( ldap_tls_inplace( ld ) ) {
2882 return LDAP_LOCAL_ERROR;
2885 rc = ldap_extended_operation_s( ld, LDAP_EXOP_START_TLS,
2886 NULL, serverctrls, clientctrls, &rspoid, &rspdata );
2888 if ( rspoid != NULL ) {
2889 LDAP_FREE(rspoid);
2892 if ( rspdata != NULL ) {
2893 ber_bvfree( rspdata );
2896 if ( rc == LDAP_SUCCESS ) {
2897 rc = ldap_int_tls_start( ld, ld->ld_defconn, NULL );
2900 return rc;
2901 #endif
2904 /* These tags probably all belong in lber.h, but they're
2905 * not normally encountered when processing LDAP, so maybe
2906 * they belong somewhere else instead.
2909 #define LBER_TAG_OID ((ber_tag_t) 0x06UL)
2911 /* Tags for string types used in a DirectoryString.
2913 * Note that IA5string is not one of the defined choices for
2914 * DirectoryString in X.520, but it gets used for email AVAs.
2916 #define LBER_TAG_UTF8 ((ber_tag_t) 0x0cUL)
2917 #define LBER_TAG_PRINTABLE ((ber_tag_t) 0x13UL)
2918 #define LBER_TAG_TELETEX ((ber_tag_t) 0x14UL)
2919 #define LBER_TAG_IA5 ((ber_tag_t) 0x16UL)
2920 #define LBER_TAG_UNIVERSAL ((ber_tag_t) 0x1cUL)
2921 #define LBER_TAG_BMP ((ber_tag_t) 0x1eUL)
2923 static oid_name *
2924 find_oid( struct berval *oid )
2926 int i;
2928 for ( i=0; !BER_BVISNULL( &oids[i].oid ); i++ ) {
2929 if ( oids[i].oid.bv_len != oid->bv_len ) continue;
2930 if ( !strcmp( oids[i].oid.bv_val, oid->bv_val ))
2931 return &oids[i];
2933 return NULL;
2936 /* Convert a structured DN from an X.509 certificate into an LDAPV3 DN.
2937 * x509_name must be raw DER. If func is non-NULL, the
2938 * constructed DN will use numeric OIDs to identify attributeTypes,
2939 * and the func() will be invoked to rewrite the DN with the given
2940 * flags.
2942 * Otherwise the DN will use shortNames from a hardcoded table.
2945 ldap_X509dn2bv( void *x509_name, struct berval *bv, LDAPDN_rewrite_func *func,
2946 unsigned flags )
2948 LDAPDN newDN;
2949 LDAPRDN newRDN;
2950 LDAPAVA *newAVA, *baseAVA;
2951 BerElementBuffer berbuf;
2952 BerElement *ber = (BerElement *)&berbuf;
2953 char oids[8192], *oidptr = oids, *oidbuf = NULL;
2954 void *ptrs[2048];
2955 char *dn_end, *rdn_end;
2956 int i, navas, nrdns, rc = LDAP_SUCCESS;
2957 size_t dnsize, oidrem = sizeof(oids), oidsize = 0;
2958 int csize;
2959 ber_tag_t tag;
2960 ber_len_t len;
2961 oid_name *oidname;
2963 struct berval Oid, Val, oid2, *in = x509_name;
2965 assert( bv != NULL );
2967 bv->bv_len = 0;
2968 bv->bv_val = NULL;
2970 navas = 0;
2971 nrdns = 0;
2973 /* A DN is a SEQUENCE of RDNs. An RDN is a SET of AVAs.
2974 * An AVA is a SEQUENCE of attr and value.
2975 * Count the number of AVAs and RDNs
2977 ber_init2( ber, in, LBER_USE_DER );
2978 tag = ber_peek_tag( ber, &len );
2979 if ( tag != LBER_SEQUENCE )
2980 return LDAP_DECODING_ERROR;
2982 for ( tag = ber_first_element( ber, &len, &dn_end );
2983 tag == LBER_SET;
2984 tag = ber_next_element( ber, &len, dn_end )) {
2985 nrdns++;
2986 for ( tag = ber_first_element( ber, &len, &rdn_end );
2987 tag == LBER_SEQUENCE;
2988 tag = ber_next_element( ber, &len, rdn_end )) {
2989 tag = ber_skip_tag( ber, &len );
2990 ber_skip_data( ber, len );
2991 navas++;
2995 /* Allocate the DN/RDN/AVA stuff as a single block */
2996 dnsize = sizeof(LDAPRDN) * (nrdns+1);
2997 dnsize += sizeof(LDAPAVA *) * (navas+nrdns);
2998 dnsize += sizeof(LDAPAVA) * navas;
2999 if (dnsize > sizeof(ptrs)) {
3000 newDN = (LDAPDN)LDAP_MALLOC( dnsize );
3001 if ( newDN == NULL )
3002 return LDAP_NO_MEMORY;
3003 } else {
3004 newDN = (LDAPDN)(char *)ptrs;
3007 newDN[nrdns] = NULL;
3008 newRDN = (LDAPRDN)(newDN + nrdns+1);
3009 newAVA = (LDAPAVA *)(newRDN + navas + nrdns);
3010 baseAVA = newAVA;
3012 /* Rewind and start extracting */
3013 ber_rewind( ber );
3015 tag = ber_first_element( ber, &len, &dn_end );
3016 for ( i = nrdns - 1; i >= 0; i-- ) {
3017 newDN[i] = newRDN;
3019 for ( tag = ber_first_element( ber, &len, &rdn_end );
3020 tag == LBER_SEQUENCE;
3021 tag = ber_next_element( ber, &len, rdn_end )) {
3023 *newRDN++ = newAVA;
3024 tag = ber_skip_tag( ber, &len );
3025 tag = ber_get_stringbv( ber, &Oid, LBER_BV_NOTERM );
3026 if ( tag != LBER_TAG_OID ) {
3027 rc = LDAP_DECODING_ERROR;
3028 goto nomem;
3031 oid2.bv_val = oidptr;
3032 oid2.bv_len = oidrem;
3033 if ( ber_decode_oid( &Oid, &oid2 ) < 0 ) {
3034 rc = LDAP_DECODING_ERROR;
3035 goto nomem;
3037 oidname = find_oid( &oid2 );
3038 if ( !oidname ) {
3039 newAVA->la_attr = oid2;
3040 oidptr += oid2.bv_len + 1;
3041 oidrem -= oid2.bv_len + 1;
3043 /* Running out of OID buffer space? */
3044 if (oidrem < 128) {
3045 if ( oidsize == 0 ) {
3046 oidsize = sizeof(oids) * 2;
3047 oidrem = oidsize;
3048 oidbuf = LDAP_MALLOC( oidsize );
3049 if ( oidbuf == NULL ) goto nomem;
3050 oidptr = oidbuf;
3051 } else {
3052 char *old = oidbuf;
3053 oidbuf = LDAP_REALLOC( oidbuf, oidsize*2 );
3054 if ( oidbuf == NULL ) goto nomem;
3055 /* Buffer moved! Fix AVA pointers */
3056 if ( old != oidbuf ) {
3057 LDAPAVA *a;
3058 long dif = oidbuf - old;
3060 for (a=baseAVA; a<=newAVA; a++){
3061 if (a->la_attr.bv_val >= old &&
3062 a->la_attr.bv_val <= (old + oidsize))
3063 a->la_attr.bv_val += dif;
3066 oidptr = oidbuf + oidsize - oidrem;
3067 oidrem += oidsize;
3068 oidsize *= 2;
3071 } else {
3072 if ( func ) {
3073 newAVA->la_attr = oidname->oid;
3074 } else {
3075 newAVA->la_attr = oidname->name;
3078 tag = ber_get_stringbv( ber, &Val, LBER_BV_NOTERM );
3079 switch(tag) {
3080 case LBER_TAG_UNIVERSAL:
3081 /* This uses 32-bit ISO 10646-1 */
3082 csize = 4; goto to_utf8;
3083 case LBER_TAG_BMP:
3084 /* This uses 16-bit ISO 10646-1 */
3085 csize = 2; goto to_utf8;
3086 case LBER_TAG_TELETEX:
3087 /* This uses 8-bit, assume ISO 8859-1 */
3088 csize = 1;
3089 to_utf8: rc = ldap_ucs_to_utf8s( &Val, csize, &newAVA->la_value );
3090 newAVA->la_flags |= LDAP_AVA_FREE_VALUE;
3091 if (rc != LDAP_SUCCESS) goto nomem;
3092 newAVA->la_flags = LDAP_AVA_NONPRINTABLE;
3093 break;
3094 case LBER_TAG_UTF8:
3095 newAVA->la_flags = LDAP_AVA_NONPRINTABLE;
3096 /* This is already in UTF-8 encoding */
3097 case LBER_TAG_IA5:
3098 case LBER_TAG_PRINTABLE:
3099 /* These are always 7-bit strings */
3100 newAVA->la_value = Val;
3101 default:
3104 newAVA->la_private = NULL;
3105 newAVA->la_flags = LDAP_AVA_STRING;
3106 newAVA++;
3108 *newRDN++ = NULL;
3109 tag = ber_next_element( ber, &len, dn_end );
3112 if ( func ) {
3113 rc = func( newDN, flags, NULL );
3114 if ( rc != LDAP_SUCCESS )
3115 goto nomem;
3118 rc = ldap_dn2bv_x( newDN, bv, LDAP_DN_FORMAT_LDAPV3, NULL );
3120 nomem:
3121 for (;baseAVA < newAVA; baseAVA++) {
3122 if (baseAVA->la_flags & LDAP_AVA_FREE_ATTR)
3123 LDAP_FREE( baseAVA->la_attr.bv_val );
3124 if (baseAVA->la_flags & LDAP_AVA_FREE_VALUE)
3125 LDAP_FREE( baseAVA->la_value.bv_val );
3128 if ( oidsize != 0 )
3129 LDAP_FREE( oidbuf );
3130 if ( newDN != (LDAPDN)(char *) ptrs )
3131 LDAP_FREE( newDN );
3132 return rc;