tls_o.c 28.6 KB
Newer Older
Howard Chu's avatar
Howard Chu committed
1
/* tls_o.c - Handle tls/ssl using OpenSSL */
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
2
3
4
/* $OpenLDAP$ */
/* This work is part of OpenLDAP Software <http://www.openldap.org/>.
 *
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
5
 * Copyright 2008-2018 The OpenLDAP Foundation.
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted only as authorized by the OpenLDAP
 * Public License.
 *
 * A copy of this license is available in the file LICENSE in the
 * top-level directory of the distribution or, alternatively, at
 * <http://www.OpenLDAP.org/license.html>.
 */
/* ACKNOWLEDGEMENTS: Rewritten by Howard Chu
 */

#include "portable.h"

#ifdef HAVE_OPENSSL

#include "ldap_config.h"

#include <stdio.h>

#include <ac/stdlib.h>
#include <ac/errno.h>
#include <ac/socket.h>
#include <ac/string.h>
#include <ac/ctype.h>
#include <ac/time.h>
#include <ac/unistd.h>
#include <ac/param.h>
#include <ac/dirent.h>

#include "ldap-int.h"
#include "ldap-tls.h"

#ifdef HAVE_OPENSSL_SSL_H
#include <openssl/ssl.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include <openssl/safestack.h>
Howard Chu's avatar
Howard Chu committed
46
47
48
#include <openssl/bn.h>
#include <openssl/rsa.h>
#include <openssl/dh.h>
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
49
50
51
52
#elif defined( HAVE_SSL_H )
#include <ssl.h>
#endif

53
54
55
56
#if OPENSSL_VERSION_NUMBER >= 0x10100000
#define ASN1_STRING_data(x)	ASN1_STRING_get0_data(x)
#endif

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
57
58
59
typedef SSL_CTX tlso_ctx;
typedef SSL tlso_session;

60
61
62
static BIO_METHOD * tlso_bio_method = NULL;
static BIO_METHOD * tlso_bio_setup( void );

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
63
64
65
66
67
68
69
static int  tlso_opt_trace = 1;

static void tlso_report_error( void );

static void tlso_info_cb( const SSL *ssl, int where, int ret );
static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
70
static int tlso_seed_PRNG( const char *randfile );
71
#if OPENSSL_VERSION_NUMBER < 0x10100000
72
73
74
/*
 * OpenSSL 1.1 API and later has new locking code
*/
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
75
76
77
78
static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );

#ifdef LDAP_R_COMPILE
/*
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
79
 * provide mutexes for the OpenSSL library.
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
80
81
82
83
84
85
86
87
88
89
90
91
 */
static ldap_pvt_thread_mutex_t	tlso_mutexes[CRYPTO_NUM_LOCKS];

static void tlso_locking_cb( int mode, int type, const char *file, int line )
{
	if ( mode & CRYPTO_LOCK ) {
		ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
	} else {
		ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
	}
}

92
93
94
95
96
97
98
#if OPENSSL_VERSION_NUMBER >= 0x0909000
static void tlso_thread_self( CRYPTO_THREADID *id )
{
	CRYPTO_THREADID_set_pointer( id, (void *)ldap_pvt_thread_self() );
}
#define CRYPTO_set_id_callback(foo)	CRYPTO_THREADID_set_callback(foo)
#else
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
99
100
101
102
103
104
105
106
107
108
109
110
static unsigned long tlso_thread_self( void )
{
	/* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
	 * is an integral type that fits in an unsigned long
	 */

	/* force an error if the ldap_pvt_thread_t type is too large */
	enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
	typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];

	return (unsigned long) ldap_pvt_thread_self();
}
111
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
112
113
114
115
116
117
118
119
120
121
122
123

static void tlso_thr_init( void )
{
	int i;

	for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
		ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
	}
	CRYPTO_set_locking_callback( tlso_locking_cb );
	CRYPTO_set_id_callback( tlso_thread_self );
}
#endif /* LDAP_R_COMPILE */
124
125
126
127
#else
#ifdef LDAP_R_COMPILE
static void tlso_thr_init( void ) {}
#endif
128
#endif /* OpenSSL 1.1 */
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
129

