1 /* tls_o.c - Handle tls/ssl using OpenSSL */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2008-2021 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
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>.
15  */
16 /* ACKNOWLEDGEMENTS: Rewritten by Howard Chu
17  */
18 
19 #include "portable.h"
20 
21 #ifdef HAVE_OPENSSL
22 
23 #include "ldap_config.h"
24 
25 #include <stdio.h>
26 
27 #include <ac/stdlib.h>
28 #include <ac/errno.h>
29 #include <ac/socket.h>
30 #include <ac/string.h>
31 #include <ac/ctype.h>
32 #include <ac/time.h>
33 #include <ac/unistd.h>
34 #include <ac/param.h>
35 #include <ac/dirent.h>
36 
37 #include "ldap-int.h"
38 #include "ldap-tls.h"
39 
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 #include <openssl/bn.h>
47 #include <openssl/rsa.h>
48 #include <openssl/dh.h>
49 #elif defined( HAVE_SSL_H )
50 #include <ssl.h>
51 #endif
52 
53 #if OPENSSL_VERSION_NUMBER >= 0x10100000
54 #define ASN1_STRING_data(x)	ASN1_STRING_get0_data(x)
55 #endif
56 
57 typedef SSL_CTX tlso_ctx;
58 typedef SSL tlso_session;
59 
60 static BIO_METHOD * tlso_bio_method = NULL;
61 static BIO_METHOD * tlso_bio_setup( void );
62 
63 static int  tlso_opt_trace = 1;
64 
65 static void tlso_report_error( void );
66 
67 static void tlso_info_cb( const SSL *ssl, int where, int ret );
68 static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
69 static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
70 static int tlso_seed_PRNG( const char *randfile );
71 #if OPENSSL_VERSION_NUMBER < 0x10100000
72 /*
73  * OpenSSL 1.1 API and later has new locking code
74 */
75 static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
76 
77 #ifdef LDAP_R_COMPILE
78 /*
79  * provide mutexes for the OpenSSL library.
80  */
81 static ldap_pvt_thread_mutex_t	tlso_mutexes[CRYPTO_NUM_LOCKS];
82 
tlso_locking_cb(int mode,int type,const char * file,int line)83 static void tlso_locking_cb( int mode, int type, const char *file, int line )
84 {
85 	if ( mode & CRYPTO_LOCK ) {
86 		ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
87 	} else {
88 		ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
89 	}
90 }
91 
92 #if OPENSSL_VERSION_NUMBER >= 0x0909000
tlso_thread_self(CRYPTO_THREADID * id)93 static void tlso_thread_self( CRYPTO_THREADID *id )
94 {
95 	CRYPTO_THREADID_set_pointer( id, (void *)ldap_pvt_thread_self() );
96 }
97 #define CRYPTO_set_id_callback(foo)	CRYPTO_THREADID_set_callback(foo)
98 #else
tlso_thread_self(void)99 static unsigned long tlso_thread_self( void )
100 {
101 	/* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
102 	 * is an integral type that fits in an unsigned long
103 	 */
104 
105 	/* force an error if the ldap_pvt_thread_t type is too large */
106 	enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
107 	typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
108 
109 	return (unsigned long) ldap_pvt_thread_self();
110 }
111 #endif
112 
tlso_thr_init(void)113 static void tlso_thr_init( void )
114 {
115 	int i;
116 
117 	for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
118 		ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
119 	}
120 	CRYPTO_set_locking_callback( tlso_locking_cb );
121 	CRYPTO_set_id_callback( tlso_thread_self );
122 }
123 #endif /* LDAP_R_COMPILE */
124 #else
125 #ifdef LDAP_R_COMPILE
tlso_thr_init(void)126 static void tlso_thr_init( void ) {}
127 #endif
128 #endif /* OpenSSL 1.1 */
129 
130 #if OPENSSL_VERSION_NUMBER < 0x10100000
131 /*
132  * OpenSSL 1.1 API and later makes the BIO method concrete types internal.
133  */
134 
135 static BIO_METHOD *
BIO_meth_new(int type,const char * name)136 BIO_meth_new( int type, const char *name )
137 {
138 	BIO_METHOD *method = LDAP_MALLOC( sizeof(BIO_METHOD) );
139 	memset( method, 0, sizeof(BIO_METHOD) );
140 
141 	method->type = type;
142 	method->name = name;
143 
144 	return method;
145 }
146 
147 static void
BIO_meth_free(BIO_METHOD * meth)148 BIO_meth_free( BIO_METHOD *meth )
149 {
150 	if ( meth == NULL ) {
151 		return;
152 	}
153 
154 	LDAP_FREE( meth );
155 }
156 
157 #define BIO_meth_set_write(m, f) (m)->bwrite = (f)
158 #define BIO_meth_set_read(m, f) (m)->bread = (f)
159 #define BIO_meth_set_puts(m, f) (m)->bputs = (f)
160 #define BIO_meth_set_gets(m, f) (m)->bgets = (f)
161 #define BIO_meth_set_ctrl(m, f) (m)->ctrl = (f)
162 #define BIO_meth_set_create(m, f) (m)->create = (f)
163 #define BIO_meth_set_destroy(m, f) (m)->destroy = (f)
164 
165 #endif /* OpenSSL 1.1 */
166 
STACK_OF(X509_NAME)167 static STACK_OF(X509_NAME) *
168 tlso_ca_list( char * bundle, char * dir )
169 {
170 	STACK_OF(X509_NAME) *ca_list = NULL;
171 
172 	if ( bundle ) {
173 		ca_list = SSL_load_client_CA_file( bundle );
174 	}
175 #if defined(HAVE_DIRENT_H) || defined(dirent)
176 	if ( dir ) {
177 		int freeit = 0;
178 
179 		if ( !ca_list ) {
180 			ca_list = sk_X509_NAME_new_null();
181 			freeit = 1;
182 		}
183 		if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
184 			freeit ) {
185 			sk_X509_NAME_free( ca_list );
186 			ca_list = NULL;
187 		}
188 	}
189 #endif
190 	return ca_list;
191 }
192 
193 /*
194  * Initialize TLS subsystem. Should be called only once.
195  */
196 static int
tlso_init(void)197 tlso_init( void )
198 {
199 	struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
200 #ifdef HAVE_EBCDIC
201 	{
202 		char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
203 		if ( file ) __atoe( file );
204 		(void) tlso_seed_PRNG( file );
205 		LDAP_FREE( file );
206 	}
207 #else
208 	(void) tlso_seed_PRNG( lo->ldo_tls_randfile );
209 #endif
210 
211 #if OPENSSL_VERSION_NUMBER < 0x10100000
212 	SSL_load_error_strings();
213 	SSL_library_init();
214 	OpenSSL_add_all_digests();
215 #else
216 	OPENSSL_init_ssl(0, NULL);
217 #endif
218 
219 	/* FIXME: mod_ssl does this */
220 	X509V3_add_standard_extensions();
221 
222 	tlso_bio_method = tlso_bio_setup();
223 
224 	return 0;
225 }
226 
227 /*
228  * Tear down the TLS subsystem. Should only be called once.
229  */
230 static void
tlso_destroy(void)231 tlso_destroy( void )
232 {
233 	struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
234 
235 	BIO_meth_free( tlso_bio_method );
236 
237 #if OPENSSL_VERSION_NUMBER < 0x10100000
238 	EVP_cleanup();
239 #if OPENSSL_VERSION_NUMBER < 0x10000000
240 	ERR_remove_state(0);
241 #else
242 	ERR_remove_thread_state(NULL);
243 #endif
244 	ERR_free_strings();
245 #endif
246 
247 	if ( lo->ldo_tls_randfile ) {
248 		LDAP_FREE( lo->ldo_tls_randfile );
249 		lo->ldo_tls_randfile = NULL;
250 	}
251 }
252 
253 static tls_ctx *
tlso_ctx_new(struct ldapoptions * lo)254 tlso_ctx_new( struct ldapoptions *lo )
255 {
256 	return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
257 }
258 
259 static void
tlso_ctx_ref(tls_ctx * ctx)260 tlso_ctx_ref( tls_ctx *ctx )
261 {
262 	tlso_ctx *c = (tlso_ctx *)ctx;
263 #if OPENSSL_VERSION_NUMBER < 0x10100000
264 #define	SSL_CTX_up_ref(ctx)	CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
265 #endif
266 	SSL_CTX_up_ref( c );
267 }
268 
269 static void
tlso_ctx_free(tls_ctx * ctx)270 tlso_ctx_free ( tls_ctx *ctx )
271 {
272 	tlso_ctx *c = (tlso_ctx *)ctx;
273 	SSL_CTX_free( c );
274 }
275 
276 #if OPENSSL_VERSION_NUMBER >= 0x10101000 && !defined(OPENSSL_NO_TLS1_3)
277 static char *
tlso_stecpy(char * dst,const char * src,const char * end)278 tlso_stecpy( char *dst, const char *src, const char *end )
279 {
280 	while ( dst < end && *src )
281 		*dst++ = *src++;
282 	if ( dst < end )
283 		*dst = '\0';
284 	return dst;
285 }
286 
287 /* OpenSSL 1.1.1 uses a separate API for TLS1.3 ciphersuites.
288  * Try to find any TLS1.3 ciphers in the given list of suites.
289  */
290 static void
tlso_ctx_cipher13(tlso_ctx * ctx,char * suites)291 tlso_ctx_cipher13( tlso_ctx *ctx, char *suites )
292 {
293 	char tls13_suites[1024], *ts = tls13_suites, *te = tls13_suites + sizeof(tls13_suites);
294 	char *ptr, *colon, *nptr;
295 	char sname[128];
296 	STACK_OF(SSL_CIPHER) *cs;
297 	SSL *s = SSL_new( ctx );
298 	int ret;
299 
300 	if ( !s )
301 		return;
302 
303 	*ts = '\0';
304 
305 	/* check individual suites in a separate SSL handle before
306 	 * mucking with the provided ctx. Init it to a known
307 	 * mostly-empty state.
308 	 */
309 	SSL_set_ciphersuites( s, "" );
310 	SSL_set_cipher_list( s, SSL3_TXT_RSA_NULL_SHA );
311 
312 	for ( ptr = suites;; ) {
313 		colon = strchr( ptr, ':' );
314 		if ( colon ) {
315 			int len = colon - ptr;
316 			if ( len > 63 ) len = 63;
317 			strncpy( sname, ptr, len );
318 			sname[len] = '\0';
319 			nptr = sname;
320 		} else {
321 			nptr = ptr;
322 		}
323 		if ( SSL_set_ciphersuites( s, nptr )) {
324 			cs = SSL_get_ciphers( s );
325 			if ( cs ) {
326 				const char *ver = SSL_CIPHER_get_version( sk_SSL_CIPHER_value( cs, 0 ));
327 				if ( !strncmp( ver, "TLSv", 4 ) && strncmp( ver+4, "1.3", 3 ) >= 0 ) {
328 					if ( tls13_suites[0] )
329 						ts = tlso_stecpy( ts, ":", te );
330 					ts = tlso_stecpy( ts, sname, te );
331 				}
332 			}
333 		}
334 		if ( !colon || ts >= te )
335 			break;
336 		ptr = colon+1;
337 	}
338 	SSL_free( s );
339 
340 	/* If no TLS1.3 ciphersuites were specified, leave current settings untouched. */
341 	if ( tls13_suites[0] )
342 		SSL_CTX_set_ciphersuites( ctx, tls13_suites );
343 }
344 #endif /* OpenSSL 1.1.1 TLS 1.3 */
345 
346 /*
347  * initialize a new TLS context
348  */
349 static int
tlso_ctx_init(struct ldapoptions * lo,struct ldaptls * lt,int is_server)350 tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
351 {
352 	tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
353 	int i;
354 
355 	if ( is_server ) {
356 		SSL_CTX_set_session_id_context( ctx,
357 			(const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
358 	}
359 
360 #ifdef SSL_OP_NO_TLSv1
361 #ifdef SSL_OP_NO_TLSv1_1
362 #ifdef SSL_OP_NO_TLSv1_2
363 	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
364 		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
365 			SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
366 			SSL_OP_NO_TLSv1_2 );
367 	else
368 #endif
369 	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
370 		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
371 			SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
372 	else
373 #endif
374 	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
375 		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
376 			SSL_OP_NO_TLSv1);
377 	else
378 #endif
379 	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
380 		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
381 	else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
382 		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );
383 
384 	if ( lo->ldo_tls_ciphersuite ) {
385 #if OPENSSL_VERSION_NUMBER >= 0x10101000 && !defined(OPENSSL_NO_TLS1_3)
386 		tlso_ctx_cipher13( ctx, lt->lt_ciphersuite );
387 #endif /* OpenSSL 1.1.1 */
388 		if ( !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
389 		{
390 			Debug( LDAP_DEBUG_ANY,
391 				   "TLS: could not set cipher list %s.\n",
392 				   lo->ldo_tls_ciphersuite, 0, 0 );
393 			tlso_report_error();
394 			return -1;
395 		}
396 	}
397 
398 	if ( lo->ldo_tls_cacertfile == NULL && lo->ldo_tls_cacertdir == NULL ) {
399 		if ( !SSL_CTX_set_default_verify_paths( ctx ) ) {
400 			Debug( LDAP_DEBUG_ANY, "TLS: "
401 				"could not use default certificate paths", 0, 0, 0 );
402 			tlso_report_error();
403 			return -1;
404 		}
405 	} else {
406 		if ( !SSL_CTX_load_verify_locations( ctx,
407 				lt->lt_cacertfile, lt->lt_cacertdir ) )
408 		{
409 			Debug( LDAP_DEBUG_ANY, "TLS: "
410 				"could not load verify locations (file:`%s',dir:`%s').\n",
411 				lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
412 				lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
413 				0 );
414 			tlso_report_error();
415 			return -1;
416 		}
417 
418 		if ( is_server ) {
419 			STACK_OF(X509_NAME) *calist;
420 			/* List of CA names to send to a client */
421 			calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
422 			if ( !calist ) {
423 				Debug( LDAP_DEBUG_ANY, "TLS: "
424 					"could not load client CA list (file:`%s',dir:`%s').\n",
425 					lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
426 					lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
427 					0 );
428 				tlso_report_error();
429 				return -1;
430 			}
431 
432 			SSL_CTX_set_client_CA_list( ctx, calist );
433 		}
434 	}
435 
436 	if ( lo->ldo_tls_certfile &&
437 		!SSL_CTX_use_certificate_file( ctx,
438 			lt->lt_certfile, SSL_FILETYPE_PEM ) )
439 	{
440 		Debug( LDAP_DEBUG_ANY,
441 			"TLS: could not use certificate `%s'.\n",
442 			lo->ldo_tls_certfile,0,0);
443 		tlso_report_error();
444 		return -1;
445 	}
446 
447 	/* Key validity is checked automatically if cert has already been set */
448 	if ( lo->ldo_tls_keyfile &&
449 		!SSL_CTX_use_PrivateKey_file( ctx,
450 			lt->lt_keyfile, SSL_FILETYPE_PEM ) )
451 	{
452 		Debug( LDAP_DEBUG_ANY,
453 			"TLS: could not use key file `%s'.\n",
454 			lo->ldo_tls_keyfile,0,0);
455 		tlso_report_error();
456 		return -1;
457 	}
458 
459 	if ( is_server && lo->ldo_tls_dhfile ) {
460 		DH *dh;
461 		BIO *bio;
462 
463 		if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
464 			Debug( LDAP_DEBUG_ANY,
465 				"TLS: could not use DH parameters file `%s'.\n",
466 				lo->ldo_tls_dhfile,0,0);
467 			tlso_report_error();
468 			return -1;
469 		}
470 		if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
471 			Debug( LDAP_DEBUG_ANY,
472 				"TLS: could not read DH parameters file `%s'.\n",
473 				lo->ldo_tls_dhfile,0,0);
474 			tlso_report_error();
475 			BIO_free( bio );
476 			return -1;
477 		}
478 		BIO_free( bio );
479 		SSL_CTX_set_tmp_dh( ctx, dh );
480 		SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
481 		DH_free( dh );
482 	}
483 
484 	if ( lo->ldo_tls_ecname ) {
485 #ifdef OPENSSL_NO_EC
486 		Debug( LDAP_DEBUG_ANY,
487 			"TLS: Elliptic Curves not supported.\n", 0,0,0 );
488 		return -1;
489 #else
490 		if ( !SSL_CTX_set1_curves_list( ctx, lt->lt_ecname )) {
491 			Debug( LDAP_DEBUG_ANY,
492 				"TLS: could not set EC name `%s'.\n",
493 				lo->ldo_tls_ecname,0,0);
494 			tlso_report_error();
495 			return -1;
496 		}
497 	/*
498 	 * This is a NOP in OpenSSL 1.1.0 and later, where curves are always
499 	 * auto-negotiated.
500 	 */
501 #if OPENSSL_VERSION_NUMBER < 0x10100000UL
502 		if ( SSL_CTX_set_ecdh_auto( ctx, 1 ) <= 0 ) {
503 			Debug( LDAP_DEBUG_ANY,
504 				"TLS: could not enable automatic EC negotiation.\n", 0, 0, 0 );
505 		}
506 #endif
507 #endif	/* OPENSSL_NO_EC */
508 	}
509 
510 	if ( tlso_opt_trace ) {
511 		SSL_CTX_set_info_callback( ctx, tlso_info_cb );
512 	}
513 
514 	i = SSL_VERIFY_NONE;
515 	if ( lo->ldo_tls_require_cert ) {
516 		i = SSL_VERIFY_PEER;
517 		if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
518 			 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
519 			i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
520 		}
521 	}
522 
523 	SSL_CTX_set_verify( ctx, i,
524 		lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
525 		tlso_verify_ok : tlso_verify_cb );
526 #if OPENSSL_VERSION_NUMBER < 0x10100000
527 	SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
528 #endif
529 #ifdef HAVE_OPENSSL_CRL
530 	if ( lo->ldo_tls_crlcheck ) {
531 		X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
532 		if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
533 			X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
534 		} else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
535 			X509_STORE_set_flags( x509_s,
536 					X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL  );
537 		}
538 	}
539 #endif
540 	return 0;
541 }
542 
543 static tls_session *
tlso_session_new(tls_ctx * ctx,int is_server)544 tlso_session_new( tls_ctx *ctx, int is_server )
545 {
546 	tlso_ctx *c = (tlso_ctx *)ctx;
547 	return (tls_session *)SSL_new( c );
548 }
549 
550 static int
tlso_session_connect(LDAP * ld,tls_session * sess)551 tlso_session_connect( LDAP *ld, tls_session *sess )
552 {
553 	tlso_session *s = (tlso_session *)sess;
554 
555 	/* Caller expects 0 = success, OpenSSL returns 1 = success */
556 	int rc = SSL_connect( s ) - 1;
557 #ifdef LDAP_USE_NON_BLOCKING_TLS
558 	if ( rc < 0 ) {
559 		int sockerr = sock_errno();
560 		int sslerr = SSL_get_error( s, rc+1 );
561 		if ( sslerr == SSL_ERROR_WANT_READ || sslerr == SSL_ERROR_WANT_WRITE ) {
562 			rc = 0;
563 		} else if ( sslerr == SSL_ERROR_SYSCALL &&
564 			( sockerr == EAGAIN || sockerr == ENOTCONN )) {
565 			rc = 0;
566 		}
567 	}
568 #endif /* LDAP_USE_NON_BLOCKING_TLS */
569 	return rc;
570 }
571 
572 static int
tlso_session_accept(tls_session * sess)573 tlso_session_accept( tls_session *sess )
574 {
575 	tlso_session *s = (tlso_session *)sess;
576 
577 	/* Caller expects 0 = success, OpenSSL returns 1 = success */
578 	return SSL_accept( s ) - 1;
579 }
580 
581 static int
tlso_session_upflags(Sockbuf * sb,tls_session * sess,int rc)582 tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
583 {
584 	tlso_session *s = (tlso_session *)sess;
585 
586 	/* 1 was subtracted above, offset it back now */
587 	rc = SSL_get_error(s, rc+1);
588 	if (rc == SSL_ERROR_WANT_READ) {
589 		sb->sb_trans_needs_read  = 1;
590 		return 1;
591 
592 	} else if (rc == SSL_ERROR_WANT_WRITE) {
593 		sb->sb_trans_needs_write = 1;
594 		return 1;
595 
596 	} else if (rc == SSL_ERROR_WANT_CONNECT) {
597 		return 1;
598 	}
599 	return 0;
600 }
601 
602 static char *
tlso_session_errmsg(tls_session * sess,int rc,char * buf,size_t len)603 tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
604 {
605 	char err[256] = "";
606 	const char *certerr=NULL;
607 	tlso_session *s = (tlso_session *)sess;
608 
609 	rc = ERR_peek_error();
610 	if ( rc ) {
611 		ERR_error_string_n( rc, err, sizeof(err) );
612 		if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
613 				( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
614 			int certrc = SSL_get_verify_result(s);
615 			certerr = (char *)X509_verify_cert_error_string(certrc);
616 		}
617 		snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
618 				certerr ? certerr : "", certerr ?  ")" : "" );
619 		return buf;
620 	}
621 	return NULL;
622 }
623 
624 static int
tlso_session_my_dn(tls_session * sess,struct berval * der_dn)625 tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
626 {
627 	tlso_session *s = (tlso_session *)sess;
628 	X509 *x;
629 	X509_NAME *xn;
630 
631 	x = SSL_get_certificate( s );
632 
633 	if (!x) return LDAP_INVALID_CREDENTIALS;
634 
635 	xn = X509_get_subject_name(x);
636 #if OPENSSL_VERSION_NUMBER < 0x10100000
637 	der_dn->bv_len = i2d_X509_NAME( xn, NULL );
638 	der_dn->bv_val = xn->bytes->data;
639 #else
640 	{
641 		size_t len = 0;
642 		der_dn->bv_val = NULL;
643 		X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
644 		der_dn->bv_len = len;
645 	}
646 #endif
647 	/* Don't X509_free, the session is still using it */
648 	return 0;
649 }
650 
651 static X509 *
tlso_get_cert(SSL * s)652 tlso_get_cert( SSL *s )
653 {
654 	/* If peer cert was bad, treat as if no cert was given */
655 	if (SSL_get_verify_result(s)) {
656 		return NULL;
657 	}
658 	return SSL_get_peer_certificate(s);
659 }
660 
661 static int
tlso_session_peer_dn(tls_session * sess,struct berval * der_dn)662 tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
663 {
664 	tlso_session *s = (tlso_session *)sess;
665 	X509 *x = tlso_get_cert( s );
666 	X509_NAME *xn;
667 
668 	if ( !x )
669 		return LDAP_INVALID_CREDENTIALS;
670 
671 	xn = X509_get_subject_name(x);
672 #if OPENSSL_VERSION_NUMBER < 0x10100000
673 	der_dn->bv_len = i2d_X509_NAME( xn, NULL );
674 	der_dn->bv_val = xn->bytes->data;
675 #else
676 	{
677 		size_t len = 0;
678 		der_dn->bv_val = NULL;
679 		X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
680 		der_dn->bv_len = len;
681 	}
682 #endif
683 	X509_free(x);
684 	return 0;
685 }
686 
687 /* what kind of hostname were we given? */
688 #define	IS_DNS	0
689 #define	IS_IP4	1
690 #define	IS_IP6	2
691 
692 static int
tlso_session_chkhost(LDAP * ld,tls_session * sess,const char * name_in)693 tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
694 {
695 	tlso_session *s = (tlso_session *)sess;
696 	int i, ret = LDAP_LOCAL_ERROR;
697 	int chkSAN = ld->ld_options.ldo_tls_require_san, gotSAN = 0;
698 	X509 *x;
699 	const char *name;
700 	char *ptr;
701 	int ntype = IS_DNS, nlen;
702 #ifdef LDAP_PF_INET6
703 	struct in6_addr addr;
704 #else
705 	struct in_addr addr;
706 #endif
707 
708 	if( ldap_int_hostname &&
709 		( !name_in || !strcasecmp( name_in, "localhost" ) ) )
710 	{
711 		name = ldap_int_hostname;
712 	} else {
713 		name = name_in;
714 	}
715 	nlen = strlen(name);
716 
717 	x = tlso_get_cert(s);
718 	if (!x) {
719 		Debug( LDAP_DEBUG_ANY,
720 			"TLS: unable to get peer certificate.\n",
721 			0, 0, 0 );
722 		/* If this was a fatal condition, things would have
723 		 * aborted long before now.
724 		 */
725 		return LDAP_SUCCESS;
726 	}
727 
728 #ifdef LDAP_PF_INET6
729 	if (inet_pton(AF_INET6, name, &addr)) {
730 		ntype = IS_IP6;
731 	} else
732 #endif
733 	if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
734 		if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
735 	}
736 
737 	if (chkSAN) {
738 	i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
739 	if (i >= 0) {
740 		X509_EXTENSION *ex;
741 		STACK_OF(GENERAL_NAME) *alt;
742 
743 		ex = X509_get_ext(x, i);
744 		alt = X509V3_EXT_d2i(ex);
745 		if (alt) {
746 			int n, len2 = 0;
747 			char *domain = NULL;
748 			GENERAL_NAME *gn;
749 
750 			gotSAN = 1;
751 			if (ntype == IS_DNS) {
752 				domain = strchr(name, '.');
753 				if (domain) {
754 					len2 = nlen - (domain-name);
755 				}
756 			}
757 			n = sk_GENERAL_NAME_num(alt);
758 			for (i=0; i<n; i++) {
759 				char *sn;
760 				int sl;
761 				gn = sk_GENERAL_NAME_value(alt, i);
762 				if (gn->type == GEN_DNS) {
763 					if (ntype != IS_DNS) continue;
764 
765 					sn = (char *) ASN1_STRING_data(gn->d.ia5);
766 					sl = ASN1_STRING_length(gn->d.ia5);
767 
768 					/* ignore empty */
769 					if (sl == 0) continue;
770 
771 					/* Is this an exact match? */
772 					if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
773 						break;
774 					}
775 
776 					/* Is this a wildcard match? */
777 					if (domain && (sn[0] == '*') && (sn[1] == '.') &&
778 						(len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
779 					{
780 						break;
781 					}
782 
783 				} else if (gn->type == GEN_IPADD) {
784 					if (ntype == IS_DNS) continue;
785 
786 					sn = (char *) ASN1_STRING_data(gn->d.ia5);
787 					sl = ASN1_STRING_length(gn->d.ia5);
788 
789 #ifdef LDAP_PF_INET6
790 					if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
791 						continue;
792 					} else
793 #endif
794 					if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
795 						continue;
796 					}
797 					if (!memcmp(sn, &addr, sl)) {
798 						break;
799 					}
800 				}
801 			}
802 
803 			GENERAL_NAMES_free(alt);
804 			if (i < n) {	/* Found a match */
805 				ret = LDAP_SUCCESS;
806 			}
807 		}
808 	}
809 	}
810 	if (ret != LDAP_SUCCESS && chkSAN) {
811 		switch(chkSAN) {
812 		case LDAP_OPT_X_TLS_DEMAND:
813 		case LDAP_OPT_X_TLS_HARD:
814 			if (!gotSAN) {
815 				Debug( LDAP_DEBUG_ANY,
816 					"TLS: unable to get subjectAltName from peer certificate.\n", 0, 0, 0 );
817 				ret = LDAP_CONNECT_ERROR;
818 				if ( ld->ld_error ) {
819 					LDAP_FREE( ld->ld_error );
820 				}
821 				ld->ld_error = LDAP_STRDUP(
822 					_("TLS: unable to get subjectAltName from peer certificate"));
823 				goto done;
824 			}
825 			/* FALLTHRU */
826 		case LDAP_OPT_X_TLS_TRY:
827 			if (gotSAN) {
828 				Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
829 					"subjectAltName in certificate.\n",
830 					name, 0, 0 );
831 				ret = LDAP_CONNECT_ERROR;
832 				if ( ld->ld_error ) {
833 					LDAP_FREE( ld->ld_error );
834 				}
835 				ld->ld_error = LDAP_STRDUP(
836 					_("TLS: hostname does not match subjectAltName in peer certificate"));
837 				goto done;
838 			}
839 			break;
840 		case LDAP_OPT_X_TLS_ALLOW:
841 			break;
842 		}
843 	}
844 
845 	if (ret != LDAP_SUCCESS) {
846 		X509_NAME *xn;
847 		X509_NAME_ENTRY *ne;
848 		ASN1_OBJECT *obj;
849 		ASN1_STRING *cn = NULL;
850 		int navas;
851 
852 		/* find the last CN */
853 		obj = OBJ_nid2obj( NID_commonName );
854 		if ( !obj ) goto no_cn;	/* should never happen */
855 
856 		xn = X509_get_subject_name(x);
857 		navas = X509_NAME_entry_count( xn );
858 		for ( i=navas-1; i>=0; i-- ) {
859 			ne = X509_NAME_get_entry( xn, i );
860 			if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
861 				cn = X509_NAME_ENTRY_get_data( ne );
862 				break;
863 			}
864 		}
865 
866 		if( !cn )
867 		{
868 no_cn:
869 			Debug( LDAP_DEBUG_ANY,
870 				"TLS: unable to get common name from peer certificate.\n",
871 				0, 0, 0 );
872 			ret = LDAP_CONNECT_ERROR;
873 			if ( ld->ld_error ) {
874 				LDAP_FREE( ld->ld_error );
875 			}
876 			ld->ld_error = LDAP_STRDUP(
877 				_("TLS: unable to get CN from peer certificate"));
878 
879 		} else if ( cn->length == nlen &&
880 			strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
881 			ret = LDAP_SUCCESS;
882 
883 		} else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
884 			char *domain = strchr(name, '.');
885 			if( domain ) {
886 				int dlen;
887 
888 				dlen = nlen - (domain-name);
889 
890 				/* Is this a wildcard match? */
891 				if ((dlen == cn->length-1) &&
892 					!strncasecmp(domain, (char *) &cn->data[1], dlen)) {
893 					ret = LDAP_SUCCESS;
894 				}
895 			}
896 		}
897 
898 		if( ret == LDAP_LOCAL_ERROR ) {
899 			Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
900 				"common name in certificate (%.*s).\n",
901 				name, cn->length, cn->data );
902 			ret = LDAP_CONNECT_ERROR;
903 			if ( ld->ld_error ) {
904 				LDAP_FREE( ld->ld_error );
905 			}
906 			ld->ld_error = LDAP_STRDUP(
907 				_("TLS: hostname does not match name in peer certificate"));
908 		}
909 	}
910 done:
911 	X509_free(x);
912 	return ret;
913 }
914 
915 static int
tlso_session_strength(tls_session * sess)916 tlso_session_strength( tls_session *sess )
917 {
918 	tlso_session *s = (tlso_session *)sess;
919 
920 	return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
921 }
922 
923 /*
924  * TLS support for LBER Sockbufs
925  */
926 
927 struct tls_data {
928 	tlso_session		*session;
929 	Sockbuf_IO_Desc		*sbiod;
930 };
931 
932 #if OPENSSL_VERSION_NUMBER < 0x10100000
933 #define BIO_set_init(b, x)	b->init = x
934 #define BIO_set_data(b, x)	b->ptr = x
935 #define BIO_clear_flags(b, x)	b->flags &= ~(x)
936 #define BIO_get_data(b)	b->ptr
937 #endif
938 static int
tlso_bio_create(BIO * b)939 tlso_bio_create( BIO *b ) {
940 	BIO_set_init( b, 1 );
941 	BIO_set_data( b, NULL );
942 	BIO_clear_flags( b, ~0 );
943 	return 1;
944 }
945 
946 static int
tlso_bio_destroy(BIO * b)947 tlso_bio_destroy( BIO *b )
948 {
949 	if ( b == NULL ) return 0;
950 
951 	BIO_set_data( b, NULL );		/* sb_tls_remove() will free it */
952 	BIO_set_init( b, 0 );
953 	BIO_clear_flags( b, ~0 );
954 	return 1;
955 }
956 
957 static int
tlso_bio_read(BIO * b,char * buf,int len)958 tlso_bio_read( BIO *b, char *buf, int len )
959 {
960 	struct tls_data		*p;
961 	int			ret;
962 
963 	if ( buf == NULL || len <= 0 ) return 0;
964 
965 	p = (struct tls_data *)BIO_get_data(b);
966 
967 	if ( p == NULL || p->sbiod == NULL ) {
968 		return 0;
969 	}
970 
971 	ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
972 
973 	BIO_clear_retry_flags( b );
974 	if ( ret < 0 ) {
975 		int err = sock_errno();
976 		if ( err == EAGAIN || err == EWOULDBLOCK ) {
977 			BIO_set_retry_read( b );
978 		}
979 	}
980 
981 	return ret;
982 }
983 
984 static int
tlso_bio_write(BIO * b,const char * buf,int len)985 tlso_bio_write( BIO *b, const char *buf, int len )
986 {
987 	struct tls_data		*p;
988 	int			ret;
989 
990 	if ( buf == NULL || len <= 0 ) return 0;
991 
992 	p = (struct tls_data *)BIO_get_data(b);
993 
994 	if ( p == NULL || p->sbiod == NULL ) {
995 		return 0;
996 	}
997 
998 	ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
999 
1000 	BIO_clear_retry_flags( b );
1001 	if ( ret < 0 ) {
1002 		int err = sock_errno();
1003 		if ( err == EAGAIN || err == EWOULDBLOCK ) {
1004 			BIO_set_retry_write( b );
1005 		}
1006 	}
1007 
1008 	return ret;
1009 }
1010 
1011 static long
tlso_bio_ctrl(BIO * b,int cmd,long num,void * ptr)1012 tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
1013 {
1014 	if ( cmd == BIO_CTRL_FLUSH ) {
1015 		/* The OpenSSL library needs this */
1016 		return 1;
1017 	}
1018 	return 0;
1019 }
1020 
1021 static int
tlso_bio_gets(BIO * b,char * buf,int len)1022 tlso_bio_gets( BIO *b, char *buf, int len )
1023 {
1024 	return -1;
1025 }
1026 
1027 static int
tlso_bio_puts(BIO * b,const char * str)1028 tlso_bio_puts( BIO *b, const char *str )
1029 {
1030 	return tlso_bio_write( b, str, strlen( str ) );
1031 }
1032 
1033 static BIO_METHOD *
tlso_bio_setup(void)1034 tlso_bio_setup( void )
1035 {
1036 	/* it's a source/sink BIO */
1037 	BIO_METHOD * method = BIO_meth_new( 100 | 0x400, "sockbuf glue" );
1038 	BIO_meth_set_write( method, tlso_bio_write );
1039 	BIO_meth_set_read( method, tlso_bio_read );
1040 	BIO_meth_set_puts( method, tlso_bio_puts );
1041 	BIO_meth_set_gets( method, tlso_bio_gets );
1042 	BIO_meth_set_ctrl( method, tlso_bio_ctrl );
1043 	BIO_meth_set_create( method, tlso_bio_create );
1044 	BIO_meth_set_destroy( method, tlso_bio_destroy );
1045 
1046 	return method;
1047 }
1048 
1049 static int
tlso_sb_setup(Sockbuf_IO_Desc * sbiod,void * arg)1050 tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
1051 {
1052 	struct tls_data		*p;
1053 	BIO			*bio;
1054 
1055 	assert( sbiod != NULL );
1056 
1057 	p = LBER_MALLOC( sizeof( *p ) );
1058 	if ( p == NULL ) {
1059 		return -1;
1060 	}
1061 
1062 	p->session = arg;
1063 	p->sbiod = sbiod;
1064 	bio = BIO_new( tlso_bio_method );
1065 	BIO_set_data( bio, p );
1066 	SSL_set_bio( p->session, bio, bio );
1067 	sbiod->sbiod_pvt = p;
1068 	return 0;
1069 }
1070 
1071 static int
tlso_sb_remove(Sockbuf_IO_Desc * sbiod)1072 tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
1073 {
1074 	struct tls_data		*p;
1075 
1076 	assert( sbiod != NULL );
1077 	assert( sbiod->sbiod_pvt != NULL );
1078 
1079 	p = (struct tls_data *)sbiod->sbiod_pvt;
1080 	SSL_free( p->session );
1081 	LBER_FREE( sbiod->sbiod_pvt );
1082 	sbiod->sbiod_pvt = NULL;
1083 	return 0;
1084 }
1085 
1086 static int
tlso_sb_close(Sockbuf_IO_Desc * sbiod)1087 tlso_sb_close( Sockbuf_IO_Desc *sbiod )
1088 {
1089 	struct tls_data		*p;
1090 
1091 	assert( sbiod != NULL );
1092 	assert( sbiod->sbiod_pvt != NULL );
1093 
1094 	p = (struct tls_data *)sbiod->sbiod_pvt;
1095 	SSL_shutdown( p->session );
1096 	return 0;
1097 }
1098 
1099 static int
tlso_sb_ctrl(Sockbuf_IO_Desc * sbiod,int opt,void * arg)1100 tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
1101 {
1102 	struct tls_data		*p;
1103 
1104 	assert( sbiod != NULL );
1105 	assert( sbiod->sbiod_pvt != NULL );
1106 
1107 	p = (struct tls_data *)sbiod->sbiod_pvt;
1108 
1109 	if ( opt == LBER_SB_OPT_GET_SSL ) {
1110 		*((tlso_session **)arg) = p->session;
1111 		return 1;
1112 
1113 	} else if ( opt == LBER_SB_OPT_DATA_READY ) {
1114 		if( SSL_pending( p->session ) > 0 ) {
1115 			return 1;
1116 		}
1117 	}
1118 
1119 	return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1120 }
1121 
1122 static ber_slen_t
tlso_sb_read(Sockbuf_IO_Desc * sbiod,void * buf,ber_len_t len)1123 tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1124 {
1125 	struct tls_data		*p;
1126 	ber_slen_t		ret;
1127 	int			err;
1128 
1129 	assert( sbiod != NULL );
1130 	assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1131 
1132 	p = (struct tls_data *)sbiod->sbiod_pvt;
1133 
1134 	ret = SSL_read( p->session, (char *)buf, len );
1135 #ifdef HAVE_WINSOCK
1136 	errno = WSAGetLastError();
1137 #endif
1138 	err = SSL_get_error( p->session, ret );
1139 	if (err == SSL_ERROR_WANT_READ ) {
1140 		sbiod->sbiod_sb->sb_trans_needs_read = 1;
1141 		sock_errset(EWOULDBLOCK);
1142 	}
1143 	else
1144 		sbiod->sbiod_sb->sb_trans_needs_read = 0;
1145 	return ret;
1146 }
1147 
1148 static ber_slen_t
tlso_sb_write(Sockbuf_IO_Desc * sbiod,void * buf,ber_len_t len)1149 tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1150 {
1151 	struct tls_data		*p;
1152 	ber_slen_t		ret;
1153 	int			err;
1154 
1155 	assert( sbiod != NULL );
1156 	assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1157 
1158 	p = (struct tls_data *)sbiod->sbiod_pvt;
1159 
1160 	ret = SSL_write( p->session, (char *)buf, len );
1161 #ifdef HAVE_WINSOCK
1162 	errno = WSAGetLastError();
1163 #endif
1164 	err = SSL_get_error( p->session, ret );
1165 	if (err == SSL_ERROR_WANT_WRITE ) {
1166 		sbiod->sbiod_sb->sb_trans_needs_write = 1;
1167 		sock_errset(EWOULDBLOCK);
1168 
1169 	} else {
1170 		sbiod->sbiod_sb->sb_trans_needs_write = 0;
1171 	}
1172 	return ret;
1173 }
1174 
1175 static Sockbuf_IO tlso_sbio =
1176 {
1177 	tlso_sb_setup,		/* sbi_setup */
1178 	tlso_sb_remove,		/* sbi_remove */
1179 	tlso_sb_ctrl,		/* sbi_ctrl */
1180 	tlso_sb_read,		/* sbi_read */
1181 	tlso_sb_write,		/* sbi_write */
1182 	tlso_sb_close		/* sbi_close */
1183 };
1184 
1185 /* Derived from openssl/apps/s_cb.c */
1186 static void
tlso_info_cb(const SSL * ssl,int where,int ret)1187 tlso_info_cb( const SSL *ssl, int where, int ret )
1188 {
1189 	int w;
1190 	char *op;
1191 	char *state = (char *) SSL_state_string_long( (SSL *)ssl );
1192 
1193 	w = where & ~SSL_ST_MASK;
1194 	if ( w & SSL_ST_CONNECT ) {
1195 		op = "SSL_connect";
1196 	} else if ( w & SSL_ST_ACCEPT ) {
1197 		op = "SSL_accept";
1198 	} else {
1199 		op = "undefined";
1200 	}
1201 
1202 #ifdef HAVE_EBCDIC
1203 	if ( state ) {
1204 		state = LDAP_STRDUP( state );
1205 		__etoa( state );
1206 	}
1207 #endif
1208 	if ( where & SSL_CB_LOOP ) {
1209 		Debug( LDAP_DEBUG_TRACE,
1210 			   "TLS trace: %s:%s\n",
1211 			   op, state, 0 );
1212 
1213 	} else if ( where & SSL_CB_ALERT ) {
1214 		char *atype = (char *) SSL_alert_type_string_long( ret );
1215 		char *adesc = (char *) SSL_alert_desc_string_long( ret );
1216 		op = ( where & SSL_CB_READ ) ? "read" : "write";
1217 #ifdef HAVE_EBCDIC
1218 		if ( atype ) {
1219 			atype = LDAP_STRDUP( atype );
1220 			__etoa( atype );
1221 		}
1222 		if ( adesc ) {
1223 			adesc = LDAP_STRDUP( adesc );
1224 			__etoa( adesc );
1225 		}
1226 #endif
1227 		Debug( LDAP_DEBUG_TRACE,
1228 			   "TLS trace: SSL3 alert %s:%s:%s\n",
1229 			   op, atype, adesc );
1230 #ifdef HAVE_EBCDIC
1231 		if ( atype ) LDAP_FREE( atype );
1232 		if ( adesc ) LDAP_FREE( adesc );
1233 #endif
1234 	} else if ( where & SSL_CB_EXIT ) {
1235 		if ( ret == 0 ) {
1236 			Debug( LDAP_DEBUG_TRACE,
1237 				   "TLS trace: %s:failed in %s\n",
1238 				   op, state, 0 );
1239 		} else if ( ret < 0 ) {
1240 			Debug( LDAP_DEBUG_TRACE,
1241 				   "TLS trace: %s:error in %s\n",
1242 				   op, state, 0 );
1243 		}
1244 	}
1245 #ifdef HAVE_EBCDIC
1246 	if ( state ) LDAP_FREE( state );
1247 #endif
1248 }
1249 
1250 static int
tlso_verify_cb(int ok,X509_STORE_CTX * ctx)1251 tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
1252 {
1253 	X509 *cert;
1254 	int errnum;
1255 	int errdepth;
1256 	X509_NAME *subject;
1257 	X509_NAME *issuer;
1258 	char *sname;
1259 	char *iname;
1260 	char *certerr = NULL;
1261 
1262 	cert = X509_STORE_CTX_get_current_cert( ctx );
1263 	errnum = X509_STORE_CTX_get_error( ctx );
1264 	errdepth = X509_STORE_CTX_get_error_depth( ctx );
1265 
1266 	/*
1267 	 * X509_get_*_name return pointers to the internal copies of
1268 	 * those things requested.  So do not free them.
1269 	 */
1270 	subject = X509_get_subject_name( cert );
1271 	issuer = X509_get_issuer_name( cert );
1272 	/* X509_NAME_oneline, if passed a NULL buf, allocate memomry */
1273 	sname = X509_NAME_oneline( subject, NULL, 0 );
1274 	iname = X509_NAME_oneline( issuer, NULL, 0 );
1275 	if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
1276 #ifdef HAVE_EBCDIC
1277 	if ( sname ) __etoa( sname );
1278 	if ( iname ) __etoa( iname );
1279 	if ( certerr ) {
1280 		certerr = LDAP_STRDUP( certerr );
1281 		__etoa( certerr );
1282 	}
1283 #endif
1284 	Debug( LDAP_DEBUG_TRACE,
1285 		   "TLS certificate verification: depth: %d, err: %d, subject: %s,",
1286 		   errdepth, errnum,
1287 		   sname ? sname : "-unknown-" );
1288 	Debug( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-", 0, 0 );
1289 	if ( !ok ) {
1290 		Debug( LDAP_DEBUG_ANY,
1291 			"TLS certificate verification: Error, %s\n",
1292 			certerr, 0, 0 );
1293 	}
1294 	if ( sname )
1295 		OPENSSL_free ( sname );
1296 	if ( iname )
1297 		OPENSSL_free ( iname );
1298 #ifdef HAVE_EBCDIC
1299 	if ( certerr ) LDAP_FREE( certerr );
1300 #endif
1301 	return ok;
1302 }
1303 
1304 static int
tlso_verify_ok(int ok,X509_STORE_CTX * ctx)1305 tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
1306 {
1307 	(void) tlso_verify_cb( ok, ctx );
1308 	return 1;
1309 }
1310 
1311 /* Inspired by ERR_print_errors in OpenSSL */
1312 static void
tlso_report_error(void)1313 tlso_report_error( void )
1314 {
1315 	unsigned long l;
1316 	char buf[200];
1317 	const char *file;
1318 	int line;
1319 
1320 	while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
1321 		ERR_error_string_n( l, buf, sizeof( buf ) );
1322 #ifdef HAVE_EBCDIC
1323 		if ( file ) {
1324 			file = LDAP_STRDUP( file );
1325 			__etoa( (char *)file );
1326 		}
1327 		__etoa( buf );
1328 #endif
1329 		Debug( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
1330 			buf, file, line );
1331 #ifdef HAVE_EBCDIC
1332 		if ( file ) LDAP_FREE( (void *)file );
1333 #endif
1334 	}
1335 }
1336 
1337 #if OPENSSL_VERSION_NUMBER < 0x10100000
1338 static RSA *
tlso_tmp_rsa_cb(SSL * ssl,int is_export,int key_length)1339 tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
1340 {
1341 	RSA *tmp_rsa;
1342 	/* FIXME:  Pregenerate the key on startup */
1343 	/* FIXME:  Who frees the key? */
1344 #if OPENSSL_VERSION_NUMBER >= 0x00908000
1345 	BIGNUM *bn = BN_new();
1346 	tmp_rsa = NULL;
1347 	if ( bn ) {
1348 		if ( BN_set_word( bn, RSA_F4 )) {
1349 			tmp_rsa = RSA_new();
1350 			if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
1351 				RSA_free( tmp_rsa );
1352 				tmp_rsa = NULL;
1353 			}
1354 		}
1355 		BN_free( bn );
1356 	}
1357 #else
1358 	tmp_rsa = RSA_generate_key( key_length, RSA_F4, NULL, NULL );
1359 #endif
1360 
1361 	if ( !tmp_rsa ) {
1362 		Debug( LDAP_DEBUG_ANY,
1363 			"TLS: Failed to generate temporary %d-bit %s RSA key\n",
1364 			key_length, is_export ? "export" : "domestic", 0 );
1365 	}
1366 	return tmp_rsa;
1367 }
1368 #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
1369 
1370 static int
tlso_seed_PRNG(const char * randfile)1371 tlso_seed_PRNG( const char *randfile )
1372 {
1373 #ifndef URANDOM_DEVICE
1374 	/* no /dev/urandom (or equiv) */
1375 	long total=0;
1376 	char buffer[MAXPATHLEN];
1377 
1378 	if (randfile == NULL) {
1379 		/* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
1380 		 * If $HOME is not set or buffer too small to hold the pathname,
1381 		 * an error occurs.	- From RAND_file_name() man page.
1382 		 * The fact is that when $HOME is NULL, .rnd is used.
1383 		 */
1384 		randfile = RAND_file_name( buffer, sizeof( buffer ) );
1385 	}
1386 #ifndef OPENSSL_NO_EGD
1387 	else if (RAND_egd(randfile) > 0) {
1388 		/* EGD socket */
1389 		return 0;
1390 	}
1391 #endif
1392 
1393 	if (randfile == NULL) {
1394 		Debug( LDAP_DEBUG_ANY,
1395 			"TLS: Use configuration file or $RANDFILE to define seed PRNG\n",
1396 			0, 0, 0);
1397 		return -1;
1398 	}
1399 
1400 	total = RAND_load_file(randfile, -1);
1401 
1402 	if (RAND_status() == 0) {
1403 		Debug( LDAP_DEBUG_ANY,
1404 			"TLS: PRNG not been seeded with enough data\n",
1405 			0, 0, 0);
1406 		return -1;
1407 	}
1408 
1409 	/* assume if there was enough bits to seed that it's okay
1410 	 * to write derived bits to the file
1411 	 */
1412 	RAND_write_file(randfile);
1413 
1414 #endif
1415 
1416 	return 0;
1417 }
1418 
1419 
1420 tls_impl ldap_int_tls_impl = {
1421 	"OpenSSL",
1422 
1423 	tlso_init,
1424 	tlso_destroy,
1425 
1426 	tlso_ctx_new,
1427 	tlso_ctx_ref,
1428 	tlso_ctx_free,
1429 	tlso_ctx_init,
1430 
1431 	tlso_session_new,
1432 	tlso_session_connect,
1433 	tlso_session_accept,
1434 	tlso_session_upflags,
1435 	tlso_session_errmsg,
1436 	tlso_session_my_dn,
1437 	tlso_session_peer_dn,
1438 	tlso_session_chkhost,
1439 	tlso_session_strength,
1440 
1441 	&tlso_sbio,
1442 
1443 #ifdef LDAP_R_COMPILE
1444 	tlso_thr_init,
1445 #else
1446 	NULL,
1447 #endif
1448 
1449 	0
1450 };
1451 
1452 #endif /* HAVE_OPENSSL */
1453