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