1 /* tls.c - Handle tls/ssl using SSLeay or OpenSSL. */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 1998-2005 The OpenLDAP Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted only as authorized by the OpenLDAP
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>.
18 #include "ldap_config.h"
22 #include <ac/stdlib.h>
24 #include <ac/socket.h>
25 #include <ac/string.h>
28 #include <ac/unistd.h>
30 #include <ac/dirent.h>
37 #include <ldap_pvt_thread.h>
40 #ifdef HAVE_OPENSSL_SSL_H
41 #include <openssl/ssl.h>
42 #include <openssl/x509v3.h>
43 #include <openssl/err.h>
44 #include <openssl/rand.h>
45 #include <openssl/safestack.h>
46 #elif defined( HAVE_SSL_H )
50 static int tls_opt_trace = 1;
51 static char *tls_opt_certfile = NULL;
52 static char *tls_opt_keyfile = NULL;
53 static char *tls_opt_cacertfile = NULL;
54 static char *tls_opt_cacertdir = NULL;
55 static int tls_opt_require_cert = LDAP_OPT_X_TLS_DEMAND;
56 #ifdef HAVE_OPENSSL_CRL
57 static int tls_opt_crlcheck = LDAP_OPT_X_TLS_CRL_NONE;
59 static char *tls_opt_ciphersuite = NULL;
60 static char *tls_opt_randfile = NULL;
62 #define HAS_TLS( sb ) ber_sockbuf_ctrl( sb, LBER_SB_OPT_HAS_IO, \
63 (void *)&sb_tls_sbio )
65 static void tls_report_error( void );
67 static void tls_info_cb( const SSL *ssl, int where, int ret );
68 static int tls_verify_cb( int ok, X509_STORE_CTX *ctx );
69 static int tls_verify_ok( int ok, X509_STORE_CTX *ctx );
70 static RSA * tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
71 static STACK_OF(X509_NAME) * get_ca_list( char * bundle, char * dir );
73 #if 0 /* Currently this is not used by anyone */
74 static DH * tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length );
77 static SSL_CTX *tls_def_ctx = NULL;
79 static int tls_seed_PRNG( const char *randfile );
83 * provide mutexes for the SSLeay library.
85 static ldap_pvt_thread_mutex_t tls_mutexes[CRYPTO_NUM_LOCKS];
87 static void tls_locking_cb( int mode, int type, const char *file, int line )
89 if ( mode & CRYPTO_LOCK ) {
90 ldap_pvt_thread_mutex_lock( &tls_mutexes[type] );
92 ldap_pvt_thread_mutex_unlock( &tls_mutexes[type] );
97 * an extra mutex for the default ctx.
100 static ldap_pvt_thread_mutex_t tls_def_ctx_mutex;
102 static void tls_init_threads( void )
106 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
107 ldap_pvt_thread_mutex_init( &tls_mutexes[i] );
109 CRYPTO_set_locking_callback( tls_locking_cb );
110 /* FIXME: the thread id should be added somehow... */
112 ldap_pvt_thread_mutex_init( &tls_def_ctx_mutex );
114 #endif /* LDAP_R_COMPILE */
117 * Tear down the TLS subsystem. Should only be called once.
120 ldap_pvt_tls_destroy( void )
122 SSL_CTX_free(tls_def_ctx);
129 if ( tls_opt_certfile ) {
130 LDAP_FREE( tls_opt_certfile );
131 tls_opt_certfile = NULL;
133 if ( tls_opt_keyfile ) {
134 LDAP_FREE( tls_opt_keyfile );
135 tls_opt_keyfile = NULL;
137 if ( tls_opt_cacertfile ) {
138 LDAP_FREE( tls_opt_cacertfile );
139 tls_opt_cacertfile = NULL;
141 if ( tls_opt_cacertdir ) {
142 LDAP_FREE( tls_opt_cacertdir );
143 tls_opt_cacertdir = NULL;
145 if ( tls_opt_ciphersuite ) {
146 LDAP_FREE( tls_opt_ciphersuite );
147 tls_opt_ciphersuite = NULL;
149 if ( tls_opt_randfile ) {
150 LDAP_FREE( tls_opt_randfile );
151 tls_opt_randfile = NULL;
156 * Initialize TLS subsystem. Should be called only once.
159 ldap_pvt_tls_init( void )
161 static int tls_initialized = 0;
163 if ( tls_initialized++ ) return 0;
167 char *file = LDAP_STRDUP( tls_opt_randfile );
168 if ( file ) __atoe( file );
169 (void) tls_seed_PRNG( file );
173 (void) tls_seed_PRNG( tls_opt_randfile );
176 #ifdef LDAP_R_COMPILE
180 SSL_load_error_strings();
181 SSLeay_add_ssl_algorithms();
183 /* FIXME: mod_ssl does this */
184 X509V3_add_standard_extensions();
189 * initialize the default context
192 ldap_pvt_tls_init_def_ctx( void )
194 STACK_OF(X509_NAME) *calist;
196 char *ciphersuite = tls_opt_ciphersuite;
197 char *cacertfile = tls_opt_cacertfile;
198 char *cacertdir = tls_opt_cacertdir;
199 char *certfile = tls_opt_certfile;
200 char *keyfile = tls_opt_keyfile;
203 /* This ASCII/EBCDIC handling is a real pain! */
205 ciphersuite = LDAP_STRDUP( ciphersuite );
206 __atoe( ciphersuite );
209 cacertfile = LDAP_STRDUP( cacertfile );
210 __atoe( cacertfile );
213 cacertdir = LDAP_STRDUP( cacertdir );
217 certfile = LDAP_STRDUP( certfile );
221 keyfile = LDAP_STRDUP( keyfile );
226 #ifdef LDAP_R_COMPILE
227 ldap_pvt_thread_mutex_lock( &tls_def_ctx_mutex );
229 if ( tls_def_ctx == NULL ) {
231 tls_def_ctx = SSL_CTX_new( SSLv23_method() );
232 if ( tls_def_ctx == NULL ) {
233 Debug( LDAP_DEBUG_ANY,
234 "TLS: could not allocate default ctx (%lu).\n",
235 ERR_peek_error(),0,0);
240 SSL_CTX_set_session_id_context( tls_def_ctx,
241 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
243 if ( tls_opt_ciphersuite &&
244 !SSL_CTX_set_cipher_list( tls_def_ctx, ciphersuite ) )
246 Debug( LDAP_DEBUG_ANY,
247 "TLS: could not set cipher list %s.\n",
248 tls_opt_ciphersuite, 0, 0 );
254 if (tls_opt_cacertfile != NULL || tls_opt_cacertdir != NULL) {
255 if ( !SSL_CTX_load_verify_locations( tls_def_ctx,
256 cacertfile, cacertdir ) ||
257 !SSL_CTX_set_default_verify_paths( tls_def_ctx ) )
259 Debug( LDAP_DEBUG_ANY, "TLS: "
260 "could not load verify locations (file:`%s',dir:`%s').\n",
261 tls_opt_cacertfile ? tls_opt_cacertfile : "",
262 tls_opt_cacertdir ? tls_opt_cacertdir : "",
269 calist = get_ca_list( cacertfile, cacertdir );
271 Debug( LDAP_DEBUG_ANY, "TLS: "
272 "could not load client CA list (file:`%s',dir:`%s').\n",
273 tls_opt_cacertfile ? tls_opt_cacertfile : "",
274 tls_opt_cacertdir ? tls_opt_cacertdir : "",
281 SSL_CTX_set_client_CA_list( tls_def_ctx, calist );
284 if ( tls_opt_keyfile &&
285 !SSL_CTX_use_PrivateKey_file( tls_def_ctx,
286 keyfile, SSL_FILETYPE_PEM ) )
288 Debug( LDAP_DEBUG_ANY,
289 "TLS: could not use key file `%s'.\n",
290 tls_opt_keyfile,0,0);
296 if ( tls_opt_certfile &&
297 !SSL_CTX_use_certificate_file( tls_def_ctx,
298 certfile, SSL_FILETYPE_PEM ) )
300 Debug( LDAP_DEBUG_ANY,
301 "TLS: could not use certificate `%s'.\n",
302 tls_opt_certfile,0,0);
308 if ( ( tls_opt_certfile || tls_opt_keyfile ) &&
309 !SSL_CTX_check_private_key( tls_def_ctx ) )
311 Debug( LDAP_DEBUG_ANY,
312 "TLS: private key mismatch.\n",
319 if ( tls_opt_trace ) {
320 SSL_CTX_set_info_callback( tls_def_ctx, tls_info_cb );
324 if ( tls_opt_require_cert ) {
326 if ( tls_opt_require_cert == LDAP_OPT_X_TLS_DEMAND ||
327 tls_opt_require_cert == LDAP_OPT_X_TLS_HARD ) {
328 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
332 SSL_CTX_set_verify( tls_def_ctx, i,
333 tls_opt_require_cert == LDAP_OPT_X_TLS_ALLOW ?
334 tls_verify_ok : tls_verify_cb );
335 SSL_CTX_set_tmp_rsa_callback( tls_def_ctx, tls_tmp_rsa_cb );
336 /* SSL_CTX_set_tmp_dh_callback( tls_def_ctx, tls_tmp_dh_cb ); */
337 #ifdef HAVE_OPENSSL_CRL
338 if ( tls_opt_crlcheck ) {
339 X509_STORE *x509_s = SSL_CTX_get_cert_store( tls_def_ctx );
340 if ( tls_opt_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
341 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
342 } else if ( tls_opt_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
343 X509_STORE_set_flags( x509_s,
344 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
350 if ( rc == -1 && tls_def_ctx != NULL ) {
351 SSL_CTX_free( tls_def_ctx );
355 LDAP_FREE( ciphersuite );
356 LDAP_FREE( cacertfile );
357 LDAP_FREE( cacertdir );
358 LDAP_FREE( certfile );
359 LDAP_FREE( keyfile );
361 #ifdef LDAP_R_COMPILE
362 ldap_pvt_thread_mutex_unlock( &tls_def_ctx_mutex );
367 static STACK_OF(X509_NAME) *
368 get_ca_list( char * bundle, char * dir )
370 STACK_OF(X509_NAME) *ca_list = NULL;
373 ca_list = SSL_load_client_CA_file( bundle );
375 #if defined(HAVE_DIRENT_H) || defined(dirent)
380 ca_list = sk_X509_NAME_new_null();
383 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
385 sk_X509_NAME_free( ca_list );
394 alloc_handle( void *ctx_arg )
400 ctx = (SSL_CTX *) ctx_arg;
402 if ( ldap_pvt_tls_init_def_ctx() < 0 ) return NULL;
406 ssl = SSL_new( ctx );
408 Debug( LDAP_DEBUG_ANY,"TLS: can't create ssl handle.\n",0,0,0);
415 update_flags( Sockbuf *sb, SSL * ssl, int rc )
417 int err = SSL_get_error(ssl, rc);
419 sb->sb_trans_needs_read = 0;
420 sb->sb_trans_needs_write = 0;
422 if (err == SSL_ERROR_WANT_READ) {
423 sb->sb_trans_needs_read = 1;
426 } else if (err == SSL_ERROR_WANT_WRITE) {
427 sb->sb_trans_needs_write = 1;
430 } else if (err == SSL_ERROR_WANT_CONNECT) {
437 * TLS support for LBER Sockbufs
442 Sockbuf_IO_Desc *sbiod;
445 static BIO_METHOD sb_tls_bio_method;
448 sb_tls_setup( Sockbuf_IO_Desc *sbiod, void *arg )
453 assert( sbiod != NULL );
455 p = LBER_MALLOC( sizeof( *p ) );
462 bio = BIO_new( &sb_tls_bio_method );
463 bio->ptr = (void *)p;
464 SSL_set_bio( p->ssl, bio, bio );
465 sbiod->sbiod_pvt = p;
470 sb_tls_remove( Sockbuf_IO_Desc *sbiod )
474 assert( sbiod != NULL );
475 assert( sbiod->sbiod_pvt != NULL );
477 p = (struct tls_data *)sbiod->sbiod_pvt;
479 LBER_FREE( sbiod->sbiod_pvt );
480 sbiod->sbiod_pvt = NULL;
485 sb_tls_close( Sockbuf_IO_Desc *sbiod )
489 assert( sbiod != NULL );
490 assert( sbiod->sbiod_pvt != NULL );
492 p = (struct tls_data *)sbiod->sbiod_pvt;
493 SSL_shutdown( p->ssl );
498 sb_tls_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
502 assert( sbiod != NULL );
503 assert( sbiod->sbiod_pvt != NULL );
505 p = (struct tls_data *)sbiod->sbiod_pvt;
507 if ( opt == LBER_SB_OPT_GET_SSL ) {
508 *((SSL **)arg) = p->ssl;
511 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
512 if( SSL_pending( p->ssl ) > 0 ) {
517 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
521 sb_tls_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
527 assert( sbiod != NULL );
528 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
530 p = (struct tls_data *)sbiod->sbiod_pvt;
532 ret = SSL_read( p->ssl, (char *)buf, len );
534 errno = WSAGetLastError();
536 err = SSL_get_error( p->ssl, ret );
537 if (err == SSL_ERROR_WANT_READ ) {
538 sbiod->sbiod_sb->sb_trans_needs_read = 1;
542 sbiod->sbiod_sb->sb_trans_needs_read = 0;
547 sb_tls_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
553 assert( sbiod != NULL );
554 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
556 p = (struct tls_data *)sbiod->sbiod_pvt;
558 ret = SSL_write( p->ssl, (char *)buf, len );
560 errno = WSAGetLastError();
562 err = SSL_get_error( p->ssl, ret );
563 if (err == SSL_ERROR_WANT_WRITE ) {
564 sbiod->sbiod_sb->sb_trans_needs_write = 1;
568 sbiod->sbiod_sb->sb_trans_needs_write = 0;
573 static Sockbuf_IO sb_tls_sbio =
575 sb_tls_setup, /* sbi_setup */
576 sb_tls_remove, /* sbi_remove */
577 sb_tls_ctrl, /* sbi_ctrl */
578 sb_tls_read, /* sbi_read */
579 sb_tls_write, /* sbi_write */
580 sb_tls_close /* sbi_close */
584 sb_tls_bio_create( BIO *b ) {
593 sb_tls_bio_destroy( BIO *b )
595 if ( b == NULL ) return 0;
597 b->ptr = NULL; /* sb_tls_remove() will free it */
604 sb_tls_bio_read( BIO *b, char *buf, int len )
609 if ( buf == NULL || len <= 0 ) return 0;
611 p = (struct tls_data *)b->ptr;
613 if ( p == NULL || p->sbiod == NULL ) {
617 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
619 BIO_clear_retry_flags( b );
622 if ( err == EAGAIN || err == EWOULDBLOCK ) {
623 BIO_set_retry_read( b );
631 sb_tls_bio_write( BIO *b, const 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_WRITE_NEXT( p->sbiod, (char *)buf, len );
646 BIO_clear_retry_flags( b );
649 if ( err == EAGAIN || err == EWOULDBLOCK ) {
650 BIO_set_retry_write( b );
658 sb_tls_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
660 if ( cmd == BIO_CTRL_FLUSH ) {
661 /* The OpenSSL library needs this */
668 sb_tls_bio_gets( BIO *b, char *buf, int len )
674 sb_tls_bio_puts( BIO *b, const char *str )
676 return sb_tls_bio_write( b, str, strlen( str ) );
679 static BIO_METHOD sb_tls_bio_method =
681 ( 100 | 0x400 ), /* it's a source/sink BIO */
693 * Call this to do a TLS connect on a sockbuf. ctx_arg can be
694 * a SSL_CTX * or NULL, in which case the default ctx is used.
698 * 0 - Success. Connection is ready for communication.
699 * <0 - Error. Can't create a TLS stream.
700 * >0 - Partial success.
701 * Do a select (using information from lber_pvt_sb_needs_{read,write}
706 ldap_int_tls_connect( LDAP *ld, LDAPConn *conn )
708 Sockbuf *sb = conn->lconn_sb;
712 if ( HAS_TLS( sb ) ) {
713 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
716 struct ldapoptions *lo;
717 void *ctx = ld->ld_defconn
718 ? ld->ld_defconn->lconn_tls_ctx : NULL;
720 ssl = alloc_handle( ctx );
722 if ( ssl == NULL ) return -1;
725 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
726 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
728 ber_sockbuf_add_io( sb, &sb_tls_sbio,
729 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
733 conn->lconn_tls_ctx = tls_def_ctx;
735 lo = &ld->ld_options;
736 if ( lo->ldo_tls_connect_cb )
737 lo->ldo_tls_connect_cb( ld, ssl, ctx, lo->ldo_tls_connect_arg );
738 lo = LDAP_INT_GLOBAL_OPT();
739 if ( lo && lo->ldo_tls_connect_cb )
740 lo->ldo_tls_connect_cb( ld, ssl, ctx, lo->ldo_tls_connect_arg );
743 err = SSL_connect( ssl );
746 errno = WSAGetLastError();
750 if ( update_flags( sb, ssl, err )) {
754 if ((err = ERR_peek_error())) {
756 ld->ld_error = LDAP_STRDUP(ERR_error_string(err, buf));
758 if ( ld->ld_error ) __etoa(ld->ld_error);
762 Debug( LDAP_DEBUG_ANY,"TLS: can't connect.\n",0,0,0);
764 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
765 LBER_SBIOD_LEVEL_TRANSPORT );
767 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
768 LBER_SBIOD_LEVEL_TRANSPORT );
777 * Call this to do a TLS accept on a sockbuf.
778 * Everything else is the same as with tls_connect.
781 ldap_pvt_tls_accept( Sockbuf *sb, void *ctx_arg )
786 if ( HAS_TLS( sb ) ) {
787 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&ssl );
790 ssl = alloc_handle( ctx_arg );
791 if ( ssl == NULL ) return -1;
794 ber_sockbuf_add_io( sb, &ber_sockbuf_io_debug,
795 LBER_SBIOD_LEVEL_TRANSPORT, (void *)"tls_" );
797 ber_sockbuf_add_io( sb, &sb_tls_sbio,
798 LBER_SBIOD_LEVEL_TRANSPORT, (void *)ssl );
801 err = SSL_accept( ssl );
804 errno = WSAGetLastError();
807 if ( update_flags( sb, ssl, err )) return 1;
809 Debug( LDAP_DEBUG_ANY,"TLS: can't accept.\n",0,0,0 );
812 ber_sockbuf_remove_io( sb, &sb_tls_sbio,
813 LBER_SBIOD_LEVEL_TRANSPORT );
815 ber_sockbuf_remove_io( sb, &ber_sockbuf_io_debug,
816 LBER_SBIOD_LEVEL_TRANSPORT );
825 ldap_pvt_tls_inplace ( Sockbuf *sb )
827 return HAS_TLS( sb ) ? 1 : 0;
831 ldap_tls_inplace( LDAP *ld )
836 rc = ldap_get_option( ld, LDAP_OPT_SOCKBUF, (void *)&sb );
837 if ( rc != LDAP_SUCCESS || sb == NULL ) {
841 return ldap_pvt_tls_inplace( sb );
845 tls_get_cert( SSL *s )
847 /* If peer cert was bad, treat as if no cert was given */
848 if (SSL_get_verify_result(s)) {
849 /* If we can send an alert, do so */
850 if (SSL_version(s) != SSL2_VERSION) {
851 ssl3_send_alert(s,SSL3_AL_WARNING,SSL3_AD_BAD_CERTIFICATE);
855 return SSL_get_peer_certificate(s);
859 ldap_pvt_tls_get_peer_dn( void *s, struct berval *dn,
860 LDAPDN_rewrite_dummy *func, unsigned flags )
866 x = tls_get_cert((SSL *)s);
868 if (!x) return LDAP_INVALID_CREDENTIALS;
870 xn = X509_get_subject_name(x);
871 rc = ldap_X509dn2bv(xn, dn, (LDAPDN_rewrite_func *)func, flags);
877 ldap_pvt_tls_get_peer_hostname( void *s )
884 x = tls_get_cert((SSL *)s);
887 xn = X509_get_subject_name(x);
889 ret = X509_NAME_get_text_by_NID(xn, NID_commonName, buf, sizeof(buf));
895 p = LDAP_STRDUP(buf);
900 /* what kind of hostname were we given? */
906 ldap_pvt_tls_check_hostname( LDAP *ld, void *s, const char *name_in )
908 int i, ret = LDAP_LOCAL_ERROR;
914 struct in6_addr addr;
919 if( ldap_int_hostname &&
920 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
922 name = ldap_int_hostname;
927 x = tls_get_cert((SSL *)s);
929 Debug( LDAP_DEBUG_ANY,
930 "TLS: unable to get peer certificate.\n",
932 /* If this was a fatal condition, things would have
933 * aborted long before now.
939 if (name[0] == '[' && strchr(name, ']')) {
940 char *n2 = ldap_strdup(name+1);
941 *strchr(n2, ']') = 2;
942 if (inet_pton(AF_INET6, n2, &addr))
947 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
948 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
951 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
954 STACK_OF(GENERAL_NAME) *alt;
956 ex = X509_get_ext(x, i);
957 alt = X509V3_EXT_d2i(ex);
959 int n, len1 = 0, len2 = 0;
963 if (ntype == IS_DNS) {
965 domain = strchr(name, '.');
967 len2 = len1 - (domain-name);
970 n = sk_GENERAL_NAME_num(alt);
971 for (i=0; i<n; i++) {
974 gn = sk_GENERAL_NAME_value(alt, i);
975 if (gn->type == GEN_DNS) {
976 if (ntype != IS_DNS) continue;
978 sn = (char *) ASN1_STRING_data(gn->d.ia5);
979 sl = ASN1_STRING_length(gn->d.ia5);
982 if (sl == 0) continue;
984 /* Is this an exact match? */
985 if ((len1 == sl) && !strncasecmp(name, sn, len1)) {
989 /* Is this a wildcard match? */
990 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
991 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
996 } else if (gn->type == GEN_IPADD) {
997 if (ntype == IS_DNS) continue;
999 sn = (char *) ASN1_STRING_data(gn->d.ia5);
1000 sl = ASN1_STRING_length(gn->d.ia5);
1002 #ifdef LDAP_PF_INET6
1003 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
1007 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
1010 if (!memcmp(sn, &addr, sl)) {
1016 GENERAL_NAMES_free(alt);
1017 if (i < n) { /* Found a match */
1023 if (ret != LDAP_SUCCESS) {
1028 xn = X509_get_subject_name(x);
1029 if( X509_NAME_get_text_by_NID( xn, NID_commonName,
1030 buf, sizeof(buf)) == -1)
1032 Debug( LDAP_DEBUG_ANY,
1033 "TLS: unable to get common name from peer certificate.\n",
1035 ret = LDAP_CONNECT_ERROR;
1036 ld->ld_error = LDAP_STRDUP(
1037 _("TLS: unable to get CN from peer certificate"));
1039 } else if (strcasecmp(name, buf) == 0 ) {
1042 } else if (( buf[0] == '*' ) && ( buf[1] == '.' )) {
1043 char *domain = strchr(name, '.');
1049 dlen = sl - (domain-name);
1052 /* Is this a wildcard match? */
1053 if ((dlen == sl-1) && !strncasecmp(domain, &buf[1], dlen)) {
1059 if( ret == LDAP_LOCAL_ERROR ) {
1060 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
1061 "common name in certificate (%s).\n",
1063 ret = LDAP_CONNECT_ERROR;
1064 ld->ld_error = LDAP_STRDUP(
1065 _("TLS: hostname does not match CN in peer certificate"));
1073 ldap_pvt_tls_get_peer_issuer( void *s )
1075 #if 0 /* currently unused; see ldap_pvt_tls_get_peer_dn() if needed */
1080 x = SSL_get_peer_certificate((SSL *)s);
1082 if (!x) return NULL;
1084 xn = X509_get_issuer_name(x);
1085 p = LDAP_STRDUP(X509_NAME_oneline(xn, buf, sizeof(buf)));
1094 ldap_int_tls_config( LDAP *ld, int option, const char *arg )
1099 case LDAP_OPT_X_TLS_CACERTFILE:
1100 case LDAP_OPT_X_TLS_CACERTDIR:
1101 case LDAP_OPT_X_TLS_CERTFILE:
1102 case LDAP_OPT_X_TLS_KEYFILE:
1103 case LDAP_OPT_X_TLS_RANDOM_FILE:
1104 case LDAP_OPT_X_TLS_CIPHER_SUITE:
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 );
1134 #ifdef HAVE_OPENSSL_CRL
1135 case LDAP_OPT_X_TLS_CRLCHECK:
1137 if ( strcasecmp( arg, "none" ) == 0 ) {
1138 i = LDAP_OPT_X_TLS_CRL_NONE ;
1139 } else if ( strcasecmp( arg, "peer" ) == 0 ) {
1140 i = LDAP_OPT_X_TLS_CRL_PEER ;
1141 } else if ( strcasecmp( arg, "all" ) == 0 ) {
1142 i = LDAP_OPT_X_TLS_CRL_ALL ;
1145 return ldap_pvt_tls_set_option( ld, option, &i );
1154 ldap_pvt_tls_get_option( LDAP *ld, int option, void *arg )
1156 struct ldapoptions *lo;
1159 assert( LDAP_VALID( ld ) );
1161 if( !LDAP_VALID( ld ) ) {
1162 return LDAP_OPT_ERROR;
1165 lo = &ld->ld_options;
1168 /* Get pointer to global option structure */
1169 lo = LDAP_INT_GLOBAL_OPT();
1171 return LDAP_NO_MEMORY;
1176 case LDAP_OPT_X_TLS:
1177 *(int *)arg = lo->ldo_tls_mode;
1179 case LDAP_OPT_X_TLS_CTX:
1181 *(void **)arg = (void *) tls_def_ctx;
1183 *(void **)arg = ld->ld_defconn->lconn_tls_ctx;
1186 case LDAP_OPT_X_TLS_CACERTFILE:
1187 *(char **)arg = tls_opt_cacertfile ?
1188 LDAP_STRDUP( tls_opt_cacertfile ) : NULL;
1190 case LDAP_OPT_X_TLS_CACERTDIR:
1191 *(char **)arg = tls_opt_cacertdir ?
1192 LDAP_STRDUP( tls_opt_cacertdir ) : NULL;
1194 case LDAP_OPT_X_TLS_CERTFILE:
1195 *(char **)arg = tls_opt_certfile ?
1196 LDAP_STRDUP( tls_opt_certfile ) : NULL;
1198 case LDAP_OPT_X_TLS_KEYFILE:
1199 *(char **)arg = tls_opt_keyfile ?
1200 LDAP_STRDUP( tls_opt_keyfile ) : NULL;
1202 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1203 *(int *)arg = tls_opt_require_cert;
1205 #ifdef HAVE_OPENSSL_CRL
1206 case LDAP_OPT_X_TLS_CRLCHECK:
1207 *(int *)arg = tls_opt_crlcheck;
1210 case LDAP_OPT_X_TLS_RANDOM_FILE:
1211 *(char **)arg = tls_opt_randfile ?
1212 LDAP_STRDUP( tls_opt_randfile ) : NULL;
1214 case LDAP_OPT_X_TLS_SSL_CTX: {
1217 LDAPConn *conn = ld->ld_defconn;
1218 if ( conn != NULL ) {
1219 Sockbuf *sb = conn->lconn_sb;
1220 retval = ldap_pvt_tls_sb_ctx( sb );
1223 *(void **)arg = retval;
1226 case LDAP_OPT_X_TLS_CONNECT_CB:
1227 *(LDAP_TLS_CONNECT_CB **)arg = lo->ldo_tls_connect_cb;
1229 case LDAP_OPT_X_TLS_CONNECT_ARG:
1230 *(void **)arg = lo->ldo_tls_connect_arg;
1239 ldap_pvt_tls_set_option( LDAP *ld, int option, void *arg )
1241 struct ldapoptions *lo;
1244 assert( LDAP_VALID( ld ) );
1246 if( !LDAP_VALID( ld ) ) {
1247 return LDAP_OPT_ERROR;
1250 lo = &ld->ld_options;
1253 /* Get pointer to global option structure */
1254 lo = LDAP_INT_GLOBAL_OPT();
1256 return LDAP_NO_MEMORY;
1261 case LDAP_OPT_X_TLS:
1262 switch( *(int *) arg ) {
1263 case LDAP_OPT_X_TLS_NEVER:
1264 case LDAP_OPT_X_TLS_DEMAND:
1265 case LDAP_OPT_X_TLS_ALLOW:
1266 case LDAP_OPT_X_TLS_TRY:
1267 case LDAP_OPT_X_TLS_HARD:
1269 lo->ldo_tls_mode = *(int *)arg;
1276 case LDAP_OPT_X_TLS_CTX:
1278 tls_def_ctx = (SSL_CTX *) arg;
1281 ld->ld_defconn->lconn_tls_ctx = arg;
1284 case LDAP_OPT_X_TLS_CONNECT_CB:
1285 lo->ldo_tls_connect_cb = (LDAP_TLS_CONNECT_CB *)arg;
1287 case LDAP_OPT_X_TLS_CONNECT_ARG:
1288 lo->ldo_tls_connect_arg = arg;
1297 case LDAP_OPT_X_TLS_CACERTFILE:
1298 if ( tls_opt_cacertfile ) LDAP_FREE( tls_opt_cacertfile );
1299 tls_opt_cacertfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1301 case LDAP_OPT_X_TLS_CACERTDIR:
1302 if ( tls_opt_cacertdir ) LDAP_FREE( tls_opt_cacertdir );
1303 tls_opt_cacertdir = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1305 case LDAP_OPT_X_TLS_CERTFILE:
1306 if ( tls_opt_certfile ) LDAP_FREE( tls_opt_certfile );
1307 tls_opt_certfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1309 case LDAP_OPT_X_TLS_KEYFILE:
1310 if ( tls_opt_keyfile ) LDAP_FREE( tls_opt_keyfile );
1311 tls_opt_keyfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1313 case LDAP_OPT_X_TLS_REQUIRE_CERT:
1314 switch( *(int *) arg ) {
1315 case LDAP_OPT_X_TLS_NEVER:
1316 case LDAP_OPT_X_TLS_DEMAND:
1317 case LDAP_OPT_X_TLS_ALLOW:
1318 case LDAP_OPT_X_TLS_TRY:
1319 case LDAP_OPT_X_TLS_HARD:
1320 tls_opt_require_cert = * (int *) arg;
1324 #ifdef HAVE_OPENSSL_CRL
1325 case LDAP_OPT_X_TLS_CRLCHECK:
1326 switch( *(int *) arg ) {
1327 case LDAP_OPT_X_TLS_CRL_NONE:
1328 case LDAP_OPT_X_TLS_CRL_PEER:
1329 case LDAP_OPT_X_TLS_CRL_ALL:
1330 tls_opt_crlcheck = * (int *) arg;
1335 case LDAP_OPT_X_TLS_CIPHER_SUITE:
1336 if ( tls_opt_ciphersuite ) LDAP_FREE( tls_opt_ciphersuite );
1337 tls_opt_ciphersuite = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1339 case LDAP_OPT_X_TLS_RANDOM_FILE:
1340 if (tls_opt_randfile ) LDAP_FREE (tls_opt_randfile );
1341 tls_opt_randfile = arg ? LDAP_STRDUP( (char *) arg ) : NULL;
1350 ldap_int_tls_start ( LDAP *ld, LDAPConn *conn, LDAPURLDesc *srv )
1352 Sockbuf *sb = conn->lconn_sb;
1357 host = srv->lud_host;
1359 host = conn->lconn_server->lud_host;
1362 /* avoid NULL host */
1363 if( host == NULL ) {
1367 (void) ldap_pvt_tls_init();
1370 * Fortunately, the lib uses blocking io...
1372 if ( ldap_int_tls_connect( ld, conn ) < 0 ) {
1373 ld->ld_errno = LDAP_CONNECT_ERROR;
1374 return (ld->ld_errno);
1377 ssl = ldap_pvt_tls_sb_ctx( sb );
1378 assert( ssl != NULL );
1381 * compare host with name(s) in certificate
1383 if (tls_opt_require_cert != LDAP_OPT_X_TLS_NEVER) {
1384 ld->ld_errno = ldap_pvt_tls_check_hostname( ld, ssl, host );
1385 if (ld->ld_errno != LDAP_SUCCESS) {
1386 return ld->ld_errno;
1390 return LDAP_SUCCESS;
1393 /* Derived from openssl/apps/s_cb.c */
1395 tls_info_cb( const SSL *ssl, int where, int ret )
1399 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1401 w = where & ~SSL_ST_MASK;
1402 if ( w & SSL_ST_CONNECT ) {
1404 } else if ( w & SSL_ST_ACCEPT ) {
1412 state = LDAP_STRDUP( state );
1416 if ( where & SSL_CB_LOOP ) {
1417 Debug( LDAP_DEBUG_TRACE,
1418 "TLS trace: %s:%s\n",
1421 } else if ( where & SSL_CB_ALERT ) {
1422 char *atype = (char *) SSL_alert_type_string_long( ret );
1423 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1424 op = ( where & SSL_CB_READ ) ? "read" : "write";
1427 atype = LDAP_STRDUP( atype );
1431 adesc = LDAP_STRDUP( adesc );
1435 Debug( LDAP_DEBUG_TRACE,
1436 "TLS trace: SSL3 alert %s:%s:%s\n",
1439 if ( atype ) LDAP_FREE( atype );
1440 if ( adesc ) LDAP_FREE( adesc );
1442 } else if ( where & SSL_CB_EXIT ) {
1444 Debug( LDAP_DEBUG_TRACE,
1445 "TLS trace: %s:failed in %s\n",
1447 } else if ( ret < 0 ) {
1448 Debug( LDAP_DEBUG_TRACE,
1449 "TLS trace: %s:error in %s\n",
1454 if ( state ) LDAP_FREE( state );
1459 tls_verify_cb( int ok, X509_STORE_CTX *ctx )
1468 char *certerr = NULL;
1470 cert = X509_STORE_CTX_get_current_cert( ctx );
1471 errnum = X509_STORE_CTX_get_error( ctx );
1472 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1475 * X509_get_*_name return pointers to the internal copies of
1476 * those things requested. So do not free them.
1478 subject = X509_get_subject_name( cert );
1479 issuer = X509_get_issuer_name( cert );
1480 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1481 sname = X509_NAME_oneline( subject, NULL, 0 );
1482 iname = X509_NAME_oneline( issuer, NULL, 0 );
1483 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1485 if ( sname ) __etoa( sname );
1486 if ( iname ) __etoa( iname );
1488 certerr = LDAP_STRDUP( certerr );
1492 Debug( LDAP_DEBUG_TRACE,
1493 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1495 sname ? sname : "-unknown-" );
1496 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1498 Debug( LDAP_DEBUG_ANY,
1499 "TLS certificate verification: Error, %s\n",
1503 CRYPTO_free ( sname );
1505 CRYPTO_free ( iname );
1507 if ( certerr ) LDAP_FREE( certerr );
1513 tls_verify_ok( int ok, X509_STORE_CTX *ctx )
1515 (void) tls_verify_cb( ok, ctx );
1519 /* Inspired by ERR_print_errors in OpenSSL */
1521 tls_report_error( void )
1528 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1529 ERR_error_string_n( l, buf, sizeof( buf ) );
1532 file = LDAP_STRDUP( file );
1533 __etoa( (char *)file );
1537 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1540 if ( file ) LDAP_FREE( (void *)file );
1546 tls_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1550 /* FIXME: Pregenerate the key on startup */
1551 /* FIXME: Who frees the key? */
1552 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1555 Debug( LDAP_DEBUG_ANY,
1556 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1557 key_length, is_export ? "export" : "domestic", 0 );
1564 tls_seed_PRNG( const char *randfile )
1566 #ifndef URANDOM_DEVICE
1567 /* no /dev/urandom (or equiv) */
1569 char buffer[MAXPATHLEN];
1571 if (randfile == NULL) {
1572 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1573 * If $HOME is not set or buffer too small to hold the pathname,
1574 * an error occurs. - From RAND_file_name() man page.
1575 * The fact is that when $HOME is NULL, .rnd is used.
1577 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1579 } else if (RAND_egd(randfile) > 0) {
1584 if (randfile == NULL) {
1585 Debug( LDAP_DEBUG_ANY,
1586 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1591 total = RAND_load_file(randfile, -1);
1593 if (RAND_status() == 0) {
1594 Debug( LDAP_DEBUG_ANY,
1595 "TLS: PRNG not been seeded with enough data\n",
1600 /* assume if there was enough bits to seed that it's okay
1601 * to write derived bits to the file
1603 RAND_write_file(randfile);
1612 tls_tmp_dh_cb( SSL *ssl, int is_export, int key_length )
1620 ldap_pvt_tls_sb_ctx( Sockbuf *sb )
1625 if (HAS_TLS( sb )) {
1626 ber_sockbuf_ctrl( sb, LBER_SB_OPT_GET_SSL, (void *)&p );
1635 ldap_pvt_tls_get_strength( void *s )
1640 c = SSL_get_current_cipher((SSL *)s);
1641 return SSL_CIPHER_get_bits(c, NULL);
1649 ldap_pvt_tls_get_my_dn( void *s, struct berval *dn, LDAPDN_rewrite_dummy *func, unsigned flags )
1656 x = SSL_get_certificate((SSL *)s);
1658 if (!x) return LDAP_INVALID_CREDENTIALS;
1660 xn = X509_get_subject_name(x);
1661 rc = ldap_X509dn2bv(xn, dn, (LDAPDN_rewrite_func *)func, flags );
1664 return LDAP_NOT_SUPPORTED;
1669 ldap_start_tls( LDAP *ld,
1670 LDAPControl **serverctrls,
1671 LDAPControl **clientctrls,
1674 return ldap_extended_operation( ld, LDAP_EXOP_START_TLS,
1675 NULL, serverctrls, clientctrls, msgidp );
1679 ldap_install_tls( LDAP *ld )
1682 return LDAP_NOT_SUPPORTED;
1684 if ( ld->ld_sb != NULL && ldap_pvt_tls_inplace( ld->ld_sb ) != 0 ) {
1685 return LDAP_LOCAL_ERROR;
1688 return ldap_int_tls_start( ld, ld->ld_defconn, NULL );
1693 ldap_start_tls_s ( LDAP *ld,
1694 LDAPControl **serverctrls,
1695 LDAPControl **clientctrls )
1698 return LDAP_NOT_SUPPORTED;
1701 char *rspoid = NULL;
1702 struct berval *rspdata = NULL;
1704 /* XXYYZ: this initiates operation only on default connection! */
1706 if ( ld->ld_sb != NULL && ldap_pvt_tls_inplace( ld->ld_sb ) != 0 ) {
1707 return LDAP_LOCAL_ERROR;
1710 rc = ldap_extended_operation_s( ld, LDAP_EXOP_START_TLS,
1711 NULL, serverctrls, clientctrls, &rspoid, &rspdata );
1713 if ( rspoid != NULL ) {
1717 if ( rspdata != NULL ) {
1718 ber_bvfree( rspdata );
1721 if ( rc == LDAP_SUCCESS ) {
1722 rc = ldap_int_tls_start( ld, ld->ld_defconn, NULL );