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 if ( tls_opt_ciphersuite &&
235 !SSL_CTX_set_cipher_list( tls_def_ctx, ciphersuite ) )
238 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
239 "TLS could not set cipher list %s.\n",
240 tls_opt_ciphersuite, 0, 0 );
242 Debug( LDAP_DEBUG_ANY,
243 "TLS: could not set cipher list %s.\n",
244 tls_opt_ciphersuite, 0, 0 );
251 if (tls_opt_cacertfile != NULL || tls_opt_cacertdir != NULL) {
252 if ( !SSL_CTX_load_verify_locations( tls_def_ctx,
253 cacertfile, cacertdir ) ||
254 !SSL_CTX_set_default_verify_paths( tls_def_ctx ) )
257 LDAP_LOG ( TRANSPORT, ERR,
258 "ldap_pvt_tls_init_def_ctx: "
259 "TLS could not load verify locations "
260 "(file:`%s',dir:`%s').\n",
261 tls_opt_cacertfile ? tls_opt_cacertfile : "",
262 tls_opt_cacertdir ? tls_opt_cacertdir : "", 0 );
264 Debug( LDAP_DEBUG_ANY, "TLS: "
265 "could not load verify locations (file:`%s',dir:`%s').\n",
266 tls_opt_cacertfile ? tls_opt_cacertfile : "",
267 tls_opt_cacertdir ? tls_opt_cacertdir : "",
275 calist = get_ca_list( cacertfile, cacertdir );
278 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
279 "TLS could not load client CA list (file: `%s',dir:`%s')\n",
280 tls_opt_cacertfile ? tls_opt_cacertfile : "",
281 tls_opt_cacertdir ? tls_opt_cacertdir : "", 0 );
283 Debug( LDAP_DEBUG_ANY, "TLS: "
284 "could not load client CA list (file:`%s',dir:`%s').\n",
285 tls_opt_cacertfile ? tls_opt_cacertfile : "",
286 tls_opt_cacertdir ? tls_opt_cacertdir : "",
294 SSL_CTX_set_client_CA_list( tls_def_ctx, calist );
297 if ( tls_opt_keyfile &&
298 !SSL_CTX_use_PrivateKey_file( tls_def_ctx,
299 keyfile, SSL_FILETYPE_PEM ) )
302 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
303 "TLS could not use key file `%s'.\n", tls_opt_keyfile, 0, 0 );
305 Debug( LDAP_DEBUG_ANY,
306 "TLS: could not use key file `%s'.\n",
307 tls_opt_keyfile,0,0);
314 if ( tls_opt_certfile &&
315 !SSL_CTX_use_certificate_file( tls_def_ctx,
316 certfile, SSL_FILETYPE_PEM ) )
319 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_init_def_ctx: "
320 "TLS could not use certificate `%s'.\n",
321 tls_opt_certfile, 0, 0 );
323 Debug( LDAP_DEBUG_ANY,
324 "TLS: could not use certificate `%s'.\n",
325 tls_opt_certfile,0,0);
332 if ( ( tls_opt_certfile || tls_opt_keyfile ) &&
333 !SSL_CTX_check_private_key( tls_def_ctx ) )
336 LDAP_LOG ( TRANSPORT, ERR,
337 "ldap_pvt_tls_init_def_ctx: TLS private key mismatch.\n",
340 Debug( LDAP_DEBUG_ANY,
341 "TLS: private key mismatch.\n",
349 if ( tls_opt_trace ) {
350 SSL_CTX_set_info_callback( tls_def_ctx, tls_info_cb );
354 if ( tls_opt_require_cert ) {
356 if ( tls_opt_require_cert == LDAP_OPT_X_TLS_DEMAND ||
357 tls_opt_require_cert == LDAP_OPT_X_TLS_HARD ) {
358 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
362 SSL_CTX_set_verify( tls_def_ctx, i,
363 tls_opt_require_cert == LDAP_OPT_X_TLS_ALLOW ?
364 tls_verify_ok : tls_verify_cb );
365 SSL_CTX_set_tmp_rsa_callback( tls_def_ctx, tls_tmp_rsa_cb );
366 /* SSL_CTX_set_tmp_dh_callback( tls_def_ctx, tls_tmp_dh_cb ); */
369 if ( rc == -1 && tls_def_ctx != NULL ) {
370 SSL_CTX_free( tls_def_ctx );
374 LDAP_FREE( ciphersuite );
375 LDAP_FREE( cacertfile );
376 LDAP_FREE( cacertdir );
377 LDAP_FREE( certfile );
378 LDAP_FREE( keyfile );
380 #ifdef LDAP_R_COMPILE
381 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
386 static STACK_OF(X509_NAME) *
387 get_ca_list( char * bundle, char * dir )
389 STACK_OF(X509_NAME) *ca_list = NULL;
392 ca_list = SSL_load_client_CA_file( bundle );
394 #if defined(HAVE_DIRENT_H) || defined(dirent)
399 ca_list = sk_X509_NAME_new_null();
402 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
404 sk_X509_NAME_free( ca_list );
414 alloc_handle( void *ctx_arg )
420 ctx = (SSL_CTX *) ctx_arg;
422 if ( ldap_pvt_tls_init_def_ctx() < 0 ) return NULL;
426 ssl = SSL_new( ctx );
429 LDAP_LOG ( TRANSPORT, ERR,
430 "alloc_handle: TLS can't create ssl handle.\n", 0, 0, 0 );
432 Debug( LDAP_DEBUG_ANY,"TLS: can't create ssl handle.\n",0,0,0);
440 update_flags( Sockbuf *sb, SSL * ssl, int rc )
442 int err = SSL_get_error(ssl, rc);
444 sb->sb_trans_needs_read = 0;
445 sb->sb_trans_needs_write = 0;
447 if (err == SSL_ERROR_WANT_READ) {
448 sb->sb_trans_needs_read = 1;
451 } else if (err == SSL_ERROR_WANT_WRITE) {
452 sb->sb_trans_needs_write = 1;
455 } else if (err == SSL_ERROR_WANT_CONNECT) {
462 * TLS support for LBER Sockbufs
467 Sockbuf_IO_Desc *sbiod;
470 static BIO_METHOD sb_tls_bio_method;
473 sb_tls_setup( Sockbuf_IO_Desc *sbiod, void *arg )
478 assert( sbiod != NULL );
480 p = LBER_MALLOC( sizeof( *p ) );
487 bio = BIO_new( &sb_tls_bio_method );
488 bio->ptr = (void *)p;
489 SSL_set_bio( p->ssl, bio, bio );
490 sbiod->sbiod_pvt = p;
495 sb_tls_remove( Sockbuf_IO_Desc *sbiod )
499 assert( sbiod != NULL );
500 assert( sbiod->sbiod_pvt != NULL );
502 p = (struct tls_data *)sbiod->sbiod_pvt;
504 LBER_FREE( sbiod->sbiod_pvt );
505 sbiod->sbiod_pvt = NULL;
510 sb_tls_close( Sockbuf_IO_Desc *sbiod )
514 assert( sbiod != NULL );
515 assert( sbiod->sbiod_pvt != NULL );
517 p = (struct tls_data *)sbiod->sbiod_pvt;
518 SSL_shutdown( p->ssl );
523 sb_tls_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
527 assert( sbiod != NULL );
528 assert( sbiod->sbiod_pvt != NULL );
530 p = (struct tls_data *)sbiod->sbiod_pvt;
532 if ( opt == LBER_SB_OPT_GET_SSL ) {
533 *((SSL **)arg) = p->ssl;
536 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
537 if( SSL_pending( p->ssl ) > 0 ) {
542 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
546 sb_tls_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
552 assert( sbiod != NULL );
553 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
555 p = (struct tls_data *)sbiod->sbiod_pvt;
557 ret = SSL_read( p->ssl, (char *)buf, len );
559 errno = WSAGetLastError();
561 err = SSL_get_error( p->ssl, ret );
562 if (err == SSL_ERROR_WANT_READ ) {
563 sbiod->sbiod_sb->sb_trans_needs_read = 1;
567 sbiod->sbiod_sb->sb_trans_needs_read = 0;
572 sb_tls_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
578 assert( sbiod != NULL );
579 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
581 p = (struct tls_data *)sbiod->sbiod_pvt;
583 ret = SSL_write( p->ssl, (char *)buf, len );
585 errno = WSAGetLastError();
587 err = SSL_get_error( p->ssl, ret );
588 if (err == SSL_ERROR_WANT_WRITE ) {
589 sbiod->sbiod_sb->sb_trans_needs_write = 1;
593 sbiod->sbiod_sb->sb_trans_needs_write = 0;
598 static Sockbuf_IO sb_tls_sbio =
600 sb_tls_setup, /* sbi_setup */
601 sb_tls_remove, /* sbi_remove */
602 sb_tls_ctrl, /* sbi_ctrl */
603 sb_tls_read, /* sbi_read */
604 sb_tls_write, /* sbi_write */
605 sb_tls_close /* sbi_close */
609 sb_tls_bio_create( BIO *b ) {
618 sb_tls_bio_destroy( BIO *b )
620 if ( b == NULL ) return 0;
622 b->ptr = NULL; /* sb_tls_remove() will free it */
629 sb_tls_bio_read( BIO *b, char *buf, int len )
634 if ( buf == NULL || len <= 0 ) return 0;
636 p = (struct tls_data *)b->ptr;
638 if ( p == NULL || p->sbiod == NULL ) {
642 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
644 BIO_clear_retry_flags( b );
645 if ( ret < 0 && errno == EWOULDBLOCK ) {
646 BIO_set_retry_read( b );
653 sb_tls_bio_write( BIO *b, const char *buf, int len )
658 if ( buf == NULL || len <= 0 ) return 0;
660 p = (struct tls_data *)b->ptr;
662 if ( p == NULL || p->sbiod == NULL ) {
666 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
668 BIO_clear_retry_flags( b );
669 if ( ret < 0 && errno == EWOULDBLOCK ) {
670 BIO_set_retry_write( b );
677 sb_tls_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
679 if ( cmd == BIO_CTRL_FLUSH ) {
680 /* The OpenSSL library needs this */
687 sb_tls_bio_gets( BIO *b, char *buf, int len )
693 sb_tls_bio_puts( BIO *b, const char *str )
695 return sb_tls_bio_write( b, str, strlen( str ) );
698 static BIO_METHOD sb_tls_bio_method =
700 ( 100 | 0x400 ), /* it's a source/sink BIO */
712 * Call this to do a TLS connect on a sockbuf. ctx_arg can be
713 * a SSL_CTX * or NULL, in which case the default ctx is used.
717 * 0 - Success. Connection is ready for communication.
718 * <0 - Error. Can't create a TLS stream.
719 * >0 - Partial success.
720 * Do a select (using information from lber_pvt_sb_needs_{read,write}
725 ldap_int_tls_connect( LDAP *ld, LDAPConn *conn )
727 Sockbuf *sb = conn->lconn_sb;
731 if ( HAS_TLS( sb ) ) {
732 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
735 void *ctx = ld->ld_defconn
736 ? ld->ld_defconn->lconn_tls_ctx : NULL;
738 ssl = alloc_handle( ctx );
740 if ( ssl == NULL ) return -1;
743 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
744 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
746 ber_sockbuf_add_io( sb, &sb_tls_sbio,
747 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
750 conn->lconn_tls_ctx = tls_def_ctx;
754 err = SSL_connect( ssl );
757 errno = WSAGetLastError();
761 if ( update_flags( sb, ssl, err )) {
765 if ((err = ERR_peek_error())) {
767 ld->ld_error = LDAP_STRDUP(ERR_error_string(err, buf));
769 if ( ld->ld_error ) __etoa(ld->ld_error);
774 LDAP_LOG ( TRANSPORT, ERR,
775 "ldap_int_tls_connect: TLS can't connect.\n", 0, 0, 0 );
777 Debug( LDAP_DEBUG_ANY,"TLS: can't connect.\n",0,0,0);
780 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
781 LBER_SBIOD_LEVEL_TRANSPORT );
783 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
784 LBER_SBIOD_LEVEL_TRANSPORT );
793 * Call this to do a TLS accept on a sockbuf.
794 * Everything else is the same as with tls_connect.
797 ldap_pvt_tls_accept( Sockbuf *sb, void *ctx_arg )
802 if ( HAS_TLS( sb ) ) {
803 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
806 ssl = alloc_handle( ctx_arg );
807 if ( ssl == NULL ) return -1;
810 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
811 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
813 ber_sockbuf_add_io( sb, &sb_tls_sbio,
814 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
817 err = SSL_accept( ssl );
820 errno = WSAGetLastError();
823 if ( update_flags( sb, ssl, err )) return 1;
826 LDAP_LOG ( TRANSPORT, ERR,
827 "ldap_pvt_tls_accept: TLS can't accept.\n", 0, 0, 0 );
829 Debug( LDAP_DEBUG_ANY,"TLS: can't accept.\n",0,0,0 );
833 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
834 LBER_SBIOD_LEVEL_TRANSPORT );
836 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
837 LBER_SBIOD_LEVEL_TRANSPORT );
846 ldap_pvt_tls_inplace ( Sockbuf *sb )
848 return HAS_TLS( sb ) ? 1 : 0;
852 ldap_pvt_tls_sb_ctx( Sockbuf *sb )
857 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&p );
865 ldap_pvt_tls_get_strength( void *s )
869 c = SSL_get_current_cipher((SSL *)s);
870 return SSL_CIPHER_get_bits(c, NULL);
875 ldap_pvt_tls_get_my_dn( void *s, struct berval *dn, LDAPDN_rewrite_dummy *func, unsigned flags )
881 x = SSL_get_certificate((SSL *)s);
883 if (!x) return LDAP_INVALID_CREDENTIALS;
885 xn = X509_get_subject_name(x);
886 rc = ldap_X509dn2bv(xn, dn, (LDAPDN_rewrite_func *)func, flags );
892 tls_get_cert( SSL *s )
894 /* If peer cert was bad, treat as if no cert was given */
895 if (SSL_get_verify_result(s)) {
896 /* If we can send an alert, do so */
897 if (SSL_version(s) != SSL2_VERSION) {
898 ssl3_send_alert(s,SSL3_AL_WARNING,SSL3_AD_BAD_CERTIFICATE);
902 return SSL_get_peer_certificate(s);
906 ldap_pvt_tls_get_peer_dn( void *s, struct berval *dn, LDAPDN_rewrite_dummy *func, unsigned flags )
912 x = tls_get_cert((SSL *)s);
914 if (!x) return LDAP_INVALID_CREDENTIALS;
916 xn = X509_get_subject_name(x);
917 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));
941 p = LDAP_STRDUP(buf);
947 ldap_pvt_tls_check_hostname( LDAP *ld, void *s, const char *name_in )
949 int i, ret = LDAP_LOCAL_ERROR;
953 if( ldap_int_hostname &&
954 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
956 name = ldap_int_hostname;
961 x = tls_get_cert((SSL *)s);
964 LDAP_LOG ( TRANSPORT, ERR,
965 "ldap_pvt_tls_check_hostname: "
966 "TLS unable to get peer certificate.\n" , 0, 0, 0 );
968 Debug( LDAP_DEBUG_ANY,
969 "TLS: unable to get peer certificate.\n",
972 /* If this was a fatal condition, things would have
973 * aborted long before now.
978 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
981 STACK_OF(GENERAL_NAME) *alt;
983 ex = X509_get_ext(x, i);
984 alt = X509V3_EXT_d2i(ex);
986 int n, len1, len2 = 0;
991 n = sk_GENERAL_NAME_num(alt);
992 domain = strchr(name, '.');
994 len2 = len1 - (domain-name);
996 for (i=0; i<n; i++) {
997 gn = sk_GENERAL_NAME_value(alt, i);
998 if (gn->type == GEN_DNS) {
999 char *sn = ASN1_STRING_data(gn->d.ia5);
1000 int sl = ASN1_STRING_length(gn->d.ia5);
1002 /* Is this an exact match? */
1003 if ((len1 == sl) && !strncasecmp(name, sn, len1)) {
1007 /* Is this a wildcard match? */
1008 if ((*sn == '*') && domain && (len2 == sl-1) &&
1009 !strncasecmp(domain, sn+1, len2))
1015 /* Is this a RFC 2549 style wildcard match? */
1016 if ((*sn == '.') && domain && (len2 == sl) &&
1017 !strncasecmp(domain, sn, len2))
1025 GENERAL_NAMES_free(alt);
1026 if (i < n) { /* Found a match */
1032 if (ret != LDAP_SUCCESS) {
1036 xn = X509_get_subject_name(x);
1038 if( X509_NAME_get_text_by_NID( xn, NID_commonName,
1039 buf, sizeof(buf)) == -1)
1042 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_check_hostname: "
1043 "TLS unable to get common name from peer certificate.\n",
1046 Debug( LDAP_DEBUG_ANY,
1047 "TLS: unable to get common name from peer certificate.\n",
1050 ld->ld_error = LDAP_STRDUP("TLS: unable to get CN from peer certificate");
1052 } else if (strcasecmp(name, buf)) {
1054 LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_check_hostname: "
1055 "TLS hostname (%s) does not match "
1056 "common name in certificate (%s).\n", name, buf, 0 );
1058 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
1059 "common name in certificate (%s).\n",
1062 ret = LDAP_CONNECT_ERROR;
1063 ld->ld_error = LDAP_STRDUP("TLS: hostname does not match CN in peer certificate");
1074 ldap_pvt_tls_get_peer_issuer( void *s )
1076 #if 0 /* currently unused; see ldap_pvt_tls_get_peer_dn() if needed */
1081 x = SSL_get_peer_certificate((SSL *)s);
1083 if (!x) return NULL;
1085 xn = X509_get_issuer_name(x);
1086 p = LDAP_STRDUP(X509_NAME_oneline(xn, buf, sizeof(buf)));
1095 ldap_int_tls_config( LDAP *ld, int option, const char *arg )
1100 case LDAP_OPT_X_TLS_CACERTFILE:
1101 case LDAP_OPT_X_TLS_CACERTDIR:
1102 case LDAP_OPT_X_TLS_CERTFILE:
1103 case LDAP_OPT_X_TLS_KEYFILE:
1104 case LDAP_OPT_X_TLS_RANDOM_FILE:
1105 return ldap_pvt_tls_set_option( ld, option, (void *) arg );
1107 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1108 case LDAP_OPT_X_TLS:
1110 if ( strcasecmp( arg, "never" ) == 0 ) {
1111 i = LDAP_OPT_X_TLS_NEVER ;
1113 } else if ( strcasecmp( arg, "demand" ) == 0 ) {
1114 i = LDAP_OPT_X_TLS_DEMAND ;
1116 } else if ( strcasecmp( arg, "allow" ) == 0 ) {
1117 i = LDAP_OPT_X_TLS_ALLOW ;
1119 } else if ( strcasecmp( arg, "try" ) == 0 ) {
1120 i = LDAP_OPT_X_TLS_TRY ;
1122 } else if ( ( strcasecmp( arg, "hard" ) == 0 ) ||
1123 ( strcasecmp( arg, "on" ) == 0 ) ||
1124 ( strcasecmp( arg, "yes" ) == 0) ||
1125 ( strcasecmp( arg, "true" ) == 0 ) )
1127 i = LDAP_OPT_X_TLS_HARD ;
1131 return ldap_pvt_tls_set_option( ld, option, &i );
1140 ldap_pvt_tls_get_option( LDAP *ld, int option, void *arg )
1142 struct ldapoptions *lo;
1145 assert( LDAP_VALID( ld ) );
1147 if( !LDAP_VALID( ld ) ) {
1148 return LDAP_OPT_ERROR;
1151 lo = &ld->ld_options;
1154 /* Get pointer to global option structure */
1155 lo = LDAP_INT_GLOBAL_OPT();
1157 return LDAP_NO_MEMORY;
1162 case LDAP_OPT_X_TLS:
1163 *(int *)arg = lo->ldo_tls_mode;
1165 case LDAP_OPT_X_TLS_CTX:
1167 *(void **)arg = (void *) tls_def_ctx;
1169 *(void **)arg = ld->ld_defconn->lconn_tls_ctx;
1172 case LDAP_OPT_X_TLS_CACERTFILE:
1173 *(char **)arg = tls_opt_cacertfile ?
1174 LDAP_STRDUP( tls_opt_cacertfile ) : NULL;
1176 case LDAP_OPT_X_TLS_CACERTDIR:
1177 *(char **)arg = tls_opt_cacertdir ?
1178 LDAP_STRDUP( tls_opt_cacertdir ) : NULL;
1180 case LDAP_OPT_X_TLS_CERTFILE:
1181 *(char **)arg = tls_opt_certfile ?
1182 LDAP_STRDUP( tls_opt_certfile ) : NULL;
1184 case LDAP_OPT_X_TLS_KEYFILE:
1185 *(char **)arg = tls_opt_keyfile ?
1186 LDAP_STRDUP( tls_opt_keyfile ) : NULL;
1188 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1189 *(int *)arg = tls_opt_require_cert;
1191 case LDAP_OPT_X_TLS_RANDOM_FILE:
1192 *(char **)arg = tls_opt_randfile ?
1193 LDAP_STRDUP( tls_opt_randfile ) : NULL;
1195 case LDAP_OPT_X_TLS_SSL_CTX: {
1198 LDAPConn *conn = ld->ld_defconn;
1199 if ( conn != NULL ) {
1200 Sockbuf *sb = conn->lconn_sb;
1201 retval = ldap_pvt_tls_sb_ctx( sb );
1204 *(void **)arg = retval;
1214 ldap_pvt_tls_set_option( LDAP *ld, int option, void *arg )
1216 struct ldapoptions *lo;
1219 assert( LDAP_VALID( ld ) );
1221 if( !LDAP_VALID( ld ) ) {
1222 return LDAP_OPT_ERROR;
1225 lo = &ld->ld_options;
1228 /* Get pointer to global option structure */
1229 lo = LDAP_INT_GLOBAL_OPT();
1231 return LDAP_NO_MEMORY;
1236 case LDAP_OPT_X_TLS:
1237 switch( *(int *) arg ) {
1238 case LDAP_OPT_X_TLS_NEVER:
1239 case LDAP_OPT_X_TLS_DEMAND:
1240 case LDAP_OPT_X_TLS_ALLOW:
1241 case LDAP_OPT_X_TLS_TRY:
1242 case LDAP_OPT_X_TLS_HARD:
1244 lo->ldo_tls_mode = *(int *)arg;
1251 case LDAP_OPT_X_TLS_CTX:
1253 tls_def_ctx = (SSL_CTX *) arg;
1256 ld->ld_defconn->lconn_tls_ctx = arg;
1266 case LDAP_OPT_X_TLS_CACERTFILE:
1267 if ( tls_opt_cacertfile ) LDAP_FREE( tls_opt_cacertfile );
1268 tls_opt_cacertfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1270 case LDAP_OPT_X_TLS_CACERTDIR:
1271 if ( tls_opt_cacertdir ) LDAP_FREE( tls_opt_cacertdir );
1272 tls_opt_cacertdir = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1274 case LDAP_OPT_X_TLS_CERTFILE:
1275 if ( tls_opt_certfile ) LDAP_FREE( tls_opt_certfile );
1276 tls_opt_certfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1278 case LDAP_OPT_X_TLS_KEYFILE:
1279 if ( tls_opt_keyfile ) LDAP_FREE( tls_opt_keyfile );
1280 tls_opt_keyfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1282 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1283 switch( *(int *) arg ) {
1284 case LDAP_OPT_X_TLS_NEVER:
1285 case LDAP_OPT_X_TLS_DEMAND:
1286 case LDAP_OPT_X_TLS_ALLOW:
1287 case LDAP_OPT_X_TLS_TRY:
1288 case LDAP_OPT_X_TLS_HARD:
1289 tls_opt_require_cert = * (int *) arg;
1293 case LDAP_OPT_X_TLS_CIPHER_SUITE:
1294 if ( tls_opt_ciphersuite ) LDAP_FREE( tls_opt_ciphersuite );
1295 tls_opt_ciphersuite = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1297 case LDAP_OPT_X_TLS_RANDOM_FILE:
1298 if (tls_opt_randfile ) LDAP_FREE (tls_opt_randfile );
1299 tls_opt_randfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1308 ldap_int_tls_start ( LDAP *ld, LDAPConn *conn, LDAPURLDesc *srv )
1310 Sockbuf *sb = conn->lconn_sb;
1315 host = srv->lud_host;
1317 host = conn->lconn_server->lud_host;
1320 /* avoid NULL host */
1321 if( host == NULL ) {
1325 (void) ldap_pvt_tls_init();
1328 * Fortunately, the lib uses blocking io...
1330 if ( ldap_int_tls_connect( ld, conn ) < 0 ) {
1331 ld->ld_errno = LDAP_CONNECT_ERROR;
1332 return (ld->ld_errno);
1335 ssl = ldap_pvt_tls_sb_ctx( sb );
1336 assert( ssl != NULL );
1339 * compare host with name(s) in certificate
1341 ld->ld_errno = ldap_pvt_tls_check_hostname( ld, ssl, host );
1342 if (ld->ld_errno != LDAP_SUCCESS) {
1343 return ld->ld_errno;
1347 * set SASL properties to TLS ssf and authid
1350 struct berval authid = { 0, NULL };
1353 /* we need to let SASL know */
1354 ssf = ldap_pvt_tls_get_strength( ssl );
1355 /* failure is OK, we just can't use SASL EXTERNAL */
1356 (void) ldap_pvt_tls_get_my_dn( ssl, &authid, NULL, 0 );
1358 (void) ldap_int_sasl_external( ld, conn, authid.bv_val, ssf );
1359 LDAP_FREE( authid.bv_val );
1362 return LDAP_SUCCESS;
1365 /* Derived from openssl/apps/s_cb.c */
1367 tls_info_cb( SSL *ssl, int where, int ret )
1371 char *state = SSL_state_string_long( ssl );
1373 w = where & ~SSL_ST_MASK;
1374 if ( w & SSL_ST_CONNECT ) {
1376 } else if ( w & SSL_ST_ACCEPT ) {
1384 state = LDAP_STRDUP( state );
1388 if ( where & SSL_CB_LOOP ) {
1390 LDAP_LOG ( TRANSPORT, DETAIL1, "tls_info_cb: "
1391 "TLS trace: %s:%s\n", op, state, 0 );
1393 Debug( LDAP_DEBUG_TRACE,
1394 "TLS trace: %s:%s\n",
1398 } else if ( where & SSL_CB_ALERT ) {
1399 char *atype = SSL_alert_type_string_long( ret );
1400 char *adesc = SSL_alert_desc_string_long( ret );
1401 op = ( where & SSL_CB_READ ) ? "read" : "write";
1404 atype = LDAP_STRDUP( atype );
1408 adesc = LDAP_STRDUP( adesc );
1413 LDAP_LOG ( TRANSPORT, DETAIL1,
1414 "tls_info_cb: TLS trace: SSL3 alert %s:%s:%s\n",
1417 Debug( LDAP_DEBUG_TRACE,
1418 "TLS trace: SSL3 alert %s:%s:%s\n",
1422 if ( atype ) LDAP_FREE( atype );
1423 if ( adesc ) LDAP_FREE( adesc );
1425 } else if ( where & SSL_CB_EXIT ) {
1428 LDAP_LOG ( TRANSPORT, ERR,
1429 "tls_info_cb: TLS trace: %s:failed in %s\n",
1432 Debug( LDAP_DEBUG_TRACE,
1433 "TLS trace: %s:failed in %s\n",
1436 } else if ( ret < 0 ) {
1438 LDAP_LOG ( TRANSPORT, ERR,
1439 "tls_info_cb: TLS trace: %s:error in %s\n",
1442 Debug( LDAP_DEBUG_TRACE,
1443 "TLS trace: %s:error in %s\n",
1449 if ( state ) LDAP_FREE( state );
1454 tls_verify_cb( int ok, X509_STORE_CTX *ctx )
1463 char *certerr = NULL;
1465 cert = X509_STORE_CTX_get_current_cert( ctx );
1466 errnum = X509_STORE_CTX_get_error( ctx );
1467 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1470 * X509_get_*_name return pointers to the internal copies of
1471 * those things requested. So do not free them.
1473 subject = X509_get_subject_name( cert );
1474 issuer = X509_get_issuer_name( cert );
1475 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1476 sname = X509_NAME_oneline( subject, NULL, 0 );
1477 iname = X509_NAME_oneline( issuer, NULL, 0 );
1478 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1480 if ( sname ) __etoa( sname );
1481 if ( iname ) __etoa( iname );
1483 certerr = LDAP_STRDUP( certerr );
1488 LDAP_LOG( TRANSPORT, ERR,
1489 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1491 sname ? sname : "-unknown-" );
1492 LDAP_LOG( TRANSPORT, ERR, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1494 LDAP_LOG ( TRANSPORT, ERR,
1495 "TLS certificate verification: Error, %s\n",
1499 Debug( LDAP_DEBUG_TRACE,
1500 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1502 sname ? sname : "-unknown-" );
1503 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1505 Debug( LDAP_DEBUG_ANY,
1506 "TLS certificate verification: Error, %s\n",
1511 CRYPTO_free ( sname );
1513 CRYPTO_free ( iname );
1515 if ( certerr ) LDAP_FREE( certerr );
1521 tls_verify_ok( int ok, X509_STORE_CTX *ctx )
1523 (void) tls_verify_cb( ok, ctx );
1527 /* Inspired by ERR_print_errors in OpenSSL */
1529 tls_report_error( void )
1536 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1537 ERR_error_string_n( l, buf, sizeof( buf ) );
1540 file = LDAP_STRDUP( file );
1541 __etoa( (char *)file );
1546 LDAP_LOG ( TRANSPORT, ERR,
1547 "tls_report_error: TLS %s %s:%d\n",
1550 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1554 if ( file ) LDAP_FREE( (void *)file );
1560 tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1564 /* FIXME: Pregenerate the key on startup */
1565 /* FIXME: Who frees the key? */
1566 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1570 LDAP_LOG ( TRANSPORT, ERR,
1571 "tls_tmp_rsa_cb: TLS Failed to generate temporary %d-bit %s "
1572 "RSA key\n", key_length, is_export ? "export" : "domestic", 0 );
1574 Debug( LDAP_DEBUG_ANY,
1575 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1576 key_length, is_export ? "export" : "domestic", 0 );
1584 tls_seed_PRNG( const char *randfile )
1586 #ifndef URANDOM_DEVICE
1587 /* no /dev/urandom (or equiv) */
1589 char buffer[MAXPATHLEN];
1591 if (randfile == NULL) {
1592 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1593 * If $HOME is not set or buffer too small to hold the pathname,
1594 * an error occurs. - From RAND_file_name() man page.
1595 * The fact is that when $HOME is NULL, .rnd is used.
1597 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1599 } else if (RAND_egd(randfile) > 0) {
1604 if (randfile == NULL) {
1606 LDAP_LOG ( TRANSPORT, DETAIL1,
1607 "tls_seed_PRNG: TLS Use configuration file or "
1608 "$RANDFILE to define seed PRNG\n", 0, 0, 0 );
1610 Debug( LDAP_DEBUG_ANY,
1611 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1617 total = RAND_load_file(randfile, -1);
1619 if (RAND_status() == 0) {
1621 LDAP_LOG ( TRANSPORT, DETAIL1,
1622 "tls_seed_PRNG: TLS PRNG not been seeded with enough data\n",
1625 Debug( LDAP_DEBUG_ANY,
1626 "TLS: PRNG not been seeded with enough data\n",
1632 /* assume if there was enough bits to seed that it's okay
1633 * to write derived bits to the file
1635 RAND_write_file(randfile);
1644 tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1652 ldap_start_tls_s ( LDAP *ld,
1653 LDAPControl **serverctrls,
1654 LDAPControl **clientctrls )
1659 char *rspoid = NULL;
1660 struct berval *rspdata = NULL;
1662 /* XXYYZ: this initiates operation only on default connection! */
1664 if ( ld->ld_sb != NULL && ldap_pvt_tls_inplace( ld->ld_sb ) != 0 ) {
1665 return LDAP_LOCAL_ERROR;
1668 rc = ldap_extended_operation_s( ld, LDAP_EXOP_START_TLS,
1669 NULL, serverctrls, clientctrls, &rspoid, &rspdata );
1670 if ( rc != LDAP_SUCCESS ) {
1674 if ( rspoid != NULL ) {
1678 if ( rspdata != NULL ) {
1679 ber_bvfree( rspdata );
1682 rc = ldap_int_tls_start( ld, ld->ld_defconn, NULL );
1684 rc = LDAP_NOT_SUPPORTED;