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 ERR_remove_thread_state(x) /* deprecated, get rid of it */
52 #define ASN1_STRING_data(x) ASN1_STRING_get0_data(x)
53 #define CRYPTO_free(x) OPENSSL_free(x)
54 #define CRYPTO_NUM_LOCKS CRYPTO_num_locks()
57 typedef SSL_CTX tlso_ctx;
58 typedef SSL tlso_session;
60 static int tlso_opt_trace = 1;
62 static void tlso_report_error( void );
64 static void tlso_info_cb( const SSL *ssl, int where, int ret );
65 static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
66 static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
67 #if OPENSSL_VERSION_NUMBER < 0x10100000
68 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
71 static int tlso_seed_PRNG( const char *randfile );
75 * provide mutexes for the OpenSSL library.
77 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
79 static void tlso_locking_cb( int mode, int type, const char *file, int line )
81 if ( mode & CRYPTO_LOCK ) {
82 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
84 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
88 static unsigned long tlso_thread_self( void )
90 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
91 * is an integral type that fits in an unsigned long
94 /* force an error if the ldap_pvt_thread_t type is too large */
95 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
96 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
98 return (unsigned long) ldap_pvt_thread_self();
101 static void tlso_thr_init( void )
105 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
106 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
108 CRYPTO_set_locking_callback( tlso_locking_cb );
109 CRYPTO_set_id_callback( tlso_thread_self );
111 #endif /* LDAP_R_COMPILE */
113 static STACK_OF(X509_NAME) *
114 tlso_ca_list( char * bundle, char * dir )
116 STACK_OF(X509_NAME) *ca_list = NULL;
119 ca_list = SSL_load_client_CA_file( bundle );
121 #if defined(HAVE_DIRENT_H) || defined(dirent)
126 ca_list = sk_X509_NAME_new_null();
129 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
131 sk_X509_NAME_free( ca_list );
140 * Initialize TLS subsystem. Should be called only once.
145 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
148 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
149 if ( file ) __atoe( file );
150 (void) tlso_seed_PRNG( file );
154 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
157 SSL_load_error_strings();
159 OpenSSL_add_all_digests();
161 /* FIXME: mod_ssl does this */
162 X509V3_add_standard_extensions();
168 * Tear down the TLS subsystem. Should only be called once.
173 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
176 #if OPENSSL_VERSION_NUMBER < 0x10000000
179 ERR_remove_thread_state(NULL);
183 if ( lo->ldo_tls_randfile ) {
184 LDAP_FREE( lo->ldo_tls_randfile );
185 lo->ldo_tls_randfile = NULL;
190 tlso_ctx_new( struct ldapoptions *lo )
192 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
196 tlso_ctx_ref( tls_ctx *ctx )
198 tlso_ctx *c = (tlso_ctx *)ctx;
199 #if OPENSSL_VERSION_NUMBER < 0x10100000
200 #define SSL_CTX_up_ref(ctx) CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
206 tlso_ctx_free ( tls_ctx *ctx )
208 tlso_ctx *c = (tlso_ctx *)ctx;
213 * initialize a new TLS context
216 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
218 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
222 SSL_CTX_set_session_id_context( ctx,
223 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
226 #ifdef SSL_OP_NO_TLSv1
227 #ifdef SSL_OP_NO_TLSv1_1
228 #ifdef SSL_OP_NO_TLSv1_2
229 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
230 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
231 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
235 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
236 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
237 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
240 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
241 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
245 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
246 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
247 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
248 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
250 if ( lo->ldo_tls_ciphersuite &&
251 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
253 Debug( LDAP_DEBUG_ANY,
254 "TLS: could not set cipher list %s.\n",
255 lo->ldo_tls_ciphersuite, 0, 0 );
260 if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
261 if ( !SSL_CTX_load_verify_locations( ctx,
262 lt->lt_cacertfile, lt->lt_cacertdir ) ||
263 !SSL_CTX_set_default_verify_paths( ctx ) )
265 Debug( LDAP_DEBUG_ANY, "TLS: "
266 "could not load verify locations (file:`%s',dir:`%s').\n",
267 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
268 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
275 STACK_OF(X509_NAME) *calist;
276 /* List of CA names to send to a client */
277 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
279 Debug( LDAP_DEBUG_ANY, "TLS: "
280 "could not load client CA list (file:`%s',dir:`%s').\n",
281 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
282 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
288 SSL_CTX_set_client_CA_list( ctx, calist );
292 if ( lo->ldo_tls_certfile &&
293 !SSL_CTX_use_certificate_file( ctx,
294 lt->lt_certfile, SSL_FILETYPE_PEM ) )
296 Debug( LDAP_DEBUG_ANY,
297 "TLS: could not use certificate `%s'.\n",
298 lo->ldo_tls_certfile,0,0);
303 /* Key validity is checked automatically if cert has already been set */
304 if ( lo->ldo_tls_keyfile &&
305 !SSL_CTX_use_PrivateKey_file( ctx,
306 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
308 Debug( LDAP_DEBUG_ANY,
309 "TLS: could not use key file `%s'.\n",
310 lo->ldo_tls_keyfile,0,0);
315 if ( is_server && lo->ldo_tls_dhfile ) {
319 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
320 Debug( LDAP_DEBUG_ANY,
321 "TLS: could not use DH parameters file `%s'.\n",
322 lo->ldo_tls_dhfile,0,0);
326 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
327 Debug( LDAP_DEBUG_ANY,
328 "TLS: could not read DH parameters file `%s'.\n",
329 lo->ldo_tls_dhfile,0,0);
335 SSL_CTX_set_tmp_dh( ctx, dh );
336 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
340 if ( is_server && lo->ldo_tls_ecname ) {
342 Debug( LDAP_DEBUG_ANY,
343 "TLS: Elliptic Curves not supported.\n", 0,0,0 );
348 int nid = OBJ_sn2nid( lt->lt_ecname );
349 if ( nid == NID_undef ) {
350 Debug( LDAP_DEBUG_ANY,
351 "TLS: could not use EC name `%s'.\n",
352 lo->ldo_tls_ecname,0,0);
356 ecdh = EC_KEY_new_by_curve_name( nid );
357 if ( ecdh == NULL ) {
358 Debug( LDAP_DEBUG_ANY,
359 "TLS: could not generate key for EC name `%s'.\n",
360 lo->ldo_tls_ecname,0,0);
364 SSL_CTX_set_tmp_ecdh( ctx, ecdh );
365 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_ECDH_USE );
370 if ( tlso_opt_trace ) {
371 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
375 if ( lo->ldo_tls_require_cert ) {
377 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
378 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
379 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
383 SSL_CTX_set_verify( ctx, i,
384 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
385 tlso_verify_ok : tlso_verify_cb );
386 #if OPENSSL_VERSION_NUMBER < 0x10100000
387 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
389 #ifdef HAVE_OPENSSL_CRL
390 if ( lo->ldo_tls_crlcheck ) {
391 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
392 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
393 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
394 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
395 X509_STORE_set_flags( x509_s,
396 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
404 tlso_session_new( tls_ctx *ctx, int is_server )
406 tlso_ctx *c = (tlso_ctx *)ctx;
407 return (tls_session *)SSL_new( c );
411 tlso_session_connect( LDAP *ld, tls_session *sess )
413 tlso_session *s = (tlso_session *)sess;
415 /* Caller expects 0 = success, OpenSSL returns 1 = success */
416 return SSL_connect( s ) - 1;
420 tlso_session_accept( tls_session *sess )
422 tlso_session *s = (tlso_session *)sess;
424 /* Caller expects 0 = success, OpenSSL returns 1 = success */
425 return SSL_accept( s ) - 1;
429 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
431 tlso_session *s = (tlso_session *)sess;
433 /* 1 was subtracted above, offset it back now */
434 rc = SSL_get_error(s, rc+1);
435 if (rc == SSL_ERROR_WANT_READ) {
436 sb->sb_trans_needs_read = 1;
439 } else if (rc == SSL_ERROR_WANT_WRITE) {
440 sb->sb_trans_needs_write = 1;
443 } else if (rc == SSL_ERROR_WANT_CONNECT) {
450 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
453 const char *certerr=NULL;
454 tlso_session *s = (tlso_session *)sess;
456 rc = ERR_peek_error();
458 ERR_error_string_n( rc, err, sizeof(err) );
459 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
460 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
461 int certrc = SSL_get_verify_result(s);
462 certerr = (char *)X509_verify_cert_error_string(certrc);
464 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
465 certerr ? certerr : "", certerr ? ")" : "" );
472 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
474 tlso_session *s = (tlso_session *)sess;
478 x = SSL_get_certificate( s );
480 if (!x) return LDAP_INVALID_CREDENTIALS;
482 xn = X509_get_subject_name(x);
483 #if OPENSSL_VERSION_NUMBER < 0x10100000
484 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
485 der_dn->bv_val = xn->bytes->data;
489 der_dn->bv_val = NULL;
490 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
491 der_dn->bv_len = len;
494 /* Don't X509_free, the session is still using it */
499 tlso_get_cert( SSL *s )
501 /* If peer cert was bad, treat as if no cert was given */
502 if (SSL_get_verify_result(s)) {
505 return SSL_get_peer_certificate(s);
509 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
511 tlso_session *s = (tlso_session *)sess;
512 X509 *x = tlso_get_cert( s );
516 return LDAP_INVALID_CREDENTIALS;
518 xn = X509_get_subject_name(x);
519 #if OPENSSL_VERSION_NUMBER < 0x10100000
520 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
521 der_dn->bv_val = xn->bytes->data;
525 der_dn->bv_val = NULL;
526 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
527 der_dn->bv_len = len;
534 /* what kind of hostname were we given? */
540 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
542 tlso_session *s = (tlso_session *)sess;
543 int i, ret = LDAP_LOCAL_ERROR;
547 int ntype = IS_DNS, nlen;
549 struct in6_addr addr;
554 if( ldap_int_hostname &&
555 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
557 name = ldap_int_hostname;
563 x = tlso_get_cert(s);
565 Debug( LDAP_DEBUG_ANY,
566 "TLS: unable to get peer certificate.\n",
568 /* If this was a fatal condition, things would have
569 * aborted long before now.
575 if (inet_pton(AF_INET6, name, &addr)) {
579 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
580 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
583 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
586 STACK_OF(GENERAL_NAME) *alt;
588 ex = X509_get_ext(x, i);
589 alt = X509V3_EXT_d2i(ex);
595 if (ntype == IS_DNS) {
596 domain = strchr(name, '.');
598 len2 = nlen - (domain-name);
601 n = sk_GENERAL_NAME_num(alt);
602 for (i=0; i<n; i++) {
605 gn = sk_GENERAL_NAME_value(alt, i);
606 if (gn->type == GEN_DNS) {
607 if (ntype != IS_DNS) continue;
609 sn = (char *) ASN1_STRING_data(gn->d.ia5);
610 sl = ASN1_STRING_length(gn->d.ia5);
613 if (sl == 0) continue;
615 /* Is this an exact match? */
616 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
620 /* Is this a wildcard match? */
621 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
622 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
627 } else if (gn->type == GEN_IPADD) {
628 if (ntype == IS_DNS) continue;
630 sn = (char *) ASN1_STRING_data(gn->d.ia5);
631 sl = ASN1_STRING_length(gn->d.ia5);
634 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
638 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
641 if (!memcmp(sn, &addr, sl)) {
647 GENERAL_NAMES_free(alt);
648 if (i < n) { /* Found a match */
654 if (ret != LDAP_SUCCESS) {
658 ASN1_STRING *cn = NULL;
661 /* find the last CN */
662 obj = OBJ_nid2obj( NID_commonName );
663 if ( !obj ) goto no_cn; /* should never happen */
665 xn = X509_get_subject_name(x);
666 navas = X509_NAME_entry_count( xn );
667 for ( i=navas-1; i>=0; i-- ) {
668 ne = X509_NAME_get_entry( xn, i );
669 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
670 cn = X509_NAME_ENTRY_get_data( ne );
678 Debug( LDAP_DEBUG_ANY,
679 "TLS: unable to get common name from peer certificate.\n",
681 ret = LDAP_CONNECT_ERROR;
682 if ( ld->ld_error ) {
683 LDAP_FREE( ld->ld_error );
685 ld->ld_error = LDAP_STRDUP(
686 _("TLS: unable to get CN from peer certificate"));
688 } else if ( cn->length == nlen &&
689 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
692 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
693 char *domain = strchr(name, '.');
697 dlen = nlen - (domain-name);
699 /* Is this a wildcard match? */
700 if ((dlen == cn->length-1) &&
701 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
707 if( ret == LDAP_LOCAL_ERROR ) {
708 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
709 "common name in certificate (%.*s).\n",
710 name, cn->length, cn->data );
711 ret = LDAP_CONNECT_ERROR;
712 if ( ld->ld_error ) {
713 LDAP_FREE( ld->ld_error );
715 ld->ld_error = LDAP_STRDUP(
716 _("TLS: hostname does not match CN in peer certificate"));
724 tlso_session_strength( tls_session *sess )
726 tlso_session *s = (tlso_session *)sess;
728 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
732 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
734 tlso_session *s = (tlso_session *)sess;
736 /* Usually the client sends the finished msg. But if the
737 * session was resumed, the server sent the msg.
739 if (SSL_session_reused(s) ^ !is_server)
740 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
742 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
747 tlso_session_version( tls_session *sess )
749 tlso_session *s = (tlso_session *)sess;
750 return SSL_get_version(s);
754 tlso_session_cipher( tls_session *sess )
756 tlso_session *s = (tlso_session *)sess;
757 return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
761 tlso_session_peercert( tls_session *sess, struct berval *der )
763 tlso_session *s = (tlso_session *)sess;
765 X509 *x = SSL_get_peer_certificate(s);
766 der->bv_len = i2d_X509(x, NULL);
767 der->bv_val = LDAP_MALLOC(der->bv_len);
776 * TLS support for LBER Sockbufs
780 tlso_session *session;
781 Sockbuf_IO_Desc *sbiod;
784 #if OPENSSL_VERSION_NUMBER < 0x10100000
785 #define BIO_set_init(b, x) b->init = x
786 #define BIO_set_data(b, x) b->ptr = x
787 #define BIO_clear_flags(b, x) b->flags &= ~(x)
788 #define BIO_get_data(b) b->ptr
791 tlso_bio_create( BIO *b ) {
792 BIO_set_init( b, 1 );
793 BIO_set_data( b, NULL );
794 BIO_clear_flags( b, ~0 );
799 tlso_bio_destroy( BIO *b )
801 if ( b == NULL ) return 0;
803 BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
804 BIO_set_init( b, 0 );
805 BIO_clear_flags( b, ~0 );
810 tlso_bio_read( BIO *b, char *buf, int len )
815 if ( buf == NULL || len <= 0 ) return 0;
817 p = (struct tls_data *)BIO_get_data(b);
819 if ( p == NULL || p->sbiod == NULL ) {
823 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
825 BIO_clear_retry_flags( b );
827 int err = sock_errno();
828 if ( err == EAGAIN || err == EWOULDBLOCK ) {
829 BIO_set_retry_read( b );
837 tlso_bio_write( BIO *b, const char *buf, int len )
842 if ( buf == NULL || len <= 0 ) return 0;
844 p = (struct tls_data *)BIO_get_data(b);
846 if ( p == NULL || p->sbiod == NULL ) {
850 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
852 BIO_clear_retry_flags( b );
854 int err = sock_errno();
855 if ( err == EAGAIN || err == EWOULDBLOCK ) {
856 BIO_set_retry_write( b );
864 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
866 if ( cmd == BIO_CTRL_FLUSH ) {
867 /* The OpenSSL library needs this */
874 tlso_bio_gets( BIO *b, char *buf, int len )
880 tlso_bio_puts( BIO *b, const char *str )
882 return tlso_bio_write( b, str, strlen( str ) );
885 #if OPENSSL_VERSION_NUMBER >= 0x10100000
886 struct bio_method_st {
889 int (*bwrite) (BIO *, const char *, int);
890 int (*bread) (BIO *, char *, int);
891 int (*bputs) (BIO *, const char *);
892 int (*bgets) (BIO *, char *, int);
893 long (*ctrl) (BIO *, int, long, void *);
894 int (*create) (BIO *);
895 int (*destroy) (BIO *);
896 long (*callback_ctrl) (BIO *, int, bio_info_cb *);
900 static BIO_METHOD tlso_bio_method =
902 ( 100 | 0x400 ), /* it's a source/sink BIO */
914 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
919 assert( sbiod != NULL );
921 p = LBER_MALLOC( sizeof( *p ) );
928 bio = BIO_new( &tlso_bio_method );
929 BIO_set_data( bio, p );
930 SSL_set_bio( p->session, bio, bio );
931 sbiod->sbiod_pvt = p;
936 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
940 assert( sbiod != NULL );
941 assert( sbiod->sbiod_pvt != NULL );
943 p = (struct tls_data *)sbiod->sbiod_pvt;
944 SSL_free( p->session );
945 LBER_FREE( sbiod->sbiod_pvt );
946 sbiod->sbiod_pvt = NULL;
951 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
955 assert( sbiod != NULL );
956 assert( sbiod->sbiod_pvt != NULL );
958 p = (struct tls_data *)sbiod->sbiod_pvt;
959 SSL_shutdown( p->session );
964 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
968 assert( sbiod != NULL );
969 assert( sbiod->sbiod_pvt != NULL );
971 p = (struct tls_data *)sbiod->sbiod_pvt;
973 if ( opt == LBER_SB_OPT_GET_SSL ) {
974 *((tlso_session **)arg) = p->session;
977 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
978 if( SSL_pending( p->session ) > 0 ) {
983 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
987 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
993 assert( sbiod != NULL );
994 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
996 p = (struct tls_data *)sbiod->sbiod_pvt;
998 ret = SSL_read( p->session, (char *)buf, len );
1000 errno = WSAGetLastError();
1002 err = SSL_get_error( p->session, ret );
1003 if (err == SSL_ERROR_WANT_READ ) {
1004 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1005 sock_errset(EWOULDBLOCK);
1008 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1013 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1019 assert( sbiod != NULL );
1020 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1022 p = (struct tls_data *)sbiod->sbiod_pvt;
1024 ret = SSL_write( p->session, (char *)buf, len );
1026 errno = WSAGetLastError();
1028 err = SSL_get_error( p->session, ret );
1029 if (err == SSL_ERROR_WANT_WRITE ) {
1030 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1031 sock_errset(EWOULDBLOCK);
1034 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1039 static Sockbuf_IO tlso_sbio =
1041 tlso_sb_setup, /* sbi_setup */
1042 tlso_sb_remove, /* sbi_remove */
1043 tlso_sb_ctrl, /* sbi_ctrl */
1044 tlso_sb_read, /* sbi_read */
1045 tlso_sb_write, /* sbi_write */
1046 tlso_sb_close /* sbi_close */
1049 /* Derived from openssl/apps/s_cb.c */
1051 tlso_info_cb( const SSL *ssl, int where, int ret )
1055 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1057 w = where & ~SSL_ST_MASK;
1058 if ( w & SSL_ST_CONNECT ) {
1060 } else if ( w & SSL_ST_ACCEPT ) {
1068 state = LDAP_STRDUP( state );
1072 if ( where & SSL_CB_LOOP ) {
1073 Debug( LDAP_DEBUG_TRACE,
1074 "TLS trace: %s:%s\n",
1077 } else if ( where & SSL_CB_ALERT ) {
1078 char *atype = (char *) SSL_alert_type_string_long( ret );
1079 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1080 op = ( where & SSL_CB_READ ) ? "read" : "write";
1083 atype = LDAP_STRDUP( atype );
1087 adesc = LDAP_STRDUP( adesc );
1091 Debug( LDAP_DEBUG_TRACE,
1092 "TLS trace: SSL3 alert %s:%s:%s\n",
1095 if ( atype ) LDAP_FREE( atype );
1096 if ( adesc ) LDAP_FREE( adesc );
1098 } else if ( where & SSL_CB_EXIT ) {
1100 Debug( LDAP_DEBUG_TRACE,
1101 "TLS trace: %s:failed in %s\n",
1103 } else if ( ret < 0 ) {
1104 Debug( LDAP_DEBUG_TRACE,
1105 "TLS trace: %s:error in %s\n",
1110 if ( state ) LDAP_FREE( state );
1115 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1124 char *certerr = NULL;
1126 cert = X509_STORE_CTX_get_current_cert( ctx );
1127 errnum = X509_STORE_CTX_get_error( ctx );
1128 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1131 * X509_get_*_name return pointers to the internal copies of
1132 * those things requested. So do not free them.
1134 subject = X509_get_subject_name( cert );
1135 issuer = X509_get_issuer_name( cert );
1136 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1137 sname = X509_NAME_oneline( subject, NULL, 0 );
1138 iname = X509_NAME_oneline( issuer, NULL, 0 );
1139 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1141 if ( sname ) __etoa( sname );
1142 if ( iname ) __etoa( iname );
1144 certerr = LDAP_STRDUP( certerr );
1148 Debug( LDAP_DEBUG_TRACE,
1149 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1151 sname ? sname : "-unknown-" );
1152 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1154 Debug( LDAP_DEBUG_ANY,
1155 "TLS certificate verification: Error, %s\n",
1159 CRYPTO_free ( sname );
1161 CRYPTO_free ( iname );
1163 if ( certerr ) LDAP_FREE( certerr );
1169 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1171 (void) tlso_verify_cb( ok, ctx );
1175 /* Inspired by ERR_print_errors in OpenSSL */
1177 tlso_report_error( void )
1184 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1185 ERR_error_string_n( l, buf, sizeof( buf ) );
1188 file = LDAP_STRDUP( file );
1189 __etoa( (char *)file );
1193 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1196 if ( file ) LDAP_FREE( (void *)file );
1201 #if OPENSSL_VERSION_NUMBER < 0x10100000
1203 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1206 /* FIXME: Pregenerate the key on startup */
1207 /* FIXME: Who frees the key? */
1208 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1209 BIGNUM *bn = BN_new();
1212 if ( BN_set_word( bn, RSA_F4 )) {
1213 tmp_rsa = RSA_new();
1214 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1215 RSA_free( tmp_rsa );
1222 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1226 Debug( LDAP_DEBUG_ANY,
1227 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1228 key_length, is_export ? "export" : "domestic", 0 );
1232 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1235 tlso_seed_PRNG( const char *randfile )
1237 #ifndef URANDOM_DEVICE
1238 /* no /dev/urandom (or equiv) */
1240 char buffer[MAXPATHLEN];
1242 if (randfile == NULL) {
1243 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1244 * If $HOME is not set or buffer too small to hold the pathname,
1245 * an error occurs. - From RAND_file_name() man page.
1246 * The fact is that when $HOME is NULL, .rnd is used.
1248 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1250 } else if (RAND_egd(randfile) > 0) {
1255 if (randfile == NULL) {
1256 Debug( LDAP_DEBUG_ANY,
1257 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1262 total = RAND_load_file(randfile, -1);
1264 if (RAND_status() == 0) {
1265 Debug( LDAP_DEBUG_ANY,
1266 "TLS: PRNG not been seeded with enough data\n",
1271 /* assume if there was enough bits to seed that it's okay
1272 * to write derived bits to the file
1274 RAND_write_file(randfile);
1282 tls_impl ldap_int_tls_impl = {
1294 tlso_session_connect,
1295 tlso_session_accept,
1296 tlso_session_upflags,
1297 tlso_session_errmsg,
1299 tlso_session_peer_dn,
1300 tlso_session_chkhost,
1301 tlso_session_strength,
1302 tlso_session_unique,
1303 tlso_session_version,
1304 tlso_session_cipher,
1305 tlso_session_peercert,
1309 #ifdef LDAP_R_COMPILE
1318 #endif /* HAVE_OPENSSL */