130
131
132
133
134
#if OPENSSL_VERSION_NUMBER < 0x10100000
/*
 * OpenSSL 1.1 API and later makes the BIO method concrete types internal.
 */

Howard Chu's avatar
Howard Chu committed
135
static BIO_METHOD *
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
BIO_meth_new( int type, const char *name )
{
	BIO_METHOD *method = LDAP_MALLOC( sizeof(BIO_METHOD) );
	memset( method, 0, sizeof(BIO_METHOD) );

	method->type = type;
	method->name = name;

	return method;
}

static void
BIO_meth_free( BIO_METHOD *meth )
{
	if ( meth == NULL ) {
		return;
	}

	LDAP_FREE( meth );
}

#define BIO_meth_set_write(m, f) (m)->bwrite = (f)
#define BIO_meth_set_read(m, f) (m)->bread = (f)
#define BIO_meth_set_puts(m, f) (m)->bputs = (f)
#define BIO_meth_set_gets(m, f) (m)->bgets = (f)
#define BIO_meth_set_ctrl(m, f) (m)->ctrl = (f)
#define BIO_meth_set_create(m, f) (m)->create = (f)
#define BIO_meth_set_destroy(m, f) (m)->destroy = (f)

#endif /* OpenSSL 1.1 */

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
static STACK_OF(X509_NAME) *
tlso_ca_list( char * bundle, char * dir )
{
	STACK_OF(X509_NAME) *ca_list = NULL;

	if ( bundle ) {
		ca_list = SSL_load_client_CA_file( bundle );
	}
#if defined(HAVE_DIRENT_H) || defined(dirent)
	if ( dir ) {
		int freeit = 0;

		if ( !ca_list ) {
			ca_list = sk_X509_NAME_new_null();
			freeit = 1;
		}
		if ( !SSL_add_dir_cert_subjects_to_stack( ca_list, dir ) &&
			freeit ) {
			sk_X509_NAME_free( ca_list );
			ca_list = NULL;
		}
	}
#endif
	return ca_list;
}

/*
 * Initialize TLS subsystem. Should be called only once.
 */
static int
tlso_init( void )
{
	struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();   
#ifdef HAVE_EBCDIC
	{
		char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
		if ( file ) __atoe( file );
		(void) tlso_seed_PRNG( file );
		LDAP_FREE( file );
	}
#else
	(void) tlso_seed_PRNG( lo->ldo_tls_randfile );
#endif

211
#if OPENSSL_VERSION_NUMBER < 0x10100000
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
212
	SSL_load_error_strings();
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
213
214
	SSL_library_init();
	OpenSSL_add_all_digests();
215
216
217
#else
	OPENSSL_init_ssl(0, NULL);
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
218
219
220
221

	/* FIXME: mod_ssl does this */
	X509V3_add_standard_extensions();

222
223
	tlso_bio_method = tlso_bio_setup();

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
224
225
226
227
228
229
230
231
232
233
234
	return 0;
}

/*
 * Tear down the TLS subsystem. Should only be called once.
 */
static void
tlso_destroy( void )
{
	struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();   

235
236
	BIO_meth_free( tlso_bio_method );

237
#if OPENSSL_VERSION_NUMBER < 0x10100000
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
238
	EVP_cleanup();
Howard Chu's avatar
Howard Chu committed
239
#if OPENSSL_VERSION_NUMBER < 0x10000000
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
240
	ERR_remove_state(0);
Howard Chu's avatar
Howard Chu committed
241
242
243
#else
	ERR_remove_thread_state(NULL);
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
244
	ERR_free_strings();
245
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262

	if ( lo->ldo_tls_randfile ) {
		LDAP_FREE( lo->ldo_tls_randfile );
		lo->ldo_tls_randfile = NULL;
	}
}

static tls_ctx *
tlso_ctx_new( struct ldapoptions *lo )
{
	return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
}

static void
tlso_ctx_ref( tls_ctx *ctx )
{
	tlso_ctx *c = (tlso_ctx *)ctx;
Howard Chu's avatar
Howard Chu committed
263
264
265
266
#if OPENSSL_VERSION_NUMBER < 0x10100000
#define	SSL_CTX_up_ref(ctx)	CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
#endif
	SSL_CTX_up_ref( c );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
}

