1 /* tls_o.c - Handle tls/ssl using OpenSSL */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2017 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>.
16 /* ACKNOWLEDGEMENTS: Rewritten by Howard Chu
23 #include "ldap_config.h"
27 #include <ac/stdlib.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
33 #include <ac/unistd.h>
35 #include <ac/dirent.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 #if OPENSSL_VERSION_NUMBER >= 0x10100000
51 #define ASN1_STRING_data(x) ASN1_STRING_get0_data(x)
54 typedef SSL_CTX tlso_ctx;
55 typedef SSL tlso_session;
57 static int tlso_opt_trace = 1;
59 static void tlso_report_error( void );
61 static void tlso_info_cb( const SSL *ssl, int where, int ret );
62 static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
63 static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
64 static int tlso_seed_PRNG( const char *randfile );
65 #if OPENSSL_VERSION_NUMBER < 0x10100000
67 * OpenSSL 1.1 API and later has new locking code
69 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
73 * provide mutexes for the OpenSSL library.
75 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
77 static void tlso_locking_cb( int mode, int type, const char *file, int line )
79 if ( mode & CRYPTO_LOCK ) {
80 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
82 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
86 static unsigned long tlso_thread_self( void )
88 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
89 * is an integral type that fits in an unsigned long
92 /* force an error if the ldap_pvt_thread_t type is too large */
93 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
94 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
96 return (unsigned long) ldap_pvt_thread_self();
99 static void tlso_thr_init( void )
103 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
104 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
106 CRYPTO_set_locking_callback( tlso_locking_cb );
107 CRYPTO_set_id_callback( tlso_thread_self );
109 #endif /* LDAP_R_COMPILE */
111 #ifdef LDAP_R_COMPILE
112 static void tlso_thr_init( void ) {}
114 #endif /* OpenSSL 1.1 */
116 static STACK_OF(X509_NAME) *
117 tlso_ca_list( char * bundle, char * dir )
119 STACK_OF(X509_NAME) *ca_list = NULL;
122 ca_list = SSL_load_client_CA_file( bundle );
124 #if defined(HAVE_DIRENT_H) || defined(dirent)
129 ca_list = sk_X509_NAME_new_null();
132 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
134 sk_X509_NAME_free( ca_list );
143 * Initialize TLS subsystem. Should be called only once.
148 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
151 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
152 if ( file ) __atoe( file );
153 (void) tlso_seed_PRNG( file );
157 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
160 #if OPENSSL_VERSION_NUMBER < 0x10100000
161 SSL_load_error_strings();
163 OpenSSL_add_all_digests();
165 OPENSSL_init_ssl(0, NULL);
168 /* FIXME: mod_ssl does this */
169 X509V3_add_standard_extensions();
175 * Tear down the TLS subsystem. Should only be called once.
180 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
182 #if OPENSSL_VERSION_NUMBER < 0x10100000
184 #if OPENSSL_VERSION_NUMBER < 0x10000000
187 ERR_remove_thread_state(NULL);
192 if ( lo->ldo_tls_randfile ) {
193 LDAP_FREE( lo->ldo_tls_randfile );
194 lo->ldo_tls_randfile = NULL;
199 tlso_ctx_new( struct ldapoptions *lo )
201 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
205 tlso_ctx_ref( tls_ctx *ctx )
207 tlso_ctx *c = (tlso_ctx *)ctx;
208 #if OPENSSL_VERSION_NUMBER < 0x10100000
209 #define SSL_CTX_up_ref(ctx) CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
215 tlso_ctx_free ( tls_ctx *ctx )
217 tlso_ctx *c = (tlso_ctx *)ctx;
222 * initialize a new TLS context
225 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
227 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
231 SSL_CTX_set_session_id_context( ctx,
232 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
235 #ifdef SSL_OP_NO_TLSv1
236 #ifdef SSL_OP_NO_TLSv1_1
237 #ifdef SSL_OP_NO_TLSv1_2
238 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
239 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
240 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
244 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
245 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
246 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
249 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
250 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
254 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
255 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
256 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
257 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
259 if ( lo->ldo_tls_ciphersuite &&
260 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
262 Debug( LDAP_DEBUG_ANY,
263 "TLS: could not set cipher list %s.\n",
264 lo->ldo_tls_ciphersuite, 0, 0 );
269 if ( lo->ldo_tls_cacertfile == NULL && lo->ldo_tls_cacertdir == NULL ) {
270 if ( !SSL_CTX_set_default_verify_paths( ctx ) ) {
271 Debug( LDAP_DEBUG_ANY, "TLS: "
272 "could not use default certificate paths", 0, 0, 0 );
277 if ( !SSL_CTX_load_verify_locations( ctx,
278 lt->lt_cacertfile, lt->lt_cacertdir ) )
280 Debug( LDAP_DEBUG_ANY, "TLS: "
281 "could not load verify locations (file:`%s',dir:`%s').\n",
282 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
283 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
290 STACK_OF(X509_NAME) *calist;
291 /* List of CA names to send to a client */
292 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
294 Debug( LDAP_DEBUG_ANY, "TLS: "
295 "could not load client CA list (file:`%s',dir:`%s').\n",
296 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
297 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
303 SSL_CTX_set_client_CA_list( ctx, calist );
307 if ( lo->ldo_tls_certfile &&
308 !SSL_CTX_use_certificate_file( ctx,
309 lt->lt_certfile, SSL_FILETYPE_PEM ) )
311 Debug( LDAP_DEBUG_ANY,
312 "TLS: could not use certificate `%s'.\n",
313 lo->ldo_tls_certfile,0,0);
318 /* Key validity is checked automatically if cert has already been set */
319 if ( lo->ldo_tls_keyfile &&
320 !SSL_CTX_use_PrivateKey_file( ctx,
321 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
323 Debug( LDAP_DEBUG_ANY,
324 "TLS: could not use key file `%s'.\n",
325 lo->ldo_tls_keyfile,0,0);
330 if ( lo->ldo_tls_dhfile ) {
333 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
335 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
336 Debug( LDAP_DEBUG_ANY,
337 "TLS: could not use DH parameters file `%s'.\n",
338 lo->ldo_tls_dhfile,0,0);
342 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
343 Debug( LDAP_DEBUG_ANY,
344 "TLS: could not read DH parameters file `%s'.\n",
345 lo->ldo_tls_dhfile,0,0);
351 SSL_CTX_set_tmp_dh( ctx, dh );
354 if ( tlso_opt_trace ) {
355 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
359 if ( lo->ldo_tls_require_cert ) {
361 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
362 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
363 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
367 SSL_CTX_set_verify( ctx, i,
368 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
369 tlso_verify_ok : tlso_verify_cb );
370 #if OPENSSL_VERSION_NUMBER < 0x10100000
371 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
373 #ifdef HAVE_OPENSSL_CRL
374 if ( lo->ldo_tls_crlcheck ) {
375 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
376 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
377 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
378 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
379 X509_STORE_set_flags( x509_s,
380 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
388 tlso_session_new( tls_ctx *ctx, int is_server )
390 tlso_ctx *c = (tlso_ctx *)ctx;
391 return (tls_session *)SSL_new( c );
395 tlso_session_connect( LDAP *ld, tls_session *sess )
397 tlso_session *s = (tlso_session *)sess;
399 /* Caller expects 0 = success, OpenSSL returns 1 = success */
400 return SSL_connect( s ) - 1;
404 tlso_session_accept( tls_session *sess )
406 tlso_session *s = (tlso_session *)sess;
408 /* Caller expects 0 = success, OpenSSL returns 1 = success */
409 return SSL_accept( s ) - 1;
413 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
415 tlso_session *s = (tlso_session *)sess;
417 /* 1 was subtracted above, offset it back now */
418 rc = SSL_get_error(s, rc+1);
419 if (rc == SSL_ERROR_WANT_READ) {
420 sb->sb_trans_needs_read = 1;
423 } else if (rc == SSL_ERROR_WANT_WRITE) {
424 sb->sb_trans_needs_write = 1;
427 } else if (rc == SSL_ERROR_WANT_CONNECT) {
434 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
437 const char *certerr=NULL;
438 tlso_session *s = (tlso_session *)sess;
440 rc = ERR_peek_error();
442 ERR_error_string_n( rc, err, sizeof(err) );
443 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
444 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
445 int certrc = SSL_get_verify_result(s);
446 certerr = (char *)X509_verify_cert_error_string(certrc);
448 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
449 certerr ? certerr : "", certerr ? ")" : "" );
456 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
458 tlso_session *s = (tlso_session *)sess;
462 x = SSL_get_certificate( s );
464 if (!x) return LDAP_INVALID_CREDENTIALS;
466 xn = X509_get_subject_name(x);
467 #if OPENSSL_VERSION_NUMBER < 0x10100000
468 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
469 der_dn->bv_val = xn->bytes->data;
473 der_dn->bv_val = NULL;
474 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
475 der_dn->bv_len = len;
478 /* Don't X509_free, the session is still using it */
483 tlso_get_cert( SSL *s )
485 /* If peer cert was bad, treat as if no cert was given */
486 if (SSL_get_verify_result(s)) {
489 return SSL_get_peer_certificate(s);
493 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
495 tlso_session *s = (tlso_session *)sess;
496 X509 *x = tlso_get_cert( s );
500 return LDAP_INVALID_CREDENTIALS;
502 xn = X509_get_subject_name(x);
503 #if OPENSSL_VERSION_NUMBER < 0x10100000
504 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
505 der_dn->bv_val = xn->bytes->data;
509 der_dn->bv_val = NULL;
510 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
511 der_dn->bv_len = len;
518 /* what kind of hostname were we given? */
524 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
526 tlso_session *s = (tlso_session *)sess;
527 int i, ret = LDAP_LOCAL_ERROR;
531 int ntype = IS_DNS, nlen;
533 struct in6_addr addr;
538 if( ldap_int_hostname &&
539 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
541 name = ldap_int_hostname;
547 x = tlso_get_cert(s);
549 Debug( LDAP_DEBUG_ANY,
550 "TLS: unable to get peer certificate.\n",
552 /* If this was a fatal condition, things would have
553 * aborted long before now.
559 if (inet_pton(AF_INET6, name, &addr)) {
563 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
564 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
567 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
570 STACK_OF(GENERAL_NAME) *alt;
572 ex = X509_get_ext(x, i);
573 alt = X509V3_EXT_d2i(ex);
579 if (ntype == IS_DNS) {
580 domain = strchr(name, '.');
582 len2 = nlen - (domain-name);
585 n = sk_GENERAL_NAME_num(alt);
586 for (i=0; i<n; i++) {
589 gn = sk_GENERAL_NAME_value(alt, i);
590 if (gn->type == GEN_DNS) {
591 if (ntype != IS_DNS) continue;
593 sn = (char *) ASN1_STRING_data(gn->d.ia5);
594 sl = ASN1_STRING_length(gn->d.ia5);
597 if (sl == 0) continue;
599 /* Is this an exact match? */
600 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
604 /* Is this a wildcard match? */
605 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
606 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
611 } else if (gn->type == GEN_IPADD) {
612 if (ntype == IS_DNS) continue;
614 sn = (char *) ASN1_STRING_data(gn->d.ia5);
615 sl = ASN1_STRING_length(gn->d.ia5);
618 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
622 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
625 if (!memcmp(sn, &addr, sl)) {
631 GENERAL_NAMES_free(alt);
632 if (i < n) { /* Found a match */
638 if (ret != LDAP_SUCCESS) {
642 ASN1_STRING *cn = NULL;
645 /* find the last CN */
646 obj = OBJ_nid2obj( NID_commonName );
647 if ( !obj ) goto no_cn; /* should never happen */
649 xn = X509_get_subject_name(x);
650 navas = X509_NAME_entry_count( xn );
651 for ( i=navas-1; i>=0; i-- ) {
652 ne = X509_NAME_get_entry( xn, i );
653 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
654 cn = X509_NAME_ENTRY_get_data( ne );
662 Debug( LDAP_DEBUG_ANY,
663 "TLS: unable to get common name from peer certificate.\n",
665 ret = LDAP_CONNECT_ERROR;
666 if ( ld->ld_error ) {
667 LDAP_FREE( ld->ld_error );
669 ld->ld_error = LDAP_STRDUP(
670 _("TLS: unable to get CN from peer certificate"));
672 } else if ( cn->length == nlen &&
673 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
676 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
677 char *domain = strchr(name, '.');
681 dlen = nlen - (domain-name);
683 /* Is this a wildcard match? */
684 if ((dlen == cn->length-1) &&
685 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
691 if( ret == LDAP_LOCAL_ERROR ) {
692 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
693 "common name in certificate (%.*s).\n",
694 name, cn->length, cn->data );
695 ret = LDAP_CONNECT_ERROR;
696 if ( ld->ld_error ) {
697 LDAP_FREE( ld->ld_error );
699 ld->ld_error = LDAP_STRDUP(
700 _("TLS: hostname does not match CN in peer certificate"));
708 tlso_session_strength( tls_session *sess )
710 tlso_session *s = (tlso_session *)sess;
712 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
716 * TLS support for LBER Sockbufs
720 tlso_session *session;
721 Sockbuf_IO_Desc *sbiod;
724 #if OPENSSL_VERSION_NUMBER < 0x10100000
725 #define BIO_set_init(b, x) b->init = x
726 #define BIO_set_data(b, x) b->ptr = x
727 #define BIO_clear_flags(b, x) b->flags &= ~(x)
728 #define BIO_get_data(b) b->ptr
731 tlso_bio_create( BIO *b ) {
732 BIO_set_init( b, 1 );
733 BIO_set_data( b, NULL );
734 BIO_clear_flags( b, ~0 );
739 tlso_bio_destroy( BIO *b )
741 if ( b == NULL ) return 0;
743 BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
744 BIO_set_init( b, 0 );
745 BIO_clear_flags( b, ~0 );
750 tlso_bio_read( BIO *b, char *buf, int len )
755 if ( buf == NULL || len <= 0 ) return 0;
757 p = (struct tls_data *)BIO_get_data(b);
759 if ( p == NULL || p->sbiod == NULL ) {
763 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
765 BIO_clear_retry_flags( b );
767 int err = sock_errno();
768 if ( err == EAGAIN || err == EWOULDBLOCK ) {
769 BIO_set_retry_read( b );
777 tlso_bio_write( BIO *b, const char *buf, int len )
782 if ( buf == NULL || len <= 0 ) return 0;
784 p = (struct tls_data *)BIO_get_data(b);
786 if ( p == NULL || p->sbiod == NULL ) {
790 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
792 BIO_clear_retry_flags( b );
794 int err = sock_errno();
795 if ( err == EAGAIN || err == EWOULDBLOCK ) {
796 BIO_set_retry_write( b );
804 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
806 if ( cmd == BIO_CTRL_FLUSH ) {
807 /* The OpenSSL library needs this */
814 tlso_bio_gets( BIO *b, char *buf, int len )
820 tlso_bio_puts( BIO *b, const char *str )
822 return tlso_bio_write( b, str, strlen( str ) );
825 #if OPENSSL_VERSION_NUMBER >= 0x10100000
826 struct bio_method_st {
829 int (*bwrite) (BIO *, const char *, int);
830 int (*bread) (BIO *, char *, int);
831 int (*bputs) (BIO *, const char *);
832 int (*bgets) (BIO *, char *, int);
833 long (*ctrl) (BIO *, int, long, void *);
834 int (*create) (BIO *);
835 int (*destroy) (BIO *);
836 long (*callback_ctrl) (BIO *, int, bio_info_cb *);
840 static BIO_METHOD tlso_bio_method =
842 ( 100 | 0x400 ), /* it's a source/sink BIO */
854 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
859 assert( sbiod != NULL );
861 p = LBER_MALLOC( sizeof( *p ) );
868 bio = BIO_new( &tlso_bio_method );
869 BIO_set_data( bio, p );
870 SSL_set_bio( p->session, bio, bio );
871 sbiod->sbiod_pvt = p;
876 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
880 assert( sbiod != NULL );
881 assert( sbiod->sbiod_pvt != NULL );
883 p = (struct tls_data *)sbiod->sbiod_pvt;
884 SSL_free( p->session );
885 LBER_FREE( sbiod->sbiod_pvt );
886 sbiod->sbiod_pvt = NULL;
891 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
895 assert( sbiod != NULL );
896 assert( sbiod->sbiod_pvt != NULL );
898 p = (struct tls_data *)sbiod->sbiod_pvt;
899 SSL_shutdown( p->session );
904 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
908 assert( sbiod != NULL );
909 assert( sbiod->sbiod_pvt != NULL );
911 p = (struct tls_data *)sbiod->sbiod_pvt;
913 if ( opt == LBER_SB_OPT_GET_SSL ) {
914 *((tlso_session **)arg) = p->session;
917 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
918 if( SSL_pending( p->session ) > 0 ) {
923 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
927 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
933 assert( sbiod != NULL );
934 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
936 p = (struct tls_data *)sbiod->sbiod_pvt;
938 ret = SSL_read( p->session, (char *)buf, len );
940 errno = WSAGetLastError();
942 err = SSL_get_error( p->session, ret );
943 if (err == SSL_ERROR_WANT_READ ) {
944 sbiod->sbiod_sb->sb_trans_needs_read = 1;
945 sock_errset(EWOULDBLOCK);
948 sbiod->sbiod_sb->sb_trans_needs_read = 0;
953 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
959 assert( sbiod != NULL );
960 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
962 p = (struct tls_data *)sbiod->sbiod_pvt;
964 ret = SSL_write( p->session, (char *)buf, len );
966 errno = WSAGetLastError();
968 err = SSL_get_error( p->session, ret );
969 if (err == SSL_ERROR_WANT_WRITE ) {
970 sbiod->sbiod_sb->sb_trans_needs_write = 1;
971 sock_errset(EWOULDBLOCK);
974 sbiod->sbiod_sb->sb_trans_needs_write = 0;
979 static Sockbuf_IO tlso_sbio =
981 tlso_sb_setup, /* sbi_setup */
982 tlso_sb_remove, /* sbi_remove */
983 tlso_sb_ctrl, /* sbi_ctrl */
984 tlso_sb_read, /* sbi_read */
985 tlso_sb_write, /* sbi_write */
986 tlso_sb_close /* sbi_close */
989 /* Derived from openssl/apps/s_cb.c */
991 tlso_info_cb( const SSL *ssl, int where, int ret )
995 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
997 w = where & ~SSL_ST_MASK;
998 if ( w & SSL_ST_CONNECT ) {
1000 } else if ( w & SSL_ST_ACCEPT ) {
1008 state = LDAP_STRDUP( state );
1012 if ( where & SSL_CB_LOOP ) {
1013 Debug( LDAP_DEBUG_TRACE,
1014 "TLS trace: %s:%s\n",
1017 } else if ( where & SSL_CB_ALERT ) {
1018 char *atype = (char *) SSL_alert_type_string_long( ret );
1019 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1020 op = ( where & SSL_CB_READ ) ? "read" : "write";
1023 atype = LDAP_STRDUP( atype );
1027 adesc = LDAP_STRDUP( adesc );
1031 Debug( LDAP_DEBUG_TRACE,
1032 "TLS trace: SSL3 alert %s:%s:%s\n",
1035 if ( atype ) LDAP_FREE( atype );
1036 if ( adesc ) LDAP_FREE( adesc );
1038 } else if ( where & SSL_CB_EXIT ) {
1040 Debug( LDAP_DEBUG_TRACE,
1041 "TLS trace: %s:failed in %s\n",
1043 } else if ( ret < 0 ) {
1044 Debug( LDAP_DEBUG_TRACE,
1045 "TLS trace: %s:error in %s\n",
1050 if ( state ) LDAP_FREE( state );
1055 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1064 char *certerr = NULL;
1066 cert = X509_STORE_CTX_get_current_cert( ctx );
1067 errnum = X509_STORE_CTX_get_error( ctx );
1068 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1071 * X509_get_*_name return pointers to the internal copies of
1072 * those things requested. So do not free them.
1074 subject = X509_get_subject_name( cert );
1075 issuer = X509_get_issuer_name( cert );
1076 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1077 sname = X509_NAME_oneline( subject, NULL, 0 );
1078 iname = X509_NAME_oneline( issuer, NULL, 0 );
1079 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1081 if ( sname ) __etoa( sname );
1082 if ( iname ) __etoa( iname );
1084 certerr = LDAP_STRDUP( certerr );
1088 Debug( LDAP_DEBUG_TRACE,
1089 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1091 sname ? sname : "-unknown-" );
1092 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1094 Debug( LDAP_DEBUG_ANY,
1095 "TLS certificate verification: Error, %s\n",
1099 OPENSSL_free ( sname );
1101 OPENSSL_free ( iname );
1103 if ( certerr ) LDAP_FREE( certerr );
1109 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1111 (void) tlso_verify_cb( ok, ctx );
1115 /* Inspired by ERR_print_errors in OpenSSL */
1117 tlso_report_error( void )
1124 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1125 ERR_error_string_n( l, buf, sizeof( buf ) );
1128 file = LDAP_STRDUP( file );
1129 __etoa( (char *)file );
1133 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1136 if ( file ) LDAP_FREE( (void *)file );
1141 #if OPENSSL_VERSION_NUMBER < 0x10100000
1143 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1146 /* FIXME: Pregenerate the key on startup */
1147 /* FIXME: Who frees the key? */
1148 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1149 BIGNUM *bn = BN_new();
1152 if ( BN_set_word( bn, RSA_F4 )) {
1153 tmp_rsa = RSA_new();
1154 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1155 RSA_free( tmp_rsa );
1162 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1166 Debug( LDAP_DEBUG_ANY,
1167 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1168 key_length, is_export ? "export" : "domestic", 0 );
1172 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1175 tlso_seed_PRNG( const char *randfile )
1177 #ifndef URANDOM_DEVICE
1178 /* no /dev/urandom (or equiv) */
1180 char buffer[MAXPATHLEN];
1182 if (randfile == NULL) {
1183 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1184 * If $HOME is not set or buffer too small to hold the pathname,
1185 * an error occurs. - From RAND_file_name() man page.
1186 * The fact is that when $HOME is NULL, .rnd is used.
1188 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1190 #ifndef OPENSSL_NO_EGD
1191 else if (RAND_egd(randfile) > 0) {
1197 if (randfile == NULL) {
1198 Debug( LDAP_DEBUG_ANY,
1199 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1204 total = RAND_load_file(randfile, -1);
1206 if (RAND_status() == 0) {
1207 Debug( LDAP_DEBUG_ANY,
1208 "TLS: PRNG not been seeded with enough data\n",
1213 /* assume if there was enough bits to seed that it's okay
1214 * to write derived bits to the file
1216 RAND_write_file(randfile);
1224 tls_impl ldap_int_tls_impl = {
1236 tlso_session_connect,
1237 tlso_session_accept,
1238 tlso_session_upflags,
1239 tlso_session_errmsg,
1241 tlso_session_peer_dn,
1242 tlso_session_chkhost,
1243 tlso_session_strength,
1247 #ifdef LDAP_R_COMPILE
1256 #endif /* HAVE_OPENSSL */