1 /* tls_g.c - Handle tls/ssl using GNUTLS. */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
5 * Copyright 2008-2015 The OpenLDAP Foundation.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted only as authorized by the OpenLDAP
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>.
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).
25 #include "ldap_config.h"
29 #include <ac/stdlib.h>
31 #include <ac/socket.h>
32 #include <ac/string.h>
35 #include <ac/unistd.h>
37 #include <ac/dirent.h>
44 #include <gnutls/gnutls.h>
45 #include <gnutls/x509.h>
47 #define DH_BITS (1024)
49 typedef struct tlsg_ctx {
50 struct ldapoptions *lo;
51 gnutls_certificate_credentials_t cred;
52 gnutls_dh_params_t dh_params;
53 unsigned long verify_depth;
55 gnutls_priority_t prios;
57 ldap_pvt_thread_mutex_t ref_mutex;
61 typedef struct tlsg_session {
62 gnutls_session_t session;
64 struct berval peer_der_dn;
67 static int tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites );
68 static int tlsg_cert_verify( tlsg_session *s );
73 tlsg_mutex_init( void **priv )
76 ldap_pvt_thread_mutex_t *lock = LDAP_MALLOC( sizeof( ldap_pvt_thread_mutex_t ));
81 err = ldap_pvt_thread_mutex_init( lock );
91 tlsg_mutex_destroy( void **lock )
93 int err = ldap_pvt_thread_mutex_destroy( *lock );
99 tlsg_mutex_lock( void **lock )
101 return ldap_pvt_thread_mutex_lock( *lock );
105 tlsg_mutex_unlock( void **lock )
107 return ldap_pvt_thread_mutex_unlock( *lock );
111 tlsg_thr_init( void )
113 gnutls_global_set_mutex (tlsg_mutex_init,
118 #endif /* LDAP_R_COMPILE */
121 * Initialize TLS subsystem. Should be called only once.
126 gnutls_global_init();
131 * Tear down the TLS subsystem. Should only be called once.
136 gnutls_global_deinit();
140 tlsg_ctx_new ( struct ldapoptions *lo )
144 ctx = ber_memcalloc ( 1, sizeof (*ctx) );
147 if ( gnutls_certificate_allocate_credentials( &ctx->cred )) {
152 gnutls_priority_init( &ctx->prios, "NORMAL", NULL );
153 #ifdef LDAP_R_COMPILE
154 ldap_pvt_thread_mutex_init( &ctx->ref_mutex );
157 return (tls_ctx *)ctx;
161 tlsg_ctx_ref( tls_ctx *ctx )
163 tlsg_ctx *c = (tlsg_ctx *)ctx;
164 LDAP_MUTEX_LOCK( &c->ref_mutex );
166 LDAP_MUTEX_UNLOCK( &c->ref_mutex );
170 tlsg_ctx_free ( tls_ctx *ctx )
172 tlsg_ctx *c = (tlsg_ctx *)ctx;
177 LDAP_MUTEX_LOCK( &c->ref_mutex );
178 refcount = --c->refcount;
179 LDAP_MUTEX_UNLOCK( &c->ref_mutex );
182 gnutls_priority_deinit( c->prios );
183 gnutls_certificate_free_credentials( c->cred );
188 tlsg_getfile( const char *path, gnutls_datum_t *buf )
193 fd = open( path, O_RDONLY );
194 if ( fd >= 0 && fstat( fd, &st ) == 0 ) {
195 buf->size = st.st_size;
196 buf->data = LDAP_MALLOC( st.st_size + 1 );
198 rc = read( fd, buf->data, st.st_size );
200 if ( rc < st.st_size )
209 /* This is the GnuTLS default */
210 #define VERIFY_DEPTH 6
213 * initialize a new TLS context
216 tlsg_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
218 tlsg_ctx *ctx = lo->ldo_tls_ctx;
221 if ( lo->ldo_tls_ciphersuite &&
222 tlsg_parse_ciphers( ctx, lt->lt_ciphersuite )) {
223 Debug( LDAP_DEBUG_ANY,
224 "TLS: could not set cipher list %s.\n",
225 lo->ldo_tls_ciphersuite, 0, 0 );
229 if (lo->ldo_tls_cacertdir != NULL) {
230 Debug( LDAP_DEBUG_ANY,
231 "TLS: warning: cacertdir not implemented for gnutls\n",
235 if (lo->ldo_tls_cacertfile != NULL) {
236 rc = gnutls_certificate_set_x509_trust_file(
239 GNUTLS_X509_FMT_PEM );
240 if ( rc < 0 ) return -1;
243 if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
244 gnutls_x509_privkey_t key;
246 gnutls_x509_crt_t certs[VERIFY_DEPTH];
247 unsigned int max = VERIFY_DEPTH;
249 rc = gnutls_x509_privkey_init( &key );
252 /* OpenSSL builds the cert chain for us, but GnuTLS
253 * expects it to be present in the certfile. If it's
254 * not, we have to build it ourselves. So we have to
255 * do some special checks here...
257 rc = tlsg_getfile( lt->lt_keyfile, &buf );
259 rc = gnutls_x509_privkey_import( key, &buf,
260 GNUTLS_X509_FMT_PEM );
261 LDAP_FREE( buf.data );
262 if ( rc < 0 ) return rc;
264 rc = tlsg_getfile( lt->lt_certfile, &buf );
266 rc = gnutls_x509_crt_list_import( certs, &max, &buf,
267 GNUTLS_X509_FMT_PEM, 0 );
268 LDAP_FREE( buf.data );
269 if ( rc < 0 ) return rc;
271 /* If there's only one cert and it's not self-signed,
272 * then we have to build the cert chain.
274 if ( max == 1 && !gnutls_x509_crt_check_issuer( certs[0], certs[0] )) {
276 for ( i = 1; i<VERIFY_DEPTH; i++ ) {
277 if ( gnutls_certificate_get_issuer( ctx->cred, certs[i-1], &certs[i], 0 ))
280 /* If this CA is self-signed, we're done */
281 if ( gnutls_x509_crt_check_issuer( certs[i], certs[i] ))
285 rc = gnutls_certificate_set_x509_key( ctx->cred, certs, max, key );
287 } else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
288 Debug( LDAP_DEBUG_ANY,
289 "TLS: only one of certfile and keyfile specified\n",
294 if ( lo->ldo_tls_dhfile ) {
295 Debug( LDAP_DEBUG_ANY,
296 "TLS: warning: ignoring dhfile\n",
300 if ( lo->ldo_tls_crlfile ) {
301 rc = gnutls_certificate_set_x509_crl_file(
304 GNUTLS_X509_FMT_PEM );
305 if ( rc < 0 ) return -1;
309 /* FIXME: ITS#5992 - this should go be configurable,
310 * and V1 CA certs should be phased out ASAP.
312 gnutls_certificate_set_verify_flags( ctx->cred,
313 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT );
316 gnutls_dh_params_init(&ctx->dh_params);
317 gnutls_dh_params_generate2(ctx->dh_params, DH_BITS);
323 tlsg_session_new ( tls_ctx * ctx, int is_server )
325 tlsg_ctx *c = (tlsg_ctx *)ctx;
326 tlsg_session *session;
328 session = ber_memcalloc ( 1, sizeof (*session) );
333 gnutls_init( &session->session, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT );
334 gnutls_priority_set( session->session, c->prios );
336 gnutls_credentials_set( session->session, GNUTLS_CRD_CERTIFICATE, c->cred );
340 if ( c->lo->ldo_tls_require_cert ) {
341 flag = GNUTLS_CERT_REQUEST;
342 if ( c->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
343 c->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD )
344 flag = GNUTLS_CERT_REQUIRE;
345 gnutls_certificate_server_set_request( session->session, flag );
348 return (tls_session *)session;
352 tlsg_session_accept( tls_session *session )
354 tlsg_session *s = (tlsg_session *)session;
357 rc = gnutls_handshake( s->session );
358 if ( rc == 0 && s->ctx->lo->ldo_tls_require_cert != LDAP_OPT_X_TLS_NEVER ) {
359 const gnutls_datum_t *peer_cert_list;
360 unsigned int list_size;
362 peer_cert_list = gnutls_certificate_get_peers( s->session,
364 if ( !peer_cert_list && s->ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_TRY )
367 rc = tlsg_cert_verify( s );
368 if ( rc && s->ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW )
376 tlsg_session_connect( LDAP *ld, tls_session *session )
378 return tlsg_session_accept( session);
382 tlsg_session_upflags( Sockbuf *sb, tls_session *session, int rc )
384 tlsg_session *s = (tlsg_session *)session;
386 if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
389 switch (gnutls_record_get_direction (s->session)) {
391 sb->sb_trans_needs_read = 1;
394 sb->sb_trans_needs_write = 1;
401 tlsg_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
403 return (char *)gnutls_strerror( rc );
407 tlsg_x509_cert_dn( struct berval *cert, struct berval *dn, int get_subject )
409 BerElementBuffer berbuf;
410 BerElement *ber = (BerElement *)&berbuf;
415 ber_init2( ber, cert, LBER_USE_DER );
416 tag = ber_skip_tag( ber, &len ); /* Sequence */
417 tag = ber_skip_tag( ber, &len ); /* Sequence */
418 tag = ber_peek_tag( ber, &len ); /* Context + Constructed (version) */
419 if ( tag == 0xa0 ) { /* Version is optional */
420 tag = ber_skip_tag( ber, &len );
421 tag = ber_get_int( ber, &i ); /* Int: Version */
423 tag = ber_skip_tag( ber, &len ); /* Int: Serial (can be longer than ber_int_t) */
424 ber_skip_data( ber, len );
425 tag = ber_skip_tag( ber, &len ); /* Sequence: Signature */
426 ber_skip_data( ber, len );
427 if ( !get_subject ) {
428 tag = ber_peek_tag( ber, &len ); /* Sequence: Issuer DN */
430 tag = ber_skip_tag( ber, &len );
431 ber_skip_data( ber, len );
432 tag = ber_skip_tag( ber, &len ); /* Sequence: Validity */
433 ber_skip_data( ber, len );
434 tag = ber_peek_tag( ber, &len ); /* Sequence: Subject DN */
436 len = ber_ptrlen( ber );
437 dn->bv_val = cert->bv_val + len;
438 dn->bv_len = cert->bv_len - len;
442 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
444 tlsg_session *s = (tlsg_session *)session;
445 const gnutls_datum_t *x;
448 x = gnutls_certificate_get_ours( s->session );
450 if (!x) return LDAP_INVALID_CREDENTIALS;
452 bv.bv_val = (char *) x->data;
455 tlsg_x509_cert_dn( &bv, der_dn, 1 );
460 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
462 tlsg_session *s = (tlsg_session *)session;
463 if ( !s->peer_der_dn.bv_val ) {
464 const gnutls_datum_t *peer_cert_list;
465 unsigned int list_size;
468 peer_cert_list = gnutls_certificate_get_peers( s->session,
470 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
472 bv.bv_len = peer_cert_list->size;
473 bv.bv_val = (char *) peer_cert_list->data;
475 tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
477 *der_dn = s->peer_der_dn;
481 /* what kind of hostname were we given? */
486 #define CN_OID "2.5.4.3"
489 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
491 tlsg_session *s = (tlsg_session *)session;
493 const gnutls_datum_t *peer_cert_list;
494 unsigned int list_size;
495 char altname[NI_MAXHOST];
498 gnutls_x509_crt_t cert;
503 struct in6_addr addr;
507 int len1 = 0, len2 = 0;
510 if( ldap_int_hostname &&
511 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
513 name = ldap_int_hostname;
518 peer_cert_list = gnutls_certificate_get_peers( s->session,
520 if ( !peer_cert_list ) {
521 Debug( LDAP_DEBUG_ANY,
522 "TLS: unable to get peer certificate.\n",
524 /* If this was a fatal condition, things would have
525 * aborted long before now.
529 ret = gnutls_x509_crt_init( &cert );
531 return LDAP_LOCAL_ERROR;
532 ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
534 gnutls_x509_crt_deinit( cert );
535 return LDAP_LOCAL_ERROR;
539 if (inet_pton(AF_INET6, name, &addr)) {
543 if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
544 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
547 if (ntype == IS_DNS) {
549 domain = strchr(name, '.');
551 len2 = len1 - (domain-name);
555 for ( i=0, ret=0; ret >= 0; i++ ) {
556 altnamesize = sizeof(altname);
557 ret = gnutls_x509_crt_get_subject_alt_name( cert, i,
558 altname, &altnamesize, NULL );
559 if ( ret < 0 ) break;
562 if ( altnamesize == 0 ) continue;
564 if ( ret == GNUTLS_SAN_DNSNAME ) {
565 if (ntype != IS_DNS) continue;
567 /* Is this an exact match? */
568 if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
572 /* Is this a wildcard match? */
573 if (domain && (altname[0] == '*') && (altname[1] == '.') &&
574 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
578 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
579 if (ntype == IS_DNS) continue;
582 if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
586 if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
589 if (!memcmp(altname, &addr, altnamesize)) {
597 /* find the last CN */
601 ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
602 i, 1, altname, &altnamesize );
603 if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
610 altnamesize = sizeof(altname);
611 ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
612 i-1, 0, altname, &altnamesize );
616 Debug( LDAP_DEBUG_ANY,
617 "TLS: unable to get common name from peer certificate.\n",
619 ret = LDAP_CONNECT_ERROR;
620 if ( ld->ld_error ) {
621 LDAP_FREE( ld->ld_error );
623 ld->ld_error = LDAP_STRDUP(
624 _("TLS: unable to get CN from peer certificate"));
627 ret = LDAP_LOCAL_ERROR;
628 if ( !len1 ) len1 = strlen( name );
629 if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
632 } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
633 /* Is this a wildcard match? */
635 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
641 if( ret == LDAP_LOCAL_ERROR ) {
642 altname[altnamesize] = '\0';
643 Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
644 "common name in certificate (%s).\n",
646 ret = LDAP_CONNECT_ERROR;
647 if ( ld->ld_error ) {
648 LDAP_FREE( ld->ld_error );
650 ld->ld_error = LDAP_STRDUP(
651 _("TLS: hostname does not match CN in peer certificate"));
654 gnutls_x509_crt_deinit( cert );
659 tlsg_session_strength( tls_session *session )
661 tlsg_session *s = (tlsg_session *)session;
662 gnutls_cipher_algorithm_t c;
664 c = gnutls_cipher_get( s->session );
665 return gnutls_cipher_get_key_size( c ) * 8;
668 /* suites is a string of colon-separated cipher suite names. */
670 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
673 int rc = gnutls_priority_init( &ctx->prios, suites, &err );
680 * TLS support for LBER Sockbufs
684 tlsg_session *session;
685 Sockbuf_IO_Desc *sbiod;
689 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
693 if ( buf == NULL || len <= 0 ) return 0;
695 p = (struct tls_data *)ptr;
697 if ( p == NULL || p->sbiod == NULL ) {
701 return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
705 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
709 if ( buf == NULL || len <= 0 ) return 0;
711 p = (struct tls_data *)ptr;
713 if ( p == NULL || p->sbiod == NULL ) {
717 return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
721 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
724 tlsg_session *session = arg;
726 assert( sbiod != NULL );
728 p = LBER_MALLOC( sizeof( *p ) );
733 gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
734 gnutls_transport_set_pull_function( session->session, tlsg_recv );
735 gnutls_transport_set_push_function( session->session, tlsg_send );
736 p->session = session;
738 sbiod->sbiod_pvt = p;
743 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
747 assert( sbiod != NULL );
748 assert( sbiod->sbiod_pvt != NULL );
750 p = (struct tls_data *)sbiod->sbiod_pvt;
751 gnutls_deinit ( p->session->session );
752 LBER_FREE( p->session );
753 LBER_FREE( sbiod->sbiod_pvt );
754 sbiod->sbiod_pvt = NULL;
759 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
763 assert( sbiod != NULL );
764 assert( sbiod->sbiod_pvt != NULL );
766 p = (struct tls_data *)sbiod->sbiod_pvt;
767 gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
772 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
776 assert( sbiod != NULL );
777 assert( sbiod->sbiod_pvt != NULL );
779 p = (struct tls_data *)sbiod->sbiod_pvt;
781 if ( opt == LBER_SB_OPT_GET_SSL ) {
782 *((tlsg_session **)arg) = p->session;
785 } else if ( opt == LBER_SB_OPT_DATA_READY ) {
786 if( gnutls_record_check_pending( p->session->session ) > 0 ) {
791 return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
795 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
800 assert( sbiod != NULL );
801 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
803 p = (struct tls_data *)sbiod->sbiod_pvt;
805 ret = gnutls_record_recv ( p->session->session, buf, len );
807 case GNUTLS_E_INTERRUPTED:
809 sbiod->sbiod_sb->sb_trans_needs_read = 1;
810 sock_errset(EWOULDBLOCK);
813 case GNUTLS_E_REHANDSHAKE:
814 for ( ret = gnutls_handshake ( p->session->session );
815 ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
816 ret = gnutls_handshake ( p->session->session ) );
817 sbiod->sbiod_sb->sb_trans_needs_read = 1;
821 sbiod->sbiod_sb->sb_trans_needs_read = 0;
827 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
832 assert( sbiod != NULL );
833 assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
835 p = (struct tls_data *)sbiod->sbiod_pvt;
837 ret = gnutls_record_send ( p->session->session, (char *)buf, len );
839 if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
840 sbiod->sbiod_sb->sb_trans_needs_write = 1;
841 sock_errset(EWOULDBLOCK);
844 sbiod->sbiod_sb->sb_trans_needs_write = 0;
849 static Sockbuf_IO tlsg_sbio =
851 tlsg_sb_setup, /* sbi_setup */
852 tlsg_sb_remove, /* sbi_remove */
853 tlsg_sb_ctrl, /* sbi_ctrl */
854 tlsg_sb_read, /* sbi_read */
855 tlsg_sb_write, /* sbi_write */
856 tlsg_sb_close /* sbi_close */
859 /* Certs are not automatically varified during the handshake */
861 tlsg_cert_verify( tlsg_session *ssl )
863 unsigned int status = 0;
865 time_t now = time(0);
868 err = gnutls_certificate_verify_peers2( ssl->session, &status );
870 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
875 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
879 peertime = gnutls_certificate_expiration_time_peers( ssl->session );
880 if ( peertime == (time_t) -1 ) {
881 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
885 if ( peertime < now ) {
886 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
890 peertime = gnutls_certificate_activation_time_peers( ssl->session );
891 if ( peertime == (time_t) -1 ) {
892 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
896 if ( peertime > now ) {
897 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
904 tls_impl ldap_int_tls_impl = {
916 tlsg_session_connect,
918 tlsg_session_upflags,
921 tlsg_session_peer_dn,
922 tlsg_session_chkhost,
923 tlsg_session_strength,
927 #ifdef LDAP_R_COMPILE
936 #endif /* HAVE_GNUTLS */