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