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 ( is_server && lo->ldo_tls_dhfile ) {
334 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
335 Debug( LDAP_DEBUG_ANY,
336 "TLS: could not use DH parameters file `%s'.\n",
337 lo->ldo_tls_dhfile,0,0);
341 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
342 Debug( LDAP_DEBUG_ANY,
343 "TLS: could not read DH parameters file `%s'.\n",
344 lo->ldo_tls_dhfile,0,0);
350 SSL_CTX_set_tmp_dh( ctx, dh );
351 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
355 if ( is_server && lo->ldo_tls_ecname ) {
357 Debug( LDAP_DEBUG_ANY,
358 "TLS: Elliptic Curves not supported.\n", 0,0,0 );
363 int nid = OBJ_sn2nid( lt->lt_ecname );
364 if ( nid == NID_undef ) {
365 Debug( LDAP_DEBUG_ANY,
366 "TLS: could not use EC name `%s'.\n",
367 lo->ldo_tls_ecname,0,0);
371 ecdh = EC_KEY_new_by_curve_name( nid );
372 if ( ecdh == NULL ) {
373 Debug( LDAP_DEBUG_ANY,
374 "TLS: could not generate key for EC name `%s'.\n",
375 lo->ldo_tls_ecname,0,0);
379 SSL_CTX_set_tmp_ecdh( ctx, ecdh );
380 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_ECDH_USE );
385 if ( tlso_opt_trace ) {
386 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
390 if ( lo->ldo_tls_require_cert ) {
392 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
393 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
394 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
398 SSL_CTX_set_verify( ctx, i,
399 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
400 tlso_verify_ok : tlso_verify_cb );
401 #if OPENSSL_VERSION_NUMBER < 0x10100000
402 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
404 #ifdef HAVE_OPENSSL_CRL
405 if ( lo->ldo_tls_crlcheck ) {
406 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
407 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
408 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
409 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
410 X509_STORE_set_flags( x509_s,
411 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
419 tlso_session_new( tls_ctx *ctx, int is_server )
421 tlso_ctx *c = (tlso_ctx *)ctx;
422 return (tls_session *)SSL_new( c );
426 tlso_session_connect( LDAP *ld, tls_session *sess )
428 tlso_session *s = (tlso_session *)sess;
430 /* Caller expects 0 = success, OpenSSL returns 1 = success */
431 return SSL_connect( s ) - 1;
435 tlso_session_accept( tls_session *sess )
437 tlso_session *s = (tlso_session *)sess;
439 /* Caller expects 0 = success, OpenSSL returns 1 = success */
440 return SSL_accept( s ) - 1;
444 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
446 tlso_session *s = (tlso_session *)sess;
448 /* 1 was subtracted above, offset it back now */
449 rc = SSL_get_error(s, rc+1);
450 if (rc == SSL_ERROR_WANT_READ) {
451 sb->sb_trans_needs_read = 1;
454 } else if (rc == SSL_ERROR_WANT_WRITE) {
455 sb->sb_trans_needs_write = 1;
458 } else if (rc == SSL_ERROR_WANT_CONNECT) {
465 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
468 const char *certerr=NULL;
469 tlso_session *s = (tlso_session *)sess;
471 rc = ERR_peek_error();
473 ERR_error_string_n( rc, err, sizeof(err) );
474 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
475 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
476 int certrc = SSL_get_verify_result(s);
477 certerr = (char *)X509_verify_cert_error_string(certrc);
479 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
480 certerr ? certerr : "", certerr ? ")" : "" );
487 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
489 tlso_session *s = (tlso_session *)sess;
493 x = SSL_get_certificate( s );
495 if (!x) return LDAP_INVALID_CREDENTIALS;
497 xn = X509_get_subject_name(x);
498 #if OPENSSL_VERSION_NUMBER < 0x10100000
499 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
500 der_dn->bv_val = xn->bytes->data;
504 der_dn->bv_val = NULL;
505 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
506 der_dn->bv_len = len;
509 /* Don't X509_free, the session is still using it */
514 tlso_get_cert( SSL *s )
516 /* If peer cert was bad, treat as if no cert was given */
517 if (SSL_get_verify_result(s)) {
520 return SSL_get_peer_certificate(s);
524 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
526 tlso_session *s = (tlso_session *)sess;
527 X509 *x = tlso_get_cert( s );
531 return LDAP_INVALID_CREDENTIALS;
533 xn = X509_get_subject_name(x);
534 #if OPENSSL_VERSION_NUMBER < 0x10100000
535 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
536 der_dn->bv_val = xn->bytes->data;
540 der_dn->bv_val = NULL;
541 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
542 der_dn->bv_len = len;
549 /* what kind of hostname were we given? */
555 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
557 tlso_session *s = (tlso_session *)sess;
558 int i, ret = LDAP_LOCAL_ERROR;
562 int ntype = IS_DNS, nlen;
564 struct in6_addr addr;
569 if( ldap_int_hostname &&
570 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
572 name = ldap_int_hostname;
578 x = tlso_get_cert(s);
580 Debug( LDAP_DEBUG_ANY,
581 "TLS: unable to get peer certificate.\n",
583 /* If this was a fatal condition, things would have
584 * aborted long before now.
590 if (inet_pton(AF_INET6, name, &addr)) {
594 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
595 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
598 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
601 STACK_OF(GENERAL_NAME) *alt;
603 ex = X509_get_ext(x, i);
604 alt = X509V3_EXT_d2i(ex);
610 if (ntype == IS_DNS) {
611 domain = strchr(name, '.');
613 len2 = nlen - (domain-name);
616 n = sk_GENERAL_NAME_num(alt);
617 for (i=0; i<n; i++) {
620 gn = sk_GENERAL_NAME_value(alt, i);
621 if (gn->type == GEN_DNS) {
622 if (ntype != IS_DNS) continue;
624 sn = (char *) ASN1_STRING_data(gn->d.ia5);
625 sl = ASN1_STRING_length(gn->d.ia5);
628 if (sl == 0) continue;
630 /* Is this an exact match? */
631 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
635 /* Is this a wildcard match? */
636 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
637 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
642 } else if (gn->type == GEN_IPADD) {
643 if (ntype == IS_DNS) continue;
645 sn = (char *) ASN1_STRING_data(gn->d.ia5);
646 sl = ASN1_STRING_length(gn->d.ia5);
649 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
653 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
656 if (!memcmp(sn, &addr, sl)) {
662 GENERAL_NAMES_free(alt);
663 if (i < n) { /* Found a match */
669 if (ret != LDAP_SUCCESS) {
673 ASN1_STRING *cn = NULL;
676 /* find the last CN */
677 obj = OBJ_nid2obj( NID_commonName );
678 if ( !obj ) goto no_cn; /* should never happen */
680 xn = X509_get_subject_name(x);
681 navas = X509_NAME_entry_count( xn );
682 for ( i=navas-1; i>=0; i-- ) {
683 ne = X509_NAME_get_entry( xn, i );
684 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
685 cn = X509_NAME_ENTRY_get_data( ne );
693 Debug( LDAP_DEBUG_ANY,
694 "TLS: unable to get common name from peer certificate.\n",
696 ret = LDAP_CONNECT_ERROR;
697 if ( ld->ld_error ) {
698 LDAP_FREE( ld->ld_error );
700 ld->ld_error = LDAP_STRDUP(
701 _("TLS: unable to get CN from peer certificate"));
703 } else if ( cn->length == nlen &&
704 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
707 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
708 char *domain = strchr(name, '.');
712 dlen = nlen - (domain-name);
714 /* Is this a wildcard match? */
715 if ((dlen == cn->length-1) &&
716 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
722 if( ret == LDAP_LOCAL_ERROR ) {
723 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
724 "common name in certificate (%.*s).\n",
725 name, cn->length, cn->data );
726 ret = LDAP_CONNECT_ERROR;
727 if ( ld->ld_error ) {
728 LDAP_FREE( ld->ld_error );
730 ld->ld_error = LDAP_STRDUP(
731 _("TLS: hostname does not match CN in peer certificate"));
739 tlso_session_strength( tls_session *sess )
741 tlso_session *s = (tlso_session *)sess;
743 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
747 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
749 tlso_session *s = (tlso_session *)sess;
751 /* Usually the client sends the finished msg. But if the
752 * session was resumed, the server sent the msg.
754 if (SSL_session_reused(s) ^ !is_server)
755 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
757 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
762 tlso_session_version( tls_session *sess )
764 tlso_session *s = (tlso_session *)sess;
765 return SSL_get_version(s);
769 tlso_session_cipher( tls_session *sess )
771 tlso_session *s = (tlso_session *)sess;
772 return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
776 tlso_session_peercert( tls_session *sess, struct berval *der )
778 tlso_session *s = (tlso_session *)sess;
780 X509 *x = SSL_get_peer_certificate(s);
781 der->bv_len = i2d_X509(x, NULL);
782 der->bv_val = LDAP_MALLOC(der->bv_len);
791 * TLS support for LBER Sockbufs
795 tlso_session *session;
796 Sockbuf_IO_Desc *sbiod;
799 #if OPENSSL_VERSION_NUMBER < 0x10100000
800 #define BIO_set_init(b, x) b->init = x
801 #define BIO_set_data(b, x) b->ptr = x
802 #define BIO_clear_flags(b, x) b->flags &= ~(x)
803 #define BIO_get_data(b) b->ptr
806 tlso_bio_create( BIO *b ) {
807 BIO_set_init( b, 1 );
808 BIO_set_data( b, NULL );
809 BIO_clear_flags( b, ~0 );
814 tlso_bio_destroy( BIO *b )
816 if ( b == NULL ) return 0;
818 BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
819 BIO_set_init( b, 0 );
820 BIO_clear_flags( b, ~0 );
825 tlso_bio_read( BIO *b, char *buf, int len )
830 if ( buf == NULL || len <= 0 ) return 0;
832 p = (struct tls_data *)BIO_get_data(b);
834 if ( p == NULL || p->sbiod == NULL ) {
838 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
840 BIO_clear_retry_flags( b );
842 int err = sock_errno();
843 if ( err == EAGAIN || err == EWOULDBLOCK ) {
844 BIO_set_retry_read( b );
852 tlso_bio_write( BIO *b, const char *buf, int len )
857 if ( buf == NULL || len <= 0 ) return 0;
859 p = (struct tls_data *)BIO_get_data(b);
861 if ( p == NULL || p->sbiod == NULL ) {
865 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
867 BIO_clear_retry_flags( b );
869 int err = sock_errno();
870 if ( err == EAGAIN || err == EWOULDBLOCK ) {
871 BIO_set_retry_write( b );
879 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
881 if ( cmd == BIO_CTRL_FLUSH ) {
882 /* The OpenSSL library needs this */
889 tlso_bio_gets( BIO *b, char *buf, int len )
895 tlso_bio_puts( BIO *b, const char *str )
897 return tlso_bio_write( b, str, strlen( str ) );
900 #if OPENSSL_VERSION_NUMBER >= 0x10100000
901 struct bio_method_st {
904 int (*bwrite) (BIO *, const char *, int);
905 int (*bread) (BIO *, char *, int);
906 int (*bputs) (BIO *, const char *);
907 int (*bgets) (BIO *, char *, int);
908 long (*ctrl) (BIO *, int, long, void *);
909 int (*create) (BIO *);
910 int (*destroy) (BIO *);
911 long (*callback_ctrl) (BIO *, int, bio_info_cb *);
915 static BIO_METHOD tlso_bio_method =
917 ( 100 | 0x400 ), /* it's a source/sink BIO */
929 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
934 assert( sbiod != NULL );
936 p = LBER_MALLOC( sizeof( *p ) );
943 bio = BIO_new( &tlso_bio_method );
944 BIO_set_data( bio, p );
945 SSL_set_bio( p->session, bio, bio );
946 sbiod->sbiod_pvt = p;
951 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
955 assert( sbiod != NULL );
956 assert( sbiod->sbiod_pvt != NULL );
958 p = (struct tls_data *)sbiod->sbiod_pvt;
959 SSL_free( p->session );
960 LBER_FREE( sbiod->sbiod_pvt );
961 sbiod->sbiod_pvt = NULL;
966 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
970 assert( sbiod != NULL );
971 assert( sbiod->sbiod_pvt != NULL );
973 p = (struct tls_data *)sbiod->sbiod_pvt;
974 SSL_shutdown( p->session );
979 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
983 assert( sbiod != NULL );
984 assert( sbiod->sbiod_pvt != NULL );
986 p = (struct tls_data *)sbiod->sbiod_pvt;
988 if ( opt == LBER_SB_OPT_GET_SSL ) {
989 *((tlso_session **)arg) = p->session;
992 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
993 if( SSL_pending( p->session ) > 0 ) {
998 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1002 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1008 assert( sbiod != NULL );
1009 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1011 p = (struct tls_data *)sbiod->sbiod_pvt;
1013 ret = SSL_read( p->session, (char *)buf, len );
1015 errno = WSAGetLastError();
1017 err = SSL_get_error( p->session, ret );
1018 if (err == SSL_ERROR_WANT_READ ) {
1019 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1020 sock_errset(EWOULDBLOCK);
1023 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1028 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1034 assert( sbiod != NULL );
1035 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1037 p = (struct tls_data *)sbiod->sbiod_pvt;
1039 ret = SSL_write( p->session, (char *)buf, len );
1041 errno = WSAGetLastError();
1043 err = SSL_get_error( p->session, ret );
1044 if (err == SSL_ERROR_WANT_WRITE ) {
1045 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1046 sock_errset(EWOULDBLOCK);
1049 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1054 static Sockbuf_IO tlso_sbio =
1056 tlso_sb_setup, /* sbi_setup */
1057 tlso_sb_remove, /* sbi_remove */
1058 tlso_sb_ctrl, /* sbi_ctrl */
1059 tlso_sb_read, /* sbi_read */
1060 tlso_sb_write, /* sbi_write */
1061 tlso_sb_close /* sbi_close */
1064 /* Derived from openssl/apps/s_cb.c */
1066 tlso_info_cb( const SSL *ssl, int where, int ret )
1070 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1072 w = where & ~SSL_ST_MASK;
1073 if ( w & SSL_ST_CONNECT ) {
1075 } else if ( w & SSL_ST_ACCEPT ) {
1083 state = LDAP_STRDUP( state );
1087 if ( where & SSL_CB_LOOP ) {
1088 Debug( LDAP_DEBUG_TRACE,
1089 "TLS trace: %s:%s\n",
1092 } else if ( where & SSL_CB_ALERT ) {
1093 char *atype = (char *) SSL_alert_type_string_long( ret );
1094 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1095 op = ( where & SSL_CB_READ ) ? "read" : "write";
1098 atype = LDAP_STRDUP( atype );
1102 adesc = LDAP_STRDUP( adesc );
1106 Debug( LDAP_DEBUG_TRACE,
1107 "TLS trace: SSL3 alert %s:%s:%s\n",
1110 if ( atype ) LDAP_FREE( atype );
1111 if ( adesc ) LDAP_FREE( adesc );
1113 } else if ( where & SSL_CB_EXIT ) {
1115 Debug( LDAP_DEBUG_TRACE,
1116 "TLS trace: %s:failed in %s\n",
1118 } else if ( ret < 0 ) {
1119 Debug( LDAP_DEBUG_TRACE,
1120 "TLS trace: %s:error in %s\n",
1125 if ( state ) LDAP_FREE( state );
1130 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1139 char *certerr = NULL;
1141 cert = X509_STORE_CTX_get_current_cert( ctx );
1142 errnum = X509_STORE_CTX_get_error( ctx );
1143 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1146 * X509_get_*_name return pointers to the internal copies of
1147 * those things requested. So do not free them.
1149 subject = X509_get_subject_name( cert );
1150 issuer = X509_get_issuer_name( cert );
1151 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1152 sname = X509_NAME_oneline( subject, NULL, 0 );
1153 iname = X509_NAME_oneline( issuer, NULL, 0 );
1154 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1156 if ( sname ) __etoa( sname );
1157 if ( iname ) __etoa( iname );
1159 certerr = LDAP_STRDUP( certerr );
1163 Debug( LDAP_DEBUG_TRACE,
1164 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1166 sname ? sname : "-unknown-" );
1167 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1169 Debug( LDAP_DEBUG_ANY,
1170 "TLS certificate verification: Error, %s\n",
1174 OPENSSL_free ( sname );
1176 OPENSSL_free ( iname );
1178 if ( certerr ) LDAP_FREE( certerr );
1184 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1186 (void) tlso_verify_cb( ok, ctx );
1190 /* Inspired by ERR_print_errors in OpenSSL */
1192 tlso_report_error( void )
1199 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1200 ERR_error_string_n( l, buf, sizeof( buf ) );
1203 file = LDAP_STRDUP( file );
1204 __etoa( (char *)file );
1208 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1211 if ( file ) LDAP_FREE( (void *)file );
1216 #if OPENSSL_VERSION_NUMBER < 0x10100000
1218 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1221 /* FIXME: Pregenerate the key on startup */
1222 /* FIXME: Who frees the key? */
1223 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1224 BIGNUM *bn = BN_new();
1227 if ( BN_set_word( bn, RSA_F4 )) {
1228 tmp_rsa = RSA_new();
1229 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1230 RSA_free( tmp_rsa );
1237 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1241 Debug( LDAP_DEBUG_ANY,
1242 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1243 key_length, is_export ? "export" : "domestic", 0 );
1247 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1250 tlso_seed_PRNG( const char *randfile )
1252 #ifndef URANDOM_DEVICE
1253 /* no /dev/urandom (or equiv) */
1255 char buffer[MAXPATHLEN];
1257 if (randfile == NULL) {
1258 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1259 * If $HOME is not set or buffer too small to hold the pathname,
1260 * an error occurs. - From RAND_file_name() man page.
1261 * The fact is that when $HOME is NULL, .rnd is used.
1263 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1265 } else if (RAND_egd(randfile) > 0) {
1270 if (randfile == NULL) {
1271 Debug( LDAP_DEBUG_ANY,
1272 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1277 total = RAND_load_file(randfile, -1);
1279 if (RAND_status() == 0) {
1280 Debug( LDAP_DEBUG_ANY,
1281 "TLS: PRNG not been seeded with enough data\n",
1286 /* assume if there was enough bits to seed that it's okay
1287 * to write derived bits to the file
1289 RAND_write_file(randfile);
1297 tls_impl ldap_int_tls_impl = {
1309 tlso_session_connect,
1310 tlso_session_accept,
1311 tlso_session_upflags,
1312 tlso_session_errmsg,
1314 tlso_session_peer_dn,
1315 tlso_session_chkhost,
1316 tlso_session_strength,
1317 tlso_session_unique,
1318 tlso_session_version,
1319 tlso_session_cipher,
1320 tlso_session_peercert,
1324 #ifdef LDAP_R_COMPILE
1333 #endif /* HAVE_OPENSSL */