static void
tlso_ctx_free ( tls_ctx *ctx )
{
	tlso_ctx *c = (tlso_ctx *)ctx;
	SSL_CTX_free( c );
}

/*
 * initialize a new TLS context
 */
static int
tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
{
	tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
	int i;

	if ( is_server ) {
		SSL_CTX_set_session_id_context( ctx,
			(const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
	}

290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
#ifdef SSL_OP_NO_TLSv1
#ifdef SSL_OP_NO_TLSv1_1
#ifdef SSL_OP_NO_TLSv1_2
	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2)
		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
			SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 |
			SSL_OP_NO_TLSv1_2 );
	else
#endif
	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1)
		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
			SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 );
	else
#endif
	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0)
		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
			SSL_OP_NO_TLSv1);
	else
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
	if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 );
	else if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 )
		SSL_CTX_set_options( ctx, SSL_OP_NO_SSLv2 );

	if ( lo->ldo_tls_ciphersuite &&
		!SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
	{
		Debug( LDAP_DEBUG_ANY,
			   "TLS: could not set cipher list %s.\n",
			   lo->ldo_tls_ciphersuite, 0, 0 );
		tlso_report_error();
		return -1;
	}

324
325
326
327
328
329
330
331
	if ( lo->ldo_tls_cacertfile == NULL && lo->ldo_tls_cacertdir == NULL ) {
		if ( !SSL_CTX_set_default_verify_paths( ctx ) ) {
			Debug( LDAP_DEBUG_ANY, "TLS: "
				"could not use default certificate paths", 0, 0, 0 );
			tlso_report_error();
			return -1;
		}
	} else {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
332
		if ( !SSL_CTX_load_verify_locations( ctx,
333
				lt->lt_cacertfile, lt->lt_cacertdir ) )
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
		{
			Debug( LDAP_DEBUG_ANY, "TLS: "
				"could not load verify locations (file:`%s',dir:`%s').\n",
				lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
				lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
				0 );
			tlso_report_error();
			return -1;
		}

		if ( is_server ) {
			STACK_OF(X509_NAME) *calist;
			/* List of CA names to send to a client */
			calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir );
			if ( !calist ) {
				Debug( LDAP_DEBUG_ANY, "TLS: "
					"could not load client CA list (file:`%s',dir:`%s').\n",
					lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
					lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "",
					0 );
				tlso_report_error();
				return -1;
			}

			SSL_CTX_set_client_CA_list( ctx, calist );
		}
	}

	if ( lo->ldo_tls_certfile &&
		!SSL_CTX_use_certificate_file( ctx,
			lt->lt_certfile, SSL_FILETYPE_PEM ) )
	{
		Debug( LDAP_DEBUG_ANY,
			"TLS: could not use certificate `%s'.\n",
			lo->ldo_tls_certfile,0,0);
		tlso_report_error();
		return -1;
	}

	/* Key validity is checked automatically if cert has already been set */
	if ( lo->ldo_tls_keyfile &&
		!SSL_CTX_use_PrivateKey_file( ctx,
			lt->lt_keyfile, SSL_FILETYPE_PEM ) )
	{
		Debug( LDAP_DEBUG_ANY,
			"TLS: could not use key file `%s'.\n",
			lo->ldo_tls_keyfile,0,0);
		tlso_report_error();
		return -1;
	}

Howard Chu's avatar
Howard Chu committed
385
	if ( lo->ldo_tls_dhfile ) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
386
387
		DH *dh = NULL;
		BIO *bio;
388
		SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
389

Howard Chu's avatar
Howard Chu committed
390
391
392
393
394
395
		if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
			Debug( LDAP_DEBUG_ANY,
				"TLS: could not use DH parameters file `%s'.\n",
				lo->ldo_tls_dhfile,0,0);
			tlso_report_error();
			return -1;
396
397
		}
		if (!( dh=PEM_read_bio_DHparams( bio, NULL, NULL, NULL ))) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
398
			Debug( LDAP_DEBUG_ANY,
399
				"TLS: could not read DH parameters file `%s'.\n",
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
400
401
				lo->ldo_tls_dhfile,0,0);
			tlso_report_error();
402
			BIO_free( bio );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
403
404
405
			return -1;
		}
		BIO_free( bio );
