1 /* tls_g.c - Handle tls/ssl using GNUTLS. */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2008-2021 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS: GNUTLS support written by Howard Chu and
17  * Emily Backes; sponsored by The Written Word (thewrittenword.com)
18  * and Stanford University (stanford.edu).
19  */
20 
21 #include "portable.h"
22 
23 #ifdef HAVE_GNUTLS
24 
25 #include "ldap_config.h"
26 
27 #include <stdio.h>
28 
29 #include <ac/stdlib.h>
30 #include <ac/errno.h>
31 #include <ac/socket.h>
32 #include <ac/string.h>
33 #include <ac/ctype.h>
34 #include <ac/time.h>
35 #include <ac/unistd.h>
36 #include <ac/param.h>
37 #include <ac/dirent.h>
38 #include <sys/stat.h>
39 #include <fcntl.h>
40 
41 #include "ldap-int.h"
42 #include "ldap-tls.h"
43 
44 #include <gnutls/gnutls.h>
45 #include <gnutls/x509.h>
46 
47 typedef struct tlsg_ctx {
48 	gnutls_certificate_credentials_t cred;
49 	gnutls_dh_params_t dh_params;
50 	unsigned long verify_depth;
51 	int refcount;
52 	int reqcert;
53 	gnutls_priority_t prios;
54 #ifdef LDAP_R_COMPILE
55 	ldap_pvt_thread_mutex_t ref_mutex;
56 #endif
57 } tlsg_ctx;
58 
59 typedef struct tlsg_session {
60 	gnutls_session_t session;
61 	tlsg_ctx *ctx;
62 	struct berval peer_der_dn;
63 } tlsg_session;
64 
65 static int tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites );
66 static int tlsg_cert_verify( tlsg_session *s );
67 
68 #ifdef LDAP_R_COMPILE
69 
70 static void
tlsg_thr_init(void)71 tlsg_thr_init( void )
72 {
73 	/* do nothing */
74 }
75 #endif /* LDAP_R_COMPILE */
76 
77 /*
78  * Initialize TLS subsystem. Should be called only once.
79  */
80 static int
tlsg_init(void)81 tlsg_init( void )
82 {
83 	gnutls_global_init();
84 	return 0;
85 }
86 
87 /*
88  * Tear down the TLS subsystem. Should only be called once.
89  */
90 static void
tlsg_destroy(void)91 tlsg_destroy( void )
92 {
93 	gnutls_global_deinit();
94 }
95 
96 static tls_ctx *
tlsg_ctx_new(struct ldapoptions * lo)97 tlsg_ctx_new ( struct ldapoptions *lo )
98 {
99 	tlsg_ctx *ctx;
100 
101 	ctx = ber_memcalloc ( 1, sizeof (*ctx) );
102 	if ( ctx ) {
103 		if ( gnutls_certificate_allocate_credentials( &ctx->cred )) {
104 			ber_memfree( ctx );
105 			return NULL;
106 		}
107 		ctx->refcount = 1;
108 		gnutls_priority_init( &ctx->prios, "NORMAL", NULL );
109 #ifdef LDAP_R_COMPILE
110 		ldap_pvt_thread_mutex_init( &ctx->ref_mutex );
111 #endif
112 	}
113 	return (tls_ctx *)ctx;
114 }
115 
116 static void
tlsg_ctx_ref(tls_ctx * ctx)117 tlsg_ctx_ref( tls_ctx *ctx )
118 {
119 	tlsg_ctx *c = (tlsg_ctx *)ctx;
120 	LDAP_MUTEX_LOCK( &c->ref_mutex );
121 	c->refcount++;
122 	LDAP_MUTEX_UNLOCK( &c->ref_mutex );
123 }
124 
125 static void
tlsg_ctx_free(tls_ctx * ctx)126 tlsg_ctx_free ( tls_ctx *ctx )
127 {
128 	tlsg_ctx *c = (tlsg_ctx *)ctx;
129 	int refcount;
130 
131 	if ( !c ) return;
132 
133 	LDAP_MUTEX_LOCK( &c->ref_mutex );
134 	refcount = --c->refcount;
135 	LDAP_MUTEX_UNLOCK( &c->ref_mutex );
136 	if ( refcount )
137 		return;
138 	gnutls_priority_deinit( c->prios );
139 	gnutls_certificate_free_credentials( c->cred );
140 	if ( c->dh_params )
141 		gnutls_dh_params_deinit( c->dh_params );
142 	ber_memfree ( c );
143 }
144 
145 static int
tlsg_getfile(const char * path,gnutls_datum_t * buf)146 tlsg_getfile( const char *path, gnutls_datum_t *buf )
147 {
148 	int rc = -1, fd;
149 	struct stat st;
150 
151 	fd = open( path, O_RDONLY );
152 	if ( fd >= 0 && fstat( fd, &st ) == 0 ) {
153 		buf->size = st.st_size;
154 		buf->data = LDAP_MALLOC( st.st_size + 1 );
155 		if ( buf->data ) {
156 			rc = read( fd, buf->data, st.st_size );
157 			close( fd );
158 			if ( rc < st.st_size )
159 				rc = -1;
160 			else
161 				rc = 0;
162 		}
163 	}
164 	return rc;
165 }
166 
167 /* This is the GnuTLS default */
168 #define	VERIFY_DEPTH	6
169 
170 /*
171  * initialize a new TLS context
172  */
173 static int
tlsg_ctx_init(struct ldapoptions * lo,struct ldaptls * lt,int is_server)174 tlsg_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
175 {
176 	tlsg_ctx *ctx = lo->ldo_tls_ctx;
177 	int rc;
178 
179  	if ( lo->ldo_tls_ciphersuite &&
180 		tlsg_parse_ciphers( ctx, lt->lt_ciphersuite )) {
181  		Debug( LDAP_DEBUG_ANY,
182  			   "TLS: could not set cipher list %s.\n",
183  			   lo->ldo_tls_ciphersuite, 0, 0 );
184 		return -1;
185  	}
186 
187 	if (lo->ldo_tls_cacertdir != NULL) {
188 		Debug( LDAP_DEBUG_ANY,
189 		       "TLS: warning: cacertdir not implemented for gnutls\n",
190 		       NULL, NULL, NULL );
191 	}
192 
193 	if (lo->ldo_tls_cacertfile != NULL) {
194 		rc = gnutls_certificate_set_x509_trust_file(
195 			ctx->cred,
196 			lt->lt_cacertfile,
197 			GNUTLS_X509_FMT_PEM );
198 		if ( rc < 0 ) return -1;
199 	}
200 
201 	if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
202 		gnutls_x509_privkey_t key;
203 		gnutls_datum_t buf;
204 		gnutls_x509_crt_t certs[VERIFY_DEPTH];
205 		unsigned int max = VERIFY_DEPTH;
206 
207 		rc = gnutls_x509_privkey_init( &key );
208 		if ( rc ) return -1;
209 
210 		/* OpenSSL builds the cert chain for us, but GnuTLS
211 		 * expects it to be present in the certfile. If it's
212 		 * not, we have to build it ourselves. So we have to
213 		 * do some special checks here...
214 		 */
215 		rc = tlsg_getfile( lt->lt_keyfile, &buf );
216 		if ( rc ) return -1;
217 		rc = gnutls_x509_privkey_import( key, &buf,
218 			GNUTLS_X509_FMT_PEM );
219 		LDAP_FREE( buf.data );
220 		if ( rc < 0 ) return rc;
221 
222 		rc = tlsg_getfile( lt->lt_certfile, &buf );
223 		if ( rc ) return -1;
224 		rc = gnutls_x509_crt_list_import( certs, &max, &buf,
225 			GNUTLS_X509_FMT_PEM, 0 );
226 		LDAP_FREE( buf.data );
227 		if ( rc < 0 ) return rc;
228 
229 		/* If there's only one cert and it's not self-signed,
230 		 * then we have to build the cert chain.
231 		 */
232 		if ( max == 1 && !gnutls_x509_crt_check_issuer( certs[0], certs[0] )) {
233 			unsigned int i;
234 			for ( i = 1; i<VERIFY_DEPTH; i++ ) {
235 				if ( gnutls_certificate_get_issuer( ctx->cred, certs[i-1], &certs[i], 0 ))
236 					break;
237 				max++;
238 				/* If this CA is self-signed, we're done */
239 				if ( gnutls_x509_crt_check_issuer( certs[i], certs[i] ))
240 					break;
241 			}
242 		}
243 		rc = gnutls_certificate_set_x509_key( ctx->cred, certs, max, key );
244 		if ( rc ) return -1;
245 	} else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
246 		Debug( LDAP_DEBUG_ANY,
247 		       "TLS: only one of certfile and keyfile specified\n",
248 		       NULL, NULL, NULL );
249 		return -1;
250 	}
251 
252 	if ( lo->ldo_tls_crlfile ) {
253 		rc = gnutls_certificate_set_x509_crl_file(
254 			ctx->cred,
255 			lt->lt_crlfile,
256 			GNUTLS_X509_FMT_PEM );
257 		if ( rc < 0 ) return -1;
258 		rc = 0;
259 	}
260 
261 	/* FIXME: ITS#5992 - this should be configurable,
262 	 * and V1 CA certs should be phased out ASAP.
263 	 */
264 	gnutls_certificate_set_verify_flags( ctx->cred,
265 		GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT );
266 
267 	if ( is_server && lo->ldo_tls_dhfile ) {
268 		gnutls_datum_t buf;
269 		rc = tlsg_getfile( lo->ldo_tls_dhfile, &buf );
270 		if ( rc ) return -1;
271 		rc = gnutls_dh_params_init( &ctx->dh_params );
272 		if ( rc == 0 )
273 			rc = gnutls_dh_params_import_pkcs3( ctx->dh_params, &buf,
274 				GNUTLS_X509_FMT_PEM );
275 		LDAP_FREE( buf.data );
276 		if ( rc ) return -1;
277 		gnutls_certificate_set_dh_params( ctx->cred, ctx->dh_params );
278 	}
279 
280 	ctx->reqcert = lo->ldo_tls_require_cert;
281 
282 	return 0;
283 }
284 
285 static tls_session *
tlsg_session_new(tls_ctx * ctx,int is_server)286 tlsg_session_new ( tls_ctx * ctx, int is_server )
287 {
288 	tlsg_ctx *c = (tlsg_ctx *)ctx;
289 	tlsg_session *session;
290 
291 	session = ber_memcalloc ( 1, sizeof (*session) );
292 	if ( !session )
293 		return NULL;
294 
295 	session->ctx = c;
296 	gnutls_init( &session->session, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT );
297 	gnutls_priority_set( session->session, c->prios );
298 	if ( c->cred )
299 		gnutls_credentials_set( session->session, GNUTLS_CRD_CERTIFICATE, c->cred );
300 
301 	if ( is_server ) {
302 		int flag = 0;
303 		if ( c->reqcert ) {
304 			flag = GNUTLS_CERT_REQUEST;
305 			if ( c->reqcert == LDAP_OPT_X_TLS_DEMAND ||
306 				c->reqcert == LDAP_OPT_X_TLS_HARD )
307 				flag = GNUTLS_CERT_REQUIRE;
308 			gnutls_certificate_server_set_request( session->session, flag );
309 		}
310 	}
311 	return (tls_session *)session;
312 }
313 
314 static int
tlsg_session_accept(tls_session * session)315 tlsg_session_accept( tls_session *session )
316 {
317 	tlsg_session *s = (tlsg_session *)session;
318 	int rc;
319 
320 	rc = gnutls_handshake( s->session );
321 	if ( rc == 0 && s->ctx->reqcert != LDAP_OPT_X_TLS_NEVER ) {
322 		const gnutls_datum_t *peer_cert_list;
323 		unsigned int list_size;
324 
325 		peer_cert_list = gnutls_certificate_get_peers( s->session,
326 						&list_size );
327 		if ( !peer_cert_list && s->ctx->reqcert == LDAP_OPT_X_TLS_TRY )
328 			rc = 0;
329 		else {
330 			rc = tlsg_cert_verify( s );
331 			if ( rc && s->ctx->reqcert == LDAP_OPT_X_TLS_ALLOW )
332 				rc = 0;
333 		}
334 	}
335 	return rc;
336 }
337 
338 static int
tlsg_session_connect(LDAP * ld,tls_session * session)339 tlsg_session_connect( LDAP *ld, tls_session *session )
340 {
341 	return tlsg_session_accept( session);
342 }
343 
344 static int
tlsg_session_upflags(Sockbuf * sb,tls_session * session,int rc)345 tlsg_session_upflags( Sockbuf *sb, tls_session *session, int rc )
346 {
347 	tlsg_session *s = (tlsg_session *)session;
348 
349 	if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
350 		return 0;
351 
352 	switch (gnutls_record_get_direction (s->session)) {
353 	case 0:
354 		sb->sb_trans_needs_read = 1;
355 		return 1;
356 	case 1:
357 		sb->sb_trans_needs_write = 1;
358 		return 1;
359 	}
360 	return 0;
361 }
362 
363 static char *
tlsg_session_errmsg(tls_session * sess,int rc,char * buf,size_t len)364 tlsg_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
365 {
366 	return (char *)gnutls_strerror( rc );
367 }
368 
369 static void
tlsg_x509_cert_dn(struct berval * cert,struct berval * dn,int get_subject)370 tlsg_x509_cert_dn( struct berval *cert, struct berval *dn, int get_subject )
371 {
372 	BerElementBuffer berbuf;
373 	BerElement *ber = (BerElement *)&berbuf;
374 	ber_tag_t tag;
375 	ber_len_t len;
376 	ber_int_t i;
377 
378 	ber_init2( ber, cert, LBER_USE_DER );
379 	tag = ber_skip_tag( ber, &len );	/* Sequence */
380 	tag = ber_skip_tag( ber, &len );	/* Sequence */
381 	tag = ber_peek_tag( ber, &len );	/* Context + Constructed (version) */
382 	if ( tag == 0xa0 ) {	/* Version is optional */
383 		tag = ber_skip_tag( ber, &len );
384 		tag = ber_get_int( ber, &i );	/* Int: Version */
385 	}
386 	tag = ber_skip_tag( ber, &len );	/* Int: Serial (can be longer than ber_int_t) */
387 	ber_skip_data( ber, len );
388 	tag = ber_skip_tag( ber, &len );	/* Sequence: Signature */
389 	ber_skip_data( ber, len );
390 	if ( !get_subject ) {
391 		tag = ber_peek_tag( ber, &len );	/* Sequence: Issuer DN */
392 	} else {
393 		tag = ber_skip_tag( ber, &len );
394 		ber_skip_data( ber, len );
395 		tag = ber_skip_tag( ber, &len );	/* Sequence: Validity */
396 		ber_skip_data( ber, len );
397 		tag = ber_peek_tag( ber, &len );	/* Sequence: Subject DN */
398 	}
399 	len = ber_ptrlen( ber );
400 	dn->bv_val = cert->bv_val + len;
401 	dn->bv_len = cert->bv_len - len;
402 }
403 
404 static int
tlsg_session_my_dn(tls_session * session,struct berval * der_dn)405 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
406 {
407 	tlsg_session *s = (tlsg_session *)session;
408 	const gnutls_datum_t *x;
409 	struct berval bv;
410 
411 	x = gnutls_certificate_get_ours( s->session );
412 
413 	if (!x) return LDAP_INVALID_CREDENTIALS;
414 
415 	bv.bv_val = (char *) x->data;
416 	bv.bv_len = x->size;
417 
418 	tlsg_x509_cert_dn( &bv, der_dn, 1 );
419 	return 0;
420 }
421 
422 static int
tlsg_session_peer_dn(tls_session * session,struct berval * der_dn)423 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
424 {
425 	tlsg_session *s = (tlsg_session *)session;
426 	if ( !s->peer_der_dn.bv_val ) {
427 		const gnutls_datum_t *peer_cert_list;
428 		unsigned int list_size;
429 		struct berval bv;
430 
431 		peer_cert_list = gnutls_certificate_get_peers( s->session,
432 							&list_size );
433 		if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
434 
435 		bv.bv_len = peer_cert_list->size;
436 		bv.bv_val = (char *) peer_cert_list->data;
437 
438 		tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
439 	}
440 	*der_dn = s->peer_der_dn;
441 	return 0;
442 }
443 
444 /* what kind of hostname were we given? */
445 #define	IS_DNS	0
446 #define	IS_IP4	1
447 #define	IS_IP6	2
448 
449 #define	CN_OID	"2.5.4.3"
450 
451 static int
tlsg_session_chkhost(LDAP * ld,tls_session * session,const char * name_in)452 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
453 {
454 	tlsg_session *s = (tlsg_session *)session;
455 	int i, ret;
456 	int chkSAN = ld->ld_options.ldo_tls_require_san, gotSAN = 0;
457 	const gnutls_datum_t *peer_cert_list;
458 	unsigned int list_size;
459 	char altname[NI_MAXHOST];
460 	size_t altnamesize;
461 
462 	gnutls_x509_crt_t cert;
463 	const char *name;
464 	char *ptr;
465 	char *domain = NULL;
466 #ifdef LDAP_PF_INET6
467 	struct in6_addr addr;
468 #else
469 	struct in_addr addr;
470 #endif
471 	int len1 = 0, len2 = 0;
472 	int ntype = IS_DNS;
473 
474 	if( ldap_int_hostname &&
475 		( !name_in || !strcasecmp( name_in, "localhost" ) ) )
476 	{
477 		name = ldap_int_hostname;
478 	} else {
479 		name = name_in;
480 	}
481 
482 	peer_cert_list = gnutls_certificate_get_peers( s->session,
483 						&list_size );
484 	if ( !peer_cert_list ) {
485 		Debug( LDAP_DEBUG_ANY,
486 			"TLS: unable to get peer certificate.\n",
487 			0, 0, 0 );
488 		/* If this was a fatal condition, things would have
489 		 * aborted long before now.
490 		 */
491 		return LDAP_SUCCESS;
492 	}
493 	ret = gnutls_x509_crt_init( &cert );
494 	if ( ret < 0 )
495 		return LDAP_LOCAL_ERROR;
496 	ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
497 	if ( ret ) {
498 		gnutls_x509_crt_deinit( cert );
499 		return LDAP_LOCAL_ERROR;
500 	}
501 
502 #ifdef LDAP_PF_INET6
503 	if (inet_pton(AF_INET6, name, &addr)) {
504 		ntype = IS_IP6;
505 	} else
506 #endif
507 	if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
508 		if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
509 	}
510 
511 	if (ntype == IS_DNS) {
512 		len1 = strlen(name);
513 		domain = strchr(name, '.');
514 		if (domain) {
515 			len2 = len1 - (domain-name);
516 		}
517 	}
518 
519 	if (chkSAN) {
520 	for ( i=0, ret=0; ret >= 0; i++ ) {
521 		altnamesize = sizeof(altname);
522 		ret = gnutls_x509_crt_get_subject_alt_name( cert, i,
523 			altname, &altnamesize, NULL );
524 		if ( ret < 0 ) break;
525 
526 		gotSAN = 1;
527 		/* ignore empty */
528 		if ( altnamesize == 0 ) continue;
529 
530 		if ( ret == GNUTLS_SAN_DNSNAME ) {
531 			if (ntype != IS_DNS) continue;
532 
533 			/* Is this an exact match? */
534 			if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
535 				break;
536 			}
537 
538 			/* Is this a wildcard match? */
539 			if (domain && (altname[0] == '*') && (altname[1] == '.') &&
540 				(len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
541 			{
542 				break;
543 			}
544 		} else if ( ret == GNUTLS_SAN_IPADDRESS ) {
545 			if (ntype == IS_DNS) continue;
546 
547 #ifdef LDAP_PF_INET6
548 			if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
549 				continue;
550 			} else
551 #endif
552 			if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
553 				continue;
554 			}
555 			if (!memcmp(altname, &addr, altnamesize)) {
556 				break;
557 			}
558 		}
559 	}
560 	if ( ret >= 0 ) {
561 		ret = LDAP_SUCCESS;
562 	}
563 	}
564 	if (ret != LDAP_SUCCESS && chkSAN) {
565 		switch(chkSAN) {
566 		case LDAP_OPT_X_TLS_DEMAND:
567 		case LDAP_OPT_X_TLS_HARD:
568 			if (!gotSAN) {
569 				Debug( LDAP_DEBUG_ANY,
570 					"TLS: unable to get subjectAltName from peer certificate.\n", 0, 0, 0 );
571 				ret = LDAP_CONNECT_ERROR;
572 				if ( ld->ld_error ) {
573 					LDAP_FREE( ld->ld_error );
574 				}
575 				ld->ld_error = LDAP_STRDUP(
576 					_("TLS: unable to get subjectAltName from peer certificate"));
577 				goto done;
578 			}
579 			/* FALLTHRU */
580 		case LDAP_OPT_X_TLS_TRY:
581 			if (gotSAN) {
582 				Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
583 					"subjectAltName in certificate.\n",
584 					name, 0, 0 );
585 				ret = LDAP_CONNECT_ERROR;
586 				if ( ld->ld_error ) {
587 					LDAP_FREE( ld->ld_error );
588 				}
589 				ld->ld_error = LDAP_STRDUP(
590 					_("TLS: hostname does not match subjectAltName in peer certificate"));
591 				goto done;
592 			}
593 			break;
594 		case LDAP_OPT_X_TLS_ALLOW:
595 			break;
596 		}
597 	}
598 
599 	if ( ret != LDAP_SUCCESS ){
600 		/* find the last CN */
601 		i=0;
602 		do {
603 			altnamesize = 0;
604 			ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
605 				i, 1, altname, &altnamesize );
606 			if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
607 				i++;
608 			else
609 				break;
610 		} while ( 1 );
611 
612 		if ( i ) {
613 			altnamesize = sizeof(altname);
614 			ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
615 				i-1, 0, altname, &altnamesize );
616 		}
617 
618 		if ( ret < 0 ) {
619 			Debug( LDAP_DEBUG_ANY,
620 				"TLS: unable to get common name from peer certificate.\n",
621 				0, 0, 0 );
622 			ret = LDAP_CONNECT_ERROR;
623 			if ( ld->ld_error ) {
624 				LDAP_FREE( ld->ld_error );
625 			}
626 			ld->ld_error = LDAP_STRDUP(
627 				_("TLS: unable to get CN from peer certificate"));
628 
629 		} else {
630 			ret = LDAP_LOCAL_ERROR;
631 			if ( !len1 ) len1 = strlen( name );
632 			if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
633 				ret = LDAP_SUCCESS;
634 
635 			} else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
636 					/* Is this a wildcard match? */
637 				if( domain &&
638 					(len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
639 					ret = LDAP_SUCCESS;
640 				}
641 			}
642 		}
643 
644 		if( ret == LDAP_LOCAL_ERROR ) {
645 			altname[altnamesize] = '\0';
646 			Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
647 				"common name in certificate (%s).\n",
648 				name, altname, 0 );
649 			ret = LDAP_CONNECT_ERROR;
650 			if ( ld->ld_error ) {
651 				LDAP_FREE( ld->ld_error );
652 			}
653 			ld->ld_error = LDAP_STRDUP(
654 				_("TLS: hostname does not match name in peer certificate"));
655 		}
656 	}
657 done:
658 	gnutls_x509_crt_deinit( cert );
659 	return ret;
660 }
661 
662 static int
tlsg_session_strength(tls_session * session)663 tlsg_session_strength( tls_session *session )
664 {
665 	tlsg_session *s = (tlsg_session *)session;
666 	gnutls_cipher_algorithm_t c;
667 
668 	c = gnutls_cipher_get( s->session );
669 	return gnutls_cipher_get_key_size( c ) * 8;
670 }
671 
672 /* suites is a string of colon-separated cipher suite names. */
673 static int
tlsg_parse_ciphers(tlsg_ctx * ctx,char * suites)674 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
675 {
676 	const char *err;
677 	int rc = gnutls_priority_init( &ctx->prios, suites, &err );
678 	if ( rc )
679 		ctx->prios = NULL;
680 	return rc;
681 }
682 
683 /*
684  * TLS support for LBER Sockbufs
685  */
686 
687 struct tls_data {
688 	tlsg_session		*session;
689 	Sockbuf_IO_Desc		*sbiod;
690 };
691 
692 static ssize_t
tlsg_recv(gnutls_transport_ptr_t ptr,void * buf,size_t len)693 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
694 {
695 	struct tls_data		*p;
696 
697 	if ( buf == NULL || len <= 0 ) return 0;
698 
699 	p = (struct tls_data *)ptr;
700 
701 	if ( p == NULL || p->sbiod == NULL ) {
702 		return 0;
703 	}
704 
705 	return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
706 }
707 
708 static ssize_t
tlsg_send(gnutls_transport_ptr_t ptr,const void * buf,size_t len)709 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
710 {
711 	struct tls_data		*p;
712 
713 	if ( buf == NULL || len <= 0 ) return 0;
714 
715 	p = (struct tls_data *)ptr;
716 
717 	if ( p == NULL || p->sbiod == NULL ) {
718 		return 0;
719 	}
720 
721 	return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
722 }
723 
724 static int
tlsg_sb_setup(Sockbuf_IO_Desc * sbiod,void * arg)725 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
726 {
727 	struct tls_data		*p;
728 	tlsg_session	*session = arg;
729 
730 	assert( sbiod != NULL );
731 
732 	p = LBER_MALLOC( sizeof( *p ) );
733 	if ( p == NULL ) {
734 		return -1;
735 	}
736 
737 	gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
738 	gnutls_transport_set_pull_function( session->session, tlsg_recv );
739 	gnutls_transport_set_push_function( session->session, tlsg_send );
740 	p->session = session;
741 	p->sbiod = sbiod;
742 	sbiod->sbiod_pvt = p;
743 	return 0;
744 }
745 
746 static int
tlsg_sb_remove(Sockbuf_IO_Desc * sbiod)747 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
748 {
749 	struct tls_data		*p;
750 
751 	assert( sbiod != NULL );
752 	assert( sbiod->sbiod_pvt != NULL );
753 
754 	p = (struct tls_data *)sbiod->sbiod_pvt;
755 	gnutls_deinit ( p->session->session );
756 	LBER_FREE( p->session );
757 	LBER_FREE( sbiod->sbiod_pvt );
758 	sbiod->sbiod_pvt = NULL;
759 	return 0;
760 }
761 
762 static int
tlsg_sb_close(Sockbuf_IO_Desc * sbiod)763 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
764 {
765 	struct tls_data		*p;
766 
767 	assert( sbiod != NULL );
768 	assert( sbiod->sbiod_pvt != NULL );
769 
770 	p = (struct tls_data *)sbiod->sbiod_pvt;
771 	gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
772 	return 0;
773 }
774 
775 static int
tlsg_sb_ctrl(Sockbuf_IO_Desc * sbiod,int opt,void * arg)776 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
777 {
778 	struct tls_data		*p;
779 
780 	assert( sbiod != NULL );
781 	assert( sbiod->sbiod_pvt != NULL );
782 
783 	p = (struct tls_data *)sbiod->sbiod_pvt;
784 
785 	if ( opt == LBER_SB_OPT_GET_SSL ) {
786 		*((tlsg_session **)arg) = p->session;
787 		return 1;
788 
789 	} else if ( opt == LBER_SB_OPT_DATA_READY ) {
790 		if( gnutls_record_check_pending( p->session->session ) > 0 ) {
791 			return 1;
792 		}
793 	}
794 
795 	return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
796 }
797 
798 static ber_slen_t
tlsg_sb_read(Sockbuf_IO_Desc * sbiod,void * buf,ber_len_t len)799 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
800 {
801 	struct tls_data		*p;
802 	ber_slen_t		ret;
803 
804 	assert( sbiod != NULL );
805 	assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
806 
807 	p = (struct tls_data *)sbiod->sbiod_pvt;
808 
809 	ret = gnutls_record_recv ( p->session->session, buf, len );
810 	switch (ret) {
811 	case GNUTLS_E_INTERRUPTED:
812 	case GNUTLS_E_AGAIN:
813 		sbiod->sbiod_sb->sb_trans_needs_read = 1;
814 		sock_errset(EWOULDBLOCK);
815 		ret = 0;
816 		break;
817 	case GNUTLS_E_REHANDSHAKE:
818 		for ( ret = gnutls_handshake ( p->session->session );
819 		      ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
820 		      ret = gnutls_handshake ( p->session->session ) );
821 		sbiod->sbiod_sb->sb_trans_needs_read = 1;
822 		ret = 0;
823 		break;
824 	default:
825 		sbiod->sbiod_sb->sb_trans_needs_read = 0;
826 	}
827 	return ret;
828 }
829 
830 static ber_slen_t
tlsg_sb_write(Sockbuf_IO_Desc * sbiod,void * buf,ber_len_t len)831 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
832 {
833 	struct tls_data		*p;
834 	ber_slen_t		ret;
835 
836 	assert( sbiod != NULL );
837 	assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
838 
839 	p = (struct tls_data *)sbiod->sbiod_pvt;
840 
841 	ret = gnutls_record_send ( p->session->session, (char *)buf, len );
842 
843 	if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
844 		sbiod->sbiod_sb->sb_trans_needs_write = 1;
845 		sock_errset(EWOULDBLOCK);
846 		ret = 0;
847 	} else {
848 		sbiod->sbiod_sb->sb_trans_needs_write = 0;
849 	}
850 	return ret;
851 }
852 
853 static Sockbuf_IO tlsg_sbio =
854 {
855 	tlsg_sb_setup,		/* sbi_setup */
856 	tlsg_sb_remove,		/* sbi_remove */
857 	tlsg_sb_ctrl,		/* sbi_ctrl */
858 	tlsg_sb_read,		/* sbi_read */
859 	tlsg_sb_write,		/* sbi_write */
860 	tlsg_sb_close		/* sbi_close */
861 };
862 
863 /* Certs are not automatically varified during the handshake */
864 static int
tlsg_cert_verify(tlsg_session * ssl)865 tlsg_cert_verify( tlsg_session *ssl )
866 {
867 	unsigned int status = 0;
868 	int err;
869 	time_t now = time(0);
870 	time_t peertime;
871 
872 	err = gnutls_certificate_verify_peers2( ssl->session, &status );
873 	if ( err < 0 ) {
874 		Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
875 			err,0,0 );
876 		return -1;
877 	}
878 	if ( status ) {
879 		Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
880 			status, 0,0 );
881 		return -1;
882 	}
883 	peertime = gnutls_certificate_expiration_time_peers( ssl->session );
884 	if ( peertime == (time_t) -1 ) {
885 		Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
886 			0, 0, 0 );
887 		return -1;
888 	}
889 	if ( peertime < now ) {
890 		Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
891 			0, 0, 0 );
892 		return -1;
893 	}
894 	peertime = gnutls_certificate_activation_time_peers( ssl->session );
895 	if ( peertime == (time_t) -1 ) {
896 		Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
897 			0, 0, 0 );
898 		return -1;
899 	}
900 	if ( peertime > now ) {
901 		Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
902 			0, 0, 0 );
903 		return -1;
904 	}
905 	return 0;
906 }
907 
908 tls_impl ldap_int_tls_impl = {
909 	"GnuTLS",
910 
911 	tlsg_init,
912 	tlsg_destroy,
913 
914 	tlsg_ctx_new,
915 	tlsg_ctx_ref,
916 	tlsg_ctx_free,
917 	tlsg_ctx_init,
918 
919 	tlsg_session_new,
920 	tlsg_session_connect,
921 	tlsg_session_accept,
922 	tlsg_session_upflags,
923 	tlsg_session_errmsg,
924 	tlsg_session_my_dn,
925 	tlsg_session_peer_dn,
926 	tlsg_session_chkhost,
927 	tlsg_session_strength,
928 
929 	&tlsg_sbio,
930 
931 #ifdef LDAP_R_COMPILE
932 	tlsg_thr_init,
933 #else
934 	NULL,
935 #endif
936 
937 	0
938 };
939 
940 #endif /* HAVE_GNUTLS */
941