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 BIO_METHOD * tlso_bio_method = NULL;
58 static BIO_METHOD * tlso_bio_setup( void );
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 static int tlso_seed_PRNG( const char *randfile );
68 #if OPENSSL_VERSION_NUMBER < 0x10100000
70 * OpenSSL 1.1 API and later has new locking code
72 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
76 * provide mutexes for the OpenSSL library.
78 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
80 static void tlso_locking_cb( int mode, int type, const char *file, int line )
82 if ( mode & CRYPTO_LOCK ) {
83 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
85 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
89 static unsigned long tlso_thread_self( void )
91 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
92 * is an integral type that fits in an unsigned long
95 /* force an error if the ldap_pvt_thread_t type is too large */
96 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
97 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
99 return (unsigned long) ldap_pvt_thread_self();
102 static void tlso_thr_init( void )
106 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
107 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
109 CRYPTO_set_locking_callback( tlso_locking_cb );
110 CRYPTO_set_id_callback( tlso_thread_self );
112 #endif /* LDAP_R_COMPILE */
114 #ifdef LDAP_R_COMPILE
115 static void tlso_thr_init( void ) {}
117 #endif /* OpenSSL 1.1 */
119 #if OPENSSL_VERSION_NUMBER < 0x10100000
121 * OpenSSL 1.1 API and later makes the BIO method concrete types internal.
125 BIO_meth_new( int type, const char *name )
127 BIO_METHOD *method = LDAP_MALLOC( sizeof(BIO_METHOD) );
128 memset( method, 0, sizeof(BIO_METHOD) );
137 BIO_meth_free( BIO_METHOD *meth )
139 if ( meth == NULL ) {
146 #define BIO_meth_set_write(m, f) (m)->bwrite = (f)
147 #define BIO_meth_set_read(m, f) (m)->bread = (f)
148 #define BIO_meth_set_puts(m, f) (m)->bputs = (f)
149 #define BIO_meth_set_gets(m, f) (m)->bgets = (f)
150 #define BIO_meth_set_ctrl(m, f) (m)->ctrl = (f)
151 #define BIO_meth_set_create(m, f) (m)->create = (f)
152 #define BIO_meth_set_destroy(m, f) (m)->destroy = (f)
154 #endif /* OpenSSL 1.1 */
156 static STACK_OF(X509_NAME) *
157 tlso_ca_list( char * bundle, char * dir, X509 *cert )
159 STACK_OF(X509_NAME) *ca_list = NULL;
162 ca_list = SSL_load_client_CA_file( bundle );
164 #if defined(HAVE_DIRENT_H) || defined(dirent)
169 ca_list = sk_X509_NAME_new_null();
172 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
174 sk_X509_NAME_free( ca_list );
180 X509_NAME *xn = X509_get_subject_name( cert );
181 xn = X509_NAME_dup( xn );
183 ca_list = sk_X509_NAME_new_null();
185 sk_X509_NAME_push( ca_list, xn );
191 * Initialize TLS subsystem. Should be called only once.
196 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
199 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
200 if ( file ) __atoe( file );
201 (void) tlso_seed_PRNG( file );
205 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
208 #if OPENSSL_VERSION_NUMBER < 0x10100000
209 SSL_load_error_strings();
211 OpenSSL_add_all_digests();
213 OPENSSL_init_ssl(0, NULL);
216 /* FIXME: mod_ssl does this */
217 X509V3_add_standard_extensions();
219 tlso_bio_method = tlso_bio_setup();
225 * Tear down the TLS subsystem. Should only be called once.
230 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
232 BIO_meth_free( tlso_bio_method );
234 #if OPENSSL_VERSION_NUMBER < 0x10100000
236 #if OPENSSL_VERSION_NUMBER < 0x10000000
239 ERR_remove_thread_state(NULL);
244 if ( lo->ldo_tls_randfile ) {
245 LDAP_FREE( lo->ldo_tls_randfile );
246 lo->ldo_tls_randfile = NULL;
251 tlso_ctx_new( struct ldapoptions *lo )
253 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
257 tlso_ctx_ref( tls_ctx *ctx )
259 tlso_ctx *c = (tlso_ctx *)ctx;
260 #if OPENSSL_VERSION_NUMBER < 0x10100000
261 #define SSL_CTX_up_ref(ctx) CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
267 tlso_ctx_free ( tls_ctx *ctx )
269 tlso_ctx *c = (tlso_ctx *)ctx;
274 * initialize a new TLS context
277 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
279 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
283 SSL_CTX_set_session_id_context( ctx,
284 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
287 #ifdef SSL_OP_NO_TLSv1
288 #ifdef SSL_OP_NO_TLSv1_1
289 #ifdef SSL_OP_NO_TLSv1_2
290 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
291 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
292 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
296 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
297 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
298 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
301 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
302 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
306 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
307 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
308 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
309 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
311 if ( lo->ldo_tls_ciphersuite &&
312 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
314 Debug( LDAP_DEBUG_ANY,
315 "TLS: could not set cipher list %s.\n",
316 lo->ldo_tls_ciphersuite, 0, 0 );
321 if ( lo->ldo_tls_cacertfile == NULL && lo->ldo_tls_cacertdir == NULL &&
322 lo->ldo_tls_cacert.bv_val == NULL ) {
323 if ( !SSL_CTX_set_default_verify_paths( ctx ) ) {
324 Debug( LDAP_DEBUG_ANY, "TLS: "
325 "could not use default certificate paths", 0, 0, 0 );
331 if ( lo->ldo_tls_cacert.bv_val ) {
332 const unsigned char *pp = lo->ldo_tls_cacert.bv_val;
333 cert = d2i_X509( NULL, &pp, lo->ldo_tls_cacert.bv_len );
334 X509_STORE *store = SSL_CTX_get_cert_store( ctx );
335 if ( !X509_STORE_add_cert( store, cert )) {
336 Debug( LDAP_DEBUG_ANY, "TLS: "
337 "could not use CA certificate", 0, 0, 0 );
342 if (( lt->lt_cacertfile || lt->lt_cacertdir ) && !SSL_CTX_load_verify_locations( ctx,
343 lt->lt_cacertfile, lt->lt_cacertdir ) )
345 Debug( LDAP_DEBUG_ANY, "TLS: "
346 "could not load verify locations (file:`%s',dir:`%s').\n",
347 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
348 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
355 STACK_OF(X509_NAME) *calist;
356 /* List of CA names to send to a client */
357 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir, cert );
359 Debug( LDAP_DEBUG_ANY, "TLS: "
360 "could not load client CA list (file:`%s',dir:`%s').\n",
361 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
362 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
368 SSL_CTX_set_client_CA_list( ctx, calist );
374 if ( lo->ldo_tls_cert.bv_val )
376 const unsigned char *pp = lo->ldo_tls_cert.bv_val;
377 X509 *cert = d2i_X509( NULL, &pp, lo->ldo_tls_cert.bv_len );
378 if ( !SSL_CTX_use_certificate( ctx, cert )) {
379 Debug( LDAP_DEBUG_ANY,
380 "TLS: could not use certificate.\n", 0,0,0);
386 if ( lo->ldo_tls_certfile &&
387 !SSL_CTX_use_certificate_file( ctx,
388 lt->lt_certfile, SSL_FILETYPE_PEM ) )
390 Debug( LDAP_DEBUG_ANY,
391 "TLS: could not use certificate file `%s'.\n",
392 lo->ldo_tls_certfile,0,0);
397 /* Key validity is checked automatically if cert has already been set */
398 if ( lo->ldo_tls_key.bv_val )
400 const unsigned char *pp = lo->ldo_tls_key.bv_val;
401 EVP_PKEY *pkey = d2i_AutoPrivateKey( NULL, &pp, lo->ldo_tls_key.bv_len );
402 if ( !SSL_CTX_use_PrivateKey( ctx, pkey ))
404 Debug( LDAP_DEBUG_ANY,
405 "TLS: could not use private key.\n", 0,0,0);
409 EVP_PKEY_free( pkey );
411 if ( lo->ldo_tls_keyfile &&
412 !SSL_CTX_use_PrivateKey_file( ctx,
413 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
415 Debug( LDAP_DEBUG_ANY,
416 "TLS: could not use key file `%s'.\n",
417 lo->ldo_tls_keyfile,0,0);
422 if ( is_server && lo->ldo_tls_dhfile ) {
426 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
427 Debug( LDAP_DEBUG_ANY,
428 "TLS: could not use DH parameters file `%s'.\n",
429 lo->ldo_tls_dhfile,0,0);
433 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
434 Debug( LDAP_DEBUG_ANY,
435 "TLS: could not read DH parameters file `%s'.\n",
436 lo->ldo_tls_dhfile,0,0);
442 SSL_CTX_set_tmp_dh( ctx, dh );
443 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
447 if ( is_server && lo->ldo_tls_ecname ) {
449 Debug( LDAP_DEBUG_ANY,
450 "TLS: Elliptic Curves not supported.\n", 0,0,0 );
455 int nid = OBJ_sn2nid( lt->lt_ecname );
456 if ( nid == NID_undef ) {
457 Debug( LDAP_DEBUG_ANY,
458 "TLS: could not use EC name `%s'.\n",
459 lo->ldo_tls_ecname,0,0);
463 ecdh = EC_KEY_new_by_curve_name( nid );
464 if ( ecdh == NULL ) {
465 Debug( LDAP_DEBUG_ANY,
466 "TLS: could not generate key for EC name `%s'.\n",
467 lo->ldo_tls_ecname,0,0);
471 SSL_CTX_set_tmp_ecdh( ctx, ecdh );
472 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_ECDH_USE );
477 if ( tlso_opt_trace ) {
478 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
482 if ( lo->ldo_tls_require_cert ) {
484 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
485 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
486 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
490 SSL_CTX_set_verify( ctx, i,
491 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
492 tlso_verify_ok : tlso_verify_cb );
493 #if OPENSSL_VERSION_NUMBER < 0x10100000
494 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
496 #ifdef HAVE_OPENSSL_CRL
497 if ( lo->ldo_tls_crlcheck ) {
498 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
499 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
500 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
501 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
502 X509_STORE_set_flags( x509_s,
503 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
511 tlso_session_new( tls_ctx *ctx, int is_server )
513 tlso_ctx *c = (tlso_ctx *)ctx;
514 return (tls_session *)SSL_new( c );
518 tlso_session_connect( LDAP *ld, tls_session *sess )
520 tlso_session *s = (tlso_session *)sess;
522 /* Caller expects 0 = success, OpenSSL returns 1 = success */
523 return SSL_connect( s ) - 1;
527 tlso_session_accept( tls_session *sess )
529 tlso_session *s = (tlso_session *)sess;
531 /* Caller expects 0 = success, OpenSSL returns 1 = success */
532 return SSL_accept( s ) - 1;
536 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
538 tlso_session *s = (tlso_session *)sess;
540 /* 1 was subtracted above, offset it back now */
541 rc = SSL_get_error(s, rc+1);
542 if (rc == SSL_ERROR_WANT_READ) {
543 sb->sb_trans_needs_read = 1;
546 } else if (rc == SSL_ERROR_WANT_WRITE) {
547 sb->sb_trans_needs_write = 1;
550 } else if (rc == SSL_ERROR_WANT_CONNECT) {
557 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
560 const char *certerr=NULL;
561 tlso_session *s = (tlso_session *)sess;
563 rc = ERR_peek_error();
565 ERR_error_string_n( rc, err, sizeof(err) );
566 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
567 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
568 int certrc = SSL_get_verify_result(s);
569 certerr = (char *)X509_verify_cert_error_string(certrc);
571 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
572 certerr ? certerr : "", certerr ? ")" : "" );
579 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
581 tlso_session *s = (tlso_session *)sess;
585 x = SSL_get_certificate( s );
587 if (!x) return LDAP_INVALID_CREDENTIALS;
589 xn = X509_get_subject_name(x);
590 #if OPENSSL_VERSION_NUMBER < 0x10100000
591 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
592 der_dn->bv_val = xn->bytes->data;
596 der_dn->bv_val = NULL;
597 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
598 der_dn->bv_len = len;
601 /* Don't X509_free, the session is still using it */
606 tlso_get_cert( SSL *s )
608 /* If peer cert was bad, treat as if no cert was given */
609 if (SSL_get_verify_result(s)) {
612 return SSL_get_peer_certificate(s);
616 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
618 tlso_session *s = (tlso_session *)sess;
619 X509 *x = tlso_get_cert( s );
623 return LDAP_INVALID_CREDENTIALS;
625 xn = X509_get_subject_name(x);
626 #if OPENSSL_VERSION_NUMBER < 0x10100000
627 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
628 der_dn->bv_val = xn->bytes->data;
632 der_dn->bv_val = NULL;
633 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
634 der_dn->bv_len = len;
641 /* what kind of hostname were we given? */
647 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
649 tlso_session *s = (tlso_session *)sess;
650 int i, ret = LDAP_LOCAL_ERROR;
654 int ntype = IS_DNS, nlen;
656 struct in6_addr addr;
661 if( ldap_int_hostname &&
662 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
664 name = ldap_int_hostname;
670 x = tlso_get_cert(s);
672 Debug( LDAP_DEBUG_ANY,
673 "TLS: unable to get peer certificate.\n",
675 /* If this was a fatal condition, things would have
676 * aborted long before now.
682 if (inet_pton(AF_INET6, name, &addr)) {
686 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
687 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
690 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
693 STACK_OF(GENERAL_NAME) *alt;
695 ex = X509_get_ext(x, i);
696 alt = X509V3_EXT_d2i(ex);
702 if (ntype == IS_DNS) {
703 domain = strchr(name, '.');
705 len2 = nlen - (domain-name);
708 n = sk_GENERAL_NAME_num(alt);
709 for (i=0; i<n; i++) {
712 gn = sk_GENERAL_NAME_value(alt, i);
713 if (gn->type == GEN_DNS) {
714 if (ntype != IS_DNS) continue;
716 sn = (char *) ASN1_STRING_data(gn->d.ia5);
717 sl = ASN1_STRING_length(gn->d.ia5);
720 if (sl == 0) continue;
722 /* Is this an exact match? */
723 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
727 /* Is this a wildcard match? */
728 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
729 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
734 } else if (gn->type == GEN_IPADD) {
735 if (ntype == IS_DNS) continue;
737 sn = (char *) ASN1_STRING_data(gn->d.ia5);
738 sl = ASN1_STRING_length(gn->d.ia5);
741 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
745 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
748 if (!memcmp(sn, &addr, sl)) {
754 GENERAL_NAMES_free(alt);
755 if (i < n) { /* Found a match */
761 if (ret != LDAP_SUCCESS) {
765 ASN1_STRING *cn = NULL;
768 /* find the last CN */
769 obj = OBJ_nid2obj( NID_commonName );
770 if ( !obj ) goto no_cn; /* should never happen */
772 xn = X509_get_subject_name(x);
773 navas = X509_NAME_entry_count( xn );
774 for ( i=navas-1; i>=0; i-- ) {
775 ne = X509_NAME_get_entry( xn, i );
776 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
777 cn = X509_NAME_ENTRY_get_data( ne );
785 Debug( LDAP_DEBUG_ANY,
786 "TLS: unable to get common name from peer certificate.\n",
788 ret = LDAP_CONNECT_ERROR;
789 if ( ld->ld_error ) {
790 LDAP_FREE( ld->ld_error );
792 ld->ld_error = LDAP_STRDUP(
793 _("TLS: unable to get CN from peer certificate"));
795 } else if ( cn->length == nlen &&
796 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
799 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
800 char *domain = strchr(name, '.');
804 dlen = nlen - (domain-name);
806 /* Is this a wildcard match? */
807 if ((dlen == cn->length-1) &&
808 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
814 if( ret == LDAP_LOCAL_ERROR ) {
815 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
816 "common name in certificate (%.*s).\n",
817 name, cn->length, cn->data );
818 ret = LDAP_CONNECT_ERROR;
819 if ( ld->ld_error ) {
820 LDAP_FREE( ld->ld_error );
822 ld->ld_error = LDAP_STRDUP(
823 _("TLS: hostname does not match CN in peer certificate"));
831 tlso_session_strength( tls_session *sess )
833 tlso_session *s = (tlso_session *)sess;
835 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
839 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
841 tlso_session *s = (tlso_session *)sess;
843 /* Usually the client sends the finished msg. But if the
844 * session was resumed, the server sent the msg.
846 if (SSL_session_reused(s) ^ !is_server)
847 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
849 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
854 tlso_session_version( tls_session *sess )
856 tlso_session *s = (tlso_session *)sess;
857 return SSL_get_version(s);
861 tlso_session_cipher( tls_session *sess )
863 tlso_session *s = (tlso_session *)sess;
864 return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
868 tlso_session_peercert( tls_session *sess, struct berval *der )
870 tlso_session *s = (tlso_session *)sess;
872 X509 *x = SSL_get_peer_certificate(s);
873 der->bv_len = i2d_X509(x, NULL);
874 der->bv_val = LDAP_MALLOC(der->bv_len);
883 tlso_session_pinning( LDAP *ld, tls_session *sess, char *hashalg, struct berval *hash )
885 tlso_session *s = (tlso_session *)sess;
886 unsigned char *tmp, digest[EVP_MAX_MD_SIZE];
888 keyhash = { .bv_val = digest, .bv_len = sizeof(digest) };
889 X509 *cert = SSL_get_peer_certificate(s);
890 int len, rc = LDAP_SUCCESS;
892 len = i2d_X509_PUBKEY( X509_get_X509_PUBKEY(cert), NULL );
894 key.bv_val = tmp = LDAP_MALLOC( len );
899 key.bv_len = i2d_X509_PUBKEY( X509_get_X509_PUBKEY(cert), &tmp );
904 unsigned int len = keyhash.bv_len;
906 md = EVP_get_digestbyname( hashalg );
908 Debug( LDAP_DEBUG_TRACE, "tlso_session_pinning: "
909 "hash %s not recognised by OpenSSL\n", hashalg, 0, 0 );
914 #if OPENSSL_VERSION_NUMBER >= 0x10100000
915 mdctx = EVP_MD_CTX_new();
917 mdctx = EVP_MD_CTX_create();
924 EVP_DigestInit_ex( mdctx, md, NULL );
925 EVP_DigestUpdate( mdctx, key.bv_val, key.bv_len );
926 EVP_DigestFinal_ex( mdctx, (unsigned char *)keyhash.bv_val, &len );
927 keyhash.bv_len = len;
928 #if OPENSSL_VERSION_NUMBER >= 0x10100000
929 EVP_MD_CTX_free( mdctx );
931 EVP_MD_CTX_destroy( mdctx );
937 if ( ber_bvcmp( hash, &keyhash ) ) {
938 rc = LDAP_CONNECT_ERROR;
939 Debug( LDAP_DEBUG_ANY, "tlso_session_pinning: "
940 "public key hash does not match provided pin.\n", 0, 0, 0 );
941 if ( ld->ld_error ) {
942 LDAP_FREE( ld->ld_error );
944 ld->ld_error = LDAP_STRDUP(
945 _("TLS: public key hash does not match provided pin"));
949 LDAP_FREE( key.bv_val );
954 * TLS support for LBER Sockbufs
958 tlso_session *session;
959 Sockbuf_IO_Desc *sbiod;
962 #if OPENSSL_VERSION_NUMBER < 0x10100000
963 #define BIO_set_init(b, x) b->init = x
964 #define BIO_set_data(b, x) b->ptr = x
965 #define BIO_clear_flags(b, x) b->flags &= ~(x)
966 #define BIO_get_data(b) b->ptr
969 tlso_bio_create( BIO *b ) {
970 BIO_set_init( b, 1 );
971 BIO_set_data( b, NULL );
972 BIO_clear_flags( b, ~0 );
977 tlso_bio_destroy( BIO *b )
979 if ( b == NULL ) return 0;
981 BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
982 BIO_set_init( b, 0 );
983 BIO_clear_flags( b, ~0 );
988 tlso_bio_read( BIO *b, char *buf, int len )
993 if ( buf == NULL || len <= 0 ) return 0;
995 p = (struct tls_data *)BIO_get_data(b);
997 if ( p == NULL || p->sbiod == NULL ) {
1001 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
1003 BIO_clear_retry_flags( b );
1005 int err = sock_errno();
1006 if ( err == EAGAIN || err == EWOULDBLOCK ) {
1007 BIO_set_retry_read( b );
1015 tlso_bio_write( BIO *b, const char *buf, int len )
1020 if ( buf == NULL || len <= 0 ) return 0;
1022 p = (struct tls_data *)BIO_get_data(b);
1024 if ( p == NULL || p->sbiod == NULL ) {
1028 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
1030 BIO_clear_retry_flags( b );
1032 int err = sock_errno();
1033 if ( err == EAGAIN || err == EWOULDBLOCK ) {
1034 BIO_set_retry_write( b );
1042 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
1044 if ( cmd == BIO_CTRL_FLUSH ) {
1045 /* The OpenSSL library needs this */
1052 tlso_bio_gets( BIO *b, char *buf, int len )
1058 tlso_bio_puts( BIO *b, const char *str )
1060 return tlso_bio_write( b, str, strlen( str ) );
1064 tlso_bio_setup( void )
1066 /* it's a source/sink BIO */
1067 BIO_METHOD * method = BIO_meth_new( 100 | 0x400, "sockbuf glue" );
1068 BIO_meth_set_write( method, tlso_bio_write );
1069 BIO_meth_set_read( method, tlso_bio_read );
1070 BIO_meth_set_puts( method, tlso_bio_puts );
1071 BIO_meth_set_gets( method, tlso_bio_gets );
1072 BIO_meth_set_ctrl( method, tlso_bio_ctrl );
1073 BIO_meth_set_create( method, tlso_bio_create );
1074 BIO_meth_set_destroy( method, tlso_bio_destroy );
1080 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
1085 assert( sbiod != NULL );
1087 p = LBER_MALLOC( sizeof( *p ) );
1094 bio = BIO_new( tlso_bio_method );
1095 BIO_set_data( bio, p );
1096 SSL_set_bio( p->session, bio, bio );
1097 sbiod->sbiod_pvt = p;
1102 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
1106 assert( sbiod != NULL );
1107 assert( sbiod->sbiod_pvt != NULL );
1109 p = (struct tls_data *)sbiod->sbiod_pvt;
1110 SSL_free( p->session );
1111 LBER_FREE( sbiod->sbiod_pvt );
1112 sbiod->sbiod_pvt = NULL;
1117 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
1121 assert( sbiod != NULL );
1122 assert( sbiod->sbiod_pvt != NULL );
1124 p = (struct tls_data *)sbiod->sbiod_pvt;
1125 SSL_shutdown( p->session );
1130 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
1134 assert( sbiod != NULL );
1135 assert( sbiod->sbiod_pvt != NULL );
1137 p = (struct tls_data *)sbiod->sbiod_pvt;
1139 if ( opt == LBER_SB_OPT_GET_SSL ) {
1140 *((tlso_session **)arg) = p->session;
1143 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
1144 if( SSL_pending( p->session ) > 0 ) {
1149 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1153 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1159 assert( sbiod != NULL );
1160 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1162 p = (struct tls_data *)sbiod->sbiod_pvt;
1164 ret = SSL_read( p->session, (char *)buf, len );
1166 errno = WSAGetLastError();
1168 err = SSL_get_error( p->session, ret );
1169 if (err == SSL_ERROR_WANT_READ ) {
1170 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1171 sock_errset(EWOULDBLOCK);
1174 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1179 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1185 assert( sbiod != NULL );
1186 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1188 p = (struct tls_data *)sbiod->sbiod_pvt;
1190 ret = SSL_write( p->session, (char *)buf, len );
1192 errno = WSAGetLastError();
1194 err = SSL_get_error( p->session, ret );
1195 if (err == SSL_ERROR_WANT_WRITE ) {
1196 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1197 sock_errset(EWOULDBLOCK);
1200 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1205 static Sockbuf_IO tlso_sbio =
1207 tlso_sb_setup, /* sbi_setup */
1208 tlso_sb_remove, /* sbi_remove */
1209 tlso_sb_ctrl, /* sbi_ctrl */
1210 tlso_sb_read, /* sbi_read */
1211 tlso_sb_write, /* sbi_write */
1212 tlso_sb_close /* sbi_close */
1215 /* Derived from openssl/apps/s_cb.c */
1217 tlso_info_cb( const SSL *ssl, int where, int ret )
1221 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1223 w = where & ~SSL_ST_MASK;
1224 if ( w & SSL_ST_CONNECT ) {
1226 } else if ( w & SSL_ST_ACCEPT ) {
1234 state = LDAP_STRDUP( state );
1238 if ( where & SSL_CB_LOOP ) {
1239 Debug( LDAP_DEBUG_TRACE,
1240 "TLS trace: %s:%s\n",
1243 } else if ( where & SSL_CB_ALERT ) {
1244 char *atype = (char *) SSL_alert_type_string_long( ret );
1245 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1246 op = ( where & SSL_CB_READ ) ? "read" : "write";
1249 atype = LDAP_STRDUP( atype );
1253 adesc = LDAP_STRDUP( adesc );
1257 Debug( LDAP_DEBUG_TRACE,
1258 "TLS trace: SSL3 alert %s:%s:%s\n",
1261 if ( atype ) LDAP_FREE( atype );
1262 if ( adesc ) LDAP_FREE( adesc );
1264 } else if ( where & SSL_CB_EXIT ) {
1266 Debug( LDAP_DEBUG_TRACE,
1267 "TLS trace: %s:failed in %s\n",
1269 } else if ( ret < 0 ) {
1270 Debug( LDAP_DEBUG_TRACE,
1271 "TLS trace: %s:error in %s\n",
1276 if ( state ) LDAP_FREE( state );
1281 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1290 char *certerr = NULL;
1292 cert = X509_STORE_CTX_get_current_cert( ctx );
1293 errnum = X509_STORE_CTX_get_error( ctx );
1294 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1297 * X509_get_*_name return pointers to the internal copies of
1298 * those things requested. So do not free them.
1300 subject = X509_get_subject_name( cert );
1301 issuer = X509_get_issuer_name( cert );
1302 /* X509_NAME_oneline, if passed a NULL buf, allocate memory */
1303 sname = X509_NAME_oneline( subject, NULL, 0 );
1304 iname = X509_NAME_oneline( issuer, NULL, 0 );
1305 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1307 if ( sname ) __etoa( sname );
1308 if ( iname ) __etoa( iname );
1310 certerr = LDAP_STRDUP( certerr );
1314 Debug( LDAP_DEBUG_TRACE,
1315 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1317 sname ? sname : "-unknown-" );
1318 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1320 Debug( LDAP_DEBUG_ANY,
1321 "TLS certificate verification: Error, %s\n",
1325 OPENSSL_free ( sname );
1327 OPENSSL_free ( iname );
1329 if ( certerr ) LDAP_FREE( certerr );
1335 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1337 (void) tlso_verify_cb( ok, ctx );
1341 /* Inspired by ERR_print_errors in OpenSSL */
1343 tlso_report_error( void )
1350 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1351 ERR_error_string_n( l, buf, sizeof( buf ) );
1354 file = LDAP_STRDUP( file );
1355 __etoa( (char *)file );
1359 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1362 if ( file ) LDAP_FREE( (void *)file );
1367 #if OPENSSL_VERSION_NUMBER < 0x10100000
1369 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1372 /* FIXME: Pregenerate the key on startup */
1373 /* FIXME: Who frees the key? */
1374 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1375 BIGNUM *bn = BN_new();
1378 if ( BN_set_word( bn, RSA_F4 )) {
1379 tmp_rsa = RSA_new();
1380 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1381 RSA_free( tmp_rsa );
1388 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1392 Debug( LDAP_DEBUG_ANY,
1393 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1394 key_length, is_export ? "export" : "domestic", 0 );
1398 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1401 tlso_seed_PRNG( const char *randfile )
1403 #ifndef URANDOM_DEVICE
1404 /* no /dev/urandom (or equiv) */
1406 char buffer[MAXPATHLEN];
1408 if (randfile == NULL) {
1409 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1410 * If $HOME is not set or buffer too small to hold the pathname,
1411 * an error occurs. - From RAND_file_name() man page.
1412 * The fact is that when $HOME is NULL, .rnd is used.
1414 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1416 #ifndef OPENSSL_NO_EGD
1417 else if (RAND_egd(randfile) > 0) {
1423 if (randfile == NULL) {
1424 Debug( LDAP_DEBUG_ANY,
1425 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1430 total = RAND_load_file(randfile, -1);
1432 if (RAND_status() == 0) {
1433 Debug( LDAP_DEBUG_ANY,
1434 "TLS: PRNG not been seeded with enough data\n",
1439 /* assume if there was enough bits to seed that it's okay
1440 * to write derived bits to the file
1442 RAND_write_file(randfile);
1450 tls_impl ldap_int_tls_impl = {
1462 tlso_session_connect,
1463 tlso_session_accept,
1464 tlso_session_upflags,
1465 tlso_session_errmsg,
1467 tlso_session_peer_dn,
1468 tlso_session_chkhost,
1469 tlso_session_strength,
1470 tlso_session_unique,
1471 tlso_session_version,
1472 tlso_session_cipher,
1473 tlso_session_peercert,
1474 tlso_session_pinning,
1478 #ifdef LDAP_R_COMPILE
1487 #endif /* HAVE_OPENSSL */