406
		SSL_CTX_set_tmp_dh( ctx, dh );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
	}

	if ( tlso_opt_trace ) {
		SSL_CTX_set_info_callback( ctx, tlso_info_cb );
	}

	i = SSL_VERIFY_NONE;
	if ( lo->ldo_tls_require_cert ) {
		i = SSL_VERIFY_PEER;
		if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
			 lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
			i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
		}
	}

	SSL_CTX_set_verify( ctx, i,
		lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
		tlso_verify_ok : tlso_verify_cb );
425
#if OPENSSL_VERSION_NUMBER < 0x10100000
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
426
	SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
427
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
#ifdef HAVE_OPENSSL_CRL
	if ( lo->ldo_tls_crlcheck ) {
		X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
		if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
			X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
		} else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
			X509_STORE_set_flags( x509_s, 
					X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL  );
		}
	}
#endif
	return 0;
}

static tls_session *
tlso_session_new( tls_ctx *ctx, int is_server )
{
	tlso_ctx *c = (tlso_ctx *)ctx;
	return (tls_session *)SSL_new( c );
}

static int
tlso_session_connect( LDAP *ld, tls_session *sess )
{
	tlso_session *s = (tlso_session *)sess;

	/* Caller expects 0 = success, OpenSSL returns 1 = success */
	return SSL_connect( s ) - 1;
}

static int
tlso_session_accept( tls_session *sess )
{
	tlso_session *s = (tlso_session *)sess;

	/* Caller expects 0 = success, OpenSSL returns 1 = success */
	return SSL_accept( s ) - 1;
}

static int
tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
{
	tlso_session *s = (tlso_session *)sess;

	/* 1 was subtracted above, offset it back now */
	rc = SSL_get_error(s, rc+1);
	if (rc == SSL_ERROR_WANT_READ) {
		sb->sb_trans_needs_read  = 1;
		return 1;

	} else if (rc == SSL_ERROR_WANT_WRITE) {
		sb->sb_trans_needs_write = 1;
		return 1;

	} else if (rc == SSL_ERROR_WANT_CONNECT) {
		return 1;
	}
	return 0;
}

static char *
489
tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
490
{
491
492
493
494
	char err[256] = "";
	const char *certerr=NULL;
	tlso_session *s = (tlso_session *)sess;

Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
495
496
	rc = ERR_peek_error();
	if ( rc ) {
497
498
499
500
501
502
503
504
		ERR_error_string_n( rc, err, sizeof(err) );
		if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) && 
				( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
			int certrc = SSL_get_verify_result(s);
			certerr = (char *)X509_verify_cert_error_string(certrc);
		}
		snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"", 
				certerr ? certerr : "", certerr ?  ")" : "" );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
		return buf;
	}
	return NULL;
}

static int
tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
{
	tlso_session *s = (tlso_session *)sess;
	X509 *x;
	X509_NAME *xn;

	x = SSL_get_certificate( s );

	if (!x) return LDAP_INVALID_CREDENTIALS;
	
	xn = X509_get_subject_name(x);
522
#if OPENSSL_VERSION_NUMBER < 0x10100000
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
523
524
	der_dn->bv_len = i2d_X509_NAME( xn, NULL );
	der_dn->bv_val = xn->bytes->data;
525
526
527
528
#else
	{
		size_t len = 0;
		der_dn->bv_val = NULL;
529
		X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
530
531
532
		der_dn->bv_len = len;
	}
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
533
	/* Don't X509_free, the session is still using it */
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
	return 0;
}

static X509 *
tlso_get_cert( SSL *s )
{
	/* If peer cert was bad, treat as if no cert was given */
	if (SSL_get_verify_result(s)) {
		return NULL;
	}
	return SSL_get_peer_certificate(s);
}

static int
tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
{
	tlso_session *s = (tlso_session *)sess;
	X509 *x = tlso_get_cert( s );
	X509_NAME *xn;

	if ( !x )
		return LDAP_INVALID_CREDENTIALS;

	xn = X509_get_subject_name(x);
558
#if OPENSSL_VERSION_NUMBER < 0x10100000
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
559
560
	der_dn->bv_len = i2d_X509_NAME( xn, NULL );
	der_dn->bv_val = xn->bytes->data;
561
562
563
564
#else
	{
		size_t len = 0;
		der_dn->bv_val = NULL;
565
		X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
566
567
568
		der_dn->bv_len = len;
	}
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
	X509_free(x);
	return 0;
}

