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