]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_g.c
ITS#7430 GnuTLS: Avoid use of deprecated function
[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-2014 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 #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_dhfile ) {
413                 Debug( LDAP_DEBUG_ANY, 
414                        "TLS: warning: ignoring dhfile\n", 
415                        NULL, NULL, NULL );
416         }
417
418         if ( lo->ldo_tls_crlfile ) {
419                 rc = gnutls_certificate_set_x509_crl_file( 
420                         ctx->cred,
421                         lt->lt_crlfile,
422                         GNUTLS_X509_FMT_PEM );
423                 if ( rc < 0 ) return -1;
424                 rc = 0;
425         }
426
427         /* FIXME: ITS#5992 - this should go be configurable,
428          * and V1 CA certs should be phased out ASAP.
429          */
430         gnutls_certificate_set_verify_flags( ctx->cred,
431                 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT );
432
433         if ( is_server ) {
434                 gnutls_dh_params_init(&ctx->dh_params);
435                 gnutls_dh_params_generate2(ctx->dh_params, DH_BITS);
436         }
437         return 0;
438 }
439
440 static tls_session *
441 tlsg_session_new ( tls_ctx * ctx, int is_server )
442 {
443         tlsg_ctx *c = (tlsg_ctx *)ctx;
444         tlsg_session *session;
445
446         session = ber_memcalloc ( 1, sizeof (*session) );
447         if ( !session )
448                 return NULL;
449
450         session->ctx = c;
451         gnutls_init( &session->session, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT );
452 #ifdef HAVE_CIPHERSUITES
453         gnutls_priority_set( session->session, c->prios );
454 #else
455         gnutls_set_default_priority( session->session );
456         if ( c->kx_list ) {
457                 gnutls_kx_set_priority( session->session, c->kx_list );
458                 gnutls_cipher_set_priority( session->session, c->cipher_list );
459                 gnutls_mac_set_priority( session->session, c->mac_list );
460         }
461 #endif
462         if ( c->cred )
463                 gnutls_credentials_set( session->session, GNUTLS_CRD_CERTIFICATE, c->cred );
464         
465         if ( is_server ) {
466                 int flag = 0;
467                 if ( c->lo->ldo_tls_require_cert ) {
468                         flag = GNUTLS_CERT_REQUEST;
469                         if ( c->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
470                                 c->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD )
471                                 flag = GNUTLS_CERT_REQUIRE;
472                         gnutls_certificate_server_set_request( session->session, flag );
473                 }
474         }
475         return (tls_session *)session;
476
477
478 static int
479 tlsg_session_accept( tls_session *session )
480 {
481         tlsg_session *s = (tlsg_session *)session;
482         int rc;
483
484         rc = gnutls_handshake( s->session );
485         if ( rc == 0 && s->ctx->lo->ldo_tls_require_cert != LDAP_OPT_X_TLS_NEVER ) {
486                 const gnutls_datum_t *peer_cert_list;
487                 unsigned int list_size;
488
489                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
490                                                 &list_size );
491                 if ( !peer_cert_list && s->ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_TRY ) 
492                         rc = 0;
493                 else {
494                         rc = tlsg_cert_verify( s );
495                         if ( rc && s->ctx->lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW )
496                                 rc = 0;
497                 }
498         }
499         return rc;
500 }
501
502 static int
503 tlsg_session_connect( LDAP *ld, tls_session *session )
504 {
505         return tlsg_session_accept( session);
506 }
507
508 static int
509 tlsg_session_upflags( Sockbuf *sb, tls_session *session, int rc )
510 {
511         tlsg_session *s = (tlsg_session *)session;
512
513         if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
514                 return 0;
515
516         switch (gnutls_record_get_direction (s->session)) {
517         case 0: 
518                 sb->sb_trans_needs_read = 1;
519                 return 1;
520         case 1:
521                 sb->sb_trans_needs_write = 1;
522                 return 1;
523         }
524         return 0;
525 }
526
527 static char *
528 tlsg_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
529 {
530         return (char *)gnutls_strerror( rc );
531 }
532
533 static void
534 tlsg_x509_cert_dn( struct berval *cert, struct berval *dn, int get_subject )
535 {
536         BerElementBuffer berbuf;
537         BerElement *ber = (BerElement *)&berbuf;
538         ber_tag_t tag;
539         ber_len_t len;
540         ber_int_t i;
541
542         ber_init2( ber, cert, LBER_USE_DER );
543         tag = ber_skip_tag( ber, &len );        /* Sequence */
544         tag = ber_skip_tag( ber, &len );        /* Sequence */
545         tag = ber_peek_tag( ber, &len );        /* Context + Constructed (version) */
546         if ( tag == 0xa0 ) {    /* Version is optional */
547                 tag = ber_skip_tag( ber, &len );
548                 tag = ber_get_int( ber, &i );   /* Int: Version */
549         }
550         tag = ber_skip_tag( ber, &len );        /* Int: Serial (can be longer than ber_int_t) */
551         ber_skip_data( ber, len );
552         tag = ber_skip_tag( ber, &len );        /* Sequence: Signature */
553         ber_skip_data( ber, len );
554         if ( !get_subject ) {
555                 tag = ber_peek_tag( ber, &len );        /* Sequence: Issuer DN */
556         } else {
557                 tag = ber_skip_tag( ber, &len );
558                 ber_skip_data( ber, len );
559                 tag = ber_skip_tag( ber, &len );        /* Sequence: Validity */
560                 ber_skip_data( ber, len );
561                 tag = ber_peek_tag( ber, &len );        /* Sequence: Subject DN */
562         }
563         len = ber_ptrlen( ber );
564         dn->bv_val = cert->bv_val + len;
565         dn->bv_len = cert->bv_len - len;
566 }
567
568 static int
569 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
570 {
571         tlsg_session *s = (tlsg_session *)session;
572         const gnutls_datum_t *x;
573         struct berval bv;
574
575         x = gnutls_certificate_get_ours( s->session );
576
577         if (!x) return LDAP_INVALID_CREDENTIALS;
578         
579         bv.bv_val = (char *) x->data;
580         bv.bv_len = x->size;
581
582         tlsg_x509_cert_dn( &bv, der_dn, 1 );
583         return 0;
584 }
585
586 static int
587 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
588 {
589         tlsg_session *s = (tlsg_session *)session;
590         if ( !s->peer_der_dn.bv_val ) {
591                 const gnutls_datum_t *peer_cert_list;
592                 unsigned int list_size;
593                 struct berval bv;
594
595                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
596                                                         &list_size );
597                 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
598
599                 bv.bv_len = peer_cert_list->size;
600                 bv.bv_val = (char *) peer_cert_list->data;
601
602                 tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
603         }
604         *der_dn = s->peer_der_dn;
605         return 0;
606 }
607
608 /* what kind of hostname were we given? */
609 #define IS_DNS  0
610 #define IS_IP4  1
611 #define IS_IP6  2
612
613 #define CN_OID  "2.5.4.3"
614
615 static int
616 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
617 {
618         tlsg_session *s = (tlsg_session *)session;
619         int i, ret;
620         const gnutls_datum_t *peer_cert_list;
621         unsigned int list_size;
622         char altname[NI_MAXHOST];
623         size_t altnamesize;
624
625         gnutls_x509_crt_t cert;
626         const char *name;
627         char *ptr;
628         char *domain = NULL;
629 #ifdef LDAP_PF_INET6
630         struct in6_addr addr;
631 #else
632         struct in_addr addr;
633 #endif
634         int len1 = 0, len2 = 0;
635         int ntype = IS_DNS;
636
637         if( ldap_int_hostname &&
638                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
639         {
640                 name = ldap_int_hostname;
641         } else {
642                 name = name_in;
643         }
644
645         peer_cert_list = gnutls_certificate_get_peers( s->session, 
646                                                 &list_size );
647         if ( !peer_cert_list ) {
648                 Debug( LDAP_DEBUG_ANY,
649                         "TLS: unable to get peer certificate.\n",
650                         0, 0, 0 );
651                 /* If this was a fatal condition, things would have
652                  * aborted long before now.
653                  */
654                 return LDAP_SUCCESS;
655         }
656         ret = gnutls_x509_crt_init( &cert );
657         if ( ret < 0 )
658                 return LDAP_LOCAL_ERROR;
659         ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
660         if ( ret ) {
661                 gnutls_x509_crt_deinit( cert );
662                 return LDAP_LOCAL_ERROR;
663         }
664
665 #ifdef LDAP_PF_INET6
666         if (inet_pton(AF_INET6, name, &addr)) {
667                 ntype = IS_IP6;
668         } else 
669 #endif
670         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
671                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
672         }
673         
674         if (ntype == IS_DNS) {
675                 len1 = strlen(name);
676                 domain = strchr(name, '.');
677                 if (domain) {
678                         len2 = len1 - (domain-name);
679                 }
680         }
681
682         for ( i=0, ret=0; ret >= 0; i++ ) {
683                 altnamesize = sizeof(altname);
684                 ret = gnutls_x509_crt_get_subject_alt_name( cert, i, 
685                         altname, &altnamesize, NULL );
686                 if ( ret < 0 ) break;
687
688                 /* ignore empty */
689                 if ( altnamesize == 0 ) continue;
690
691                 if ( ret == GNUTLS_SAN_DNSNAME ) {
692                         if (ntype != IS_DNS) continue;
693         
694                         /* Is this an exact match? */
695                         if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
696                                 break;
697                         }
698
699                         /* Is this a wildcard match? */
700                         if (domain && (altname[0] == '*') && (altname[1] == '.') &&
701                                 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
702                         {
703                                 break;
704                         }
705                 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
706                         if (ntype == IS_DNS) continue;
707
708 #ifdef LDAP_PF_INET6
709                         if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
710                                 continue;
711                         } else
712 #endif
713                         if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
714                                 continue;
715                         }
716                         if (!memcmp(altname, &addr, altnamesize)) {
717                                 break;
718                         }
719                 }
720         }
721         if ( ret >= 0 ) {
722                 ret = LDAP_SUCCESS;
723         } else {
724                 /* find the last CN */
725                 i=0;
726                 do {
727                         altnamesize = 0;
728                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
729                                 i, 1, altname, &altnamesize );
730                         if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
731                                 i++;
732                         else
733                                 break;
734                 } while ( 1 );
735
736                 if ( i ) {
737                         altnamesize = sizeof(altname);
738                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
739                                 i-1, 0, altname, &altnamesize );
740                 }
741
742                 if ( ret < 0 ) {
743                         Debug( LDAP_DEBUG_ANY,
744                                 "TLS: unable to get common name from peer certificate.\n",
745                                 0, 0, 0 );
746                         ret = LDAP_CONNECT_ERROR;
747                         if ( ld->ld_error ) {
748                                 LDAP_FREE( ld->ld_error );
749                         }
750                         ld->ld_error = LDAP_STRDUP(
751                                 _("TLS: unable to get CN from peer certificate"));
752
753                 } else {
754                         ret = LDAP_LOCAL_ERROR;
755                         if ( !len1 ) len1 = strlen( name );
756                         if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
757                                 ret = LDAP_SUCCESS;
758
759                         } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
760                                         /* Is this a wildcard match? */
761                                 if( domain &&
762                                         (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
763                                         ret = LDAP_SUCCESS;
764                                 }
765                         }
766                 }
767
768                 if( ret == LDAP_LOCAL_ERROR ) {
769                         altname[altnamesize] = '\0';
770                         Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
771                                 "common name in certificate (%s).\n", 
772                                 name, altname, 0 );
773                         ret = LDAP_CONNECT_ERROR;
774                         if ( ld->ld_error ) {
775                                 LDAP_FREE( ld->ld_error );
776                         }
777                         ld->ld_error = LDAP_STRDUP(
778                                 _("TLS: hostname does not match CN in peer certificate"));
779                 }
780         }
781         gnutls_x509_crt_deinit( cert );
782         return ret;
783 }
784
785 static int
786 tlsg_session_strength( tls_session *session )
787 {
788         tlsg_session *s = (tlsg_session *)session;
789         gnutls_cipher_algorithm_t c;
790
791         c = gnutls_cipher_get( s->session );
792         return gnutls_cipher_get_key_size( c ) * 8;
793 }
794
795 /* suites is a string of colon-separated cipher suite names. */
796 static int
797 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
798 {
799 #ifdef HAVE_CIPHERSUITES
800         const char *err;
801         int rc = gnutls_priority_init( &ctx->prios, suites, &err );
802         if ( rc )
803                 ctx->prios = NULL;
804         return rc;
805 #else
806         char *ptr, *end;
807         int i, j, len, num;
808         int *list, nkx = 0, ncipher = 0, nmac = 0;
809         int *kx, *cipher, *mac;
810
811         num = 0;
812         ptr = suites;
813         do {
814                 end = strchr(ptr, ':');
815                 if ( end )
816                         len = end - ptr;
817                 else
818                         len = strlen(ptr);
819                 for (i=0; i<tlsg_n_ciphers; i++) {
820                         if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
821                                 num++;
822                                 break;
823                         }
824                 }
825                 if ( i == tlsg_n_ciphers ) {
826                         /* unrecognized cipher suite */
827                         return -1;
828                 }
829                 ptr += len + 1;
830         } while (end);
831
832         /* Space for all 3 lists */
833         list = LDAP_MALLOC( (num+1) * sizeof(int) * 3 );
834         if ( !list )
835                 return -1;
836         kx = list;
837         cipher = kx+num+1;
838         mac = cipher+num+1;
839
840         ptr = suites;
841         do {
842                 end = strchr(ptr, ':');
843                 if ( end )
844                         len = end - ptr;
845                 else
846                         len = strlen(ptr);
847                 for (i=0; i<tlsg_n_ciphers; i++) {
848                         /* For each cipher suite, insert its algorithms into
849                          * their respective priority lists. Make sure they
850                          * only appear once in each list.
851                          */
852                         if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
853                                 for (j=0; j<nkx; j++)
854                                         if ( kx[j] == tlsg_ciphers[i].kx )
855                                                 break;
856                                 if ( j == nkx )
857                                         kx[nkx++] = tlsg_ciphers[i].kx;
858                                 for (j=0; j<ncipher; j++)
859                                         if ( cipher[j] == tlsg_ciphers[i].cipher )
860                                                 break;
861                                 if ( j == ncipher ) 
862                                         cipher[ncipher++] = tlsg_ciphers[i].cipher;
863                                 for (j=0; j<nmac; j++)
864                                         if ( mac[j] == tlsg_ciphers[i].mac )
865                                                 break;
866                                 if ( j == nmac )
867                                         mac[nmac++] = tlsg_ciphers[i].mac;
868                                 break;
869                         }
870                 }
871                 ptr += len + 1;
872         } while (end);
873         kx[nkx] = 0;
874         cipher[ncipher] = 0;
875         mac[nmac] = 0;
876         ctx->kx_list = kx;
877         ctx->cipher_list = cipher;
878         ctx->mac_list = mac;
879         return 0;
880 #endif
881 }
882
883 /*
884  * TLS support for LBER Sockbufs
885  */
886
887 struct tls_data {
888         tlsg_session            *session;
889         Sockbuf_IO_Desc         *sbiod;
890 };
891
892 static ssize_t
893 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
894 {
895         struct tls_data         *p;
896
897         if ( buf == NULL || len <= 0 ) return 0;
898
899         p = (struct tls_data *)ptr;
900
901         if ( p == NULL || p->sbiod == NULL ) {
902                 return 0;
903         }
904
905         return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
906 }
907
908 static ssize_t
909 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
910 {
911         struct tls_data         *p;
912         
913         if ( buf == NULL || len <= 0 ) return 0;
914         
915         p = (struct tls_data *)ptr;
916
917         if ( p == NULL || p->sbiod == NULL ) {
918                 return 0;
919         }
920
921         return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
922 }
923
924 static int
925 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
926 {
927         struct tls_data         *p;
928         tlsg_session    *session = arg;
929
930         assert( sbiod != NULL );
931
932         p = LBER_MALLOC( sizeof( *p ) );
933         if ( p == NULL ) {
934                 return -1;
935         }
936         
937         gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
938         gnutls_transport_set_pull_function( session->session, tlsg_recv );
939         gnutls_transport_set_push_function( session->session, tlsg_send );
940         p->session = session;
941         p->sbiod = sbiod;
942         sbiod->sbiod_pvt = p;
943         return 0;
944 }
945
946 static int
947 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
948 {
949         struct tls_data         *p;
950         
951         assert( sbiod != NULL );
952         assert( sbiod->sbiod_pvt != NULL );
953
954         p = (struct tls_data *)sbiod->sbiod_pvt;
955         gnutls_deinit ( p->session->session );
956         LBER_FREE( p->session );
957         LBER_FREE( sbiod->sbiod_pvt );
958         sbiod->sbiod_pvt = NULL;
959         return 0;
960 }
961
962 static int
963 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
964 {
965         struct tls_data         *p;
966         
967         assert( sbiod != NULL );
968         assert( sbiod->sbiod_pvt != NULL );
969
970         p = (struct tls_data *)sbiod->sbiod_pvt;
971         gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
972         return 0;
973 }
974
975 static int
976 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
977 {
978         struct tls_data         *p;
979         
980         assert( sbiod != NULL );
981         assert( sbiod->sbiod_pvt != NULL );
982
983         p = (struct tls_data *)sbiod->sbiod_pvt;
984         
985         if ( opt == LBER_SB_OPT_GET_SSL ) {
986                 *((tlsg_session **)arg) = p->session;
987                 return 1;
988                 
989         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
990                 if( gnutls_record_check_pending( p->session->session ) > 0 ) {
991                         return 1;
992                 }
993         }
994         
995         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
996 }
997
998 static ber_slen_t
999 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1000 {
1001         struct tls_data         *p;
1002         ber_slen_t              ret;
1003
1004         assert( sbiod != NULL );
1005         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1006
1007         p = (struct tls_data *)sbiod->sbiod_pvt;
1008
1009         ret = gnutls_record_recv ( p->session->session, buf, len );
1010         switch (ret) {
1011         case GNUTLS_E_INTERRUPTED:
1012         case GNUTLS_E_AGAIN:
1013                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1014                 sock_errset(EWOULDBLOCK);
1015                 ret = 0;
1016                 break;
1017         case GNUTLS_E_REHANDSHAKE:
1018                 for ( ret = gnutls_handshake ( p->session->session );
1019                       ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
1020                       ret = gnutls_handshake ( p->session->session ) );
1021                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1022                 ret = 0;
1023                 break;
1024         default:
1025                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1026         }
1027         return ret;
1028 }
1029
1030 static ber_slen_t
1031 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1032 {
1033         struct tls_data         *p;
1034         ber_slen_t              ret;
1035
1036         assert( sbiod != NULL );
1037         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1038
1039         p = (struct tls_data *)sbiod->sbiod_pvt;
1040
1041         ret = gnutls_record_send ( p->session->session, (char *)buf, len );
1042
1043         if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
1044                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1045                 sock_errset(EWOULDBLOCK);
1046                 ret = 0;
1047         } else {
1048                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1049         }
1050         return ret;
1051 }
1052
1053 static Sockbuf_IO tlsg_sbio =
1054 {
1055         tlsg_sb_setup,          /* sbi_setup */
1056         tlsg_sb_remove,         /* sbi_remove */
1057         tlsg_sb_ctrl,           /* sbi_ctrl */
1058         tlsg_sb_read,           /* sbi_read */
1059         tlsg_sb_write,          /* sbi_write */
1060         tlsg_sb_close           /* sbi_close */
1061 };
1062
1063 /* Certs are not automatically varified during the handshake */
1064 static int
1065 tlsg_cert_verify( tlsg_session *ssl )
1066 {
1067         unsigned int status = 0;
1068         int err;
1069         time_t now = time(0);
1070         time_t peertime;
1071
1072         err = gnutls_certificate_verify_peers2( ssl->session, &status );
1073         if ( err < 0 ) {
1074                 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
1075                         err,0,0 );
1076                 return -1;
1077         }
1078         if ( status ) {
1079                 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
1080                         status, 0,0 );
1081                 return -1;
1082         }
1083         peertime = gnutls_certificate_expiration_time_peers( ssl->session );
1084         if ( peertime == (time_t) -1 ) {
1085                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
1086                         0, 0, 0 );
1087                 return -1;
1088         }
1089         if ( peertime < now ) {
1090                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
1091                         0, 0, 0 );
1092                 return -1;
1093         }
1094         peertime = gnutls_certificate_activation_time_peers( ssl->session );
1095         if ( peertime == (time_t) -1 ) {
1096                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
1097                         0, 0, 0 );
1098                 return -1;
1099         }
1100         if ( peertime > now ) {
1101                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
1102                         0, 0, 0 );
1103                 return -1;
1104         }
1105         return 0;
1106 }
1107
1108 tls_impl ldap_int_tls_impl = {
1109         "GnuTLS",
1110
1111         tlsg_init,
1112         tlsg_destroy,
1113
1114         tlsg_ctx_new,
1115         tlsg_ctx_ref,
1116         tlsg_ctx_free,
1117         tlsg_ctx_init,
1118
1119         tlsg_session_new,
1120         tlsg_session_connect,
1121         tlsg_session_accept,
1122         tlsg_session_upflags,
1123         tlsg_session_errmsg,
1124         tlsg_session_my_dn,
1125         tlsg_session_peer_dn,
1126         tlsg_session_chkhost,
1127         tlsg_session_strength,
1128
1129         &tlsg_sbio,
1130
1131 #ifdef LDAP_R_COMPILE
1132         tlsg_thr_init,
1133 #else
1134         NULL,
1135 #endif
1136
1137         0
1138 };
1139
1140 #endif /* HAVE_GNUTLS */