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