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, X509 *cert )
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 );
140 X509_NAME *xn = X509_get_subject_name( cert );
141 xn = X509_NAME_dup( xn );
143 ca_list = sk_X509_NAME_new_null();
145 sk_X509_NAME_push( ca_list, xn );
151 * Initialize TLS subsystem. Should be called only once.
156 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
159 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
160 if ( file ) __atoe( file );
161 (void) tlso_seed_PRNG( file );
165 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
168 #if OPENSSL_VERSION_NUMBER < 0x10100000
169 SSL_load_error_strings();
171 OpenSSL_add_all_digests();
173 OPENSSL_init_ssl(0, NULL);
176 /* FIXME: mod_ssl does this */
177 X509V3_add_standard_extensions();
183 * Tear down the TLS subsystem. Should only be called once.
188 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
190 #if OPENSSL_VERSION_NUMBER < 0x10100000
192 #if OPENSSL_VERSION_NUMBER < 0x10000000
195 ERR_remove_thread_state(NULL);
200 if ( lo->ldo_tls_randfile ) {
201 LDAP_FREE( lo->ldo_tls_randfile );
202 lo->ldo_tls_randfile = NULL;
207 tlso_ctx_new( struct ldapoptions *lo )
209 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
213 tlso_ctx_ref( tls_ctx *ctx )
215 tlso_ctx *c = (tlso_ctx *)ctx;
216 #if OPENSSL_VERSION_NUMBER < 0x10100000
217 #define SSL_CTX_up_ref(ctx) CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
223 tlso_ctx_free ( tls_ctx *ctx )
225 tlso_ctx *c = (tlso_ctx *)ctx;
230 * initialize a new TLS context
233 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
235 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
239 SSL_CTX_set_session_id_context( ctx,
240 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
243 #ifdef SSL_OP_NO_TLSv1
244 #ifdef SSL_OP_NO_TLSv1_1
245 #ifdef SSL_OP_NO_TLSv1_2
246 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
247 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
248 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
252 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
253 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
254 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
257 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
258 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
262 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
263 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
264 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
265 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
267 if ( lo->ldo_tls_ciphersuite &&
268 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
270 Debug( LDAP_DEBUG_ANY,
271 "TLS: could not set cipher list %s.\n",
272 lo->ldo_tls_ciphersuite, 0, 0 );
277 if ( lo->ldo_tls_cacertfile == NULL && lo->ldo_tls_cacertdir == NULL &&
278 lo->ldo_tls_cacert.bv_val == NULL ) {
279 if ( !SSL_CTX_set_default_verify_paths( ctx ) ) {
280 Debug( LDAP_DEBUG_ANY, "TLS: "
281 "could not use default certificate paths", 0, 0, 0 );
287 if ( lo->ldo_tls_cacert.bv_val ) {
288 const unsigned char *pp = lo->ldo_tls_cacert.bv_val;
289 cert = d2i_X509( NULL, &pp, lo->ldo_tls_cacert.bv_len );
290 X509_STORE *store = SSL_CTX_get_cert_store( ctx );
291 if ( !X509_STORE_add_cert( store, cert )) {
292 Debug( LDAP_DEBUG_ANY, "TLS: "
293 "could not use CA certificate", 0, 0, 0 );
298 if (( lt->lt_cacertfile || lt->lt_cacertdir ) && !SSL_CTX_load_verify_locations( ctx,
299 lt->lt_cacertfile, lt->lt_cacertdir ) )
301 Debug( LDAP_DEBUG_ANY, "TLS: "
302 "could not load verify locations (file:`%s',dir:`%s').\n",
303 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
304 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
311 STACK_OF(X509_NAME) *calist;
312 /* List of CA names to send to a client */
313 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir, cert );
315 Debug( LDAP_DEBUG_ANY, "TLS: "
316 "could not load client CA list (file:`%s',dir:`%s').\n",
317 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
318 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
324 SSL_CTX_set_client_CA_list( ctx, calist );
330 if ( lo->ldo_tls_cert.bv_val )
332 const unsigned char *pp = lo->ldo_tls_cert.bv_val;
333 X509 *cert = d2i_X509( NULL, &pp, lo->ldo_tls_cert.bv_len );
334 if ( !SSL_CTX_use_certificate( ctx, cert )) {
335 Debug( LDAP_DEBUG_ANY,
336 "TLS: could not use certificate.\n", 0,0,0);
342 if ( lo->ldo_tls_certfile &&
343 !SSL_CTX_use_certificate_file( ctx,
344 lt->lt_certfile, SSL_FILETYPE_PEM ) )
346 Debug( LDAP_DEBUG_ANY,
347 "TLS: could not use certificate file `%s'.\n",
348 lo->ldo_tls_certfile,0,0);
353 /* Key validity is checked automatically if cert has already been set */
354 if ( lo->ldo_tls_key.bv_val )
356 const unsigned char *pp = lo->ldo_tls_key.bv_val;
357 EVP_PKEY *pkey = d2i_AutoPrivateKey( NULL, &pp, lo->ldo_tls_key.bv_len );
358 if ( !SSL_CTX_use_PrivateKey( ctx, pkey ))
360 Debug( LDAP_DEBUG_ANY,
361 "TLS: could not use private key.\n", 0,0,0);
365 EVP_PKEY_free( pkey );
367 if ( lo->ldo_tls_keyfile &&
368 !SSL_CTX_use_PrivateKey_file( ctx,
369 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
371 Debug( LDAP_DEBUG_ANY,
372 "TLS: could not use key file `%s'.\n",
373 lo->ldo_tls_keyfile,0,0);
378 if ( is_server && lo->ldo_tls_dhfile ) {
382 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
383 Debug( LDAP_DEBUG_ANY,
384 "TLS: could not use DH parameters file `%s'.\n",
385 lo->ldo_tls_dhfile,0,0);
389 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
390 Debug( LDAP_DEBUG_ANY,
391 "TLS: could not read DH parameters file `%s'.\n",
392 lo->ldo_tls_dhfile,0,0);
398 SSL_CTX_set_tmp_dh( ctx, dh );
399 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
403 if ( is_server && lo->ldo_tls_ecname ) {
405 Debug( LDAP_DEBUG_ANY,
406 "TLS: Elliptic Curves not supported.\n", 0,0,0 );
411 int nid = OBJ_sn2nid( lt->lt_ecname );
412 if ( nid == NID_undef ) {
413 Debug( LDAP_DEBUG_ANY,
414 "TLS: could not use EC name `%s'.\n",
415 lo->ldo_tls_ecname,0,0);
419 ecdh = EC_KEY_new_by_curve_name( nid );
420 if ( ecdh == NULL ) {
421 Debug( LDAP_DEBUG_ANY,
422 "TLS: could not generate key for EC name `%s'.\n",
423 lo->ldo_tls_ecname,0,0);
427 SSL_CTX_set_tmp_ecdh( ctx, ecdh );
428 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_ECDH_USE );
433 if ( tlso_opt_trace ) {
434 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
438 if ( lo->ldo_tls_require_cert ) {
440 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
441 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
442 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
446 SSL_CTX_set_verify( ctx, i,
447 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
448 tlso_verify_ok : tlso_verify_cb );
449 #if OPENSSL_VERSION_NUMBER < 0x10100000
450 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
452 #ifdef HAVE_OPENSSL_CRL
453 if ( lo->ldo_tls_crlcheck ) {
454 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
455 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
456 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
457 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
458 X509_STORE_set_flags( x509_s,
459 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
467 tlso_session_new( tls_ctx *ctx, int is_server )
469 tlso_ctx *c = (tlso_ctx *)ctx;
470 return (tls_session *)SSL_new( c );
474 tlso_session_connect( LDAP *ld, tls_session *sess )
476 tlso_session *s = (tlso_session *)sess;
478 /* Caller expects 0 = success, OpenSSL returns 1 = success */
479 return SSL_connect( s ) - 1;
483 tlso_session_accept( tls_session *sess )
485 tlso_session *s = (tlso_session *)sess;
487 /* Caller expects 0 = success, OpenSSL returns 1 = success */
488 return SSL_accept( s ) - 1;
492 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
494 tlso_session *s = (tlso_session *)sess;
496 /* 1 was subtracted above, offset it back now */
497 rc = SSL_get_error(s, rc+1);
498 if (rc == SSL_ERROR_WANT_READ) {
499 sb->sb_trans_needs_read = 1;
502 } else if (rc == SSL_ERROR_WANT_WRITE) {
503 sb->sb_trans_needs_write = 1;
506 } else if (rc == SSL_ERROR_WANT_CONNECT) {
513 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
516 const char *certerr=NULL;
517 tlso_session *s = (tlso_session *)sess;
519 rc = ERR_peek_error();
521 ERR_error_string_n( rc, err, sizeof(err) );
522 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
523 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
524 int certrc = SSL_get_verify_result(s);
525 certerr = (char *)X509_verify_cert_error_string(certrc);
527 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
528 certerr ? certerr : "", certerr ? ")" : "" );
535 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
537 tlso_session *s = (tlso_session *)sess;
541 x = SSL_get_certificate( s );
543 if (!x) return LDAP_INVALID_CREDENTIALS;
545 xn = X509_get_subject_name(x);
546 #if OPENSSL_VERSION_NUMBER < 0x10100000
547 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
548 der_dn->bv_val = xn->bytes->data;
552 der_dn->bv_val = NULL;
553 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
554 der_dn->bv_len = len;
557 /* Don't X509_free, the session is still using it */
562 tlso_get_cert( SSL *s )
564 /* If peer cert was bad, treat as if no cert was given */
565 if (SSL_get_verify_result(s)) {
568 return SSL_get_peer_certificate(s);
572 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
574 tlso_session *s = (tlso_session *)sess;
575 X509 *x = tlso_get_cert( s );
579 return LDAP_INVALID_CREDENTIALS;
581 xn = X509_get_subject_name(x);
582 #if OPENSSL_VERSION_NUMBER < 0x10100000
583 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
584 der_dn->bv_val = xn->bytes->data;
588 der_dn->bv_val = NULL;
589 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
590 der_dn->bv_len = len;
597 /* what kind of hostname were we given? */
603 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
605 tlso_session *s = (tlso_session *)sess;
606 int i, ret = LDAP_LOCAL_ERROR;
610 int ntype = IS_DNS, nlen;
612 struct in6_addr addr;
617 if( ldap_int_hostname &&
618 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
620 name = ldap_int_hostname;
626 x = tlso_get_cert(s);
628 Debug( LDAP_DEBUG_ANY,
629 "TLS: unable to get peer certificate.\n",
631 /* If this was a fatal condition, things would have
632 * aborted long before now.
638 if (inet_pton(AF_INET6, name, &addr)) {
642 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
643 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
646 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
649 STACK_OF(GENERAL_NAME) *alt;
651 ex = X509_get_ext(x, i);
652 alt = X509V3_EXT_d2i(ex);
658 if (ntype == IS_DNS) {
659 domain = strchr(name, '.');
661 len2 = nlen - (domain-name);
664 n = sk_GENERAL_NAME_num(alt);
665 for (i=0; i<n; i++) {
668 gn = sk_GENERAL_NAME_value(alt, i);
669 if (gn->type == GEN_DNS) {
670 if (ntype != IS_DNS) continue;
672 sn = (char *) ASN1_STRING_data(gn->d.ia5);
673 sl = ASN1_STRING_length(gn->d.ia5);
676 if (sl == 0) continue;
678 /* Is this an exact match? */
679 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
683 /* Is this a wildcard match? */
684 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
685 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
690 } else if (gn->type == GEN_IPADD) {
691 if (ntype == IS_DNS) continue;
693 sn = (char *) ASN1_STRING_data(gn->d.ia5);
694 sl = ASN1_STRING_length(gn->d.ia5);
697 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
701 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
704 if (!memcmp(sn, &addr, sl)) {
710 GENERAL_NAMES_free(alt);
711 if (i < n) { /* Found a match */
717 if (ret != LDAP_SUCCESS) {
721 ASN1_STRING *cn = NULL;
724 /* find the last CN */
725 obj = OBJ_nid2obj( NID_commonName );
726 if ( !obj ) goto no_cn; /* should never happen */
728 xn = X509_get_subject_name(x);
729 navas = X509_NAME_entry_count( xn );
730 for ( i=navas-1; i>=0; i-- ) {
731 ne = X509_NAME_get_entry( xn, i );
732 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
733 cn = X509_NAME_ENTRY_get_data( ne );
741 Debug( LDAP_DEBUG_ANY,
742 "TLS: unable to get common name from peer certificate.\n",
744 ret = LDAP_CONNECT_ERROR;
745 if ( ld->ld_error ) {
746 LDAP_FREE( ld->ld_error );
748 ld->ld_error = LDAP_STRDUP(
749 _("TLS: unable to get CN from peer certificate"));
751 } else if ( cn->length == nlen &&
752 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
755 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
756 char *domain = strchr(name, '.');
760 dlen = nlen - (domain-name);
762 /* Is this a wildcard match? */
763 if ((dlen == cn->length-1) &&
764 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
770 if( ret == LDAP_LOCAL_ERROR ) {
771 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
772 "common name in certificate (%.*s).\n",
773 name, cn->length, cn->data );
774 ret = LDAP_CONNECT_ERROR;
775 if ( ld->ld_error ) {
776 LDAP_FREE( ld->ld_error );
778 ld->ld_error = LDAP_STRDUP(
779 _("TLS: hostname does not match CN in peer certificate"));
787 tlso_session_strength( tls_session *sess )
789 tlso_session *s = (tlso_session *)sess;
791 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
795 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
797 tlso_session *s = (tlso_session *)sess;
799 /* Usually the client sends the finished msg. But if the
800 * session was resumed, the server sent the msg.
802 if (SSL_session_reused(s) ^ !is_server)
803 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
805 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
810 tlso_session_version( tls_session *sess )
812 tlso_session *s = (tlso_session *)sess;
813 return SSL_get_version(s);
817 tlso_session_cipher( tls_session *sess )
819 tlso_session *s = (tlso_session *)sess;
820 return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
824 tlso_session_peercert( tls_session *sess, struct berval *der )
826 tlso_session *s = (tlso_session *)sess;
828 X509 *x = SSL_get_peer_certificate(s);
829 der->bv_len = i2d_X509(x, NULL);
830 der->bv_val = LDAP_MALLOC(der->bv_len);
839 * TLS support for LBER Sockbufs
843 tlso_session *session;
844 Sockbuf_IO_Desc *sbiod;
847 #if OPENSSL_VERSION_NUMBER < 0x10100000
848 #define BIO_set_init(b, x) b->init = x
849 #define BIO_set_data(b, x) b->ptr = x
850 #define BIO_clear_flags(b, x) b->flags &= ~(x)
851 #define BIO_get_data(b) b->ptr
854 tlso_bio_create( BIO *b ) {
855 BIO_set_init( b, 1 );
856 BIO_set_data( b, NULL );
857 BIO_clear_flags( b, ~0 );
862 tlso_bio_destroy( BIO *b )
864 if ( b == NULL ) return 0;
866 BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
867 BIO_set_init( b, 0 );
868 BIO_clear_flags( b, ~0 );
873 tlso_bio_read( BIO *b, char *buf, int len )
878 if ( buf == NULL || len <= 0 ) return 0;
880 p = (struct tls_data *)BIO_get_data(b);
882 if ( p == NULL || p->sbiod == NULL ) {
886 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
888 BIO_clear_retry_flags( b );
890 int err = sock_errno();
891 if ( err == EAGAIN || err == EWOULDBLOCK ) {
892 BIO_set_retry_read( b );
900 tlso_bio_write( BIO *b, const char *buf, int len )
905 if ( buf == NULL || len <= 0 ) return 0;
907 p = (struct tls_data *)BIO_get_data(b);
909 if ( p == NULL || p->sbiod == NULL ) {
913 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
915 BIO_clear_retry_flags( b );
917 int err = sock_errno();
918 if ( err == EAGAIN || err == EWOULDBLOCK ) {
919 BIO_set_retry_write( b );
927 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
929 if ( cmd == BIO_CTRL_FLUSH ) {
930 /* The OpenSSL library needs this */
937 tlso_bio_gets( BIO *b, char *buf, int len )
943 tlso_bio_puts( BIO *b, const char *str )
945 return tlso_bio_write( b, str, strlen( str ) );
948 #if OPENSSL_VERSION_NUMBER >= 0x10100000
949 struct bio_method_st {
952 int (*bwrite) (BIO *, const char *, int);
953 int (*bread) (BIO *, char *, int);
954 int (*bputs) (BIO *, const char *);
955 int (*bgets) (BIO *, char *, int);
956 long (*ctrl) (BIO *, int, long, void *);
957 int (*create) (BIO *);
958 int (*destroy) (BIO *);
959 long (*callback_ctrl) (BIO *, int, bio_info_cb *);
963 static BIO_METHOD tlso_bio_method =
965 ( 100 | 0x400 ), /* it's a source/sink BIO */
977 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
982 assert( sbiod != NULL );
984 p = LBER_MALLOC( sizeof( *p ) );
991 bio = BIO_new( &tlso_bio_method );
992 BIO_set_data( bio, p );
993 SSL_set_bio( p->session, bio, bio );
994 sbiod->sbiod_pvt = p;
999 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
1003 assert( sbiod != NULL );
1004 assert( sbiod->sbiod_pvt != NULL );
1006 p = (struct tls_data *)sbiod->sbiod_pvt;
1007 SSL_free( p->session );
1008 LBER_FREE( sbiod->sbiod_pvt );
1009 sbiod->sbiod_pvt = NULL;
1014 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
1018 assert( sbiod != NULL );
1019 assert( sbiod->sbiod_pvt != NULL );
1021 p = (struct tls_data *)sbiod->sbiod_pvt;
1022 SSL_shutdown( p->session );
1027 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
1031 assert( sbiod != NULL );
1032 assert( sbiod->sbiod_pvt != NULL );
1034 p = (struct tls_data *)sbiod->sbiod_pvt;
1036 if ( opt == LBER_SB_OPT_GET_SSL ) {
1037 *((tlso_session **)arg) = p->session;
1040 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
1041 if( SSL_pending( p->session ) > 0 ) {
1046 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1050 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1056 assert( sbiod != NULL );
1057 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1059 p = (struct tls_data *)sbiod->sbiod_pvt;
1061 ret = SSL_read( p->session, (char *)buf, len );
1063 errno = WSAGetLastError();
1065 err = SSL_get_error( p->session, ret );
1066 if (err == SSL_ERROR_WANT_READ ) {
1067 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1068 sock_errset(EWOULDBLOCK);
1071 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1076 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1082 assert( sbiod != NULL );
1083 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1085 p = (struct tls_data *)sbiod->sbiod_pvt;
1087 ret = SSL_write( p->session, (char *)buf, len );
1089 errno = WSAGetLastError();
1091 err = SSL_get_error( p->session, ret );
1092 if (err == SSL_ERROR_WANT_WRITE ) {
1093 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1094 sock_errset(EWOULDBLOCK);
1097 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1102 static Sockbuf_IO tlso_sbio =
1104 tlso_sb_setup, /* sbi_setup */
1105 tlso_sb_remove, /* sbi_remove */
1106 tlso_sb_ctrl, /* sbi_ctrl */
1107 tlso_sb_read, /* sbi_read */
1108 tlso_sb_write, /* sbi_write */
1109 tlso_sb_close /* sbi_close */
1112 /* Derived from openssl/apps/s_cb.c */
1114 tlso_info_cb( const SSL *ssl, int where, int ret )
1118 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1120 w = where & ~SSL_ST_MASK;
1121 if ( w & SSL_ST_CONNECT ) {
1123 } else if ( w & SSL_ST_ACCEPT ) {
1131 state = LDAP_STRDUP( state );
1135 if ( where & SSL_CB_LOOP ) {
1136 Debug( LDAP_DEBUG_TRACE,
1137 "TLS trace: %s:%s\n",
1140 } else if ( where & SSL_CB_ALERT ) {
1141 char *atype = (char *) SSL_alert_type_string_long( ret );
1142 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1143 op = ( where & SSL_CB_READ ) ? "read" : "write";
1146 atype = LDAP_STRDUP( atype );
1150 adesc = LDAP_STRDUP( adesc );
1154 Debug( LDAP_DEBUG_TRACE,
1155 "TLS trace: SSL3 alert %s:%s:%s\n",
1158 if ( atype ) LDAP_FREE( atype );
1159 if ( adesc ) LDAP_FREE( adesc );
1161 } else if ( where & SSL_CB_EXIT ) {
1163 Debug( LDAP_DEBUG_TRACE,
1164 "TLS trace: %s:failed in %s\n",
1166 } else if ( ret < 0 ) {
1167 Debug( LDAP_DEBUG_TRACE,
1168 "TLS trace: %s:error in %s\n",
1173 if ( state ) LDAP_FREE( state );
1178 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1187 char *certerr = NULL;
1189 cert = X509_STORE_CTX_get_current_cert( ctx );
1190 errnum = X509_STORE_CTX_get_error( ctx );
1191 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1194 * X509_get_*_name return pointers to the internal copies of
1195 * those things requested. So do not free them.
1197 subject = X509_get_subject_name( cert );
1198 issuer = X509_get_issuer_name( cert );
1199 /* X509_NAME_oneline, if passed a NULL buf, allocate memory */
1200 sname = X509_NAME_oneline( subject, NULL, 0 );
1201 iname = X509_NAME_oneline( issuer, NULL, 0 );
1202 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1204 if ( sname ) __etoa( sname );
1205 if ( iname ) __etoa( iname );
1207 certerr = LDAP_STRDUP( certerr );
1211 Debug( LDAP_DEBUG_TRACE,
1212 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1214 sname ? sname : "-unknown-" );
1215 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1217 Debug( LDAP_DEBUG_ANY,
1218 "TLS certificate verification: Error, %s\n",
1222 OPENSSL_free ( sname );
1224 OPENSSL_free ( iname );
1226 if ( certerr ) LDAP_FREE( certerr );
1232 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1234 (void) tlso_verify_cb( ok, ctx );
1238 /* Inspired by ERR_print_errors in OpenSSL */
1240 tlso_report_error( void )
1247 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1248 ERR_error_string_n( l, buf, sizeof( buf ) );
1251 file = LDAP_STRDUP( file );
1252 __etoa( (char *)file );
1256 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1259 if ( file ) LDAP_FREE( (void *)file );
1264 #if OPENSSL_VERSION_NUMBER < 0x10100000
1266 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1269 /* FIXME: Pregenerate the key on startup */
1270 /* FIXME: Who frees the key? */
1271 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1272 BIGNUM *bn = BN_new();
1275 if ( BN_set_word( bn, RSA_F4 )) {
1276 tmp_rsa = RSA_new();
1277 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1278 RSA_free( tmp_rsa );
1285 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1289 Debug( LDAP_DEBUG_ANY,
1290 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1291 key_length, is_export ? "export" : "domestic", 0 );
1295 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1298 tlso_seed_PRNG( const char *randfile )
1300 #ifndef URANDOM_DEVICE
1301 /* no /dev/urandom (or equiv) */
1303 char buffer[MAXPATHLEN];
1305 if (randfile == NULL) {
1306 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1307 * If $HOME is not set or buffer too small to hold the pathname,
1308 * an error occurs. - From RAND_file_name() man page.
1309 * The fact is that when $HOME is NULL, .rnd is used.
1311 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1313 #ifndef OPENSSL_NO_EGD
1314 else if (RAND_egd(randfile) > 0) {
1320 if (randfile == NULL) {
1321 Debug( LDAP_DEBUG_ANY,
1322 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1327 total = RAND_load_file(randfile, -1);
1329 if (RAND_status() == 0) {
1330 Debug( LDAP_DEBUG_ANY,
1331 "TLS: PRNG not been seeded with enough data\n",
1336 /* assume if there was enough bits to seed that it's okay
1337 * to write derived bits to the file
1339 RAND_write_file(randfile);
1347 tls_impl ldap_int_tls_impl = {
1359 tlso_session_connect,
1360 tlso_session_accept,
1361 tlso_session_upflags,
1362 tlso_session_errmsg,
1364 tlso_session_peer_dn,
1365 tlso_session_chkhost,
1366 tlso_session_strength,
1367 tlso_session_unique,
1368 tlso_session_version,
1369 tlso_session_cipher,
1370 tlso_session_peercert,
1374 #ifdef LDAP_R_COMPILE
1383 #endif /* HAVE_OPENSSL */