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_set_default_verify_paths( ctx ) ) {
262 Debug( LDAP_DEBUG_ANY, "TLS: "
263 "could not use default certificate paths", 0, 0, 0 );
268 if ( !SSL_CTX_load_verify_locations( ctx,
269 lt->lt_cacertfile, lt->lt_cacertdir ) )
271 Debug( LDAP_DEBUG_ANY, "TLS: "
272 "could not load verify locations (file:`%s',dir:`%s').\n",
273 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
274 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
281 STACK_OF(X509_NAME) *calist;
282 /* List of CA names to send to a client */
283 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
285 Debug( LDAP_DEBUG_ANY, "TLS: "
286 "could not load client CA list (file:`%s',dir:`%s').\n",
287 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
288 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
294 SSL_CTX_set_client_CA_list( ctx, calist );
298 if ( lo->ldo_tls_certfile &&
299 !SSL_CTX_use_certificate_file( ctx,
300 lt->lt_certfile, SSL_FILETYPE_PEM ) )
302 Debug( LDAP_DEBUG_ANY,
303 "TLS: could not use certificate `%s'.\n",
304 lo->ldo_tls_certfile,0,0);
309 /* Key validity is checked automatically if cert has already been set */
310 if ( lo->ldo_tls_keyfile &&
311 !SSL_CTX_use_PrivateKey_file( ctx,
312 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
314 Debug( LDAP_DEBUG_ANY,
315 "TLS: could not use key file `%s'.\n",
316 lo->ldo_tls_keyfile,0,0);
321 if ( is_server && lo->ldo_tls_dhfile ) {
325 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
326 Debug( LDAP_DEBUG_ANY,
327 "TLS: could not use DH parameters file `%s'.\n",
328 lo->ldo_tls_dhfile,0,0);
332 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
333 Debug( LDAP_DEBUG_ANY,
334 "TLS: could not read DH parameters file `%s'.\n",
335 lo->ldo_tls_dhfile,0,0);
341 SSL_CTX_set_tmp_dh( ctx, dh );
342 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
346 if ( is_server && lo->ldo_tls_ecname ) {
348 Debug( LDAP_DEBUG_ANY,
349 "TLS: Elliptic Curves not supported.\n", 0,0,0 );
354 int nid = OBJ_sn2nid( lt->lt_ecname );
355 if ( nid == NID_undef ) {
356 Debug( LDAP_DEBUG_ANY,
357 "TLS: could not use EC name `%s'.\n",
358 lo->ldo_tls_ecname,0,0);
362 ecdh = EC_KEY_new_by_curve_name( nid );
363 if ( ecdh == NULL ) {
364 Debug( LDAP_DEBUG_ANY,
365 "TLS: could not generate key for EC name `%s'.\n",
366 lo->ldo_tls_ecname,0,0);
370 SSL_CTX_set_tmp_ecdh( ctx, ecdh );
371 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_ECDH_USE );
376 if ( tlso_opt_trace ) {
377 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
381 if ( lo->ldo_tls_require_cert ) {
383 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
384 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
385 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
389 SSL_CTX_set_verify( ctx, i,
390 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
391 tlso_verify_ok : tlso_verify_cb );
392 #if OPENSSL_VERSION_NUMBER < 0x10100000
393 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
395 #ifdef HAVE_OPENSSL_CRL
396 if ( lo->ldo_tls_crlcheck ) {
397 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
398 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
399 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
400 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
401 X509_STORE_set_flags( x509_s,
402 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
410 tlso_session_new( tls_ctx *ctx, int is_server )
412 tlso_ctx *c = (tlso_ctx *)ctx;
413 return (tls_session *)SSL_new( c );
417 tlso_session_connect( LDAP *ld, tls_session *sess )
419 tlso_session *s = (tlso_session *)sess;
421 /* Caller expects 0 = success, OpenSSL returns 1 = success */
422 return SSL_connect( s ) - 1;
426 tlso_session_accept( tls_session *sess )
428 tlso_session *s = (tlso_session *)sess;
430 /* Caller expects 0 = success, OpenSSL returns 1 = success */
431 return SSL_accept( s ) - 1;
435 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
437 tlso_session *s = (tlso_session *)sess;
439 /* 1 was subtracted above, offset it back now */
440 rc = SSL_get_error(s, rc+1);
441 if (rc == SSL_ERROR_WANT_READ) {
442 sb->sb_trans_needs_read = 1;
445 } else if (rc == SSL_ERROR_WANT_WRITE) {
446 sb->sb_trans_needs_write = 1;
449 } else if (rc == SSL_ERROR_WANT_CONNECT) {
456 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
459 const char *certerr=NULL;
460 tlso_session *s = (tlso_session *)sess;
462 rc = ERR_peek_error();
464 ERR_error_string_n( rc, err, sizeof(err) );
465 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
466 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
467 int certrc = SSL_get_verify_result(s);
468 certerr = (char *)X509_verify_cert_error_string(certrc);
470 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
471 certerr ? certerr : "", certerr ? ")" : "" );
478 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
480 tlso_session *s = (tlso_session *)sess;
484 x = SSL_get_certificate( s );
486 if (!x) return LDAP_INVALID_CREDENTIALS;
488 xn = X509_get_subject_name(x);
489 #if OPENSSL_VERSION_NUMBER < 0x10100000
490 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
491 der_dn->bv_val = xn->bytes->data;
495 der_dn->bv_val = NULL;
496 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
497 der_dn->bv_len = len;
500 /* Don't X509_free, the session is still using it */
505 tlso_get_cert( SSL *s )
507 /* If peer cert was bad, treat as if no cert was given */
508 if (SSL_get_verify_result(s)) {
511 return SSL_get_peer_certificate(s);
515 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
517 tlso_session *s = (tlso_session *)sess;
518 X509 *x = tlso_get_cert( s );
522 return LDAP_INVALID_CREDENTIALS;
524 xn = X509_get_subject_name(x);
525 #if OPENSSL_VERSION_NUMBER < 0x10100000
526 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
527 der_dn->bv_val = xn->bytes->data;
531 der_dn->bv_val = NULL;
532 X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
533 der_dn->bv_len = len;
540 /* what kind of hostname were we given? */
546 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
548 tlso_session *s = (tlso_session *)sess;
549 int i, ret = LDAP_LOCAL_ERROR;
553 int ntype = IS_DNS, nlen;
555 struct in6_addr addr;
560 if( ldap_int_hostname &&
561 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
563 name = ldap_int_hostname;
569 x = tlso_get_cert(s);
571 Debug( LDAP_DEBUG_ANY,
572 "TLS: unable to get peer certificate.\n",
574 /* If this was a fatal condition, things would have
575 * aborted long before now.
581 if (inet_pton(AF_INET6, name, &addr)) {
585 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
586 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
589 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
592 STACK_OF(GENERAL_NAME) *alt;
594 ex = X509_get_ext(x, i);
595 alt = X509V3_EXT_d2i(ex);
601 if (ntype == IS_DNS) {
602 domain = strchr(name, '.');
604 len2 = nlen - (domain-name);
607 n = sk_GENERAL_NAME_num(alt);
608 for (i=0; i<n; i++) {
611 gn = sk_GENERAL_NAME_value(alt, i);
612 if (gn->type == GEN_DNS) {
613 if (ntype != IS_DNS) continue;
615 sn = (char *) ASN1_STRING_data(gn->d.ia5);
616 sl = ASN1_STRING_length(gn->d.ia5);
619 if (sl == 0) continue;
621 /* Is this an exact match? */
622 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
626 /* Is this a wildcard match? */
627 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
628 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
633 } else if (gn->type == GEN_IPADD) {
634 if (ntype == IS_DNS) continue;
636 sn = (char *) ASN1_STRING_data(gn->d.ia5);
637 sl = ASN1_STRING_length(gn->d.ia5);
640 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
644 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
647 if (!memcmp(sn, &addr, sl)) {
653 GENERAL_NAMES_free(alt);
654 if (i < n) { /* Found a match */
660 if (ret != LDAP_SUCCESS) {
664 ASN1_STRING *cn = NULL;
667 /* find the last CN */
668 obj = OBJ_nid2obj( NID_commonName );
669 if ( !obj ) goto no_cn; /* should never happen */
671 xn = X509_get_subject_name(x);
672 navas = X509_NAME_entry_count( xn );
673 for ( i=navas-1; i>=0; i-- ) {
674 ne = X509_NAME_get_entry( xn, i );
675 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
676 cn = X509_NAME_ENTRY_get_data( ne );
684 Debug( LDAP_DEBUG_ANY,
685 "TLS: unable to get common name from peer certificate.\n",
687 ret = LDAP_CONNECT_ERROR;
688 if ( ld->ld_error ) {
689 LDAP_FREE( ld->ld_error );
691 ld->ld_error = LDAP_STRDUP(
692 _("TLS: unable to get CN from peer certificate"));
694 } else if ( cn->length == nlen &&
695 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
698 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
699 char *domain = strchr(name, '.');
703 dlen = nlen - (domain-name);
705 /* Is this a wildcard match? */
706 if ((dlen == cn->length-1) &&
707 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
713 if( ret == LDAP_LOCAL_ERROR ) {
714 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
715 "common name in certificate (%.*s).\n",
716 name, cn->length, cn->data );
717 ret = LDAP_CONNECT_ERROR;
718 if ( ld->ld_error ) {
719 LDAP_FREE( ld->ld_error );
721 ld->ld_error = LDAP_STRDUP(
722 _("TLS: hostname does not match CN in peer certificate"));
730 tlso_session_strength( tls_session *sess )
732 tlso_session *s = (tlso_session *)sess;
734 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
738 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
740 tlso_session *s = (tlso_session *)sess;
742 /* Usually the client sends the finished msg. But if the
743 * session was resumed, the server sent the msg.
745 if (SSL_session_reused(s) ^ !is_server)
746 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
748 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
753 tlso_session_version( tls_session *sess )
755 tlso_session *s = (tlso_session *)sess;
756 return SSL_get_version(s);
760 tlso_session_cipher( tls_session *sess )
762 tlso_session *s = (tlso_session *)sess;
763 return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
767 tlso_session_peercert( tls_session *sess, struct berval *der )
769 tlso_session *s = (tlso_session *)sess;
771 X509 *x = SSL_get_peer_certificate(s);
772 der->bv_len = i2d_X509(x, NULL);
773 der->bv_val = LDAP_MALLOC(der->bv_len);
782 * TLS support for LBER Sockbufs
786 tlso_session *session;
787 Sockbuf_IO_Desc *sbiod;
790 #if OPENSSL_VERSION_NUMBER < 0x10100000
791 #define BIO_set_init(b, x) b->init = x
792 #define BIO_set_data(b, x) b->ptr = x
793 #define BIO_clear_flags(b, x) b->flags &= ~(x)
794 #define BIO_get_data(b) b->ptr
797 tlso_bio_create( BIO *b ) {
798 BIO_set_init( b, 1 );
799 BIO_set_data( b, NULL );
800 BIO_clear_flags( b, ~0 );
805 tlso_bio_destroy( BIO *b )
807 if ( b == NULL ) return 0;
809 BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
810 BIO_set_init( b, 0 );
811 BIO_clear_flags( b, ~0 );
816 tlso_bio_read( BIO *b, char *buf, int len )
821 if ( buf == NULL || len <= 0 ) return 0;
823 p = (struct tls_data *)BIO_get_data(b);
825 if ( p == NULL || p->sbiod == NULL ) {
829 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
831 BIO_clear_retry_flags( b );
833 int err = sock_errno();
834 if ( err == EAGAIN || err == EWOULDBLOCK ) {
835 BIO_set_retry_read( b );
843 tlso_bio_write( BIO *b, const char *buf, int len )
848 if ( buf == NULL || len <= 0 ) return 0;
850 p = (struct tls_data *)BIO_get_data(b);
852 if ( p == NULL || p->sbiod == NULL ) {
856 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
858 BIO_clear_retry_flags( b );
860 int err = sock_errno();
861 if ( err == EAGAIN || err == EWOULDBLOCK ) {
862 BIO_set_retry_write( b );
870 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
872 if ( cmd == BIO_CTRL_FLUSH ) {
873 /* The OpenSSL library needs this */
880 tlso_bio_gets( BIO *b, char *buf, int len )
886 tlso_bio_puts( BIO *b, const char *str )
888 return tlso_bio_write( b, str, strlen( str ) );
891 #if OPENSSL_VERSION_NUMBER >= 0x10100000
892 struct bio_method_st {
895 int (*bwrite) (BIO *, const char *, int);
896 int (*bread) (BIO *, char *, int);
897 int (*bputs) (BIO *, const char *);
898 int (*bgets) (BIO *, char *, int);
899 long (*ctrl) (BIO *, int, long, void *);
900 int (*create) (BIO *);
901 int (*destroy) (BIO *);
902 long (*callback_ctrl) (BIO *, int, bio_info_cb *);
906 static BIO_METHOD tlso_bio_method =
908 ( 100 | 0x400 ), /* it's a source/sink BIO */
920 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
925 assert( sbiod != NULL );
927 p = LBER_MALLOC( sizeof( *p ) );
934 bio = BIO_new( &tlso_bio_method );
935 BIO_set_data( bio, p );
936 SSL_set_bio( p->session, bio, bio );
937 sbiod->sbiod_pvt = p;
942 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
946 assert( sbiod != NULL );
947 assert( sbiod->sbiod_pvt != NULL );
949 p = (struct tls_data *)sbiod->sbiod_pvt;
950 SSL_free( p->session );
951 LBER_FREE( sbiod->sbiod_pvt );
952 sbiod->sbiod_pvt = NULL;
957 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
961 assert( sbiod != NULL );
962 assert( sbiod->sbiod_pvt != NULL );
964 p = (struct tls_data *)sbiod->sbiod_pvt;
965 SSL_shutdown( p->session );
970 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
974 assert( sbiod != NULL );
975 assert( sbiod->sbiod_pvt != NULL );
977 p = (struct tls_data *)sbiod->sbiod_pvt;
979 if ( opt == LBER_SB_OPT_GET_SSL ) {
980 *((tlso_session **)arg) = p->session;
983 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
984 if( SSL_pending( p->session ) > 0 ) {
989 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
993 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
999 assert( sbiod != NULL );
1000 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1002 p = (struct tls_data *)sbiod->sbiod_pvt;
1004 ret = SSL_read( p->session, (char *)buf, len );
1006 errno = WSAGetLastError();
1008 err = SSL_get_error( p->session, ret );
1009 if (err == SSL_ERROR_WANT_READ ) {
1010 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1011 sock_errset(EWOULDBLOCK);
1014 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1019 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1025 assert( sbiod != NULL );
1026 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1028 p = (struct tls_data *)sbiod->sbiod_pvt;
1030 ret = SSL_write( p->session, (char *)buf, len );
1032 errno = WSAGetLastError();
1034 err = SSL_get_error( p->session, ret );
1035 if (err == SSL_ERROR_WANT_WRITE ) {
1036 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1037 sock_errset(EWOULDBLOCK);
1040 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1045 static Sockbuf_IO tlso_sbio =
1047 tlso_sb_setup, /* sbi_setup */
1048 tlso_sb_remove, /* sbi_remove */
1049 tlso_sb_ctrl, /* sbi_ctrl */
1050 tlso_sb_read, /* sbi_read */
1051 tlso_sb_write, /* sbi_write */
1052 tlso_sb_close /* sbi_close */
1055 /* Derived from openssl/apps/s_cb.c */
1057 tlso_info_cb( const SSL *ssl, int where, int ret )
1061 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1063 w = where & ~SSL_ST_MASK;
1064 if ( w & SSL_ST_CONNECT ) {
1066 } else if ( w & SSL_ST_ACCEPT ) {
1074 state = LDAP_STRDUP( state );
1078 if ( where & SSL_CB_LOOP ) {
1079 Debug( LDAP_DEBUG_TRACE,
1080 "TLS trace: %s:%s\n",
1083 } else if ( where & SSL_CB_ALERT ) {
1084 char *atype = (char *) SSL_alert_type_string_long( ret );
1085 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1086 op = ( where & SSL_CB_READ ) ? "read" : "write";
1089 atype = LDAP_STRDUP( atype );
1093 adesc = LDAP_STRDUP( adesc );
1097 Debug( LDAP_DEBUG_TRACE,
1098 "TLS trace: SSL3 alert %s:%s:%s\n",
1101 if ( atype ) LDAP_FREE( atype );
1102 if ( adesc ) LDAP_FREE( adesc );
1104 } else if ( where & SSL_CB_EXIT ) {
1106 Debug( LDAP_DEBUG_TRACE,
1107 "TLS trace: %s:failed in %s\n",
1109 } else if ( ret < 0 ) {
1110 Debug( LDAP_DEBUG_TRACE,
1111 "TLS trace: %s:error in %s\n",
1116 if ( state ) LDAP_FREE( state );
1121 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1130 char *certerr = NULL;
1132 cert = X509_STORE_CTX_get_current_cert( ctx );
1133 errnum = X509_STORE_CTX_get_error( ctx );
1134 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1137 * X509_get_*_name return pointers to the internal copies of
1138 * those things requested. So do not free them.
1140 subject = X509_get_subject_name( cert );
1141 issuer = X509_get_issuer_name( cert );
1142 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1143 sname = X509_NAME_oneline( subject, NULL, 0 );
1144 iname = X509_NAME_oneline( issuer, NULL, 0 );
1145 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1147 if ( sname ) __etoa( sname );
1148 if ( iname ) __etoa( iname );
1150 certerr = LDAP_STRDUP( certerr );
1154 Debug( LDAP_DEBUG_TRACE,
1155 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1157 sname ? sname : "-unknown-" );
1158 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1160 Debug( LDAP_DEBUG_ANY,
1161 "TLS certificate verification: Error, %s\n",
1165 CRYPTO_free ( sname );
1167 CRYPTO_free ( iname );
1169 if ( certerr ) LDAP_FREE( certerr );
1175 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1177 (void) tlso_verify_cb( ok, ctx );
1181 /* Inspired by ERR_print_errors in OpenSSL */
1183 tlso_report_error( void )
1190 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1191 ERR_error_string_n( l, buf, sizeof( buf ) );
1194 file = LDAP_STRDUP( file );
1195 __etoa( (char *)file );
1199 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1202 if ( file ) LDAP_FREE( (void *)file );
1207 #if OPENSSL_VERSION_NUMBER < 0x10100000
1209 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1212 /* FIXME: Pregenerate the key on startup */
1213 /* FIXME: Who frees the key? */
1214 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1215 BIGNUM *bn = BN_new();
1218 if ( BN_set_word( bn, RSA_F4 )) {
1219 tmp_rsa = RSA_new();
1220 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1221 RSA_free( tmp_rsa );
1228 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1232 Debug( LDAP_DEBUG_ANY,
1233 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1234 key_length, is_export ? "export" : "domestic", 0 );
1238 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1241 tlso_seed_PRNG( const char *randfile )
1243 #ifndef URANDOM_DEVICE
1244 /* no /dev/urandom (or equiv) */
1246 char buffer[MAXPATHLEN];
1248 if (randfile == NULL) {
1249 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1250 * If $HOME is not set or buffer too small to hold the pathname,
1251 * an error occurs. - From RAND_file_name() man page.
1252 * The fact is that when $HOME is NULL, .rnd is used.
1254 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1256 } else if (RAND_egd(randfile) > 0) {
1261 if (randfile == NULL) {
1262 Debug( LDAP_DEBUG_ANY,
1263 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1268 total = RAND_load_file(randfile, -1);
1270 if (RAND_status() == 0) {
1271 Debug( LDAP_DEBUG_ANY,
1272 "TLS: PRNG not been seeded with enough data\n",
1277 /* assume if there was enough bits to seed that it's okay
1278 * to write derived bits to the file
1280 RAND_write_file(randfile);
1288 tls_impl ldap_int_tls_impl = {
1300 tlso_session_connect,
1301 tlso_session_accept,
1302 tlso_session_upflags,
1303 tlso_session_errmsg,
1305 tlso_session_peer_dn,
1306 tlso_session_chkhost,
1307 tlso_session_strength,
1308 tlso_session_unique,
1309 tlso_session_version,
1310 tlso_session_cipher,
1311 tlso_session_peercert,
1315 #ifdef LDAP_R_COMPILE
1324 #endif /* HAVE_OPENSSL */