3 * Copyright 1998-2002 The OpenLDAP Foundation, All Rights Reserved.
4 * COPYING RESTRICTIONS APPLY, see COPYRIGHT file
6 * tls.c - Handle tls/ssl using SSLeay or OpenSSL.
10 #include "ldap_config.h"
14 #include <ac/stdlib.h>
16 #include <ac/socket.h>
17 #include <ac/string.h>
19 #include <ac/unistd.h>
21 #include <ac/dirent.h>
28 #include <ldap_pvt_thread.h>
31 #ifdef HAVE_OPENSSL_SSL_H
32 #include <openssl/ssl.h>
33 #include <openssl/x509v3.h>
34 #include <openssl/err.h>
35 #include <openssl/rand.h>
36 #include <openssl/safestack.h>
37 #elif defined( HAVE_SSL_H )
41 static int tls_opt_trace = 1;
42 static char *tls_opt_certfile = NULL;
43 static char *tls_opt_keyfile = NULL;
44 static char *tls_opt_cacertfile = NULL;
45 static char *tls_opt_cacertdir = NULL;
46 static int tls_opt_require_cert = LDAP_OPT_X_TLS_DEMAND;
47 static char *tls_opt_ciphersuite = NULL;
48 static char *tls_opt_randfile = NULL;
50 #define HAS_TLS( sb ) ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO, \
51 (void *)&sb_tls_sbio )
53 static void tls_report_error( void );
55 static void tls_info_cb( SSL *ssl, int where, int ret );
56 static int tls_verify_cb( int ok, X509_STORE_CTX *ctx );
57 static int tls_verify_ok( int ok, X509_STORE_CTX *ctx );
58 static RSA * tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
59 static STACK_OF(X509_NAME) * get_ca_list( char * bundle, char * dir );
61 #if 0 /* Currently this is not used by anyone */
62 static DH * tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
65 static SSL_CTX *tls_def_ctx = NULL;
67 static int tls_seed_PRNG( const char *randfile );
71 * provide mutexes for the SSLeay library.
73 static ldap_pvt_thread_mutex_t tls_mutexes[CRYPTO_NUM_LOCKS];
75 static void tls_locking_cb( int mode, int type, const char *file, int line )
77 if ( mode & CRYPTO_LOCK ) {
78 ldap_pvt_thread_mutex_lock( &tls_mutexes[type] );
80 ldap_pvt_thread_mutex_unlock( &tls_mutexes[type] );
85 * an extra mutex for the default ctx.
88 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex;
90 static void tls_init_threads( void )
94 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
95 ldap_pvt_thread_mutex_init( &tls_mutexes[i] );
97 CRYPTO_set_locking_callback( tls_locking_cb );
98 /* FIXME: the thread id should be added somehow... */
100 ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex );
102 #endif /* LDAP_R_COMPILE */
105 * Tear down the TLS subsystem. Should only be called once.
108 ldap_pvt_tls_destroy( void )
110 SSL_CTX_free(tls_def_ctx);
116 if ( tls_opt_certfile ) {
117 LDAP_FREE( tls_opt_certfile );
118 tls_opt_certfile = NULL;
120 if ( tls_opt_keyfile ) {
121 LDAP_FREE( tls_opt_keyfile );
122 tls_opt_keyfile = NULL;
124 if ( tls_opt_cacertfile ) {
125 LDAP_FREE( tls_opt_cacertfile );
126 tls_opt_cacertfile = NULL;
128 if ( tls_opt_cacertdir ) {
129 LDAP_FREE( tls_opt_cacertdir );
130 tls_opt_cacertdir = NULL;
132 if ( tls_opt_ciphersuite ) {
133 LDAP_FREE( tls_opt_ciphersuite );
134 tls_opt_ciphersuite = NULL;
136 if ( tls_opt_randfile ) {
137 LDAP_FREE( tls_opt_randfile );
138 tls_opt_randfile = NULL;
143 * Initialize TLS subsystem. Should be called only once.
146 ldap_pvt_tls_init( void )
148 static int tls_initialized = 0;
150 if ( tls_initialized ) return 0;
155 char *file = LDAP_STRDUP( tls_opt_randfile );
156 if ( file ) __atoe( file );
157 (void) tls_seed_PRNG( file );
161 (void) tls_seed_PRNG( tls_opt_randfile );
164 #ifdef LDAP_R_COMPILE
168 SSL_load_error_strings();
169 SSLeay_add_ssl_algorithms();
171 /* FIXME: mod_ssl does this */
172 X509V3_add_standard_extensions();
177 * initialize the default context
180 ldap_pvt_tls_init_def_ctx( void )
182 STACK_OF(X509_NAME) *calist;
184 char *ciphersuite = tls_opt_ciphersuite;
185 char *cacertfile = tls_opt_cacertfile;
186 char *cacertdir = tls_opt_cacertdir;
187 char *certfile = tls_opt_certfile;
188 char *keyfile = tls_opt_keyfile;
191 /* This ASCII/EBCDIC handling is a real pain! */
193 ciphersuite = LDAP_STRDUP( ciphersuite );
194 __atoe( ciphersuite );
197 cacertfile = LDAP_STRDUP( cacertfile );
198 __atoe( cacertfile );
201 cacertdir = LDAP_STRDUP( cacertdir );
205 certfile = LDAP_STRDUP( certfile );
209 keyfile = LDAP_STRDUP( keyfile );
214 #ifdef LDAP_R_COMPILE
215 ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex );
217 if ( tls_def_ctx == NULL ) {
219 tls_def_ctx = SSL_CTX_new( SSLv23_method() );
220 if ( tls_def_ctx == NULL ) {
222 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
223 "TLS could not allocate default ctx (%d).\n",
224 ERR_peek_error(), 0, 0 );
226 Debug( LDAP_DEBUG_ANY,
227 "TLS: could not allocate default ctx (%lu).\n",
228 ERR_peek_error(),0,0);
234 SSL_CTX_set_session_id_context( tls_def_ctx,
235 "OpenLDAP", sizeof("OpenLDAP")-1 );
236 if ( tls_opt_ciphersuite &&
237 !SSL_CTX_set_cipher_list( tls_def_ctx, ciphersuite ) )
240 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
241 "TLS could not set cipher list %s.\n",
242 tls_opt_ciphersuite, 0, 0 );
244 Debug( LDAP_DEBUG_ANY,
245 "TLS: could not set cipher list %s.\n",
246 tls_opt_ciphersuite, 0, 0 );
253 if (tls_opt_cacertfile != NULL || tls_opt_cacertdir != NULL) {
254 if ( !SSL_CTX_load_verify_locations( tls_def_ctx,
255 cacertfile, cacertdir ) ||
256 !SSL_CTX_set_default_verify_paths( tls_def_ctx ) )
259 LDAP_LOG ( TRANSPORT, ERR,
260 "ldap_pvt_tls_init_def_ctx: "
261 "TLS could not load verify locations "
262 "(file:`%s',dir:`%s').\n",
263 tls_opt_cacertfile ? tls_opt_cacertfile : "",
264 tls_opt_cacertdir ? tls_opt_cacertdir : "", 0 );
266 Debug( LDAP_DEBUG_ANY, "TLS: "
267 "could not load verify locations (file:`%s',dir:`%s').\n",
268 tls_opt_cacertfile ? tls_opt_cacertfile : "",
269 tls_opt_cacertdir ? tls_opt_cacertdir : "",
277 calist = get_ca_list( cacertfile, cacertdir );
280 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
281 "TLS could not load client CA list (file: `%s',dir:`%s')\n",
282 tls_opt_cacertfile ? tls_opt_cacertfile : "",
283 tls_opt_cacertdir ? tls_opt_cacertdir : "", 0 );
285 Debug( LDAP_DEBUG_ANY, "TLS: "
286 "could not load client CA list (file:`%s',dir:`%s').\n",
287 tls_opt_cacertfile ? tls_opt_cacertfile : "",
288 tls_opt_cacertdir ? tls_opt_cacertdir : "",
296 SSL_CTX_set_client_CA_list( tls_def_ctx, calist );
299 if ( tls_opt_keyfile &&
300 !SSL_CTX_use_PrivateKey_file( tls_def_ctx,
301 keyfile, SSL_FILETYPE_PEM ) )
304 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
305 "TLS could not use key file `%s'.\n", tls_opt_keyfile, 0, 0 );
307 Debug( LDAP_DEBUG_ANY,
308 "TLS: could not use key file `%s'.\n",
309 tls_opt_keyfile,0,0);
316 if ( tls_opt_certfile &&
317 !SSL_CTX_use_certificate_file( tls_def_ctx,
318 certfile, SSL_FILETYPE_PEM ) )
321 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
322 "TLS could not use certificate `%s'.\n",
323 tls_opt_certfile, 0, 0 );
325 Debug( LDAP_DEBUG_ANY,
326 "TLS: could not use certificate `%s'.\n",
327 tls_opt_certfile,0,0);
334 if ( ( tls_opt_certfile || tls_opt_keyfile ) &&
335 !SSL_CTX_check_private_key( tls_def_ctx ) )
338 LDAP_LOG ( TRANSPORT, ERR,
339 "ldap_pvt_tls_init_def_ctx: TLS private key mismatch.\n",
342 Debug( LDAP_DEBUG_ANY,
343 "TLS: private key mismatch.\n",
351 if ( tls_opt_trace ) {
352 SSL_CTX_set_info_callback( tls_def_ctx, tls_info_cb );
356 if ( tls_opt_require_cert ) {
358 if ( tls_opt_require_cert == LDAP_OPT_X_TLS_DEMAND ||
359 tls_opt_require_cert == LDAP_OPT_X_TLS_HARD ) {
360 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
364 SSL_CTX_set_verify( tls_def_ctx, i,
365 tls_opt_require_cert == LDAP_OPT_X_TLS_ALLOW ?
366 tls_verify_ok : tls_verify_cb );
367 SSL_CTX_set_tmp_rsa_callback( tls_def_ctx, tls_tmp_rsa_cb );
368 /* SSL_CTX_set_tmp_dh_callback( tls_def_ctx, tls_tmp_dh_cb ); */
371 if ( rc == -1 && tls_def_ctx != NULL ) {
372 SSL_CTX_free( tls_def_ctx );
376 LDAP_FREE( ciphersuite );
377 LDAP_FREE( cacertfile );
378 LDAP_FREE( cacertdir );
379 LDAP_FREE( certfile );
380 LDAP_FREE( keyfile );
382 #ifdef LDAP_R_COMPILE
383 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
388 static STACK_OF(X509_NAME) *
389 get_ca_list( char * bundle, char * dir )
391 STACK_OF(X509_NAME) *ca_list = NULL;
394 ca_list = SSL_load_client_CA_file( bundle );
396 #if defined(HAVE_DIRENT_H) || defined(dirent)
401 ca_list = sk_X509_NAME_new_null();
404 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
406 sk_X509_NAME_free( ca_list );
416 alloc_handle( void *ctx_arg )
422 ctx = (SSL_CTX *) ctx_arg;
424 if ( ldap_pvt_tls_init_def_ctx() < 0 ) return NULL;
428 ssl = SSL_new( ctx );
431 LDAP_LOG ( TRANSPORT, ERR,
432 "alloc_handle: TLS can't create ssl handle.\n", 0, 0, 0 );
434 Debug( LDAP_DEBUG_ANY,"TLS: can't create ssl handle.\n",0,0,0);
442 update_flags( Sockbuf *sb, SSL * ssl, int rc )
444 int err = SSL_get_error(ssl, rc);
446 sb->sb_trans_needs_read = 0;
447 sb->sb_trans_needs_write = 0;
449 if (err == SSL_ERROR_WANT_READ) {
450 sb->sb_trans_needs_read = 1;
453 } else if (err == SSL_ERROR_WANT_WRITE) {
454 sb->sb_trans_needs_write = 1;
457 } else if (err == SSL_ERROR_WANT_CONNECT) {
464 * TLS support for LBER Sockbufs
469 Sockbuf_IO_Desc *sbiod;
472 static BIO_METHOD sb_tls_bio_method;
475 sb_tls_setup( Sockbuf_IO_Desc *sbiod, void *arg )
480 assert( sbiod != NULL );
482 p = LBER_MALLOC( sizeof( *p ) );
489 bio = BIO_new( &sb_tls_bio_method );
490 bio->ptr = (void *)p;
491 SSL_set_bio( p->ssl, bio, bio );
492 sbiod->sbiod_pvt = p;
497 sb_tls_remove( Sockbuf_IO_Desc *sbiod )
501 assert( sbiod != NULL );
502 assert( sbiod->sbiod_pvt != NULL );
504 p = (struct tls_data *)sbiod->sbiod_pvt;
506 LBER_FREE( sbiod->sbiod_pvt );
507 sbiod->sbiod_pvt = NULL;
512 sb_tls_close( Sockbuf_IO_Desc *sbiod )
516 assert( sbiod != NULL );
517 assert( sbiod->sbiod_pvt != NULL );
519 p = (struct tls_data *)sbiod->sbiod_pvt;
520 SSL_shutdown( p->ssl );
525 sb_tls_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
529 assert( sbiod != NULL );
530 assert( sbiod->sbiod_pvt != NULL );
532 p = (struct tls_data *)sbiod->sbiod_pvt;
534 if ( opt == LBER_SB_OPT_GET_SSL ) {
535 *((SSL **)arg) = p->ssl;
538 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
539 if( SSL_pending( p->ssl ) > 0 ) {
544 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
548 sb_tls_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
554 assert( sbiod != NULL );
555 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
557 p = (struct tls_data *)sbiod->sbiod_pvt;
559 ret = SSL_read( p->ssl, (char *)buf, len );
561 errno = WSAGetLastError();
563 err = SSL_get_error( p->ssl, ret );
564 if (err == SSL_ERROR_WANT_READ ) {
565 sbiod->sbiod_sb->sb_trans_needs_read = 1;
569 sbiod->sbiod_sb->sb_trans_needs_read = 0;
574 sb_tls_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
580 assert( sbiod != NULL );
581 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
583 p = (struct tls_data *)sbiod->sbiod_pvt;
585 ret = SSL_write( p->ssl, (char *)buf, len );
587 errno = WSAGetLastError();
589 err = SSL_get_error( p->ssl, ret );
590 if (err == SSL_ERROR_WANT_WRITE ) {
591 sbiod->sbiod_sb->sb_trans_needs_write = 1;
595 sbiod->sbiod_sb->sb_trans_needs_write = 0;
600 static Sockbuf_IO sb_tls_sbio =
602 sb_tls_setup, /* sbi_setup */
603 sb_tls_remove, /* sbi_remove */
604 sb_tls_ctrl, /* sbi_ctrl */
605 sb_tls_read, /* sbi_read */
606 sb_tls_write, /* sbi_write */
607 sb_tls_close /* sbi_close */
611 sb_tls_bio_create( BIO *b ) {
620 sb_tls_bio_destroy( BIO *b )
622 if ( b == NULL ) return 0;
624 b->ptr = NULL; /* sb_tls_remove() will free it */
631 sb_tls_bio_read( BIO *b, char *buf, int len )
636 if ( buf == NULL || len <= 0 ) return 0;
638 p = (struct tls_data *)b->ptr;
640 if ( p == NULL || p->sbiod == NULL ) {
644 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
646 BIO_clear_retry_flags( b );
647 if ( ret < 0 && errno == EWOULDBLOCK ) {
648 BIO_set_retry_read( b );
655 sb_tls_bio_write( BIO *b, const char *buf, int len )
660 if ( buf == NULL || len <= 0 ) return 0;
662 p = (struct tls_data *)b->ptr;
664 if ( p == NULL || p->sbiod == NULL ) {
668 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
670 BIO_clear_retry_flags( b );
671 if ( ret < 0 && errno == EWOULDBLOCK ) {
672 BIO_set_retry_write( b );
679 sb_tls_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
681 if ( cmd == BIO_CTRL_FLUSH ) {
682 /* The OpenSSL library needs this */
689 sb_tls_bio_gets( BIO *b, char *buf, int len )
695 sb_tls_bio_puts( BIO *b, const char *str )
697 return sb_tls_bio_write( b, str, strlen( str ) );
700 static BIO_METHOD sb_tls_bio_method =
702 ( 100 | 0x400 ), /* it's a source/sink BIO */
714 * Call this to do a TLS connect on a sockbuf. ctx_arg can be
715 * a SSL_CTX * or NULL, in which case the default ctx is used.
719 * 0 - Success. Connection is ready for communication.
720 * <0 - Error. Can't create a TLS stream.
721 * >0 - Partial success.
722 * Do a select (using information from lber_pvt_sb_needs_{read,write}
727 ldap_int_tls_connect( LDAP *ld, LDAPConn *conn )
729 Sockbuf *sb = conn->lconn_sb;
733 if ( HAS_TLS( sb ) ) {
734 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
737 void *ctx = ld->ld_defconn
738 ? ld->ld_defconn->lconn_tls_ctx : NULL;
740 ssl = alloc_handle( ctx );
742 if ( ssl == NULL ) return -1;
745 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
746 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
748 ber_sockbuf_add_io( sb, &sb_tls_sbio,
749 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
752 conn->lconn_tls_ctx = tls_def_ctx;
756 err = SSL_connect( ssl );
759 errno = WSAGetLastError();
763 if ( update_flags( sb, ssl, err )) {
767 if ((err = ERR_peek_error())) {
769 ld->ld_error = LDAP_STRDUP(ERR_error_string(err, buf));
771 if ( ld->ld_error ) __etoa(ld->ld_error);
776 LDAP_LOG ( TRANSPORT, ERR,
777 "ldap_int_tls_connect: TLS can't connect.\n", 0, 0, 0 );
779 Debug( LDAP_DEBUG_ANY,"TLS: can't connect.\n",0,0,0);
782 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
783 LBER_SBIOD_LEVEL_TRANSPORT );
785 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
786 LBER_SBIOD_LEVEL_TRANSPORT );
795 * Call this to do a TLS accept on a sockbuf.
796 * Everything else is the same as with tls_connect.
799 ldap_pvt_tls_accept( Sockbuf *sb, void *ctx_arg )
804 if ( HAS_TLS( sb ) ) {
805 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
808 ssl = alloc_handle( ctx_arg );
809 if ( ssl == NULL ) return -1;
812 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
813 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
815 ber_sockbuf_add_io( sb, &sb_tls_sbio,
816 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
819 err = SSL_accept( ssl );
822 errno = WSAGetLastError();
825 if ( update_flags( sb, ssl, err )) return 1;
828 LDAP_LOG ( TRANSPORT, ERR,
829 "ldap_pvt_tls_accept: TLS can't accept.\n", 0, 0, 0 );
831 Debug( LDAP_DEBUG_ANY,"TLS: can't accept.\n",0,0,0 );
835 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
836 LBER_SBIOD_LEVEL_TRANSPORT );
838 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
839 LBER_SBIOD_LEVEL_TRANSPORT );
848 ldap_pvt_tls_inplace ( Sockbuf *sb )
850 return HAS_TLS( sb ) ? 1 : 0;
854 ldap_pvt_tls_sb_ctx( Sockbuf *sb )
859 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&p );
867 ldap_pvt_tls_get_strength( void *s )
871 c = SSL_get_current_cipher((SSL *)s);
872 return SSL_CIPHER_get_bits(c, NULL);
877 ldap_pvt_tls_get_my_dn( void *s, struct berval *dn, LDAPDN_rewrite_dummy *func, unsigned flags )
883 x = SSL_get_certificate((SSL *)s);
885 if (!x) return LDAP_INVALID_CREDENTIALS;
887 xn = X509_get_subject_name(x);
888 rc = ldap_X509dn2bv(xn, dn, (LDAPDN_rewrite_func *)func, flags );
893 tls_get_cert( SSL *s )
895 /* If peer cert was bad, treat as if no cert was given */
896 if (SSL_get_verify_result(s)) {
897 /* If we can send an alert, do so */
898 if (SSL_version(s) != SSL2_VERSION) {
899 ssl3_send_alert(s,SSL3_AL_WARNING,SSL3_AD_BAD_CERTIFICATE);
903 return SSL_get_peer_certificate(s);
907 ldap_pvt_tls_get_peer_dn( void *s, struct berval *dn, LDAPDN_rewrite_dummy *func, unsigned flags )
913 x = tls_get_cert((SSL *)s);
915 if (!x) return LDAP_INVALID_CREDENTIALS;
917 xn = X509_get_subject_name(x);
918 rc = ldap_X509dn2bv(xn, dn, (LDAPDN_rewrite_func *)func, flags);
923 ldap_pvt_tls_get_peer_hostname( void *s )
930 x = tls_get_cert((SSL *)s);
933 xn = X509_get_subject_name(x);
935 ret = X509_NAME_get_text_by_NID(xn, NID_commonName, buf, sizeof(buf));
940 p = LDAP_STRDUP(buf);
945 ldap_pvt_tls_check_hostname( LDAP *ld, void *s, const char *name_in )
947 int i, ret = LDAP_LOCAL_ERROR;
951 if( ldap_int_hostname &&
952 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
954 name = ldap_int_hostname;
959 x = tls_get_cert((SSL *)s);
962 LDAP_LOG ( TRANSPORT, ERR,
963 "ldap_pvt_tls_check_hostname: "
964 "TLS unable to get peer certificate.\n" , 0, 0, 0 );
966 Debug( LDAP_DEBUG_ANY,
967 "TLS: unable to get peer certificate.\n",
970 /* If this was a fatal condition, things would have
971 * aborted long before now.
976 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
979 STACK_OF(GENERAL_NAME) *alt;
981 ex = X509_get_ext(x, i);
982 alt = X509V3_EXT_d2i(ex);
984 int n, len1, len2 = 0;
989 n = sk_GENERAL_NAME_num(alt);
990 domain = strchr(name, '.');
992 len2 = len1 - (domain-name);
994 for (i=0; i<n; i++) {
995 gn = sk_GENERAL_NAME_value(alt, i);
996 if (gn->type == GEN_DNS) {
997 char *sn = ASN1_STRING_data(gn->d.ia5);
998 int sl = ASN1_STRING_length(gn->d.ia5);
1000 /* Is this an exact match? */
1001 if ((len1 == sl) && !strncasecmp(name, sn, len1)) {
1005 /* Is this a wildcard match? */
1006 if ((*sn == '*') && domain && (len2 == sl-1) &&
1007 !strncasecmp(domain, sn+1, len2))
1013 /* Is this a RFC 2549 style wildcard match? */
1014 if ((*sn == '.') && domain && (len2 == sl) &&
1015 !strncasecmp(domain, sn, len2))
1023 GENERAL_NAMES_free(alt);
1024 if (i < n) { /* Found a match */
1030 if (ret != LDAP_SUCCESS) {
1034 xn = X509_get_subject_name(x);
1036 if( X509_NAME_get_text_by_NID( xn, NID_commonName,
1037 buf, sizeof(buf)) == -1)
1040 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_check_hostname: "
1041 "TLS unable to get common name from peer certificate.\n",
1044 Debug( LDAP_DEBUG_ANY,
1045 "TLS: unable to get common name from peer certificate.\n",
1048 ld->ld_error = LDAP_STRDUP("TLS: unable to get CN from peer certificate");
1050 } else if (strcasecmp(name, buf)) {
1052 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_check_hostname: "
1053 "TLS hostname (%s) does not match "
1054 "common name in certificate (%s).\n", name, buf, 0 );
1056 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
1057 "common name in certificate (%s).\n",
1060 ret = LDAP_CONNECT_ERROR;
1061 ld->ld_error = LDAP_STRDUP("TLS: hostname does not match CN in peer certificate");
1071 ldap_pvt_tls_get_peer_issuer( void *s )
1073 #if 0 /* currently unused; see ldap_pvt_tls_get_peer_dn() if needed */
1078 x = SSL_get_peer_certificate((SSL *)s);
1080 if (!x) return NULL;
1082 xn = X509_get_issuer_name(x);
1083 p = LDAP_STRDUP(X509_NAME_oneline(xn, buf, sizeof(buf)));
1091 ldap_int_tls_config( LDAP *ld, int option, const char *arg )
1096 case LDAP_OPT_X_TLS_CACERTFILE:
1097 case LDAP_OPT_X_TLS_CACERTDIR:
1098 case LDAP_OPT_X_TLS_CERTFILE:
1099 case LDAP_OPT_X_TLS_KEYFILE:
1100 case LDAP_OPT_X_TLS_RANDOM_FILE:
1101 return ldap_pvt_tls_set_option( ld, option, (void *) arg );
1103 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1104 case LDAP_OPT_X_TLS:
1106 if ( strcasecmp( arg, "never" ) == 0 ) {
1107 i = LDAP_OPT_X_TLS_NEVER ;
1109 } else if ( strcasecmp( arg, "demand" ) == 0 ) {
1110 i = LDAP_OPT_X_TLS_DEMAND ;
1112 } else if ( strcasecmp( arg, "allow" ) == 0 ) {
1113 i = LDAP_OPT_X_TLS_ALLOW ;
1115 } else if ( strcasecmp( arg, "try" ) == 0 ) {
1116 i = LDAP_OPT_X_TLS_TRY ;
1118 } else if ( ( strcasecmp( arg, "hard" ) == 0 ) ||
1119 ( strcasecmp( arg, "on" ) == 0 ) ||
1120 ( strcasecmp( arg, "yes" ) == 0) ||
1121 ( strcasecmp( arg, "true" ) == 0 ) )
1123 i = LDAP_OPT_X_TLS_HARD ;
1127 return ldap_pvt_tls_set_option( ld, option, &i );
1136 ldap_pvt_tls_get_option( LDAP *ld, int option, void *arg )
1138 struct ldapoptions *lo;
1141 assert( LDAP_VALID( ld ) );
1143 if( !LDAP_VALID( ld ) ) {
1144 return LDAP_OPT_ERROR;
1147 lo = &ld->ld_options;
1150 /* Get pointer to global option structure */
1151 lo = LDAP_INT_GLOBAL_OPT();
1153 return LDAP_NO_MEMORY;
1158 case LDAP_OPT_X_TLS:
1159 *(int *)arg = lo->ldo_tls_mode;
1161 case LDAP_OPT_X_TLS_CTX:
1163 *(void **)arg = (void *) tls_def_ctx;
1165 *(void **)arg = ld->ld_defconn->lconn_tls_ctx;
1168 case LDAP_OPT_X_TLS_CACERTFILE:
1169 *(char **)arg = tls_opt_cacertfile ?
1170 LDAP_STRDUP( tls_opt_cacertfile ) : NULL;
1172 case LDAP_OPT_X_TLS_CACERTDIR:
1173 *(char **)arg = tls_opt_cacertdir ?
1174 LDAP_STRDUP( tls_opt_cacertdir ) : NULL;
1176 case LDAP_OPT_X_TLS_CERTFILE:
1177 *(char **)arg = tls_opt_certfile ?
1178 LDAP_STRDUP( tls_opt_certfile ) : NULL;
1180 case LDAP_OPT_X_TLS_KEYFILE:
1181 *(char **)arg = tls_opt_keyfile ?
1182 LDAP_STRDUP( tls_opt_keyfile ) : NULL;
1184 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1185 *(int *)arg = tls_opt_require_cert;
1187 case LDAP_OPT_X_TLS_RANDOM_FILE:
1188 *(char **)arg = tls_opt_randfile ?
1189 LDAP_STRDUP( tls_opt_randfile ) : NULL;
1191 case LDAP_OPT_X_TLS_SSL_CTX: {
1194 LDAPConn *conn = ld->ld_defconn;
1195 if ( conn != NULL ) {
1196 Sockbuf *sb = conn->lconn_sb;
1197 retval = ldap_pvt_tls_sb_ctx( sb );
1200 *(void **)arg = retval;
1210 ldap_pvt_tls_set_option( LDAP *ld, int option, void *arg )
1212 struct ldapoptions *lo;
1215 assert( LDAP_VALID( ld ) );
1217 if( !LDAP_VALID( ld ) ) {
1218 return LDAP_OPT_ERROR;
1221 lo = &ld->ld_options;
1224 /* Get pointer to global option structure */
1225 lo = LDAP_INT_GLOBAL_OPT();
1227 return LDAP_NO_MEMORY;
1232 case LDAP_OPT_X_TLS:
1233 switch( *(int *) arg ) {
1234 case LDAP_OPT_X_TLS_NEVER:
1235 case LDAP_OPT_X_TLS_DEMAND:
1236 case LDAP_OPT_X_TLS_ALLOW:
1237 case LDAP_OPT_X_TLS_TRY:
1238 case LDAP_OPT_X_TLS_HARD:
1240 lo->ldo_tls_mode = *(int *)arg;
1247 case LDAP_OPT_X_TLS_CTX:
1249 tls_def_ctx = (SSL_CTX *) arg;
1252 ld->ld_defconn->lconn_tls_ctx = arg;
1262 case LDAP_OPT_X_TLS_CACERTFILE:
1263 if ( tls_opt_cacertfile ) LDAP_FREE( tls_opt_cacertfile );
1264 tls_opt_cacertfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1266 case LDAP_OPT_X_TLS_CACERTDIR:
1267 if ( tls_opt_cacertdir ) LDAP_FREE( tls_opt_cacertdir );
1268 tls_opt_cacertdir = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1270 case LDAP_OPT_X_TLS_CERTFILE:
1271 if ( tls_opt_certfile ) LDAP_FREE( tls_opt_certfile );
1272 tls_opt_certfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1274 case LDAP_OPT_X_TLS_KEYFILE:
1275 if ( tls_opt_keyfile ) LDAP_FREE( tls_opt_keyfile );
1276 tls_opt_keyfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1278 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1279 switch( *(int *) arg ) {
1280 case LDAP_OPT_X_TLS_NEVER:
1281 case LDAP_OPT_X_TLS_DEMAND:
1282 case LDAP_OPT_X_TLS_ALLOW:
1283 case LDAP_OPT_X_TLS_TRY:
1284 case LDAP_OPT_X_TLS_HARD:
1285 tls_opt_require_cert = * (int *) arg;
1289 case LDAP_OPT_X_TLS_CIPHER_SUITE:
1290 if ( tls_opt_ciphersuite ) LDAP_FREE( tls_opt_ciphersuite );
1291 tls_opt_ciphersuite = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1293 case LDAP_OPT_X_TLS_RANDOM_FILE:
1294 if (tls_opt_randfile ) LDAP_FREE (tls_opt_randfile );
1295 tls_opt_randfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1304 ldap_int_tls_start ( LDAP *ld, LDAPConn *conn, LDAPURLDesc *srv )
1306 Sockbuf *sb = conn->lconn_sb;
1311 host = srv->lud_host;
1313 host = conn->lconn_server->lud_host;
1316 /* avoid NULL host */
1317 if( host == NULL ) {
1321 (void) ldap_pvt_tls_init();
1324 * Fortunately, the lib uses blocking io...
1326 if ( ldap_int_tls_connect( ld, conn ) < 0 ) {
1327 ld->ld_errno = LDAP_CONNECT_ERROR;
1328 return (ld->ld_errno);
1331 ssl = ldap_pvt_tls_sb_ctx( sb );
1332 assert( ssl != NULL );
1335 * compare host with name(s) in certificate
1337 ld->ld_errno = ldap_pvt_tls_check_hostname( ld, ssl, host );
1338 if (ld->ld_errno != LDAP_SUCCESS) {
1339 return ld->ld_errno;
1343 * set SASL properties to TLS ssf and authid
1346 struct berval authid = { 0, NULL };
1349 /* we need to let SASL know */
1350 ssf = ldap_pvt_tls_get_strength( ssl );
1351 /* failure is OK, we just can't use SASL EXTERNAL */
1352 (void) ldap_pvt_tls_get_my_dn( ssl, &authid, NULL, 0 );
1354 (void) ldap_int_sasl_external( ld, conn, authid.bv_val, ssf );
1355 LDAP_FREE( authid.bv_val );
1358 return LDAP_SUCCESS;
1361 /* Derived from openssl/apps/s_cb.c */
1363 tls_info_cb( SSL *ssl, int where, int ret )
1367 char *state = SSL_state_string_long( ssl );
1369 w = where & ~SSL_ST_MASK;
1370 if ( w & SSL_ST_CONNECT ) {
1372 } else if ( w & SSL_ST_ACCEPT ) {
1380 state = LDAP_STRDUP( state );
1384 if ( where & SSL_CB_LOOP ) {
1386 LDAP_LOG ( TRANSPORT, DETAIL1, "tls_info_cb: "
1387 "TLS trace: %s:%s\n", op, state, 0 );
1389 Debug( LDAP_DEBUG_TRACE,
1390 "TLS trace: %s:%s\n",
1394 } else if ( where & SSL_CB_ALERT ) {
1395 char *atype = SSL_alert_type_string_long( ret );
1396 char *adesc = SSL_alert_desc_string_long( ret );
1397 op = ( where & SSL_CB_READ ) ? "read" : "write";
1400 atype = LDAP_STRDUP( atype );
1404 adesc = LDAP_STRDUP( adesc );
1409 LDAP_LOG ( TRANSPORT, DETAIL1,
1410 "tls_info_cb: TLS trace: SSL3 alert %s:%s:%s\n",
1413 Debug( LDAP_DEBUG_TRACE,
1414 "TLS trace: SSL3 alert %s:%s:%s\n",
1418 if ( atype ) LDAP_FREE( atype );
1419 if ( adesc ) LDAP_FREE( adesc );
1421 } else if ( where & SSL_CB_EXIT ) {
1424 LDAP_LOG ( TRANSPORT, ERR,
1425 "tls_info_cb: TLS trace: %s:failed in %s\n",
1428 Debug( LDAP_DEBUG_TRACE,
1429 "TLS trace: %s:failed in %s\n",
1432 } else if ( ret < 0 ) {
1434 LDAP_LOG ( TRANSPORT, ERR,
1435 "tls_info_cb: TLS trace: %s:error in %s\n",
1438 Debug( LDAP_DEBUG_TRACE,
1439 "TLS trace: %s:error in %s\n",
1445 if ( state ) LDAP_FREE( state );
1450 tls_verify_cb( int ok, X509_STORE_CTX *ctx )
1459 char *certerr = NULL;
1461 cert = X509_STORE_CTX_get_current_cert( ctx );
1462 errnum = X509_STORE_CTX_get_error( ctx );
1463 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1466 * X509_get_*_name return pointers to the internal copies of
1467 * those things requested. So do not free them.
1469 subject = X509_get_subject_name( cert );
1470 issuer = X509_get_issuer_name( cert );
1471 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1472 sname = X509_NAME_oneline( subject, NULL, 0 );
1473 iname = X509_NAME_oneline( issuer, NULL, 0 );
1474 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1476 if ( sname ) __etoa( sname );
1477 if ( iname ) __etoa( iname );
1479 certerr = LDAP_STRDUP( certerr );
1484 LDAP_LOG( TRANSPORT, ERR,
1485 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1487 sname ? sname : "-unknown-" );
1488 LDAP_LOG( TRANSPORT, ERR, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1490 LDAP_LOG ( TRANSPORT, ERR,
1491 "TLS certificate verification: Error, %s\n",
1495 Debug( LDAP_DEBUG_TRACE,
1496 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1498 sname ? sname : "-unknown-" );
1499 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1501 Debug( LDAP_DEBUG_ANY,
1502 "TLS certificate verification: Error, %s\n",
1507 CRYPTO_free ( sname );
1509 CRYPTO_free ( iname );
1511 if ( certerr ) LDAP_FREE( certerr );
1517 tls_verify_ok( int ok, X509_STORE_CTX *ctx )
1519 (void) tls_verify_cb( ok, ctx );
1523 /* Inspired by ERR_print_errors in OpenSSL */
1525 tls_report_error( void )
1532 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1533 ERR_error_string_n( l, buf, sizeof( buf ) );
1536 file = LDAP_STRDUP( file );
1537 __etoa( (char *)file );
1542 LDAP_LOG ( TRANSPORT, ERR,
1543 "tls_report_error: TLS %s %s:%d\n",
1546 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1550 if ( file ) LDAP_FREE( (void *)file );
1556 tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1560 /* FIXME: Pregenerate the key on startup */
1561 /* FIXME: Who frees the key? */
1562 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1566 LDAP_LOG ( TRANSPORT, ERR,
1567 "tls_tmp_rsa_cb: TLS Failed to generate temporary %d-bit %s "
1568 "RSA key\n", key_length, is_export ? "export" : "domestic", 0 );
1570 Debug( LDAP_DEBUG_ANY,
1571 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1572 key_length, is_export ? "export" : "domestic", 0 );
1580 tls_seed_PRNG( const char *randfile )
1582 #ifndef URANDOM_DEVICE
1583 /* no /dev/urandom (or equiv) */
1585 char buffer[MAXPATHLEN];
1587 if (randfile == NULL) {
1588 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1589 * If $HOME is not set or buffer too small to hold the pathname,
1590 * an error occurs. - From RAND_file_name() man page.
1591 * The fact is that when $HOME is NULL, .rnd is used.
1593 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1595 } else if (RAND_egd(randfile) > 0) {
1600 if (randfile == NULL) {
1602 LDAP_LOG ( TRANSPORT, DETAIL1,
1603 "tls_seed_PRNG: TLS Use configuration file or "
1604 "$RANDFILE to define seed PRNG\n", 0, 0, 0 );
1606 Debug( LDAP_DEBUG_ANY,
1607 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1613 total = RAND_load_file(randfile, -1);
1615 if (RAND_status() == 0) {
1617 LDAP_LOG ( TRANSPORT, DETAIL1,
1618 "tls_seed_PRNG: TLS PRNG not been seeded with enough data\n",
1621 Debug( LDAP_DEBUG_ANY,
1622 "TLS: PRNG not been seeded with enough data\n",
1628 /* assume if there was enough bits to seed that it's okay
1629 * to write derived bits to the file
1631 RAND_write_file(randfile);
1640 tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1648 ldap_start_tls_s ( LDAP *ld,
1649 LDAPControl **serverctrls,
1650 LDAPControl **clientctrls )
1655 char *rspoid = NULL;
1656 struct berval *rspdata = NULL;
1658 /* XXYYZ: this initiates operation only on default connection! */
1660 if ( ld->ld_sb != NULL && ldap_pvt_tls_inplace( ld->ld_sb ) != 0 ) {
1661 return LDAP_LOCAL_ERROR;
1664 rc = ldap_extended_operation_s( ld, LDAP_EXOP_START_TLS,
1665 NULL, serverctrls, clientctrls, &rspoid, &rspdata );
1666 if ( rc != LDAP_SUCCESS ) {
1670 if ( rspoid != NULL ) {
1674 if ( rspdata != NULL ) {
1675 ber_bvfree( rspdata );
1678 rc = ldap_int_tls_start( ld, ld->ld_defconn, NULL );
1680 rc = LDAP_NOT_SUPPORTED;