/* what kind of hostname were we given? */
#define	IS_DNS	0
#define	IS_IP4	1
#define	IS_IP6	2

static int
tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
{
	tlso_session *s = (tlso_session *)sess;
	int i, ret = LDAP_LOCAL_ERROR;
	X509 *x;
	const char *name;
	char *ptr;
Howard Chu's avatar
Howard Chu committed
586
	int ntype = IS_DNS, nlen;
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
587
588
589
590
591
592
593
594
595
596
597
598
599
#ifdef LDAP_PF_INET6
	struct in6_addr addr;
#else
	struct in_addr addr;
#endif

	if( ldap_int_hostname &&
		( !name_in || !strcasecmp( name_in, "localhost" ) ) )
	{
		name = ldap_int_hostname;
	} else {
		name = name_in;
	}
Howard Chu's avatar
Howard Chu committed
600
	nlen = strlen(name);
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
601
602
603
604
605
606
607
608
609
610
611
612
613

	x = tlso_get_cert(s);
	if (!x) {
		Debug( LDAP_DEBUG_ANY,
			"TLS: unable to get peer certificate.\n",
			0, 0, 0 );
		/* If this was a fatal condition, things would have
		 * aborted long before now.
		 */
		return LDAP_SUCCESS;
	}

#ifdef LDAP_PF_INET6
Howard Chu's avatar
Howard Chu committed
614
615
	if (inet_pton(AF_INET6, name, &addr)) {
		ntype = IS_IP6;
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
616
617
618
619
620
621
622
623
624
625
626
627
628
629
	} else 
#endif
	if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
		if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
	}
	
	i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
	if (i >= 0) {
		X509_EXTENSION *ex;
		STACK_OF(GENERAL_NAME) *alt;

		ex = X509_get_ext(x, i);
		alt = X509V3_EXT_d2i(ex);
		if (alt) {
Howard Chu's avatar
Howard Chu committed
630
			int n, len2 = 0;
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
631
632
633
634
635
636
			char *domain = NULL;
			GENERAL_NAME *gn;

			if (ntype == IS_DNS) {
				domain = strchr(name, '.');
				if (domain) {
Howard Chu's avatar
Howard Chu committed
637
					len2 = nlen - (domain-name);
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
				}
			}
			n = sk_GENERAL_NAME_num(alt);
			for (i=0; i<n; i++) {
				char *sn;
				int sl;
				gn = sk_GENERAL_NAME_value(alt, i);
				if (gn->type == GEN_DNS) {
					if (ntype != IS_DNS) continue;

					sn = (char *) ASN1_STRING_data(gn->d.ia5);
					sl = ASN1_STRING_length(gn->d.ia5);

					/* ignore empty */
					if (sl == 0) continue;

					/* Is this an exact match? */
Howard Chu's avatar
Howard Chu committed
655
					if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
						break;
					}

					/* Is this a wildcard match? */
					if (domain && (sn[0] == '*') && (sn[1] == '.') &&
						(len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
					{
						break;
					}

				} else if (gn->type == GEN_IPADD) {
					if (ntype == IS_DNS) continue;

					sn = (char *) ASN1_STRING_data(gn->d.ia5);
					sl = ASN1_STRING_length(gn->d.ia5);

#ifdef LDAP_PF_INET6
					if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
						continue;
					} else
#endif
					if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
						continue;
					}
					if (!memcmp(sn, &addr, sl)) {
						break;
					}
				}
			}

			GENERAL_NAMES_free(alt);
			if (i < n) {	/* Found a match */
				ret = LDAP_SUCCESS;
			}
		}
	}

	if (ret != LDAP_SUCCESS) {
		X509_NAME *xn;
695
696
697
698
699
700
701
702
		X509_NAME_ENTRY *ne;
		ASN1_OBJECT *obj;
		ASN1_STRING *cn = NULL;
		int navas;

		/* find the last CN */
		obj = OBJ_nid2obj( NID_commonName );
		if ( !obj ) goto no_cn;	/* should never happen */
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
703
704

		xn = X509_get_subject_name(x);
705
706
707
		navas = X509_NAME_entry_count( xn );
		for ( i=navas-1; i>=0; i-- ) {
			ne = X509_NAME_get_entry( xn, i );
Howard Chu's avatar
Howard Chu committed
708
			if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
709
710
711
712
713
714
				cn = X509_NAME_ENTRY_get_data( ne );
				break;
			}
		}

		if( !cn )
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
715
		{
716
no_cn:
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
717
718
719
720
721
722
723
724
725
726
			Debug( LDAP_DEBUG_ANY,
				"TLS: unable to get common name from peer certificate.\n",
				0, 0, 0 );
			ret = LDAP_CONNECT_ERROR;
			if ( ld->ld_error ) {
				LDAP_FREE( ld->ld_error );
			}
			ld->ld_error = LDAP_STRDUP(
				_("TLS: unable to get CN from peer certificate"));

727
728
		} else if ( cn->length == nlen &&
			strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
729
730
			ret = LDAP_SUCCESS;

731
		} else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
