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 */
110 #endif /* OpenSSL 1.1 */
112 static STACK_OF(X509_NAME) *
113 tlso_ca_list( char * bundle, char * dir )
115 STACK_OF(X509_NAME) *ca_list = NULL;
118 ca_list = SSL_load_client_CA_file( bundle );
120 #if defined(HAVE_DIRENT_H) || defined(dirent)
125 ca_list = sk_X509_NAME_new_null();
128 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
130 sk_X509_NAME_free( ca_list );
139 * Initialize TLS subsystem. Should be called only once.
144 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
147 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
148 if ( file ) __atoe( file );
149 (void) tlso_seed_PRNG( file );
153 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
156 #if OPENSSL_VERSION_NUMBER < 0x10100000
157 SSL_load_error_strings();
159 OpenSSL_add_all_digests();
161 OPENSSL_init_ssl(0, NULL);
164 /* FIXME: mod_ssl does this */
165 X509V3_add_standard_extensions();
171 * Tear down the TLS subsystem. Should only be called once.
176 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
178 #if OPENSSL_VERSION_NUMBER < 0x10100000
180 #if OPENSSL_VERSION_NUMBER < 0x10000000
183 ERR_remove_thread_state(NULL);
188 if ( lo->ldo_tls_randfile ) {
189 LDAP_FREE( lo->ldo_tls_randfile );
190 lo->ldo_tls_randfile = NULL;
195 tlso_ctx_new( struct ldapoptions *lo )
197 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
201 tlso_ctx_ref( tls_ctx *ctx )
203 tlso_ctx *c = (tlso_ctx *)ctx;
204 #if OPENSSL_VERSION_NUMBER < 0x10100000
205 #define SSL_CTX_up_ref(ctx) CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
211 tlso_ctx_free ( tls_ctx *ctx )
213 tlso_ctx *c = (tlso_ctx *)ctx;
218 * initialize a new TLS context
221 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
223 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
227 SSL_CTX_set_session_id_context( ctx,
228 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
231 #ifdef SSL_OP_NO_TLSv1
232 #ifdef SSL_OP_NO_TLSv1_1
233 #ifdef SSL_OP_NO_TLSv1_2
234 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
235 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
236 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
240 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
241 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
242 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
245 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
246 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
250 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
251 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
252 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
253 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
255 if ( lo->ldo_tls_ciphersuite &&
256 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
258 Debug( LDAP_DEBUG_ANY,
259 "TLS: could not set cipher list %s.\n",
260 lo->ldo_tls_ciphersuite, 0, 0 );
265 if ( lo->ldo_tls_cacertfile == NULL && lo->ldo_tls_cacertdir == NULL ) {
266 if ( !SSL_CTX_set_default_verify_paths( ctx ) ) {
267 Debug( LDAP_DEBUG_ANY, "TLS: "
268 "could not use default certificate paths", 0, 0, 0 );
273 if ( !SSL_CTX_load_verify_locations( ctx,
274 lt->lt_cacertfile, lt->lt_cacertdir ) )
276 Debug( LDAP_DEBUG_ANY, "TLS: "
277 "could not load verify locations (file:`%s',dir:`%s').\n",
278 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
279 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
286 STACK_OF(X509_NAME) *calist;
287 /* List of CA names to send to a client */
288 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
290 Debug( LDAP_DEBUG_ANY, "TLS: "
291 "could not load client CA list (file:`%s',dir:`%s').\n",
292 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
293 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
299 SSL_CTX_set_client_CA_list( ctx, calist );
303 if ( lo->ldo_tls_certfile &&
304 !SSL_CTX_use_certificate_file( ctx,
305 lt->lt_certfile, SSL_FILETYPE_PEM ) )
307 Debug( LDAP_DEBUG_ANY,
308 "TLS: could not use certificate `%s'.\n",
309 lo->ldo_tls_certfile,0,0);
314 /* Key validity is checked automatically if cert has already been set */
315 if ( lo->ldo_tls_keyfile &&
316 !SSL_CTX_use_PrivateKey_file( ctx,
317 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
319 Debug( LDAP_DEBUG_ANY,
320 "TLS: could not use key file `%s'.\n",
321 lo->ldo_tls_keyfile,0,0);
326 if ( lo->ldo_tls_dhfile ) {
329 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
331 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
332 Debug( LDAP_DEBUG_ANY,
333 "TLS: could not use DH parameters file `%s'.\n",
334 lo->ldo_tls_dhfile,0,0);
338 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
339 Debug( LDAP_DEBUG_ANY,
340 "TLS: could not read DH parameters file `%s'.\n",
341 lo->ldo_tls_dhfile,0,0);
347 SSL_CTX_set_tmp_dh( ctx, dh );
350 if ( tlso_opt_trace ) {
351 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
355 if ( lo->ldo_tls_require_cert ) {
357 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
358 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
359 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
363 SSL_CTX_set_verify( ctx, i,
364 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
365 tlso_verify_ok : tlso_verify_cb );
366 #if OPENSSL_VERSION_NUMBER < 0x10100000
367 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
369 #ifdef HAVE_OPENSSL_CRL
370 if ( lo->ldo_tls_crlcheck ) {
371 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
372 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
373 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
374 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
375 X509_STORE_set_flags( x509_s,
376 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
384 tlso_session_new( tls_ctx *ctx, int is_server )
386 tlso_ctx *c = (tlso_ctx *)ctx;
387 return (tls_session *)SSL_new( c );
391 tlso_session_connect( LDAP *ld, tls_session *sess )
393 tlso_session *s = (tlso_session *)sess;
395 /* Caller expects 0 = success, OpenSSL returns 1 = success */
396 return SSL_connect( s ) - 1;
400 tlso_session_accept( tls_session *sess )
402 tlso_session *s = (tlso_session *)sess;
404 /* Caller expects 0 = success, OpenSSL returns 1 = success */
405 return SSL_accept( s ) - 1;
409 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
411 tlso_session *s = (tlso_session *)sess;
413 /* 1 was subtracted above, offset it back now */
414 rc = SSL_get_error(s, rc+1);
415 if (rc == SSL_ERROR_WANT_READ) {
416 sb->sb_trans_needs_read = 1;
419 } else if (rc == SSL_ERROR_WANT_WRITE) {
420 sb->sb_trans_needs_write = 1;
423 } else if (rc == SSL_ERROR_WANT_CONNECT) {
430 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
433 const char *certerr=NULL;
434 tlso_session *s = (tlso_session *)sess;
436 rc = ERR_peek_error();
438 ERR_error_string_n( rc, err, sizeof(err) );
439 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
440 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
441 int certrc = SSL_get_verify_result(s);
442 certerr = (char *)X509_verify_cert_error_string(certrc);
444 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
445 certerr ? certerr : "", certerr ? ")" : "" );
452 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
454 tlso_session *s = (tlso_session *)sess;
458 x = SSL_get_certificate( s );
460 if (!x) return LDAP_INVALID_CREDENTIALS;
462 xn = X509_get_subject_name(x);
463 #if OPENSSL_VERSION_NUMBER < 0x10100000
464 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
465 der_dn->bv_val = xn->bytes->data;
469 der_dn->bv_val = NULL;
470 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
471 der_dn->bv_len = len;
474 /* Don't X509_free, the session is still using it */
479 tlso_get_cert( SSL *s )
481 /* If peer cert was bad, treat as if no cert was given */
482 if (SSL_get_verify_result(s)) {
485 return SSL_get_peer_certificate(s);
489 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
491 tlso_session *s = (tlso_session *)sess;
492 X509 *x = tlso_get_cert( s );
496 return LDAP_INVALID_CREDENTIALS;
498 xn = X509_get_subject_name(x);
499 #if OPENSSL_VERSION_NUMBER < 0x10100000
500 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
501 der_dn->bv_val = xn->bytes->data;
505 der_dn->bv_val = NULL;
506 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
507 der_dn->bv_len = len;
514 /* what kind of hostname were we given? */
520 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
522 tlso_session *s = (tlso_session *)sess;
523 int i, ret = LDAP_LOCAL_ERROR;
527 int ntype = IS_DNS, nlen;
529 struct in6_addr addr;
534 if( ldap_int_hostname &&
535 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
537 name = ldap_int_hostname;
543 x = tlso_get_cert(s);
545 Debug( LDAP_DEBUG_ANY,
546 "TLS: unable to get peer certificate.\n",
548 /* If this was a fatal condition, things would have
549 * aborted long before now.
555 if (inet_pton(AF_INET6, name, &addr)) {
559 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
560 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
563 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
566 STACK_OF(GENERAL_NAME) *alt;
568 ex = X509_get_ext(x, i);
569 alt = X509V3_EXT_d2i(ex);
575 if (ntype == IS_DNS) {
576 domain = strchr(name, '.');
578 len2 = nlen - (domain-name);
581 n = sk_GENERAL_NAME_num(alt);
582 for (i=0; i<n; i++) {
585 gn = sk_GENERAL_NAME_value(alt, i);
586 if (gn->type == GEN_DNS) {
587 if (ntype != IS_DNS) continue;
589 sn = (char *) ASN1_STRING_data(gn->d.ia5);
590 sl = ASN1_STRING_length(gn->d.ia5);
593 if (sl == 0) continue;
595 /* Is this an exact match? */
596 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
600 /* Is this a wildcard match? */
601 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
602 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
607 } else if (gn->type == GEN_IPADD) {
608 if (ntype == IS_DNS) continue;
610 sn = (char *) ASN1_STRING_data(gn->d.ia5);
611 sl = ASN1_STRING_length(gn->d.ia5);
614 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
618 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
621 if (!memcmp(sn, &addr, sl)) {
627 GENERAL_NAMES_free(alt);
628 if (i < n) { /* Found a match */
634 if (ret != LDAP_SUCCESS) {
638 ASN1_STRING *cn = NULL;
641 /* find the last CN */
642 obj = OBJ_nid2obj( NID_commonName );
643 if ( !obj ) goto no_cn; /* should never happen */
645 xn = X509_get_subject_name(x);
646 navas = X509_NAME_entry_count( xn );
647 for ( i=navas-1; i>=0; i-- ) {
648 ne = X509_NAME_get_entry( xn, i );
649 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
650 cn = X509_NAME_ENTRY_get_data( ne );
658 Debug( LDAP_DEBUG_ANY,
659 "TLS: unable to get common name from peer certificate.\n",
661 ret = LDAP_CONNECT_ERROR;
662 if ( ld->ld_error ) {
663 LDAP_FREE( ld->ld_error );
665 ld->ld_error = LDAP_STRDUP(
666 _("TLS: unable to get CN from peer certificate"));
668 } else if ( cn->length == nlen &&
669 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
672 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
673 char *domain = strchr(name, '.');
677 dlen = nlen - (domain-name);
679 /* Is this a wildcard match? */
680 if ((dlen == cn->length-1) &&
681 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
687 if( ret == LDAP_LOCAL_ERROR ) {
688 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
689 "common name in certificate (%.*s).\n",
690 name, cn->length, cn->data );
691 ret = LDAP_CONNECT_ERROR;
692 if ( ld->ld_error ) {
693 LDAP_FREE( ld->ld_error );
695 ld->ld_error = LDAP_STRDUP(
696 _("TLS: hostname does not match CN in peer certificate"));
704 tlso_session_strength( tls_session *sess )
706 tlso_session *s = (tlso_session *)sess;
708 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
712 * TLS support for LBER Sockbufs
716 tlso_session *session;
717 Sockbuf_IO_Desc *sbiod;
720 #if OPENSSL_VERSION_NUMBER < 0x10100000
721 #define BIO_set_init(b, x) b->init = x
722 #define BIO_set_data(b, x) b->ptr = x
723 #define BIO_clear_flags(b, x) b->flags &= ~(x)
724 #define BIO_get_data(b) b->ptr
727 tlso_bio_create( BIO *b ) {
728 BIO_set_init( b, 1 );
729 BIO_set_data( b, NULL );
730 BIO_clear_flags( b, ~0 );
735 tlso_bio_destroy( BIO *b )
737 if ( b == NULL ) return 0;
739 BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
740 BIO_set_init( b, 0 );
741 BIO_clear_flags( b, ~0 );
746 tlso_bio_read( BIO *b, char *buf, int len )
751 if ( buf == NULL || len <= 0 ) return 0;
753 p = (struct tls_data *)BIO_get_data(b);
755 if ( p == NULL || p->sbiod == NULL ) {
759 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
761 BIO_clear_retry_flags( b );
763 int err = sock_errno();
764 if ( err == EAGAIN || err == EWOULDBLOCK ) {
765 BIO_set_retry_read( b );
773 tlso_bio_write( BIO *b, const char *buf, int len )
778 if ( buf == NULL || len <= 0 ) return 0;
780 p = (struct tls_data *)BIO_get_data(b);
782 if ( p == NULL || p->sbiod == NULL ) {
786 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
788 BIO_clear_retry_flags( b );
790 int err = sock_errno();
791 if ( err == EAGAIN || err == EWOULDBLOCK ) {
792 BIO_set_retry_write( b );
800 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
802 if ( cmd == BIO_CTRL_FLUSH ) {
803 /* The OpenSSL library needs this */
810 tlso_bio_gets( BIO *b, char *buf, int len )
816 tlso_bio_puts( BIO *b, const char *str )
818 return tlso_bio_write( b, str, strlen( str ) );
821 #if OPENSSL_VERSION_NUMBER >= 0x10100000
822 struct bio_method_st {
825 int (*bwrite) (BIO *, const char *, int);
826 int (*bread) (BIO *, char *, int);
827 int (*bputs) (BIO *, const char *);
828 int (*bgets) (BIO *, char *, int);
829 long (*ctrl) (BIO *, int, long, void *);
830 int (*create) (BIO *);
831 int (*destroy) (BIO *);
832 long (*callback_ctrl) (BIO *, int, bio_info_cb *);
836 static BIO_METHOD tlso_bio_method =
838 ( 100 | 0x400 ), /* it's a source/sink BIO */
850 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
855 assert( sbiod != NULL );
857 p = LBER_MALLOC( sizeof( *p ) );
864 bio = BIO_new( &tlso_bio_method );
865 BIO_set_data( bio, p );
866 SSL_set_bio( p->session, bio, bio );
867 sbiod->sbiod_pvt = p;
872 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
876 assert( sbiod != NULL );
877 assert( sbiod->sbiod_pvt != NULL );
879 p = (struct tls_data *)sbiod->sbiod_pvt;
880 SSL_free( p->session );
881 LBER_FREE( sbiod->sbiod_pvt );
882 sbiod->sbiod_pvt = NULL;
887 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
891 assert( sbiod != NULL );
892 assert( sbiod->sbiod_pvt != NULL );
894 p = (struct tls_data *)sbiod->sbiod_pvt;
895 SSL_shutdown( p->session );
900 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
904 assert( sbiod != NULL );
905 assert( sbiod->sbiod_pvt != NULL );
907 p = (struct tls_data *)sbiod->sbiod_pvt;
909 if ( opt == LBER_SB_OPT_GET_SSL ) {
910 *((tlso_session **)arg) = p->session;
913 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
914 if( SSL_pending( p->session ) > 0 ) {
919 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
923 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
929 assert( sbiod != NULL );
930 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
932 p = (struct tls_data *)sbiod->sbiod_pvt;
934 ret = SSL_read( p->session, (char *)buf, len );
936 errno = WSAGetLastError();
938 err = SSL_get_error( p->session, ret );
939 if (err == SSL_ERROR_WANT_READ ) {
940 sbiod->sbiod_sb->sb_trans_needs_read = 1;
941 sock_errset(EWOULDBLOCK);
944 sbiod->sbiod_sb->sb_trans_needs_read = 0;
949 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
955 assert( sbiod != NULL );
956 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
958 p = (struct tls_data *)sbiod->sbiod_pvt;
960 ret = SSL_write( p->session, (char *)buf, len );
962 errno = WSAGetLastError();
964 err = SSL_get_error( p->session, ret );
965 if (err == SSL_ERROR_WANT_WRITE ) {
966 sbiod->sbiod_sb->sb_trans_needs_write = 1;
967 sock_errset(EWOULDBLOCK);
970 sbiod->sbiod_sb->sb_trans_needs_write = 0;
975 static Sockbuf_IO tlso_sbio =
977 tlso_sb_setup, /* sbi_setup */
978 tlso_sb_remove, /* sbi_remove */
979 tlso_sb_ctrl, /* sbi_ctrl */
980 tlso_sb_read, /* sbi_read */
981 tlso_sb_write, /* sbi_write */
982 tlso_sb_close /* sbi_close */
985 /* Derived from openssl/apps/s_cb.c */
987 tlso_info_cb( const SSL *ssl, int where, int ret )
991 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
993 w = where & ~SSL_ST_MASK;
994 if ( w & SSL_ST_CONNECT ) {
996 } else if ( w & SSL_ST_ACCEPT ) {
1004 state = LDAP_STRDUP( state );
1008 if ( where & SSL_CB_LOOP ) {
1009 Debug( LDAP_DEBUG_TRACE,
1010 "TLS trace: %s:%s\n",
1013 } else if ( where & SSL_CB_ALERT ) {
1014 char *atype = (char *) SSL_alert_type_string_long( ret );
1015 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1016 op = ( where & SSL_CB_READ ) ? "read" : "write";
1019 atype = LDAP_STRDUP( atype );
1023 adesc = LDAP_STRDUP( adesc );
1027 Debug( LDAP_DEBUG_TRACE,
1028 "TLS trace: SSL3 alert %s:%s:%s\n",
1031 if ( atype ) LDAP_FREE( atype );
1032 if ( adesc ) LDAP_FREE( adesc );
1034 } else if ( where & SSL_CB_EXIT ) {
1036 Debug( LDAP_DEBUG_TRACE,
1037 "TLS trace: %s:failed in %s\n",
1039 } else if ( ret < 0 ) {
1040 Debug( LDAP_DEBUG_TRACE,
1041 "TLS trace: %s:error in %s\n",
1046 if ( state ) LDAP_FREE( state );
1051 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1060 char *certerr = NULL;
1062 cert = X509_STORE_CTX_get_current_cert( ctx );
1063 errnum = X509_STORE_CTX_get_error( ctx );
1064 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1067 * X509_get_*_name return pointers to the internal copies of
1068 * those things requested. So do not free them.
1070 subject = X509_get_subject_name( cert );
1071 issuer = X509_get_issuer_name( cert );
1072 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1073 sname = X509_NAME_oneline( subject, NULL, 0 );
1074 iname = X509_NAME_oneline( issuer, NULL, 0 );
1075 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1077 if ( sname ) __etoa( sname );
1078 if ( iname ) __etoa( iname );
1080 certerr = LDAP_STRDUP( certerr );
1084 Debug( LDAP_DEBUG_TRACE,
1085 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1087 sname ? sname : "-unknown-" );
1088 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1090 Debug( LDAP_DEBUG_ANY,
1091 "TLS certificate verification: Error, %s\n",
1095 OPENSSL_free ( sname );
1097 OPENSSL_free ( iname );
1099 if ( certerr ) LDAP_FREE( certerr );
1105 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1107 (void) tlso_verify_cb( ok, ctx );
1111 /* Inspired by ERR_print_errors in OpenSSL */
1113 tlso_report_error( void )
1120 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1121 ERR_error_string_n( l, buf, sizeof( buf ) );
1124 file = LDAP_STRDUP( file );
1125 __etoa( (char *)file );
1129 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1132 if ( file ) LDAP_FREE( (void *)file );
1137 #if OPENSSL_VERSION_NUMBER < 0x10100000
1139 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1142 /* FIXME: Pregenerate the key on startup */
1143 /* FIXME: Who frees the key? */
1144 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1145 BIGNUM *bn = BN_new();
1148 if ( BN_set_word( bn, RSA_F4 )) {
1149 tmp_rsa = RSA_new();
1150 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1151 RSA_free( tmp_rsa );
1158 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1162 Debug( LDAP_DEBUG_ANY,
1163 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1164 key_length, is_export ? "export" : "domestic", 0 );
1168 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1171 tlso_seed_PRNG( const char *randfile )
1173 #ifndef URANDOM_DEVICE
1174 /* no /dev/urandom (or equiv) */
1176 char buffer[MAXPATHLEN];
1178 if (randfile == NULL) {
1179 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1180 * If $HOME is not set or buffer too small to hold the pathname,
1181 * an error occurs. - From RAND_file_name() man page.
1182 * The fact is that when $HOME is NULL, .rnd is used.
1184 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1186 } else if (RAND_egd(randfile) > 0) {
1191 if (randfile == NULL) {
1192 Debug( LDAP_DEBUG_ANY,
1193 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1198 total = RAND_load_file(randfile, -1);
1200 if (RAND_status() == 0) {
1201 Debug( LDAP_DEBUG_ANY,
1202 "TLS: PRNG not been seeded with enough data\n",
1207 /* assume if there was enough bits to seed that it's okay
1208 * to write derived bits to the file
1210 RAND_write_file(randfile);
1218 tls_impl ldap_int_tls_impl = {
1230 tlso_session_connect,
1231 tlso_session_accept,
1232 tlso_session_upflags,
1233 tlso_session_errmsg,
1235 tlso_session_peer_dn,
1236 tlso_session_chkhost,
1237 tlso_session_strength,
1241 #ifdef LDAP_R_COMPILE
1250 #endif /* HAVE_OPENSSL */