1 /* tls_o.c - Handle tls/ssl using OpenSSL */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2015 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 typedef SSL_CTX tlso_ctx;
51 typedef SSL tlso_session;
53 static int tlso_opt_trace = 1;
55 static void tlso_report_error( void );
57 static void tlso_info_cb( const SSL *ssl, int where, int ret );
58 static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
59 static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
60 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
62 static int tlso_seed_PRNG( const char *randfile );
66 * provide mutexes for the OpenSSL library.
68 static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
70 static void tlso_locking_cb( int mode, int type, const char *file, int line )
72 if ( mode & CRYPTO_LOCK ) {
73 ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
75 ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
79 static unsigned long tlso_thread_self( void )
81 /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
82 * is an integral type that fits in an unsigned long
85 /* force an error if the ldap_pvt_thread_t type is too large */
86 enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
87 typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
89 return (unsigned long) ldap_pvt_thread_self();
92 static void tlso_thr_init( void )
96 for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
97 ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
99 CRYPTO_set_locking_callback( tlso_locking_cb );
100 CRYPTO_set_id_callback( tlso_thread_self );
102 #endif /* LDAP_R_COMPILE */
104 static STACK_OF(X509_NAME) *
105 tlso_ca_list( char * bundle, char * dir )
107 STACK_OF(X509_NAME) *ca_list = NULL;
110 ca_list = SSL_load_client_CA_file( bundle );
112 #if defined(HAVE_DIRENT_H) || defined(dirent)
117 ca_list = sk_X509_NAME_new_null();
120 if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
122 sk_X509_NAME_free( ca_list );
131 * Initialize TLS subsystem. Should be called only once.
136 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
139 char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
140 if ( file ) __atoe( file );
141 (void) tlso_seed_PRNG( file );
145 (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
148 SSL_load_error_strings();
150 OpenSSL_add_all_digests();
152 /* FIXME: mod_ssl does this */
153 X509V3_add_standard_extensions();
159 * Tear down the TLS subsystem. Should only be called once.
164 struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
167 #if OPENSSL_VERSION_NUMBER < 0x10000000
170 ERR_remove_thread_state(NULL);
174 if ( lo->ldo_tls_randfile ) {
175 LDAP_FREE( lo->ldo_tls_randfile );
176 lo->ldo_tls_randfile = NULL;
181 tlso_ctx_new( struct ldapoptions *lo )
183 return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
187 tlso_ctx_ref( tls_ctx *ctx )
189 tlso_ctx *c = (tlso_ctx *)ctx;
190 #if OPENSSL_VERSION_NUMBER < 0x10100000
191 #define SSL_CTX_up_ref(ctx) CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
197 tlso_ctx_free ( tls_ctx *ctx )
199 tlso_ctx *c = (tlso_ctx *)ctx;
204 * initialize a new TLS context
207 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
209 tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
213 SSL_CTX_set_session_id_context( ctx,
214 (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
217 #ifdef SSL_OP_NO_TLSv1
218 #ifdef SSL_OP_NO_TLSv1_1
219 #ifdef SSL_OP_NO_TLSv1_2
220 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
221 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
222 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
226 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
227 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
228 SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
231 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
232 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
236 if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
237 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
238 else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
239 SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
241 if ( lo->ldo_tls_ciphersuite &&
242 !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
244 Debug( LDAP_DEBUG_ANY,
245 "TLS: could not set cipher list %s.\n",
246 lo->ldo_tls_ciphersuite, 0, 0 );
251 if (lo->ldo_tls_cacertfile != NULL || lo->ldo_tls_cacertdir != NULL) {
252 if ( !SSL_CTX_load_verify_locations( ctx,
253 lt->lt_cacertfile, lt->lt_cacertdir ) ||
254 !SSL_CTX_set_default_verify_paths( ctx ) )
256 Debug( LDAP_DEBUG_ANY, "TLS: "
257 "could not load verify locations (file:`%s',dir:`%s').\n",
258 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
259 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
266 STACK_OF(X509_NAME) *calist;
267 /* List of CA names to send to a client */
268 calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
270 Debug( LDAP_DEBUG_ANY, "TLS: "
271 "could not load client CA list (file:`%s',dir:`%s').\n",
272 lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
273 lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
279 SSL_CTX_set_client_CA_list( ctx, calist );
283 if ( lo->ldo_tls_certfile &&
284 !SSL_CTX_use_certificate_file( ctx,
285 lt->lt_certfile, SSL_FILETYPE_PEM ) )
287 Debug( LDAP_DEBUG_ANY,
288 "TLS: could not use certificate `%s'.\n",
289 lo->ldo_tls_certfile,0,0);
294 /* Key validity is checked automatically if cert has already been set */
295 if ( lo->ldo_tls_keyfile &&
296 !SSL_CTX_use_PrivateKey_file( ctx,
297 lt->lt_keyfile, SSL_FILETYPE_PEM ) )
299 Debug( LDAP_DEBUG_ANY,
300 "TLS: could not use key file `%s'.\n",
301 lo->ldo_tls_keyfile,0,0);
306 if ( is_server && lo->ldo_tls_dhfile ) {
310 if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
311 Debug( LDAP_DEBUG_ANY,
312 "TLS: could not use DH parameters file `%s'.\n",
313 lo->ldo_tls_dhfile,0,0);
317 if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
318 Debug( LDAP_DEBUG_ANY,
319 "TLS: could not read DH parameters file `%s'.\n",
320 lo->ldo_tls_dhfile,0,0);
326 SSL_CTX_set_tmp_dh( ctx, dh );
327 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
331 if ( is_server && lo->ldo_tls_ecname ) {
333 Debug( LDAP_DEBUG_ANY,
334 "TLS: Elliptic Curves not supported.\n", 0,0,0 );
339 int nid = OBJ_sn2nid( lt->lt_ecname );
340 if ( nid == NID_undef ) {
341 Debug( LDAP_DEBUG_ANY,
342 "TLS: could not use EC name `%s'.\n",
343 lo->ldo_tls_ecname,0,0);
347 ecdh = EC_KEY_new_by_curve_name( nid );
348 if ( ecdh == NULL ) {
349 Debug( LDAP_DEBUG_ANY,
350 "TLS: could not generate key for EC name `%s'.\n",
351 lo->ldo_tls_ecname,0,0);
355 SSL_CTX_set_tmp_ecdh( ctx, ecdh );
356 SSL_CTX_set_options( ctx, SSL_OP_SINGLE_ECDH_USE );
361 if ( tlso_opt_trace ) {
362 SSL_CTX_set_info_callback( ctx, tlso_info_cb );
366 if ( lo->ldo_tls_require_cert ) {
368 if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
369 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
370 i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
374 SSL_CTX_set_verify( ctx, i,
375 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
376 tlso_verify_ok : tlso_verify_cb );
377 SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
378 #ifdef HAVE_OPENSSL_CRL
379 if ( lo->ldo_tls_crlcheck ) {
380 X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
381 if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
382 X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
383 } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
384 X509_STORE_set_flags( x509_s,
385 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
393 tlso_session_new( tls_ctx *ctx, int is_server )
395 tlso_ctx *c = (tlso_ctx *)ctx;
396 return (tls_session *)SSL_new( c );
400 tlso_session_connect( LDAP *ld, tls_session *sess )
402 tlso_session *s = (tlso_session *)sess;
404 /* Caller expects 0 = success, OpenSSL returns 1 = success */
405 return SSL_connect( s ) - 1;
409 tlso_session_accept( tls_session *sess )
411 tlso_session *s = (tlso_session *)sess;
413 /* Caller expects 0 = success, OpenSSL returns 1 = success */
414 return SSL_accept( s ) - 1;
418 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
420 tlso_session *s = (tlso_session *)sess;
422 /* 1 was subtracted above, offset it back now */
423 rc = SSL_get_error(s, rc+1);
424 if (rc == SSL_ERROR_WANT_READ) {
425 sb->sb_trans_needs_read = 1;
428 } else if (rc == SSL_ERROR_WANT_WRITE) {
429 sb->sb_trans_needs_write = 1;
432 } else if (rc == SSL_ERROR_WANT_CONNECT) {
439 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
442 const char *certerr=NULL;
443 tlso_session *s = (tlso_session *)sess;
445 rc = ERR_peek_error();
447 ERR_error_string_n( rc, err, sizeof(err) );
448 if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
449 ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
450 int certrc = SSL_get_verify_result(s);
451 certerr = (char *)X509_verify_cert_error_string(certrc);
453 snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
454 certerr ? certerr : "", certerr ? ")" : "" );
461 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
463 tlso_session *s = (tlso_session *)sess;
467 x = SSL_get_certificate( s );
469 if (!x) return LDAP_INVALID_CREDENTIALS;
471 xn = X509_get_subject_name(x);
472 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
473 der_dn->bv_val = xn->bytes->data;
474 /* Don't X509_free, the session is still using it */
479 tlso_get_cert( SSL *s )
481 /* If peer cert was bad, treat as if no cert was given */
482 if (SSL_get_verify_result(s)) {
485 return SSL_get_peer_certificate(s);
489 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
491 tlso_session *s = (tlso_session *)sess;
492 X509 *x = tlso_get_cert( s );
496 return LDAP_INVALID_CREDENTIALS;
498 xn = X509_get_subject_name(x);
499 der_dn->bv_len = i2d_X509_NAME( xn, NULL );
500 der_dn->bv_val = xn->bytes->data;
505 /* what kind of hostname were we given? */
511 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
513 tlso_session *s = (tlso_session *)sess;
514 int i, ret = LDAP_LOCAL_ERROR;
518 int ntype = IS_DNS, nlen;
520 struct in6_addr addr;
525 if( ldap_int_hostname &&
526 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
528 name = ldap_int_hostname;
534 x = tlso_get_cert(s);
536 Debug( LDAP_DEBUG_ANY,
537 "TLS: unable to get peer certificate.\n",
539 /* If this was a fatal condition, things would have
540 * aborted long before now.
546 if (inet_pton(AF_INET6, name, &addr)) {
550 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
551 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
554 i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
557 STACK_OF(GENERAL_NAME) *alt;
559 ex = X509_get_ext(x, i);
560 alt = X509V3_EXT_d2i(ex);
566 if (ntype == IS_DNS) {
567 domain = strchr(name, '.');
569 len2 = nlen - (domain-name);
572 n = sk_GENERAL_NAME_num(alt);
573 for (i=0; i<n; i++) {
576 gn = sk_GENERAL_NAME_value(alt, i);
577 if (gn->type == GEN_DNS) {
578 if (ntype != IS_DNS) continue;
580 sn = (char *) ASN1_STRING_data(gn->d.ia5);
581 sl = ASN1_STRING_length(gn->d.ia5);
584 if (sl == 0) continue;
586 /* Is this an exact match? */
587 if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
591 /* Is this a wildcard match? */
592 if (domain && (sn[0] == '*') && (sn[1] == '.') &&
593 (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
598 } else if (gn->type == GEN_IPADD) {
599 if (ntype == IS_DNS) continue;
601 sn = (char *) ASN1_STRING_data(gn->d.ia5);
602 sl = ASN1_STRING_length(gn->d.ia5);
605 if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
609 if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
612 if (!memcmp(sn, &addr, sl)) {
618 GENERAL_NAMES_free(alt);
619 if (i < n) { /* Found a match */
625 if (ret != LDAP_SUCCESS) {
629 ASN1_STRING *cn = NULL;
632 /* find the last CN */
633 obj = OBJ_nid2obj( NID_commonName );
634 if ( !obj ) goto no_cn; /* should never happen */
636 xn = X509_get_subject_name(x);
637 navas = X509_NAME_entry_count( xn );
638 for ( i=navas-1; i>=0; i-- ) {
639 ne = X509_NAME_get_entry( xn, i );
640 if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
641 cn = X509_NAME_ENTRY_get_data( ne );
649 Debug( LDAP_DEBUG_ANY,
650 "TLS: unable to get common name from peer certificate.\n",
652 ret = LDAP_CONNECT_ERROR;
653 if ( ld->ld_error ) {
654 LDAP_FREE( ld->ld_error );
656 ld->ld_error = LDAP_STRDUP(
657 _("TLS: unable to get CN from peer certificate"));
659 } else if ( cn->length == nlen &&
660 strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
663 } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
664 char *domain = strchr(name, '.');
668 dlen = nlen - (domain-name);
670 /* Is this a wildcard match? */
671 if ((dlen == cn->length-1) &&
672 !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
678 if( ret == LDAP_LOCAL_ERROR ) {
679 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
680 "common name in certificate (%.*s).\n",
681 name, cn->length, cn->data );
682 ret = LDAP_CONNECT_ERROR;
683 if ( ld->ld_error ) {
684 LDAP_FREE( ld->ld_error );
686 ld->ld_error = LDAP_STRDUP(
687 _("TLS: hostname does not match CN in peer certificate"));
695 tlso_session_strength( tls_session *sess )
697 tlso_session *s = (tlso_session *)sess;
699 return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
703 tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
705 tlso_session *s = (tlso_session *)sess;
707 /* Usually the client sends the finished msg. But if the
708 * session was resumed, the server sent the msg.
710 if (SSL_session_reused(s) ^ !is_server)
711 buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
713 buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
718 tlso_session_version( tls_session *sess )
720 tlso_session *s = (tlso_session *)sess;
721 return SSL_get_version(s);
725 tlso_session_cipher( tls_session *sess )
727 tlso_session *s = (tlso_session *)sess;
728 return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
732 tlso_session_peercert( tls_session *sess, struct berval *der )
734 tlso_session *s = (tlso_session *)sess;
736 X509 *x = SSL_get_peer_certificate(s);
737 der->bv_len = i2d_X509(x, NULL);
738 der->bv_val = LDAP_MALLOC(der->bv_len);
747 * TLS support for LBER Sockbufs
751 tlso_session *session;
752 Sockbuf_IO_Desc *sbiod;
756 tlso_bio_create( BIO *b ) {
765 tlso_bio_destroy( BIO *b )
767 if ( b == NULL ) return 0;
769 b->ptr = NULL; /* sb_tls_remove() will free it */
776 tlso_bio_read( BIO *b, char *buf, int len )
781 if ( buf == NULL || len <= 0 ) return 0;
783 p = (struct tls_data *)b->ptr;
785 if ( p == NULL || p->sbiod == NULL ) {
789 ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
791 BIO_clear_retry_flags( b );
793 int err = sock_errno();
794 if ( err == EAGAIN || err == EWOULDBLOCK ) {
795 BIO_set_retry_read( b );
803 tlso_bio_write( BIO *b, const char *buf, int len )
808 if ( buf == NULL || len <= 0 ) return 0;
810 p = (struct tls_data *)b->ptr;
812 if ( p == NULL || p->sbiod == NULL ) {
816 ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
818 BIO_clear_retry_flags( b );
820 int err = sock_errno();
821 if ( err == EAGAIN || err == EWOULDBLOCK ) {
822 BIO_set_retry_write( b );
830 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
832 if ( cmd == BIO_CTRL_FLUSH ) {
833 /* The OpenSSL library needs this */
840 tlso_bio_gets( BIO *b, char *buf, int len )
846 tlso_bio_puts( BIO *b, const char *str )
848 return tlso_bio_write( b, str, strlen( str ) );
851 static BIO_METHOD tlso_bio_method =
853 ( 100 | 0x400 ), /* it's a source/sink BIO */
865 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
870 assert( sbiod != NULL );
872 p = LBER_MALLOC( sizeof( *p ) );
879 bio = BIO_new( &tlso_bio_method );
880 bio->ptr = (void *)p;
881 SSL_set_bio( p->session, bio, bio );
882 sbiod->sbiod_pvt = p;
887 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
891 assert( sbiod != NULL );
892 assert( sbiod->sbiod_pvt != NULL );
894 p = (struct tls_data *)sbiod->sbiod_pvt;
895 SSL_free( p->session );
896 LBER_FREE( sbiod->sbiod_pvt );
897 sbiod->sbiod_pvt = NULL;
902 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
906 assert( sbiod != NULL );
907 assert( sbiod->sbiod_pvt != NULL );
909 p = (struct tls_data *)sbiod->sbiod_pvt;
910 SSL_shutdown( p->session );
915 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
919 assert( sbiod != NULL );
920 assert( sbiod->sbiod_pvt != NULL );
922 p = (struct tls_data *)sbiod->sbiod_pvt;
924 if ( opt == LBER_SB_OPT_GET_SSL ) {
925 *((tlso_session **)arg) = p->session;
928 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
929 if( SSL_pending( p->session ) > 0 ) {
934 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
938 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
944 assert( sbiod != NULL );
945 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
947 p = (struct tls_data *)sbiod->sbiod_pvt;
949 ret = SSL_read( p->session, (char *)buf, len );
951 errno = WSAGetLastError();
953 err = SSL_get_error( p->session, ret );
954 if (err == SSL_ERROR_WANT_READ ) {
955 sbiod->sbiod_sb->sb_trans_needs_read = 1;
956 sock_errset(EWOULDBLOCK);
959 sbiod->sbiod_sb->sb_trans_needs_read = 0;
964 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
970 assert( sbiod != NULL );
971 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
973 p = (struct tls_data *)sbiod->sbiod_pvt;
975 ret = SSL_write( p->session, (char *)buf, len );
977 errno = WSAGetLastError();
979 err = SSL_get_error( p->session, ret );
980 if (err == SSL_ERROR_WANT_WRITE ) {
981 sbiod->sbiod_sb->sb_trans_needs_write = 1;
982 sock_errset(EWOULDBLOCK);
985 sbiod->sbiod_sb->sb_trans_needs_write = 0;
990 static Sockbuf_IO tlso_sbio =
992 tlso_sb_setup, /* sbi_setup */
993 tlso_sb_remove, /* sbi_remove */
994 tlso_sb_ctrl, /* sbi_ctrl */
995 tlso_sb_read, /* sbi_read */
996 tlso_sb_write, /* sbi_write */
997 tlso_sb_close /* sbi_close */
1000 /* Derived from openssl/apps/s_cb.c */
1002 tlso_info_cb( const SSL *ssl, int where, int ret )
1006 char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1008 w = where & ~SSL_ST_MASK;
1009 if ( w & SSL_ST_CONNECT ) {
1011 } else if ( w & SSL_ST_ACCEPT ) {
1019 state = LDAP_STRDUP( state );
1023 if ( where & SSL_CB_LOOP ) {
1024 Debug( LDAP_DEBUG_TRACE,
1025 "TLS trace: %s:%s\n",
1028 } else if ( where & SSL_CB_ALERT ) {
1029 char *atype = (char *) SSL_alert_type_string_long( ret );
1030 char *adesc = (char *) SSL_alert_desc_string_long( ret );
1031 op = ( where & SSL_CB_READ ) ? "read" : "write";
1034 atype = LDAP_STRDUP( atype );
1038 adesc = LDAP_STRDUP( adesc );
1042 Debug( LDAP_DEBUG_TRACE,
1043 "TLS trace: SSL3 alert %s:%s:%s\n",
1046 if ( atype ) LDAP_FREE( atype );
1047 if ( adesc ) LDAP_FREE( adesc );
1049 } else if ( where & SSL_CB_EXIT ) {
1051 Debug( LDAP_DEBUG_TRACE,
1052 "TLS trace: %s:failed in %s\n",
1054 } else if ( ret < 0 ) {
1055 Debug( LDAP_DEBUG_TRACE,
1056 "TLS trace: %s:error in %s\n",
1061 if ( state ) LDAP_FREE( state );
1066 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1075 char *certerr = NULL;
1077 cert = X509_STORE_CTX_get_current_cert( ctx );
1078 errnum = X509_STORE_CTX_get_error( ctx );
1079 errdepth = X509_STORE_CTX_get_error_depth( ctx );
1082 * X509_get_*_name return pointers to the internal copies of
1083 * those things requested. So do not free them.
1085 subject = X509_get_subject_name( cert );
1086 issuer = X509_get_issuer_name( cert );
1087 /* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1088 sname = X509_NAME_oneline( subject, NULL, 0 );
1089 iname = X509_NAME_oneline( issuer, NULL, 0 );
1090 if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1092 if ( sname ) __etoa( sname );
1093 if ( iname ) __etoa( iname );
1095 certerr = LDAP_STRDUP( certerr );
1099 Debug( LDAP_DEBUG_TRACE,
1100 "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1102 sname ? sname : "-unknown-" );
1103 Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1105 Debug( LDAP_DEBUG_ANY,
1106 "TLS certificate verification: Error, %s\n",
1110 CRYPTO_free ( sname );
1112 CRYPTO_free ( iname );
1114 if ( certerr ) LDAP_FREE( certerr );
1120 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1122 (void) tlso_verify_cb( ok, ctx );
1126 /* Inspired by ERR_print_errors in OpenSSL */
1128 tlso_report_error( void )
1135 while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1136 ERR_error_string_n( l, buf, sizeof( buf ) );
1139 file = LDAP_STRDUP( file );
1140 __etoa( (char *)file );
1144 Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1147 if ( file ) LDAP_FREE( (void *)file );
1153 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1156 /* FIXME: Pregenerate the key on startup */
1157 /* FIXME: Who frees the key? */
1158 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1159 BIGNUM *bn = BN_new();
1162 if ( BN_set_word( bn, RSA_F4 )) {
1163 tmp_rsa = RSA_new();
1164 if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1165 RSA_free( tmp_rsa );
1172 tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1176 Debug( LDAP_DEBUG_ANY,
1177 "TLS: Failed to generate temporary %d-bit %s RSA key\n",
1178 key_length, is_export ? "export" : "domestic", 0 );
1184 tlso_seed_PRNG( const char *randfile )
1186 #ifndef URANDOM_DEVICE
1187 /* no /dev/urandom (or equiv) */
1189 char buffer[MAXPATHLEN];
1191 if (randfile == NULL) {
1192 /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1193 * If $HOME is not set or buffer too small to hold the pathname,
1194 * an error occurs. - From RAND_file_name() man page.
1195 * The fact is that when $HOME is NULL, .rnd is used.
1197 randfile = RAND_file_name( buffer, sizeof( buffer ) );
1199 } else if (RAND_egd(randfile) > 0) {
1204 if (randfile == NULL) {
1205 Debug( LDAP_DEBUG_ANY,
1206 "TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1211 total = RAND_load_file(randfile, -1);
1213 if (RAND_status() == 0) {
1214 Debug( LDAP_DEBUG_ANY,
1215 "TLS: PRNG not been seeded with enough data\n",
1220 /* assume if there was enough bits to seed that it's okay
1221 * to write derived bits to the file
1223 RAND_write_file(randfile);
1231 tls_impl ldap_int_tls_impl = {
1243 tlso_session_connect,
1244 tlso_session_accept,
1245 tlso_session_upflags,
1246 tlso_session_errmsg,
1248 tlso_session_peer_dn,
1249 tlso_session_chkhost,
1250 tlso_session_strength,
1251 tlso_session_unique,
1252 tlso_session_version,
1253 tlso_session_cipher,
1254 tlso_session_peercert,
1258 #ifdef LDAP_R_COMPILE
1267 #endif /* HAVE_OPENSSL */