732
733
			char *domain = strchr(name, '.');
			if( domain ) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
734
				int dlen;
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
735

Howard Chu's avatar
Howard Chu committed
736
				dlen = nlen - (domain-name);
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
737
738

				/* Is this a wildcard match? */
739
740
				if ((dlen == cn->length-1) &&
					!strncasecmp(domain, (char *) &cn->data[1], dlen)) {
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
741
742
743
744
745
746
747
					ret = LDAP_SUCCESS;
				}
			}
		}

		if( ret == LDAP_LOCAL_ERROR ) {
			Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
748
749
				"common name in certificate (%.*s).\n", 
				name, cn->length, cn->data );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
			ret = LDAP_CONNECT_ERROR;
			if ( ld->ld_error ) {
				LDAP_FREE( ld->ld_error );
			}
			ld->ld_error = LDAP_STRDUP(
				_("TLS: hostname does not match CN in peer certificate"));
		}
	}
	X509_free(x);
	return ret;
}

static int
tlso_session_strength( tls_session *sess )
{
	tlso_session *s = (tlso_session *)sess;

767
	return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
768
769
770
771
772
773
774
775
776
777
778
}

/*
 * TLS support for LBER Sockbufs
 */

struct tls_data {
	tlso_session		*session;
	Sockbuf_IO_Desc		*sbiod;
};

779
780
781
782
783
784
#if OPENSSL_VERSION_NUMBER < 0x10100000
#define BIO_set_init(b, x)	b->init = x
#define BIO_set_data(b, x)	b->ptr = x
#define BIO_clear_flags(b, x)	b->flags &= ~(x)
#define BIO_get_data(b)	b->ptr
#endif
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
785
786
static int
tlso_bio_create( BIO *b ) {
787
788
789
	BIO_set_init( b, 1 );
	BIO_set_data( b, NULL );
	BIO_clear_flags( b, ~0 );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
790
791
792
793
794
795
796
797
	return 1;
}

static int
tlso_bio_destroy( BIO *b )
{
	if ( b == NULL ) return 0;

798
799
800
	BIO_set_data( b, NULL );		/* sb_tls_remove() will free it */
	BIO_set_init( b, 0 );
	BIO_clear_flags( b, ~0 );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
801
802
803
804
805
806
807
808
809
810
811
	return 1;
}

static int
tlso_bio_read( BIO *b, char *buf, int len )
{
	struct tls_data		*p;
	int			ret;
		
	if ( buf == NULL || len <= 0 ) return 0;

812
	p = (struct tls_data *)BIO_get_data(b);
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838

	if ( p == NULL || p->sbiod == NULL ) {
		return 0;
	}

	ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );

	BIO_clear_retry_flags( b );
	if ( ret < 0 ) {
		int err = sock_errno();
		if ( err == EAGAIN || err == EWOULDBLOCK ) {
			BIO_set_retry_read( b );
		}
	}

	return ret;
}

