]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_g.c
7396804392fd0e1f3a2015dffd639655dd89ad44
[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 #if LIBGNUTLS_VERSION_NUMBER >= 0x020200
49 #define HAVE_CIPHERSUITES       1
50 /* This is a kludge. gcrypt 1.4.x has support. Recent GnuTLS requires gcrypt 1.4.x
51  * but that dependency isn't reflected in their configure script, resulting in
52  * build errors on older gcrypt. So, if they have a working build environment,
53  * assume gcrypt is new enough.
54  */
55 #define HAVE_GCRYPT_RAND        1
56 #else
57 #undef HAVE_CIPHERSUITES
58 #undef HAVE_GCRYPT_RAND
59 #endif
60
61 #ifndef HAVE_CIPHERSUITES
62 /* Versions prior to 2.2.0 didn't handle cipher suites, so we had to
63  * kludge them ourselves.
64  */
65 typedef struct tls_cipher_suite {
66         const char *name;
67         gnutls_kx_algorithm_t kx;
68         gnutls_cipher_algorithm_t cipher;
69         gnutls_mac_algorithm_t mac;
70         gnutls_protocol_t version;
71 } tls_cipher_suite;
72 #endif
73
74 typedef struct tlsg_ctx {
75         struct ldapoptions *lo;
76         gnutls_certificate_credentials_t cred;
77         gnutls_dh_params_t dh_params;
78         unsigned long verify_depth;
79         int refcount;
80 #ifdef HAVE_CIPHERSUITES
81         gnutls_priority_t prios;
82 #else
83         int *kx_list;
84         int *cipher_list;
85         int *mac_list;
86 #endif
87 #ifdef LDAP_R_COMPILE
88         ldap_pvt_thread_mutex_t ref_mutex;
89 #endif
90 } tlsg_ctx;
91
92 typedef struct tlsg_session {
93         gnutls_session_t session;
94         tlsg_ctx *ctx;
95         struct berval peer_der_dn;
96 } tlsg_session;
97
98 #ifndef HAVE_CIPHERSUITES
99 static tls_cipher_suite *tlsg_ciphers;
100 static int tlsg_n_ciphers;
101 #endif
102
103 static int tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites );
104 static int tlsg_cert_verify( tlsg_session *s );
105
106 #ifdef LDAP_R_COMPILE
107
108 static int
109 tlsg_mutex_init( void **priv )
110 {
111         int err = 0;
112         ldap_pvt_thread_mutex_t *lock = LDAP_MALLOC( sizeof( ldap_pvt_thread_mutex_t ));
113
114         if ( !lock )
115                 err = ENOMEM;
116         if ( !err ) {
117                 err = ldap_pvt_thread_mutex_init( lock );
118                 if ( err )
119                         LDAP_FREE( lock );
120                 else
121                         *priv = lock;
122         }
123         return err;
124 }
125
126 static int
127 tlsg_mutex_destroy( void **lock )
128 {
129         int err = ldap_pvt_thread_mutex_destroy( *lock );
130         LDAP_FREE( *lock );
131         return err;
132 }
133
134 static int
135 tlsg_mutex_lock( void **lock )
136 {
137         return ldap_pvt_thread_mutex_lock( *lock );
138 }
139
140 static int
141 tlsg_mutex_unlock( void **lock )
142 {
143         return ldap_pvt_thread_mutex_unlock( *lock );
144 }
145
146 static struct gcry_thread_cbs tlsg_thread_cbs = {
147         GCRY_THREAD_OPTION_USER,
148         NULL,
149         tlsg_mutex_init,
150         tlsg_mutex_destroy,
151         tlsg_mutex_lock,
152         tlsg_mutex_unlock,
153         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
154 };
155
156 static void
157 tlsg_thr_init( void )
158 {
159         gcry_control (GCRYCTL_SET_THREAD_CBS, &tlsg_thread_cbs);
160 }
161 #endif /* LDAP_R_COMPILE */
162
163 /*
164  * Initialize TLS subsystem. Should be called only once.
165  */
166 static int
167 tlsg_init( void )
168 {
169 #ifdef HAVE_GCRYPT_RAND
170         struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
171         if ( lo->ldo_tls_randfile &&
172                 gcry_control( GCRYCTL_SET_RNDEGD_SOCKET, lo->ldo_tls_randfile )) {
173                 Debug( LDAP_DEBUG_ANY,
174                 "TLS: gcry_control GCRYCTL_SET_RNDEGD_SOCKET failed\n",
175                 0, 0, 0);
176                 return -1;
177         }
178 #endif
179
180         gnutls_global_init();
181
182 #ifndef HAVE_CIPHERSUITES
183         /* GNUtls cipher suite handling: The library ought to parse suite
184          * names for us, but it doesn't. It will return a list of suite names
185          * that it supports, so we can do parsing ourselves. It ought to tell
186          * us how long the list is, but it doesn't do that either, so we just
187          * have to count it manually...
188          */
189         {
190                 int i = 0;
191                 tls_cipher_suite *ptr, tmp;
192                 char cs_id[2];
193
194                 while ( gnutls_cipher_suite_info( i, cs_id, &tmp.kx, &tmp.cipher,
195                         &tmp.mac, &tmp.version ))
196                         i++;
197                 tlsg_n_ciphers = i;
198
199                 /* Store a copy */
200                 tlsg_ciphers = LDAP_MALLOC(tlsg_n_ciphers * sizeof(tls_cipher_suite));
201                 if ( !tlsg_ciphers )
202                         return -1;
203                 for ( i=0; i<tlsg_n_ciphers; i++ ) {
204                         tlsg_ciphers[i].name = gnutls_cipher_suite_info( i, cs_id,
205                                 &tlsg_ciphers[i].kx, &tlsg_ciphers[i].cipher, &tlsg_ciphers[i].mac,
206                                 &tlsg_ciphers[i].version );
207                 }
208         }
209 #endif
210         return 0;
211 }
212
213 /*
214  * Tear down the TLS subsystem. Should only be called once.
215  */
216 static void
217 tlsg_destroy( void )
218 {
219 #ifndef HAVE_CIPHERSUITES
220         LDAP_FREE( tlsg_ciphers );
221         tlsg_ciphers = NULL;
222         tlsg_n_ciphers = 0;
223 #endif
224         gnutls_global_deinit();
225 }
226
227 static tls_ctx *
228 tlsg_ctx_new ( struct ldapoptions *lo )
229 {
230         tlsg_ctx *ctx;
231
232         ctx = ber_memcalloc ( 1, sizeof (*ctx) );
233         if ( ctx ) {
234                 ctx->lo = lo;
235                 if ( gnutls_certificate_allocate_credentials( &ctx->cred )) {
236                         ber_memfree( ctx );
237                         return NULL;
238                 }
239                 ctx->refcount = 1;
240 #ifdef HAVE_CIPHERSUITES
241                 gnutls_priority_init( &ctx->prios, "NORMAL", NULL );
242 #endif
243 #ifdef LDAP_R_COMPILE
244                 ldap_pvt_thread_mutex_init( &ctx->ref_mutex );
245 #endif
246         }
247         return (tls_ctx *)ctx;
248 }
249
250 static void
251 tlsg_ctx_ref( tls_ctx *ctx )
252 {
253         tlsg_ctx *c = (tlsg_ctx *)ctx;
254         LDAP_MUTEX_LOCK( &c->ref_mutex );
255         c->refcount++;
256         LDAP_MUTEX_UNLOCK( &c->ref_mutex );
257 }
258
259 static void
260 tlsg_ctx_free ( tls_ctx *ctx )
261 {
262         tlsg_ctx *c = (tlsg_ctx *)ctx;
263         int refcount;
264
265         if ( !c ) return;
266
267         LDAP_MUTEX_LOCK( &c->ref_mutex );
268         refcount = --c->refcount;
269         LDAP_MUTEX_UNLOCK( &c->ref_mutex );
270         if ( refcount )
271                 return;
272 #ifdef HAVE_CIPHERSUITES
273         gnutls_priority_deinit( c->prios );
274 #else
275         LDAP_FREE( c->kx_list );
276 #endif
277         gnutls_certificate_free_credentials( c->cred );
278         if ( c->dh_params )
279                 gnutls_dh_params_deinit( c->dh_params );
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 #if GNUTLS_VERSION_NUMBER >= 0x020c00
372                         unsigned int i;
373                         for ( i = 1; i<VERIFY_DEPTH; i++ ) {
374                                 if ( gnutls_certificate_get_issuer( ctx->cred, certs[i-1], &certs[i], 0 ))
375                                         break;
376                                 max++;
377                                 /* If this CA is self-signed, we're done */
378                                 if ( gnutls_x509_crt_check_issuer( certs[i], certs[i] ))
379                                         break;
380                         }
381 #else
382                         gnutls_x509_crt_t *cas;
383                         unsigned int i, j, ncas;
384
385                         gnutls_certificate_get_x509_cas( ctx->cred, &cas, &ncas );
386                         for ( i = 1; i<VERIFY_DEPTH; i++ ) {
387                                 for ( j = 0; j<ncas; j++ ) {
388                                         if ( gnutls_x509_crt_check_issuer( certs[i-1], cas[j] )) {
389                                                 certs[i] = cas[j];
390                                                 max++;
391                                                 /* If this CA is self-signed, we're done */
392                                                 if ( gnutls_x509_crt_check_issuer( cas[j], cas[j] ))
393                                                         j = ncas;
394                                                 break;
395                                         }
396                                 }
397                                 /* only continue if we found a CA and it was not self-signed */
398                                 if ( j == ncas )
399                                         break;
400                         }
401 #endif
402                 }
403                 rc = gnutls_certificate_set_x509_key( ctx->cred, certs, max, key );
404                 if ( rc ) return -1;
405         } else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
406                 Debug( LDAP_DEBUG_ANY, 
407                        "TLS: only one of certfile and keyfile specified\n",
408                        NULL, NULL, NULL );
409                 return -1;
410         }
411
412         if ( lo->ldo_tls_crlfile ) {
413                 rc = gnutls_certificate_set_x509_crl_file( 
414                         ctx->cred,
415                         lt->lt_crlfile,
416                         GNUTLS_X509_FMT_PEM );
417                 if ( rc < 0 ) return -1;
418                 rc = 0;
419         }
420
421         /* FIXME: ITS#5992 - this should be configurable,
422          * and V1 CA certs should be phased out ASAP.
423          */
424         gnutls_certificate_set_verify_flags( ctx->cred,
425                 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT );
426
427         if ( is_server && lo->ldo_tls_dhfile ) {
428                 gnutls_datum_t buf;
429                 rc = tlsg_getfile( lo->ldo_tls_dhfile, &buf );
430                 if ( rc ) return -1;
431                 rc = gnutls_dh_params_init( &ctx->dh_params );
432                 if ( rc == 0 )
433                         rc = gnutls_dh_params_import_pkcs3( ctx->dh_params, &buf,
434                                 GNUTLS_X509_FMT_PEM );
435                 LDAP_FREE( buf.data );
436                 if ( rc ) return -1;
437                 gnutls_certificate_set_dh_params( ctx->cred, ctx->dh_params );
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_peek_tag( ber, &len );        /* Context + Constructed (version) */
548         if ( tag == 0xa0 ) {    /* Version is optional */
549                 tag = ber_skip_tag( ber, &len );
550                 tag = ber_get_int( ber, &i );   /* Int: Version */
551         }
552         tag = ber_skip_tag( ber, &len );        /* Int: Serial (can be longer than ber_int_t) */
553         ber_skip_data( ber, len );
554         tag = ber_skip_tag( ber, &len );        /* Sequence: Signature */
555         ber_skip_data( ber, len );
556         if ( !get_subject ) {
557                 tag = ber_peek_tag( ber, &len );        /* Sequence: Issuer DN */
558         } else {
559                 tag = ber_skip_tag( ber, &len );
560                 ber_skip_data( ber, len );
561                 tag = ber_skip_tag( ber, &len );        /* Sequence: Validity */
562                 ber_skip_data( ber, len );
563                 tag = ber_peek_tag( ber, &len );        /* Sequence: Subject DN */
564         }
565         len = ber_ptrlen( ber );
566         dn->bv_val = cert->bv_val + len;
567         dn->bv_len = cert->bv_len - len;
568 }
569
570 static int
571 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
572 {
573         tlsg_session *s = (tlsg_session *)session;
574         const gnutls_datum_t *x;
575         struct berval bv;
576
577         x = gnutls_certificate_get_ours( s->session );
578
579         if (!x) return LDAP_INVALID_CREDENTIALS;
580         
581         bv.bv_val = (char *) x->data;
582         bv.bv_len = x->size;
583
584         tlsg_x509_cert_dn( &bv, der_dn, 1 );
585         return 0;
586 }
587
588 static int
589 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
590 {
591         tlsg_session *s = (tlsg_session *)session;
592         if ( !s->peer_der_dn.bv_val ) {
593                 const gnutls_datum_t *peer_cert_list;
594                 unsigned int list_size;
595                 struct berval bv;
596
597                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
598                                                         &list_size );
599                 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
600
601                 bv.bv_len = peer_cert_list->size;
602                 bv.bv_val = (char *) peer_cert_list->data;
603
604                 tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
605         }
606         *der_dn = s->peer_der_dn;
607         return 0;
608 }
609
610 /* what kind of hostname were we given? */
611 #define IS_DNS  0
612 #define IS_IP4  1
613 #define IS_IP6  2
614
615 #define CN_OID  "2.5.4.3"
616
617 static int
618 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
619 {
620         tlsg_session *s = (tlsg_session *)session;
621         int i, ret;
622         const gnutls_datum_t *peer_cert_list;
623         unsigned int list_size;
624         char altname[NI_MAXHOST];
625         size_t altnamesize;
626
627         gnutls_x509_crt_t cert;
628         const char *name;
629         char *ptr;
630         char *domain = NULL;
631 #ifdef LDAP_PF_INET6
632         struct in6_addr addr;
633 #else
634         struct in_addr addr;
635 #endif
636         int len1 = 0, len2 = 0;
637         int ntype = IS_DNS;
638
639         if( ldap_int_hostname &&
640                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
641         {
642                 name = ldap_int_hostname;
643         } else {
644                 name = name_in;
645         }
646
647         peer_cert_list = gnutls_certificate_get_peers( s->session, 
648                                                 &list_size );
649         if ( !peer_cert_list ) {
650                 Debug( LDAP_DEBUG_ANY,
651                         "TLS: unable to get peer certificate.\n",
652                         0, 0, 0 );
653                 /* If this was a fatal condition, things would have
654                  * aborted long before now.
655                  */
656                 return LDAP_SUCCESS;
657         }
658         ret = gnutls_x509_crt_init( &cert );
659         if ( ret < 0 )
660                 return LDAP_LOCAL_ERROR;
661         ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
662         if ( ret ) {
663                 gnutls_x509_crt_deinit( cert );
664                 return LDAP_LOCAL_ERROR;
665         }
666
667 #ifdef LDAP_PF_INET6
668         if (inet_pton(AF_INET6, name, &addr)) {
669                 ntype = IS_IP6;
670         } else 
671 #endif
672         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
673                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
674         }
675         
676         if (ntype == IS_DNS) {
677                 len1 = strlen(name);
678                 domain = strchr(name, '.');
679                 if (domain) {
680                         len2 = len1 - (domain-name);
681                 }
682         }
683
684         for ( i=0, ret=0; ret >= 0; i++ ) {
685                 altnamesize = sizeof(altname);
686                 ret = gnutls_x509_crt_get_subject_alt_name( cert, i, 
687                         altname, &altnamesize, NULL );
688                 if ( ret < 0 ) break;
689
690                 /* ignore empty */
691                 if ( altnamesize == 0 ) continue;
692
693                 if ( ret == GNUTLS_SAN_DNSNAME ) {
694                         if (ntype != IS_DNS) continue;
695         
696                         /* Is this an exact match? */
697                         if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
698                                 break;
699                         }
700
701                         /* Is this a wildcard match? */
702                         if (domain && (altname[0] == '*') && (altname[1] == '.') &&
703                                 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
704                         {
705                                 break;
706                         }
707                 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
708                         if (ntype == IS_DNS) continue;
709
710 #ifdef LDAP_PF_INET6
711                         if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
712                                 continue;
713                         } else
714 #endif
715                         if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
716                                 continue;
717                         }
718                         if (!memcmp(altname, &addr, altnamesize)) {
719                                 break;
720                         }
721                 }
722         }
723         if ( ret >= 0 ) {
724                 ret = LDAP_SUCCESS;
725         } else {
726                 /* find the last CN */
727                 i=0;
728                 do {
729                         altnamesize = 0;
730                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
731                                 i, 1, altname, &altnamesize );
732                         if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
733                                 i++;
734                         else
735                                 break;
736                 } while ( 1 );
737
738                 if ( i ) {
739                         altnamesize = sizeof(altname);
740                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
741                                 i-1, 0, altname, &altnamesize );
742                 }
743
744                 if ( ret < 0 ) {
745                         Debug( LDAP_DEBUG_ANY,
746                                 "TLS: unable to get common name from peer certificate.\n",
747                                 0, 0, 0 );
748                         ret = LDAP_CONNECT_ERROR;
749                         if ( ld->ld_error ) {
750                                 LDAP_FREE( ld->ld_error );
751                         }
752                         ld->ld_error = LDAP_STRDUP(
753                                 _("TLS: unable to get CN from peer certificate"));
754
755                 } else {
756                         ret = LDAP_LOCAL_ERROR;
757                         if ( !len1 ) len1 = strlen( name );
758                         if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
759                                 ret = LDAP_SUCCESS;
760
761                         } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
762                                         /* Is this a wildcard match? */
763                                 if( domain &&
764                                         (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
765                                         ret = LDAP_SUCCESS;
766                                 }
767                         }
768                 }
769
770                 if( ret == LDAP_LOCAL_ERROR ) {
771                         altname[altnamesize] = '\0';
772                         Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
773                                 "common name in certificate (%s).\n", 
774                                 name, altname, 0 );
775                         ret = LDAP_CONNECT_ERROR;
776                         if ( ld->ld_error ) {
777                                 LDAP_FREE( ld->ld_error );
778                         }
779                         ld->ld_error = LDAP_STRDUP(
780                                 _("TLS: hostname does not match CN in peer certificate"));
781                 }
782         }
783         gnutls_x509_crt_deinit( cert );
784         return ret;
785 }
786
787 static int
788 tlsg_session_strength( tls_session *session )
789 {
790         tlsg_session *s = (tlsg_session *)session;
791         gnutls_cipher_algorithm_t c;
792
793         c = gnutls_cipher_get( s->session );
794         return gnutls_cipher_get_key_size( c ) * 8;
795 }
796
797 static int
798 tlsg_session_unique( tls_session *sess, struct berval *buf, int is_server)
799 {
800 /* channel bindings added in 2.12.0 */
801 #if GNUTLS_VERSION_NUMBER >= 0x020c00
802         tlsg_session *s = (tlsg_session *)sess;
803         gnutls_datum_t cb;
804         int rc;
805
806         rc = gnutls_session_channel_binding( s->session, GNUTLS_CB_TLS_UNIQUE, &cb );
807         if ( rc == 0 ) {
808                 int len = cb.size;
809                 if ( len > buf->bv_len )
810                         len = buf->bv_len;
811                 buf->bv_len = len;
812                 memcpy( buf->bv_val, cb.data, len );
813                 return len;
814         }
815 #endif
816         return 0;
817 }
818
819 static const char *
820 tlsg_session_version( tls_session *sess )
821 {
822         tlsg_session *s = (tlsg_session *)sess;
823         return gnutls_protocol_get_name(gnutls_protocol_get_version( s->session ));
824 }
825
826 static const char *
827 tlsg_session_cipher( tls_session *sess )
828 {
829         tlsg_session *s = (tlsg_session *)sess;
830         return gnutls_cipher_get_name(gnutls_cipher_get( s->session ));
831 }
832
833 static int
834 tlsg_session_peercert( tls_session *sess, struct berval *der )
835 {
836         tlsg_session *s = (tlsg_session *)sess;
837         const gnutls_datum_t *peer_cert_list;
838         unsigned int list_size;
839
840         peer_cert_list = gnutls_certificate_get_peers( s->session, &list_size );
841         if (!peer_cert_list)
842                 return -1;
843         der->bv_len = peer_cert_list[0].size;
844         der->bv_val = LDAP_MALLOC( der->bv_len );
845         if (!der->bv_val)
846                 return -1;
847         memcpy(der->bv_val, peer_cert_list[0].data, der->bv_len);
848         return 0;
849 }
850
851 /* suites is a string of colon-separated cipher suite names. */
852 static int
853 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
854 {
855 #ifdef HAVE_CIPHERSUITES
856         const char *err;
857         int rc = gnutls_priority_init( &ctx->prios, suites, &err );
858         if ( rc )
859                 ctx->prios = NULL;
860         return rc;
861 #else
862         char *ptr, *end;
863         int i, j, len, num;
864         int *list, nkx = 0, ncipher = 0, nmac = 0;
865         int *kx, *cipher, *mac;
866
867         num = 0;
868         ptr = suites;
869         do {
870                 end = strchr(ptr, ':');
871                 if ( end )
872                         len = end - ptr;
873                 else
874                         len = strlen(ptr);
875                 for (i=0; i<tlsg_n_ciphers; i++) {
876                         if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
877                                 num++;
878                                 break;
879                         }
880                 }
881                 if ( i == tlsg_n_ciphers ) {
882                         /* unrecognized cipher suite */
883                         return -1;
884                 }
885                 ptr += len + 1;
886         } while (end);
887
888         /* Space for all 3 lists */
889         list = LDAP_MALLOC( (num+1) * sizeof(int) * 3 );
890         if ( !list )
891                 return -1;
892         kx = list;
893         cipher = kx+num+1;
894         mac = cipher+num+1;
895
896         ptr = suites;
897         do {
898                 end = strchr(ptr, ':');
899                 if ( end )
900                         len = end - ptr;
901                 else
902                         len = strlen(ptr);
903                 for (i=0; i<tlsg_n_ciphers; i++) {
904                         /* For each cipher suite, insert its algorithms into
905                          * their respective priority lists. Make sure they
906                          * only appear once in each list.
907                          */
908                         if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
909                                 for (j=0; j<nkx; j++)
910                                         if ( kx[j] == tlsg_ciphers[i].kx )
911                                                 break;
912                                 if ( j == nkx )
913                                         kx[nkx++] = tlsg_ciphers[i].kx;
914                                 for (j=0; j<ncipher; j++)
915                                         if ( cipher[j] == tlsg_ciphers[i].cipher )
916                                                 break;
917                                 if ( j == ncipher ) 
918                                         cipher[ncipher++] = tlsg_ciphers[i].cipher;
919                                 for (j=0; j<nmac; j++)
920                                         if ( mac[j] == tlsg_ciphers[i].mac )
921                                                 break;
922                                 if ( j == nmac )
923                                         mac[nmac++] = tlsg_ciphers[i].mac;
924                                 break;
925                         }
926                 }
927                 ptr += len + 1;
928         } while (end);
929         kx[nkx] = 0;
930         cipher[ncipher] = 0;
931         mac[nmac] = 0;
932         ctx->kx_list = kx;
933         ctx->cipher_list = cipher;
934         ctx->mac_list = mac;
935         return 0;
936 #endif
937 }
938
939 /*
940  * TLS support for LBER Sockbufs
941  */
942
943 struct tls_data {
944         tlsg_session            *session;
945         Sockbuf_IO_Desc         *sbiod;
946 };
947
948 static ssize_t
949 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
950 {
951         struct tls_data         *p;
952
953         if ( buf == NULL || len <= 0 ) return 0;
954
955         p = (struct tls_data *)ptr;
956
957         if ( p == NULL || p->sbiod == NULL ) {
958                 return 0;
959         }
960
961         return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
962 }
963
964 static ssize_t
965 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
966 {
967         struct tls_data         *p;
968         
969         if ( buf == NULL || len <= 0 ) return 0;
970         
971         p = (struct tls_data *)ptr;
972
973         if ( p == NULL || p->sbiod == NULL ) {
974                 return 0;
975         }
976
977         return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
978 }
979
980 static int
981 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
982 {
983         struct tls_data         *p;
984         tlsg_session    *session = arg;
985
986         assert( sbiod != NULL );
987
988         p = LBER_MALLOC( sizeof( *p ) );
989         if ( p == NULL ) {
990                 return -1;
991         }
992         
993         gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
994         gnutls_transport_set_pull_function( session->session, tlsg_recv );
995         gnutls_transport_set_push_function( session->session, tlsg_send );
996         p->session = session;
997         p->sbiod = sbiod;
998         sbiod->sbiod_pvt = p;
999         return 0;
1000 }
1001
1002 static int
1003 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
1004 {
1005         struct tls_data         *p;
1006         
1007         assert( sbiod != NULL );
1008         assert( sbiod->sbiod_pvt != NULL );
1009
1010         p = (struct tls_data *)sbiod->sbiod_pvt;
1011         gnutls_deinit ( p->session->session );
1012         LBER_FREE( p->session );
1013         LBER_FREE( sbiod->sbiod_pvt );
1014         sbiod->sbiod_pvt = NULL;
1015         return 0;
1016 }
1017
1018 static int
1019 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
1020 {
1021         struct tls_data         *p;
1022         
1023         assert( sbiod != NULL );
1024         assert( sbiod->sbiod_pvt != NULL );
1025
1026         p = (struct tls_data *)sbiod->sbiod_pvt;
1027         gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
1028         return 0;
1029 }
1030
1031 static int
1032 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
1033 {
1034         struct tls_data         *p;
1035         
1036         assert( sbiod != NULL );
1037         assert( sbiod->sbiod_pvt != NULL );
1038
1039         p = (struct tls_data *)sbiod->sbiod_pvt;
1040         
1041         if ( opt == LBER_SB_OPT_GET_SSL ) {
1042                 *((tlsg_session **)arg) = p->session;
1043                 return 1;
1044                 
1045         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
1046                 if( gnutls_record_check_pending( p->session->session ) > 0 ) {
1047                         return 1;
1048                 }
1049         }
1050         
1051         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
1052 }
1053
1054 static ber_slen_t
1055 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1056 {
1057         struct tls_data         *p;
1058         ber_slen_t              ret;
1059
1060         assert( sbiod != NULL );
1061         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1062
1063         p = (struct tls_data *)sbiod->sbiod_pvt;
1064
1065         ret = gnutls_record_recv ( p->session->session, buf, len );
1066         switch (ret) {
1067         case GNUTLS_E_INTERRUPTED:
1068         case GNUTLS_E_AGAIN:
1069                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1070                 sock_errset(EWOULDBLOCK);
1071                 ret = 0;
1072                 break;
1073         case GNUTLS_E_REHANDSHAKE:
1074                 for ( ret = gnutls_handshake ( p->session->session );
1075                       ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
1076                       ret = gnutls_handshake ( p->session->session ) );
1077                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1078                 ret = 0;
1079                 break;
1080         default:
1081                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1082         }
1083         return ret;
1084 }
1085
1086 static ber_slen_t
1087 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1088 {
1089         struct tls_data         *p;
1090         ber_slen_t              ret;
1091
1092         assert( sbiod != NULL );
1093         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1094
1095         p = (struct tls_data *)sbiod->sbiod_pvt;
1096
1097         ret = gnutls_record_send ( p->session->session, (char *)buf, len );
1098
1099         if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
1100                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1101                 sock_errset(EWOULDBLOCK);
1102                 ret = 0;
1103         } else {
1104                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1105         }
1106         return ret;
1107 }
1108
1109 static Sockbuf_IO tlsg_sbio =
1110 {
1111         tlsg_sb_setup,          /* sbi_setup */
1112         tlsg_sb_remove,         /* sbi_remove */
1113         tlsg_sb_ctrl,           /* sbi_ctrl */
1114         tlsg_sb_read,           /* sbi_read */
1115         tlsg_sb_write,          /* sbi_write */
1116         tlsg_sb_close           /* sbi_close */
1117 };
1118
1119 /* Certs are not automatically varified during the handshake */
1120 static int
1121 tlsg_cert_verify( tlsg_session *ssl )
1122 {
1123         unsigned int status = 0;
1124         int err;
1125         time_t now = time(0);
1126         time_t peertime;
1127
1128         err = gnutls_certificate_verify_peers2( ssl->session, &status );
1129         if ( err < 0 ) {
1130                 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
1131                         err,0,0 );
1132                 return -1;
1133         }
1134         if ( status ) {
1135                 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
1136                         status, 0,0 );
1137                 return -1;
1138         }
1139         peertime = gnutls_certificate_expiration_time_peers( ssl->session );
1140         if ( peertime == (time_t) -1 ) {
1141                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
1142                         0, 0, 0 );
1143                 return -1;
1144         }
1145         if ( peertime < now ) {
1146                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
1147                         0, 0, 0 );
1148                 return -1;
1149         }
1150         peertime = gnutls_certificate_activation_time_peers( ssl->session );
1151         if ( peertime == (time_t) -1 ) {
1152                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
1153                         0, 0, 0 );
1154                 return -1;
1155         }
1156         if ( peertime > now ) {
1157                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
1158                         0, 0, 0 );
1159                 return -1;
1160         }
1161         return 0;
1162 }
1163
1164 tls_impl ldap_int_tls_impl = {
1165         "GnuTLS",
1166
1167         tlsg_init,
1168         tlsg_destroy,
1169
1170         tlsg_ctx_new,
1171         tlsg_ctx_ref,
1172         tlsg_ctx_free,
1173         tlsg_ctx_init,
1174
1175         tlsg_session_new,
1176         tlsg_session_connect,
1177         tlsg_session_accept,
1178         tlsg_session_upflags,
1179         tlsg_session_errmsg,
1180         tlsg_session_my_dn,
1181         tlsg_session_peer_dn,
1182         tlsg_session_chkhost,
1183         tlsg_session_strength,
1184         tlsg_session_unique,
1185         tlsg_session_version,
1186         tlsg_session_cipher,
1187         tlsg_session_peercert,
1188
1189         &tlsg_sbio,
1190
1191 #ifdef LDAP_R_COMPILE
1192         tlsg_thr_init,
1193 #else
1194         NULL,
1195 #endif
1196
1197         0
1198 };
1199
1200 #endif /* HAVE_GNUTLS */