xref: /netbsd-src/external/bsd/openldap/dist/libraries/libldap/tls_g.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*	$NetBSD: tls_g.c,v 1.1.1.2 2010/12/12 15:21:39 adam Exp $	*/
2 
3 /* tls_g.c - Handle tls/ssl using GNUTLS. */
4 /* OpenLDAP: pkg/ldap/libraries/libldap/tls_g.c,v 1.6.2.9 2010/04/14 22:10:21 quanah Exp */
5 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
6  *
7  * Copyright 2008-2010 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: GNUTLS support written by Howard Chu and
19  * Matt Backes; sponsored by The Written Word (thewrittenword.com)
20  * and Stanford University (stanford.edu).
21  */
22 
23 #include "portable.h"
24 
25 #ifdef HAVE_GNUTLS
26 
27 #include "ldap_config.h"
28 
29 #include <stdio.h>
30 
31 #include <ac/stdlib.h>
32 #include <ac/errno.h>
33 #include <ac/socket.h>
34 #include <ac/string.h>
35 #include <ac/ctype.h>
36 #include <ac/time.h>
37 #include <ac/unistd.h>
38 #include <ac/param.h>
39 #include <ac/dirent.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 
43 #include "ldap-int.h"
44 #include "ldap-tls.h"
45 
46 #ifdef LDAP_R_COMPILE
47 #include <ldap_pvt_thread.h>
48 #endif
49 
50 #include <gnutls/gnutls.h>
51 #include <gnutls/x509.h>
52 #include <gcrypt.h>
53 
54 #define DH_BITS	(1024)
55 
56 #if LIBGNUTLS_VERSION_NUMBER >= 0x020200
57 #define	HAVE_CIPHERSUITES	1
58 /* This is a kludge. gcrypt 1.4.x has support. Recent GnuTLS requires gcrypt 1.4.x
59  * but that dependency isn't reflected in their configure script, resulting in
60  * build errors on older gcrypt. So, if they have a working build environment,
61  * assume gcrypt is new enough.
62  */
63 #define HAVE_GCRYPT_RAND	1
64 #else
65 #undef HAVE_CIPHERSUITES
66 #undef HAVE_GCRYPT_RAND
67 #endif
68 
69 #ifndef HAVE_CIPHERSUITES
70 /* Versions prior to 2.2.0 didn't handle cipher suites, so we had to
71  * kludge them ourselves.
72  */
73 typedef struct tls_cipher_suite {
74 	const char *name;
75 	gnutls_kx_algorithm_t kx;
76 	gnutls_cipher_algorithm_t cipher;
77 	gnutls_mac_algorithm_t mac;
78 	gnutls_protocol_t version;
79 } tls_cipher_suite;
80 #endif
81 
82 typedef struct tlsg_ctx {
83 	struct ldapoptions *lo;
84 	gnutls_certificate_credentials_t cred;
85 	gnutls_dh_params_t dh_params;
86 	unsigned long verify_depth;
87 	int refcount;
88 #ifdef HAVE_CIPHERSUITES
89 	gnutls_priority_t prios;
90 #else
91 	int *kx_list;
92 	int *cipher_list;
93 	int *mac_list;
94 #endif
95 #ifdef LDAP_R_COMPILE
96 	ldap_pvt_thread_mutex_t ref_mutex;
97 #endif
98 } tlsg_ctx;
99 
100 typedef struct tlsg_session {
101 	gnutls_session_t session;
102 	tlsg_ctx *ctx;
103 	struct berval peer_der_dn;
104 } tlsg_session;
105 
106 #ifndef HAVE_CIPHERSUITES
107 static tls_cipher_suite *tlsg_ciphers;
108 static int tlsg_n_ciphers;
109 #endif
110 
111 static int tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites );
112 static int tlsg_cert_verify( tlsg_session *s );
113 
114 #ifdef LDAP_R_COMPILE
115 
116 static int
117 tlsg_mutex_init( void **priv )
118 {
119 	int err = 0;
120 	ldap_pvt_thread_mutex_t *lock = LDAP_MALLOC( sizeof( ldap_pvt_thread_mutex_t ));
121 
122 	if ( !lock )
123 		err = ENOMEM;
124 	if ( !err ) {
125 		err = ldap_pvt_thread_mutex_init( lock );
126 		if ( err )
127 			LDAP_FREE( lock );
128 		else
129 			*priv = lock;
130 	}
131 	return err;
132 }
133 
134 static int
135 tlsg_mutex_destroy( void **lock )
136 {
137 	int err = ldap_pvt_thread_mutex_destroy( *lock );
138 	LDAP_FREE( *lock );
139 	return err;
140 }
141 
142 static int
143 tlsg_mutex_lock( void **lock )
144 {
145 	return ldap_pvt_thread_mutex_lock( *lock );
146 }
147 
148 static int
149 tlsg_mutex_unlock( void **lock )
150 {
151 	return ldap_pvt_thread_mutex_unlock( *lock );
152 }
153 
154 static struct gcry_thread_cbs tlsg_thread_cbs = {
155 	GCRY_THREAD_OPTION_USER,
156 	NULL,
157 	tlsg_mutex_init,
158 	tlsg_mutex_destroy,
159 	tlsg_mutex_lock,
160 	tlsg_mutex_unlock,
161 	NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
162 };
163 
164 static void
165 tlsg_thr_init( void )
166 {
167 	gcry_control (GCRYCTL_SET_THREAD_CBS, &tlsg_thread_cbs);
168 }
169 #endif /* LDAP_R_COMPILE */
170 
171 /*
172  * Initialize TLS subsystem. Should be called only once.
173  */
174 static int
175 tlsg_init( void )
176 {
177 #ifdef HAVE_GCRYPT_RAND
178 	struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
179 	if ( lo->ldo_tls_randfile &&
180 		gcry_control( GCRYCTL_SET_RNDEGD_SOCKET, lo->ldo_tls_randfile )) {
181 		Debug( LDAP_DEBUG_ANY,
182 		"TLS: gcry_control GCRYCTL_SET_RNDEGD_SOCKET failed\n",
183 		0, 0, 0);
184 		return -1;
185 	}
186 #endif
187 
188 	gnutls_global_init();
189 
190 #ifndef HAVE_CIPHERSUITES
191 	/* GNUtls cipher suite handling: The library ought to parse suite
192 	 * names for us, but it doesn't. It will return a list of suite names
193 	 * that it supports, so we can do parsing ourselves. It ought to tell
194 	 * us how long the list is, but it doesn't do that either, so we just
195 	 * have to count it manually...
196 	 */
197 	{
198 		int i = 0;
199 		tls_cipher_suite *ptr, tmp;
200 		char cs_id[2];
201 
202 		while ( gnutls_cipher_suite_info( i, cs_id, &tmp.kx, &tmp.cipher,
203 			&tmp.mac, &tmp.version ))
204 			i++;
205 		tlsg_n_ciphers = i;
206 
207 		/* Store a copy */
208 		tlsg_ciphers = LDAP_MALLOC(tlsg_n_ciphers * sizeof(tls_cipher_suite));
209 		if ( !tlsg_ciphers )
210 			return -1;
211 		for ( i=0; i<tlsg_n_ciphers; i++ ) {
212 			tlsg_ciphers[i].name = gnutls_cipher_suite_info( i, cs_id,
213 				&tlsg_ciphers[i].kx, &tlsg_ciphers[i].cipher, &tlsg_ciphers[i].mac,
214 				&tlsg_ciphers[i].version );
215 		}
216 	}
217 #endif
218 	return 0;
219 }
220 
221 /*
222  * Tear down the TLS subsystem. Should only be called once.
223  */
224 static void
225 tlsg_destroy( void )
226 {
227 #ifndef HAVE_CIPHERSUITES
228 	LDAP_FREE( tlsg_ciphers );
229 	tlsg_ciphers = NULL;
230 	tlsg_n_ciphers = 0;
231 #endif
232 	gnutls_global_deinit();
233 }
234 
235 static tls_ctx *
236 tlsg_ctx_new ( struct ldapoptions *lo )
237 {
238 	tlsg_ctx *ctx;
239 
240 	ctx = ber_memcalloc ( 1, sizeof (*ctx) );
241 	if ( ctx ) {
242 		ctx->lo = lo;
243 		if ( gnutls_certificate_allocate_credentials( &ctx->cred )) {
244 			ber_memfree( ctx );
245 			return NULL;
246 		}
247 		ctx->refcount = 1;
248 #ifdef HAVE_CIPHERSUITES
249 		gnutls_priority_init( &ctx->prios, "NORMAL", NULL );
250 #endif
251 #ifdef LDAP_R_COMPILE
252 		ldap_pvt_thread_mutex_init( &ctx->ref_mutex );
253 #endif
254 	}
255 	return (tls_ctx *)ctx;
256 }
257 
258 static void
259 tlsg_ctx_ref( tls_ctx *ctx )
260 {
261 	tlsg_ctx *c = (tlsg_ctx *)ctx;
262 #ifdef LDAP_R_COMPILE
263 	ldap_pvt_thread_mutex_lock( &c->ref_mutex );
264 #endif
265 	c->refcount++;
266 #ifdef LDAP_R_COMPILE
267 	ldap_pvt_thread_mutex_unlock( &c->ref_mutex );
268 #endif
269 }
270 
271 static void
272 tlsg_ctx_free ( tls_ctx *ctx )
273 {
274 	tlsg_ctx *c = (tlsg_ctx *)ctx;
275 	int refcount;
276 
277 	if ( !c ) return;
278 
279 #ifdef LDAP_R_COMPILE
280 	ldap_pvt_thread_mutex_lock( &c->ref_mutex );
281 #endif
282 	refcount = --c->refcount;
283 #ifdef LDAP_R_COMPILE
284 	ldap_pvt_thread_mutex_unlock( &c->ref_mutex );
285 #endif
286 	if ( refcount )
287 		return;
288 #ifdef HAVE_CIPHERSUITES
289 	gnutls_priority_deinit( c->prios );
290 #else
291 	LDAP_FREE( c->kx_list );
292 #endif
293 	gnutls_certificate_free_credentials( c->cred );
294 	ber_memfree ( c );
295 }
296 
297 static int
298 tlsg_getfile( const char *path, gnutls_datum_t *buf )
299 {
300 	int rc = -1, fd;
301 	struct stat st;
302 
303 	fd = open( path, O_RDONLY );
304 	if ( fd >= 0 && fstat( fd, &st ) == 0 ) {
305 		buf->size = st.st_size;
306 		buf->data = LDAP_MALLOC( st.st_size + 1 );
307 		if ( buf->data ) {
308 			rc = read( fd, buf->data, st.st_size );
309 			close( fd );
310 			if ( rc < st.st_size )
311 				rc = -1;
312 			else
313 				rc = 0;
314 		}
315 	}
316 	return rc;
317 }
318 
319 /* This is the GnuTLS default */
320 #define	VERIFY_DEPTH	6
321 
322 /*
323  * initialize a new TLS context
324  */
325 static int
326 tlsg_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
327 {
328 	tlsg_ctx *ctx = lo->ldo_tls_ctx;
329 	int rc;
330 
331  	if ( lo->ldo_tls_ciphersuite &&
332 		tlsg_parse_ciphers( ctx, lt->lt_ciphersuite )) {
333  		Debug( LDAP_DEBUG_ANY,
334  			   "TLS: could not set cipher list %s.\n",
335  			   lo->ldo_tls_ciphersuite, 0, 0 );
336 		return -1;
337  	}
338 
339 	if (lo->ldo_tls_cacertdir != NULL) {
340 		Debug( LDAP_DEBUG_ANY,
341 		       "TLS: warning: cacertdir not implemented for gnutls\n",
342 		       NULL, NULL, NULL );
343 	}
344 
345 	if (lo->ldo_tls_cacertfile != NULL) {
346 		rc = gnutls_certificate_set_x509_trust_file(
347 			ctx->cred,
348 			lt->lt_cacertfile,
349 			GNUTLS_X509_FMT_PEM );
350 		if ( rc < 0 ) return -1;
351 	}
352 
353 	if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
354 		gnutls_x509_privkey_t key;
355 		gnutls_datum_t buf;
356 		gnutls_x509_crt_t certs[VERIFY_DEPTH];
357 		unsigned int max = VERIFY_DEPTH;
358 
359 		rc = gnutls_x509_privkey_init( &key );
360 		if ( rc ) return -1;
361 
362 		/* OpenSSL builds the cert chain for us, but GnuTLS
363 		 * expects it to be present in the certfile. If it's
364 		 * not, we have to build it ourselves. So we have to
365 		 * do some special checks here...
366 		 */
367 		rc = tlsg_getfile( lt->lt_keyfile, &buf );
368 		if ( rc ) return -1;
369 		rc = gnutls_x509_privkey_import( key, &buf,
370 			GNUTLS_X509_FMT_PEM );
371 		LDAP_FREE( buf.data );
372 		if ( rc < 0 ) return rc;
373 
374 		rc = tlsg_getfile( lt->lt_certfile, &buf );
375 		if ( rc ) return -1;
376 		rc = gnutls_x509_crt_list_import( certs, &max, &buf,
377 			GNUTLS_X509_FMT_PEM, 0 );
378 		LDAP_FREE( buf.data );
379 		if ( rc < 0 ) return rc;
380 
381 		/* If there's only one cert and it's not self-signed,
382 		 * then we have to build the cert chain.
383 		 */
384 		if ( max == 1 && !gnutls_x509_crt_check_issuer( certs[0], certs[0] )) {
385 			gnutls_x509_crt_t *cas;
386 			unsigned int i, j, ncas;
387 
388 			gnutls_certificate_get_x509_cas( ctx->cred, &cas, &ncas );
389 			for ( i = 1; i<VERIFY_DEPTH; i++ ) {
390 				for ( j = 0; j<ncas; j++ ) {
391 					if ( gnutls_x509_crt_check_issuer( certs[i-1], cas[j] )) {
392 						certs[i] = cas[j];
393 						max++;
394 						/* If this CA is self-signed, we're done */
395 						if ( gnutls_x509_crt_check_issuer( cas[j], cas[j] ))
396 							j = ncas;
397 						break;
398 					}
399 				}
400 				/* only continue if we found a CA and it was not self-signed */
401 				if ( j == ncas )
402 					break;
403 			}
404 		}
405 		rc = gnutls_certificate_set_x509_key( ctx->cred, certs, max, key );
406 		if ( rc ) return -1;
407 	} else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
408 		Debug( LDAP_DEBUG_ANY,
409 		       "TLS: only one of certfile and keyfile specified\n",
410 		       NULL, NULL, NULL );
411 		return -1;
412 	}
413 
414 	if ( lo->ldo_tls_dhfile ) {
415 		Debug( LDAP_DEBUG_ANY,
416 		       "TLS: warning: ignoring dhfile\n",
417 		       NULL, NULL, NULL );
418 	}
419 
420 	if ( lo->ldo_tls_crlfile ) {
421 		rc = gnutls_certificate_set_x509_crl_file(
422 			ctx->cred,
423 			lt->lt_crlfile,
424 			GNUTLS_X509_FMT_PEM );
425 		if ( rc < 0 ) return -1;
426 		rc = 0;
427 	}
428 
429 	/* FIXME: ITS#5992 - this should go be configurable,
430 	 * and V1 CA certs should be phased out ASAP.
431 	 */
432 	gnutls_certificate_set_verify_flags( ctx->cred,
433 		GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT );
434 
435 	if ( is_server ) {
436 		gnutls_dh_params_init(&ctx->dh_params);
437 		gnutls_dh_params_generate2(ctx->dh_params, DH_BITS);
438 	}
439 	return 0;
440 }
441 
442 static tls_session *
443 tlsg_session_new ( tls_ctx * ctx, int is_server )
444 {
445 	tlsg_ctx *c = (tlsg_ctx *)ctx;
446 	tlsg_session *session;
447 
448 	session = ber_memcalloc ( 1, sizeof (*session) );
449 	if ( !session )
450 		return NULL;
451 
452 	session->ctx = c;
453 	gnutls_init( &session->session, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT );
454 #ifdef HAVE_CIPHERSUITES
455 	gnutls_priority_set( session->session, c->prios );
456 #else
457 	gnutls_set_default_priority( session->session );
458 	if ( c->kx_list ) {
459 		gnutls_kx_set_priority( session->session, c->kx_list );
460 		gnutls_cipher_set_priority( session->session, c->cipher_list );
461 		gnutls_mac_set_priority( session->session, c->mac_list );
462 	}
463 #endif
464 	if ( c->cred )
465 		gnutls_credentials_set( session->session, GNUTLS_CRD_CERTIFICATE, c->cred );
466 
467 	if ( is_server ) {
468 		int flag = 0;
469 		if ( c->lo->ldo_tls_require_cert ) {
470 			flag = GNUTLS_CERT_REQUEST;
471 			if ( c->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
472 				c->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD )
473 				flag = GNUTLS_CERT_REQUIRE;
474 			gnutls_certificate_server_set_request( session->session, flag );
475 		}
476 	}
477 	return (tls_session *)session;
478 }
479 
480 static int
481 tlsg_session_accept( tls_session *session )
482 {
483 	tlsg_session *s = (tlsg_session *)session;
484 	int rc;
485 
486 	rc = gnutls_handshake( s->session );
487 	if ( rc == 0 && s->ctx->lo->ldo_tls_require_cert != LDAP_OPT_X_TLS_NEVER ) {
488 		const gnutls_datum_t *peer_cert_list;
489 		unsigned int list_size;
490 
491 		peer_cert_list = gnutls_certificate_get_peers( s->session,
492 						&list_size );
493 		if ( !peer_cert_list && s->ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_TRY )
494 			rc = 0;
495 		else {
496 			rc = tlsg_cert_verify( s );
497 			if ( rc && s->ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW )
498 				rc = 0;
499 		}
500 	}
501 	return rc;
502 }
503 
504 static int
505 tlsg_session_connect( LDAP *ld, tls_session *session )
506 {
507 	return tlsg_session_accept( session);
508 }
509 
510 static int
511 tlsg_session_upflags( Sockbuf *sb, tls_session *session, int rc )
512 {
513 	tlsg_session *s = (tlsg_session *)session;
514 
515 	if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
516 		return 0;
517 
518 	switch (gnutls_record_get_direction (s->session)) {
519 	case 0:
520 		sb->sb_trans_needs_read = 1;
521 		return 1;
522 	case 1:
523 		sb->sb_trans_needs_write = 1;
524 		return 1;
525 	}
526 	return 0;
527 }
528 
529 static char *
530 tlsg_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
531 {
532 	return (char *)gnutls_strerror( rc );
533 }
534 
535 static void
536 tlsg_x509_cert_dn( struct berval *cert, struct berval *dn, int get_subject )
537 {
538 	BerElementBuffer berbuf;
539 	BerElement *ber = (BerElement *)&berbuf;
540 	ber_tag_t tag;
541 	ber_len_t len;
542 	ber_int_t i;
543 
544 	ber_init2( ber, cert, LBER_USE_DER );
545 	tag = ber_skip_tag( ber, &len );	/* Sequence */
546 	tag = ber_skip_tag( ber, &len );	/* Sequence */
547 	tag = ber_skip_tag( ber, &len );	/* Context + Constructed (version) */
548 	if ( tag == 0xa0 )	/* Version is optional */
549 		tag = ber_get_int( ber, &i );	/* Int: Version */
550 	tag = ber_skip_tag( ber, &len );	/* Int: Serial (can be longer than ber_int_t) */
551 	ber_skip_data( ber, len );
552 	tag = ber_skip_tag( ber, &len );	/* Sequence: Signature */
553 	ber_skip_data( ber, len );
554 	if ( !get_subject ) {
555 		tag = ber_peek_tag( ber, &len );	/* Sequence: Issuer DN */
556 	} else {
557 		tag = ber_skip_tag( ber, &len );
558 		ber_skip_data( ber, len );
559 		tag = ber_skip_tag( ber, &len );	/* Sequence: Validity */
560 		ber_skip_data( ber, len );
561 		tag = ber_peek_tag( ber, &len );	/* Sequence: Subject DN */
562 	}
563 	len = ber_ptrlen( ber );
564 	dn->bv_val = cert->bv_val + len;
565 	dn->bv_len = cert->bv_len - len;
566 }
567 
568 static int
569 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
570 {
571 	tlsg_session *s = (tlsg_session *)session;
572 	const gnutls_datum_t *x;
573 	struct berval bv;
574 
575 	x = gnutls_certificate_get_ours( s->session );
576 
577 	if (!x) return LDAP_INVALID_CREDENTIALS;
578 
579 	bv.bv_val = (char *) x->data;
580 	bv.bv_len = x->size;
581 
582 	tlsg_x509_cert_dn( &bv, der_dn, 1 );
583 	return 0;
584 }
585 
586 static int
587 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
588 {
589 	tlsg_session *s = (tlsg_session *)session;
590 	if ( !s->peer_der_dn.bv_val ) {
591 		const gnutls_datum_t *peer_cert_list;
592 		unsigned int list_size;
593 		struct berval bv;
594 
595 		peer_cert_list = gnutls_certificate_get_peers( s->session,
596 							&list_size );
597 		if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
598 
599 		bv.bv_len = peer_cert_list->size;
600 		bv.bv_val = (char *) peer_cert_list->data;
601 
602 		tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
603 	}
604 	*der_dn = s->peer_der_dn;
605 	return 0;
606 }
607 
608 /* what kind of hostname were we given? */
609 #define	IS_DNS	0
610 #define	IS_IP4	1
611 #define	IS_IP6	2
612 
613 #define	CN_OID	"2.5.4.3"
614 
615 static int
616 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
617 {
618 	tlsg_session *s = (tlsg_session *)session;
619 	int i, ret;
620 	const gnutls_datum_t *peer_cert_list;
621 	unsigned int list_size;
622 	char altname[NI_MAXHOST];
623 	size_t altnamesize;
624 
625 	gnutls_x509_crt_t cert;
626 	const char *name;
627 	char *ptr;
628 	char *domain = NULL;
629 #ifdef LDAP_PF_INET6
630 	struct in6_addr addr;
631 #else
632 	struct in_addr addr;
633 #endif
634 	int len1 = 0, len2 = 0;
635 	int ntype = IS_DNS;
636 
637 	if( ldap_int_hostname &&
638 		( !name_in || !strcasecmp( name_in, "localhost" ) ) )
639 	{
640 		name = ldap_int_hostname;
641 	} else {
642 		name = name_in;
643 	}
644 
645 	peer_cert_list = gnutls_certificate_get_peers( s->session,
646 						&list_size );
647 	if ( !peer_cert_list ) {
648 		Debug( LDAP_DEBUG_ANY,
649 			"TLS: unable to get peer certificate.\n",
650 			0, 0, 0 );
651 		/* If this was a fatal condition, things would have
652 		 * aborted long before now.
653 		 */
654 		return LDAP_SUCCESS;
655 	}
656 	ret = gnutls_x509_crt_init( &cert );
657 	if ( ret < 0 )
658 		return LDAP_LOCAL_ERROR;
659 	ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
660 	if ( ret ) {
661 		gnutls_x509_crt_deinit( cert );
662 		return LDAP_LOCAL_ERROR;
663 	}
664 
665 #ifdef LDAP_PF_INET6
666 	if (name[0] == '[' && strchr(name, ']')) {
667 		char *n2 = ldap_strdup(name+1);
668 		*strchr(n2, ']') = 0;
669 		if (inet_pton(AF_INET6, n2, &addr))
670 			ntype = IS_IP6;
671 		LDAP_FREE(n2);
672 	} else
673 #endif
674 	if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
675 		if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
676 	}
677 
678 	if (ntype == IS_DNS) {
679 		len1 = strlen(name);
680 		domain = strchr(name, '.');
681 		if (domain) {
682 			len2 = len1 - (domain-name);
683 		}
684 	}
685 
686 	for ( i=0, ret=0; ret >= 0; i++ ) {
687 		altnamesize = sizeof(altname);
688 		ret = gnutls_x509_crt_get_subject_alt_name( cert, i,
689 			altname, &altnamesize, NULL );
690 		if ( ret < 0 ) break;
691 
692 		/* ignore empty */
693 		if ( altnamesize == 0 ) continue;
694 
695 		if ( ret == GNUTLS_SAN_DNSNAME ) {
696 			if (ntype != IS_DNS) continue;
697 
698 			/* Is this an exact match? */
699 			if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
700 				break;
701 			}
702 
703 			/* Is this a wildcard match? */
704 			if (domain && (altname[0] == '*') && (altname[1] == '.') &&
705 				(len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
706 			{
707 				break;
708 			}
709 		} else if ( ret == GNUTLS_SAN_IPADDRESS ) {
710 			if (ntype == IS_DNS) continue;
711 
712 #ifdef LDAP_PF_INET6
713 			if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
714 				continue;
715 			} else
716 #endif
717 			if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
718 				continue;
719 			}
720 			if (!memcmp(altname, &addr, altnamesize)) {
721 				break;
722 			}
723 		}
724 	}
725 	if ( ret >= 0 ) {
726 		ret = LDAP_SUCCESS;
727 	} else {
728 		/* find the last CN */
729 		i=0;
730 		do {
731 			altnamesize = 0;
732 			ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
733 				i, 1, altname, &altnamesize );
734 			if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
735 				i++;
736 			else
737 				break;
738 		} while ( 1 );
739 
740 		if ( i ) {
741 			altnamesize = sizeof(altname);
742 			ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
743 				i-1, 0, altname, &altnamesize );
744 		}
745 
746 		if ( ret < 0 ) {
747 			Debug( LDAP_DEBUG_ANY,
748 				"TLS: unable to get common name from peer certificate.\n",
749 				0, 0, 0 );
750 			ret = LDAP_CONNECT_ERROR;
751 			if ( ld->ld_error ) {
752 				LDAP_FREE( ld->ld_error );
753 			}
754 			ld->ld_error = LDAP_STRDUP(
755 				_("TLS: unable to get CN from peer certificate"));
756 
757 		} else {
758 			ret = LDAP_LOCAL_ERROR;
759 			if ( !len1 ) len1 = strlen( name );
760 			if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
761 				ret = LDAP_SUCCESS;
762 
763 			} else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
764 					/* Is this a wildcard match? */
765 				if( domain &&
766 					(len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
767 					ret = LDAP_SUCCESS;
768 				}
769 			}
770 		}
771 
772 		if( ret == LDAP_LOCAL_ERROR ) {
773 			altname[altnamesize] = '\0';
774 			Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
775 				"common name in certificate (%s).\n",
776 				name, altname, 0 );
777 			ret = LDAP_CONNECT_ERROR;
778 			if ( ld->ld_error ) {
779 				LDAP_FREE( ld->ld_error );
780 			}
781 			ld->ld_error = LDAP_STRDUP(
782 				_("TLS: hostname does not match CN in peer certificate"));
783 		}
784 	}
785 	gnutls_x509_crt_deinit( cert );
786 	return ret;
787 }
788 
789 static int
790 tlsg_session_strength( tls_session *session )
791 {
792 	tlsg_session *s = (tlsg_session *)session;
793 	gnutls_cipher_algorithm_t c;
794 
795 	c = gnutls_cipher_get( s->session );
796 	return gnutls_cipher_get_key_size( c ) * 8;
797 }
798 
799 /* suites is a string of colon-separated cipher suite names. */
800 static int
801 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
802 {
803 #ifdef HAVE_CIPHERSUITES
804 	const char *err;
805 	return gnutls_priority_init( &ctx->prios, suites, &err );
806 #else
807 	char *ptr, *end;
808 	int i, j, len, num;
809 	int *list, nkx = 0, ncipher = 0, nmac = 0;
810 	int *kx, *cipher, *mac;
811 
812 	num = 0;
813 	ptr = suites;
814 	do {
815 		end = strchr(ptr, ':');
816 		if ( end )
817 			len = end - ptr;
818 		else
819 			len = strlen(ptr);
820 		for (i=0; i<tlsg_n_ciphers; i++) {
821 			if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
822 				num++;
823 				break;
824 			}
825 		}
826 		if ( i == tlsg_n_ciphers ) {
827 			/* unrecognized cipher suite */
828 			return -1;
829 		}
830 		ptr += len + 1;
831 	} while (end);
832 
833 	/* Space for all 3 lists */
834 	list = LDAP_MALLOC( (num+1) * sizeof(int) * 3 );
835 	if ( !list )
836 		return -1;
837 	kx = list;
838 	cipher = kx+num+1;
839 	mac = cipher+num+1;
840 
841 	ptr = suites;
842 	do {
843 		end = strchr(ptr, ':');
844 		if ( end )
845 			len = end - ptr;
846 		else
847 			len = strlen(ptr);
848 		for (i=0; i<tlsg_n_ciphers; i++) {
849 			/* For each cipher suite, insert its algorithms into
850 			 * their respective priority lists. Make sure they
851 			 * only appear once in each list.
852 			 */
853 			if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
854 				for (j=0; j<nkx; j++)
855 					if ( kx[j] == tlsg_ciphers[i].kx )
856 						break;
857 				if ( j == nkx )
858 					kx[nkx++] = tlsg_ciphers[i].kx;
859 				for (j=0; j<ncipher; j++)
860 					if ( cipher[j] == tlsg_ciphers[i].cipher )
861 						break;
862 				if ( j == ncipher )
863 					cipher[ncipher++] = tlsg_ciphers[i].cipher;
864 				for (j=0; j<nmac; j++)
865 					if ( mac[j] == tlsg_ciphers[i].mac )
866 						break;
867 				if ( j == nmac )
868 					mac[nmac++] = tlsg_ciphers[i].mac;
869 				break;
870 			}
871 		}
872 		ptr += len + 1;
873 	} while (end);
874 	kx[nkx] = 0;
875 	cipher[ncipher] = 0;
876 	mac[nmac] = 0;
877 	ctx->kx_list = kx;
878 	ctx->cipher_list = cipher;
879 	ctx->mac_list = mac;
880 	return 0;
881 #endif
882 }
883 
884 /*
885  * TLS support for LBER Sockbufs
886  */
887 
888 struct tls_data {
889 	tlsg_session		*session;
890 	Sockbuf_IO_Desc		*sbiod;
891 };
892 
893 static ssize_t
894 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
895 {
896 	struct tls_data		*p;
897 
898 	if ( buf == NULL || len <= 0 ) return 0;
899 
900 	p = (struct tls_data *)ptr;
901 
902 	if ( p == NULL || p->sbiod == NULL ) {
903 		return 0;
904 	}
905 
906 	return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
907 }
908 
909 static ssize_t
910 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
911 {
912 	struct tls_data		*p;
913 
914 	if ( buf == NULL || len <= 0 ) return 0;
915 
916 	p = (struct tls_data *)ptr;
917 
918 	if ( p == NULL || p->sbiod == NULL ) {
919 		return 0;
920 	}
921 
922 	return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
923 }
924 
925 static int
926 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
927 {
928 	struct tls_data		*p;
929 	tlsg_session	*session = arg;
930 
931 	assert( sbiod != NULL );
932 
933 	p = LBER_MALLOC( sizeof( *p ) );
934 	if ( p == NULL ) {
935 		return -1;
936 	}
937 
938 	gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
939 	gnutls_transport_set_pull_function( session->session, tlsg_recv );
940 	gnutls_transport_set_push_function( session->session, tlsg_send );
941 	p->session = session;
942 	p->sbiod = sbiod;
943 	sbiod->sbiod_pvt = p;
944 	return 0;
945 }
946 
947 static int
948 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
949 {
950 	struct tls_data		*p;
951 
952 	assert( sbiod != NULL );
953 	assert( sbiod->sbiod_pvt != NULL );
954 
955 	p = (struct tls_data *)sbiod->sbiod_pvt;
956 	gnutls_deinit ( p->session->session );
957 	LBER_FREE( p->session );
958 	LBER_FREE( sbiod->sbiod_pvt );
959 	sbiod->sbiod_pvt = NULL;
960 	return 0;
961 }
962 
963 static int
964 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
965 {
966 	struct tls_data		*p;
967 
968 	assert( sbiod != NULL );
969 	assert( sbiod->sbiod_pvt != NULL );
970 
971 	p = (struct tls_data *)sbiod->sbiod_pvt;
972 	gnutls_bye ( p->session->session, GNUTLS_SHUT_RDWR );
973 	return 0;
974 }
975 
976 static int
977 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
978 {
979 	struct tls_data		*p;
980 
981 	assert( sbiod != NULL );
982 	assert( sbiod->sbiod_pvt != NULL );
983 
984 	p = (struct tls_data *)sbiod->sbiod_pvt;
985 
986 	if ( opt == LBER_SB_OPT_GET_SSL ) {
987 		*((tlsg_session **)arg) = p->session;
988 		return 1;
989 
990 	} else if ( opt == LBER_SB_OPT_DATA_READY ) {
991 		if( gnutls_record_check_pending( p->session->session ) > 0 ) {
992 			return 1;
993 		}
994 	}
995 
996 	return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
997 }
998 
999 static ber_slen_t
1000 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1001 {
1002 	struct tls_data		*p;
1003 	ber_slen_t		ret;
1004 
1005 	assert( sbiod != NULL );
1006 	assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1007 
1008 	p = (struct tls_data *)sbiod->sbiod_pvt;
1009 
1010 	ret = gnutls_record_recv ( p->session->session, buf, len );
1011 	switch (ret) {
1012 	case GNUTLS_E_INTERRUPTED:
1013 	case GNUTLS_E_AGAIN:
1014 		sbiod->sbiod_sb->sb_trans_needs_read = 1;
1015 		sock_errset(EWOULDBLOCK);
1016 		ret = 0;
1017 		break;
1018 	case GNUTLS_E_REHANDSHAKE:
1019 		for ( ret = gnutls_handshake ( p->session->session );
1020 		      ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
1021 		      ret = gnutls_handshake ( p->session->session ) );
1022 		sbiod->sbiod_sb->sb_trans_needs_read = 1;
1023 		ret = 0;
1024 		break;
1025 	default:
1026 		sbiod->sbiod_sb->sb_trans_needs_read = 0;
1027 	}
1028 	return ret;
1029 }
1030 
1031 static ber_slen_t
1032 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1033 {
1034 	struct tls_data		*p;
1035 	ber_slen_t		ret;
1036 
1037 	assert( sbiod != NULL );
1038 	assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1039 
1040 	p = (struct tls_data *)sbiod->sbiod_pvt;
1041 
1042 	ret = gnutls_record_send ( p->session->session, (char *)buf, len );
1043 
1044 	if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
1045 		sbiod->sbiod_sb->sb_trans_needs_write = 1;
1046 		sock_errset(EWOULDBLOCK);
1047 		ret = 0;
1048 	} else {
1049 		sbiod->sbiod_sb->sb_trans_needs_write = 0;
1050 	}
1051 	return ret;
1052 }
1053 
1054 static Sockbuf_IO tlsg_sbio =
1055 {
1056 	tlsg_sb_setup,		/* sbi_setup */
1057 	tlsg_sb_remove,		/* sbi_remove */
1058 	tlsg_sb_ctrl,		/* sbi_ctrl */
1059 	tlsg_sb_read,		/* sbi_read */
1060 	tlsg_sb_write,		/* sbi_write */
1061 	tlsg_sb_close		/* sbi_close */
1062 };
1063 
1064 /* Certs are not automatically varified during the handshake */
1065 static int
1066 tlsg_cert_verify( tlsg_session *ssl )
1067 {
1068 	unsigned int status = 0;
1069 	int err;
1070 	time_t now = time(0);
1071 	time_t peertime;
1072 
1073 	err = gnutls_certificate_verify_peers2( ssl->session, &status );
1074 	if ( err < 0 ) {
1075 		Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
1076 			err,0,0 );
1077 		return -1;
1078 	}
1079 	if ( status ) {
1080 		Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
1081 			status, 0,0 );
1082 		return -1;
1083 	}
1084 	peertime = gnutls_certificate_expiration_time_peers( ssl->session );
1085 	if ( peertime == (time_t) -1 ) {
1086 		Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
1087 			0, 0, 0 );
1088 		return -1;
1089 	}
1090 	if ( peertime < now ) {
1091 		Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
1092 			0, 0, 0 );
1093 		return -1;
1094 	}
1095 	peertime = gnutls_certificate_activation_time_peers( ssl->session );
1096 	if ( peertime == (time_t) -1 ) {
1097 		Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
1098 			0, 0, 0 );
1099 		return -1;
1100 	}
1101 	if ( peertime > now ) {
1102 		Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
1103 			0, 0, 0 );
1104 		return -1;
1105 	}
1106 	return 0;
1107 }
1108 
1109 tls_impl ldap_int_tls_impl = {
1110 	"GnuTLS",
1111 
1112 	tlsg_init,
1113 	tlsg_destroy,
1114 
1115 	tlsg_ctx_new,
1116 	tlsg_ctx_ref,
1117 	tlsg_ctx_free,
1118 	tlsg_ctx_init,
1119 
1120 	tlsg_session_new,
1121 	tlsg_session_connect,
1122 	tlsg_session_accept,
1123 	tlsg_session_upflags,
1124 	tlsg_session_errmsg,
1125 	tlsg_session_my_dn,
1126 	tlsg_session_peer_dn,
1127 	tlsg_session_chkhost,
1128 	tlsg_session_strength,
1129 
1130 	&tlsg_sbio,
1131 
1132 #ifdef LDAP_R_COMPILE
1133 	tlsg_thr_init,
1134 #else
1135 	NULL,
1136 #endif
1137 
1138 	0
1139 };
1140 
1141 #endif /* HAVE_GNUTLS */
1142