static int
tlso_bio_write( BIO *b, const char *buf, int len )
{
	struct tls_data		*p;
	int			ret;
	
	if ( buf == NULL || len <= 0 ) return 0;
	
839
	p = (struct tls_data *)BIO_get_data(b);
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

	if ( p == NULL || p->sbiod == NULL ) {
		return 0;
	}

	ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );

	BIO_clear_retry_flags( b );
	if ( ret < 0 ) {
		int err = sock_errno();
		if ( err == EAGAIN || err == EWOULDBLOCK ) {
			BIO_set_retry_write( b );
		}
	}

	return ret;
}

static long
tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
{
	if ( cmd == BIO_CTRL_FLUSH ) {
		/* The OpenSSL library needs this */
		return 1;
	}
	return 0;
}

static int
tlso_bio_gets( BIO *b, char *buf, int len )
{
	return -1;
}

static int
tlso_bio_puts( BIO *b, const char *str )
{
	return tlso_bio_write( b, str, strlen( str ) );
}
879

880
881
static BIO_METHOD *
tlso_bio_setup( void )
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
882
{
883
884
885
886
887
888
889
890
891
892
893
894
	/* it's a source/sink BIO */
	BIO_METHOD * method = BIO_meth_new( 100 | 0x400, "sockbuf glue" );
	BIO_meth_set_write( method, tlso_bio_write );
	BIO_meth_set_read( method, tlso_bio_read );
	BIO_meth_set_puts( method, tlso_bio_puts );
	BIO_meth_set_gets( method, tlso_bio_gets );
	BIO_meth_set_ctrl( method, tlso_bio_ctrl );
	BIO_meth_set_create( method, tlso_bio_create );
	BIO_meth_set_destroy( method, tlso_bio_destroy );

	return method;
}
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910

static int
tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
{
	struct tls_data		*p;
	BIO			*bio;

	assert( sbiod != NULL );

	p = LBER_MALLOC( sizeof( *p ) );
	if ( p == NULL ) {
		return -1;
	}
	
	p->session = arg;
	p->sbiod = sbiod;
911
	bio = BIO_new( tlso_bio_method );
912
	BIO_set_data( bio, p );
Quanah Gibson-Mount's avatar
Quanah Gibson-Mount committed
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
	SSL_set_bio( p->session, bio, bio );
	sbiod->sbiod_pvt = p;
	return 0;
}

static int
tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
{
	struct tls_data		*p;
	
	assert( sbiod != NULL );
	assert( sbiod->sbiod_pvt != NULL );

	p = (struct tls_data *)sbiod->sbiod_pvt;
	SSL_free( p->session );
	LBER_FREE( sbiod->sbiod_pvt );
	sbiod->sbiod_pvt = NULL;
	return 0;
}

static int
tlso_sb_close( Sockbuf_IO_Desc *sbiod )
{
	struct tls_data		*p;
	
	assert( sbiod != NULL );
	assert( sbiod->sbiod_pvt != NULL );

	p = (struct tls_data *)sbiod->sbiod_pvt;
	SSL_shutdown( p->session );
	return 0;
}

static int
tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
{
	struct tls_data		*p;
	
	assert( sbiod != NULL );
	assert( sbiod->sbiod_pvt != NULL );

	p = (struct tls_data *)sbiod->sbiod_pvt;
	
	if ( opt == LBER_SB_OPT_GET_SSL ) {
		*((tlso_session **)arg) = p->session;
		return 1;

	} else if ( opt == LBER_SB_OPT_DATA_READY ) {
		if( SSL_pending( p->session ) > 0 ) {
			return 1;
		}
	}
	
	return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
}

static ber_slen_t
tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
{
	struct tls_data		*p;
	ber_slen_t		ret;
	int			err;

	assert( sbiod != NULL );
	assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );

	p = (struct tls_data *)sbiod->sbiod_pvt;

	ret = SSL_read( p->session, (char *)buf, len );
#ifdef HAVE_WINSOCK
	errno = WSAGetLastError();
#endif
	err = SSL_get_error( p->session, ret );
	if (err == SSL_ERROR_WANT_READ ) {
		sbiod->sbiod_sb->sb_trans_needs_read = 1;
		sock_errset(EWOULDBLOCK);
	}
	else
		sbiod->sbiod_sb->sb_trans_needs_read = 0;
	return ret;
}

static ber_slen_t
tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
{
	struct tls_data		*p;
	ber_slen_t		ret;
	int			err;
For faster browsing, not all history is shown. View entire blame