]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_g.c
2118d1d4de693469412f46dc6a46e250fc5ff113
[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-2011 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  * Matt 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 #ifdef LDAP_R_COMPILE
45 #include <ldap_pvt_thread.h>
46 #endif
47
48 #include <gnutls/gnutls.h>
49 #include <gnutls/x509.h>
50 #include <gcrypt.h>
51
52 #define DH_BITS (1024)
53
54 #if LIBGNUTLS_VERSION_NUMBER >= 0x020200
55 #define HAVE_CIPHERSUITES       1
56 /* This is a kludge. gcrypt 1.4.x has support. Recent GnuTLS requires gcrypt 1.4.x
57  * but that dependency isn't reflected in their configure script, resulting in
58  * build errors on older gcrypt. So, if they have a working build environment,
59  * assume gcrypt is new enough.
60  */
61 #define HAVE_GCRYPT_RAND        1
62 #else
63 #undef HAVE_CIPHERSUITES
64 #undef HAVE_GCRYPT_RAND
65 #endif
66
67 #ifndef HAVE_CIPHERSUITES
68 /* Versions prior to 2.2.0 didn't handle cipher suites, so we had to
69  * kludge them ourselves.
70  */
71 typedef struct tls_cipher_suite {
72         const char *name;
73         gnutls_kx_algorithm_t kx;
74         gnutls_cipher_algorithm_t cipher;
75         gnutls_mac_algorithm_t mac;
76         gnutls_protocol_t version;
77 } tls_cipher_suite;
78 #endif
79
80 typedef struct tlsg_ctx {
81         struct ldapoptions *lo;
82         gnutls_certificate_credentials_t cred;
83         gnutls_dh_params_t dh_params;
84         unsigned long verify_depth;
85         int refcount;
86 #ifdef HAVE_CIPHERSUITES
87         gnutls_priority_t prios;
88 #else
89         int *kx_list;
90         int *cipher_list;
91         int *mac_list;
92 #endif
93 #ifdef LDAP_R_COMPILE
94         ldap_pvt_thread_mutex_t ref_mutex;
95 #endif
96 } tlsg_ctx;
97
98 typedef struct tlsg_session {
99         gnutls_session_t session;
100         tlsg_ctx *ctx;
101         struct berval peer_der_dn;
102 } tlsg_session;
103
104 #ifndef HAVE_CIPHERSUITES
105 static tls_cipher_suite *tlsg_ciphers;
106 static int tlsg_n_ciphers;
107 #endif
108
109 static int tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites );
110 static int tlsg_cert_verify( tlsg_session *s );
111
112 #ifdef LDAP_R_COMPILE
113
114 static int
115 tlsg_mutex_init( void **priv )
116 {
117         int err = 0;
118         ldap_pvt_thread_mutex_t *lock = LDAP_MALLOC( sizeof( ldap_pvt_thread_mutex_t ));
119
120         if ( !lock )
121                 err = ENOMEM;
122         if ( !err ) {
123                 err = ldap_pvt_thread_mutex_init( lock );
124                 if ( err )
125                         LDAP_FREE( lock );
126                 else
127                         *priv = lock;
128         }
129         return err;
130 }
131
132 static int
133 tlsg_mutex_destroy( void **lock )
134 {
135         int err = ldap_pvt_thread_mutex_destroy( *lock );
136         LDAP_FREE( *lock );
137         return err;
138 }
139
140 static int
141 tlsg_mutex_lock( void **lock )
142 {
143         return ldap_pvt_thread_mutex_lock( *lock );
144 }
145
146 static int
147 tlsg_mutex_unlock( void **lock )
148 {
149         return ldap_pvt_thread_mutex_unlock( *lock );
150 }
151
152 static struct gcry_thread_cbs tlsg_thread_cbs = {
153         GCRY_THREAD_OPTION_USER,
154         NULL,
155         tlsg_mutex_init,
156         tlsg_mutex_destroy,
157         tlsg_mutex_lock,
158         tlsg_mutex_unlock,
159         NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
160 };
161
162 static void
163 tlsg_thr_init( void )
164 {
165         gcry_control (GCRYCTL_SET_THREAD_CBS, &tlsg_thread_cbs);
166 }
167 #endif /* LDAP_R_COMPILE */
168
169 /*
170  * Initialize TLS subsystem. Should be called only once.
171  */
172 static int
173 tlsg_init( void )
174 {
175 #ifdef HAVE_GCRYPT_RAND
176         struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
177         if ( lo->ldo_tls_randfile &&
178                 gcry_control( GCRYCTL_SET_RNDEGD_SOCKET, lo->ldo_tls_randfile )) {
179                 Debug( LDAP_DEBUG_ANY,
180                 "TLS: gcry_control GCRYCTL_SET_RNDEGD_SOCKET failed\n",
181                 0, 0, 0);
182                 return -1;
183         }
184 #endif
185
186         gnutls_global_init();
187
188 #ifndef HAVE_CIPHERSUITES
189         /* GNUtls cipher suite handling: The library ought to parse suite
190          * names for us, but it doesn't. It will return a list of suite names
191          * that it supports, so we can do parsing ourselves. It ought to tell
192          * us how long the list is, but it doesn't do that either, so we just
193          * have to count it manually...
194          */
195         {
196                 int i = 0;
197                 tls_cipher_suite *ptr, tmp;
198                 char cs_id[2];
199
200                 while ( gnutls_cipher_suite_info( i, cs_id, &tmp.kx, &tmp.cipher,
201                         &tmp.mac, &tmp.version ))
202                         i++;
203                 tlsg_n_ciphers = i;
204
205                 /* Store a copy */
206                 tlsg_ciphers = LDAP_MALLOC(tlsg_n_ciphers * sizeof(tls_cipher_suite));
207                 if ( !tlsg_ciphers )
208                         return -1;
209                 for ( i=0; i<tlsg_n_ciphers; i++ ) {
210                         tlsg_ciphers[i].name = gnutls_cipher_suite_info( i, cs_id,
211                                 &tlsg_ciphers[i].kx, &tlsg_ciphers[i].cipher, &tlsg_ciphers[i].mac,
212                                 &tlsg_ciphers[i].version );
213                 }
214         }
215 #endif
216         return 0;
217 }
218
219 /*
220  * Tear down the TLS subsystem. Should only be called once.
221  */
222 static void
223 tlsg_destroy( void )
224 {
225 #ifndef HAVE_CIPHERSUITES
226         LDAP_FREE( tlsg_ciphers );
227         tlsg_ciphers = NULL;
228         tlsg_n_ciphers = 0;
229 #endif
230         gnutls_global_deinit();
231 }
232
233 static tls_ctx *
234 tlsg_ctx_new ( struct ldapoptions *lo )
235 {
236         tlsg_ctx *ctx;
237
238         ctx = ber_memcalloc ( 1, sizeof (*ctx) );
239         if ( ctx ) {
240                 ctx->lo = lo;
241                 if ( gnutls_certificate_allocate_credentials( &ctx->cred )) {
242                         ber_memfree( ctx );
243                         return NULL;
244                 }
245                 ctx->refcount = 1;
246 #ifdef HAVE_CIPHERSUITES
247                 gnutls_priority_init( &ctx->prios, "NORMAL", NULL );
248 #endif
249 #ifdef LDAP_R_COMPILE
250                 ldap_pvt_thread_mutex_init( &ctx->ref_mutex );
251 #endif
252         }
253         return (tls_ctx *)ctx;
254 }
255
256 static void
257 tlsg_ctx_ref( tls_ctx *ctx )
258 {
259         tlsg_ctx *c = (tlsg_ctx *)ctx;
260 #ifdef LDAP_R_COMPILE
261         ldap_pvt_thread_mutex_lock( &c->ref_mutex );
262 #endif
263         c->refcount++;
264 #ifdef LDAP_R_COMPILE
265         ldap_pvt_thread_mutex_unlock( &c->ref_mutex );
266 #endif
267 }
268
269 static void
270 tlsg_ctx_free ( tls_ctx *ctx )
271 {
272         tlsg_ctx *c = (tlsg_ctx *)ctx;
273         int refcount;
274
275         if ( !c ) return;
276
277 #ifdef LDAP_R_COMPILE
278         ldap_pvt_thread_mutex_lock( &c->ref_mutex );
279 #endif
280         refcount = --c->refcount;
281 #ifdef LDAP_R_COMPILE
282         ldap_pvt_thread_mutex_unlock( &c->ref_mutex );
283 #endif
284         if ( refcount )
285                 return;
286 #ifdef HAVE_CIPHERSUITES
287         gnutls_priority_deinit( c->prios );
288 #else
289         LDAP_FREE( c->kx_list );
290 #endif
291         gnutls_certificate_free_credentials( c->cred );
292         ber_memfree ( c );
293 }
294
295 static int
296 tlsg_getfile( const char *path, gnutls_datum_t *buf )
297 {
298         int rc = -1, fd;
299         struct stat st;
300
301         fd = open( path, O_RDONLY );
302         if ( fd >= 0 && fstat( fd, &st ) == 0 ) {
303                 buf->size = st.st_size;
304                 buf->data = LDAP_MALLOC( st.st_size + 1 );
305                 if ( buf->data ) {
306                         rc = read( fd, buf->data, st.st_size );
307                         close( fd );
308                         if ( rc < st.st_size )
309                                 rc = -1;
310                         else
311                                 rc = 0;
312                 }
313         }
314         return rc;
315 }
316
317 /* This is the GnuTLS default */
318 #define VERIFY_DEPTH    6
319
320 /*
321  * initialize a new TLS context
322  */
323 static int
324 tlsg_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
325 {
326         tlsg_ctx *ctx = lo->ldo_tls_ctx;
327         int rc;
328
329         if ( lo->ldo_tls_ciphersuite &&
330                 tlsg_parse_ciphers( ctx, lt->lt_ciphersuite )) {
331                 Debug( LDAP_DEBUG_ANY,
332                            "TLS: could not set cipher list %s.\n",
333                            lo->ldo_tls_ciphersuite, 0, 0 );
334                 return -1;
335         }
336
337         if (lo->ldo_tls_cacertdir != NULL) {
338                 Debug( LDAP_DEBUG_ANY, 
339                        "TLS: warning: cacertdir not implemented for gnutls\n",
340                        NULL, NULL, NULL );
341         }
342
343         if (lo->ldo_tls_cacertfile != NULL) {
344                 rc = gnutls_certificate_set_x509_trust_file( 
345                         ctx->cred,
346                         lt->lt_cacertfile,
347                         GNUTLS_X509_FMT_PEM );
348                 if ( rc < 0 ) return -1;
349         }
350
351         if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
352                 gnutls_x509_privkey_t key;
353                 gnutls_datum_t buf;
354                 gnutls_x509_crt_t certs[VERIFY_DEPTH];
355                 unsigned int max = VERIFY_DEPTH;
356
357                 rc = gnutls_x509_privkey_init( &key );
358                 if ( rc ) return -1;
359
360                 /* OpenSSL builds the cert chain for us, but GnuTLS
361                  * expects it to be present in the certfile. If it's
362                  * not, we have to build it ourselves. So we have to
363                  * do some special checks here...
364                  */
365                 rc = tlsg_getfile( lt->lt_keyfile, &buf );
366                 if ( rc ) return -1;
367                 rc = gnutls_x509_privkey_import( key, &buf,
368                         GNUTLS_X509_FMT_PEM );
369                 LDAP_FREE( buf.data );
370                 if ( rc < 0 ) return rc;
371
372                 rc = tlsg_getfile( lt->lt_certfile, &buf );
373                 if ( rc ) return -1;
374                 rc = gnutls_x509_crt_list_import( certs, &max, &buf,
375                         GNUTLS_X509_FMT_PEM, 0 );
376                 LDAP_FREE( buf.data );
377                 if ( rc < 0 ) return rc;
378
379                 /* If there's only one cert and it's not self-signed,
380                  * then we have to build the cert chain.
381                  */
382                 if ( max == 1 && !gnutls_x509_crt_check_issuer( certs[0], certs[0] )) {
383                         gnutls_x509_crt_t *cas;
384                         unsigned int i, j, ncas;
385
386                         gnutls_certificate_get_x509_cas( ctx->cred, &cas, &ncas );
387                         for ( i = 1; i<VERIFY_DEPTH; i++ ) {
388                                 for ( j = 0; j<ncas; j++ ) {
389                                         if ( gnutls_x509_crt_check_issuer( certs[i-1], cas[j] )) {
390                                                 certs[i] = cas[j];
391                                                 max++;
392                                                 /* If this CA is self-signed, we're done */
393                                                 if ( gnutls_x509_crt_check_issuer( cas[j], cas[j] ))
394                                                         j = ncas;
395                                                 break;
396                                         }
397                                 }
398                                 /* only continue if we found a CA and it was not self-signed */
399                                 if ( j == ncas )
400                                         break;
401                         }
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_skip_tag( ber, &len );        /* Context + Constructed (version) */
546         if ( tag == 0xa0 )      /* Version is optional */
547                 tag = ber_get_int( ber, &i );   /* Int: Version */
548         tag = ber_skip_tag( ber, &len );        /* Int: Serial (can be longer than ber_int_t) */
549         ber_skip_data( ber, len );
550         tag = ber_skip_tag( ber, &len );        /* Sequence: Signature */
551         ber_skip_data( ber, len );
552         if ( !get_subject ) {
553                 tag = ber_peek_tag( ber, &len );        /* Sequence: Issuer DN */
554         } else {
555                 tag = ber_skip_tag( ber, &len );
556                 ber_skip_data( ber, len );
557                 tag = ber_skip_tag( ber, &len );        /* Sequence: Validity */
558                 ber_skip_data( ber, len );
559                 tag = ber_peek_tag( ber, &len );        /* Sequence: Subject DN */
560         }
561         len = ber_ptrlen( ber );
562         dn->bv_val = cert->bv_val + len;
563         dn->bv_len = cert->bv_len - len;
564 }
565
566 static int
567 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
568 {
569         tlsg_session *s = (tlsg_session *)session;
570         const gnutls_datum_t *x;
571         struct berval bv;
572
573         x = gnutls_certificate_get_ours( s->session );
574
575         if (!x) return LDAP_INVALID_CREDENTIALS;
576         
577         bv.bv_val = (char *) x->data;
578         bv.bv_len = x->size;
579
580         tlsg_x509_cert_dn( &bv, der_dn, 1 );
581         return 0;
582 }
583
584 static int
585 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
586 {
587         tlsg_session *s = (tlsg_session *)session;
588         if ( !s->peer_der_dn.bv_val ) {
589                 const gnutls_datum_t *peer_cert_list;
590                 unsigned int list_size;
591                 struct berval bv;
592
593                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
594                                                         &list_size );
595                 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
596
597                 bv.bv_len = peer_cert_list->size;
598                 bv.bv_val = (char *) peer_cert_list->data;
599
600                 tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
601         }
602         *der_dn = s->peer_der_dn;
603         return 0;
604 }
605
606 /* what kind of hostname were we given? */
607 #define IS_DNS  0
608 #define IS_IP4  1
609 #define IS_IP6  2
610
611 #define CN_OID  "2.5.4.3"
612
613 static int
614 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
615 {
616         tlsg_session *s = (tlsg_session *)session;
617         int i, ret;
618         const gnutls_datum_t *peer_cert_list;
619         unsigned int list_size;
620         char altname[NI_MAXHOST];
621         size_t altnamesize;
622
623         gnutls_x509_crt_t cert;
624         const char *name;
625         char *ptr;
626         char *domain = NULL;
627 #ifdef LDAP_PF_INET6
628         struct in6_addr addr;
629 #else
630         struct in_addr addr;
631 #endif
632         int len1 = 0, len2 = 0;
633         int ntype = IS_DNS;
634
635         if( ldap_int_hostname &&
636                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
637         {
638                 name = ldap_int_hostname;
639         } else {
640                 name = name_in;
641         }
642
643         peer_cert_list = gnutls_certificate_get_peers( s->session, 
644                                                 &list_size );
645         if ( !peer_cert_list ) {
646                 Debug( LDAP_DEBUG_ANY,
647                         "TLS: unable to get peer certificate.\n",
648                         0, 0, 0 );
649                 /* If this was a fatal condition, things would have
650                  * aborted long before now.
651                  */
652                 return LDAP_SUCCESS;
653         }
654         ret = gnutls_x509_crt_init( &cert );
655         if ( ret < 0 )
656                 return LDAP_LOCAL_ERROR;
657         ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
658         if ( ret ) {
659                 gnutls_x509_crt_deinit( cert );
660                 return LDAP_LOCAL_ERROR;
661         }
662
663 #ifdef LDAP_PF_INET6
664         if (name[0] == '[' && strchr(name, ']')) {
665                 char *n2 = ldap_strdup(name+1);
666                 *strchr(n2, ']') = 0;
667                 if (inet_pton(AF_INET6, n2, &addr))
668                         ntype = IS_IP6;
669                 LDAP_FREE(n2);
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 /* suites is a string of colon-separated cipher suite names. */
798 static int
799 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
800 {
801 #ifdef HAVE_CIPHERSUITES
802         const char *err;
803         return gnutls_priority_init( &ctx->prios, suites, &err );
804 #else
805         char *ptr, *end;
806         int i, j, len, num;
807         int *list, nkx = 0, ncipher = 0, nmac = 0;
808         int *kx, *cipher, *mac;
809
810         num = 0;
811         ptr = suites;
812         do {
813                 end = strchr(ptr, ':');
814                 if ( end )
815                         len = end - ptr;
816                 else
817                         len = strlen(ptr);
818                 for (i=0; i<tlsg_n_ciphers; i++) {
819                         if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
820                                 num++;
821                                 break;
822                         }
823                 }
824                 if ( i == tlsg_n_ciphers ) {
825                         /* unrecognized cipher suite */
826                         return -1;
827                 }
828                 ptr += len + 1;
829         } while (end);
830
831         /* Space for all 3 lists */
832         list = LDAP_MALLOC( (num+1) * sizeof(int) * 3 );
833         if ( !list )
834                 return -1;
835         kx = list;
836         cipher = kx+num+1;
837         mac = cipher+num+1;
838
839         ptr = suites;
840         do {
841                 end = strchr(ptr, ':');
842                 if ( end )
843                         len = end - ptr;
844                 else
845                         len = strlen(ptr);
846                 for (i=0; i<tlsg_n_ciphers; i++) {
847                         /* For each cipher suite, insert its algorithms into
848                          * their respective priority lists. Make sure they
849                          * only appear once in each list.
850                          */
851                         if ( !strncasecmp( tlsg_ciphers[i].name, ptr, len )) {
852                                 for (j=0; j<nkx; j++)
853                                         if ( kx[j] == tlsg_ciphers[i].kx )
854                                                 break;
855                                 if ( j == nkx )
856                                         kx[nkx++] = tlsg_ciphers[i].kx;
857                                 for (j=0; j<ncipher; j++)
858                                         if ( cipher[j] == tlsg_ciphers[i].cipher )
859                                                 break;
860                                 if ( j == ncipher ) 
861                                         cipher[ncipher++] = tlsg_ciphers[i].cipher;
862                                 for (j=0; j<nmac; j++)
863                                         if ( mac[j] == tlsg_ciphers[i].mac )
864                                                 break;
865                                 if ( j == nmac )
866                                         mac[nmac++] = tlsg_ciphers[i].mac;
867                                 break;
868                         }
869                 }
870                 ptr += len + 1;
871         } while (end);
872         kx[nkx] = 0;
873         cipher[ncipher] = 0;
874         mac[nmac] = 0;
875         ctx->kx_list = kx;
876         ctx->cipher_list = cipher;
877         ctx->mac_list = mac;
878         return 0;
879 #endif
880 }
881
882 /*
883  * TLS support for LBER Sockbufs
884  */
885
886 struct tls_data {
887         tlsg_session            *session;
888         Sockbuf_IO_Desc         *sbiod;
889 };
890
891 static ssize_t
892 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
893 {
894         struct tls_data         *p;
895
896         if ( buf == NULL || len <= 0 ) return 0;
897
898         p = (struct tls_data *)ptr;
899
900         if ( p == NULL || p->sbiod == NULL ) {
901                 return 0;
902         }
903
904         return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
905 }
906
907 static ssize_t
908 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
909 {
910         struct tls_data         *p;
911         
912         if ( buf == NULL || len <= 0 ) return 0;
913         
914         p = (struct tls_data *)ptr;
915
916         if ( p == NULL || p->sbiod == NULL ) {
917                 return 0;
918         }
919
920         return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
921 }
922
923 static int
924 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
925 {
926         struct tls_data         *p;
927         tlsg_session    *session = arg;
928
929         assert( sbiod != NULL );
930
931         p = LBER_MALLOC( sizeof( *p ) );
932         if ( p == NULL ) {
933                 return -1;
934         }
935         
936         gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
937         gnutls_transport_set_pull_function( session->session, tlsg_recv );
938         gnutls_transport_set_push_function( session->session, tlsg_send );
939         p->session = session;
940         p->sbiod = sbiod;
941         sbiod->sbiod_pvt = p;
942         return 0;
943 }
944
945 static int
946 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
947 {
948         struct tls_data         *p;
949         
950         assert( sbiod != NULL );
951         assert( sbiod->sbiod_pvt != NULL );
952
953         p = (struct tls_data *)sbiod->sbiod_pvt;
954         gnutls_deinit ( p->session->session );
955         LBER_FREE( p->session );
956         LBER_FREE( sbiod->sbiod_pvt );
957         sbiod->sbiod_pvt = NULL;
958         return 0;
959 }
960
961 static int
962 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
963 {
964         struct tls_data         *p;
965         
966         assert( sbiod != NULL );
967         assert( sbiod->sbiod_pvt != NULL );
968
969         p = (struct tls_data *)sbiod->sbiod_pvt;
970         gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
971         return 0;
972 }
973
974 static int
975 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
976 {
977         struct tls_data         *p;
978         
979         assert( sbiod != NULL );
980         assert( sbiod->sbiod_pvt != NULL );
981
982         p = (struct tls_data *)sbiod->sbiod_pvt;
983         
984         if ( opt == LBER_SB_OPT_GET_SSL ) {
985                 *((tlsg_session **)arg) = p->session;
986                 return 1;
987                 
988         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
989                 if( gnutls_record_check_pending( p->session->session ) > 0 ) {
990                         return 1;
991                 }
992         }
993         
994         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
995 }
996
997 static ber_slen_t
998 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
999 {
1000         struct tls_data         *p;
1001         ber_slen_t              ret;
1002
1003         assert( sbiod != NULL );
1004         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1005
1006         p = (struct tls_data *)sbiod->sbiod_pvt;
1007
1008         ret = gnutls_record_recv ( p->session->session, buf, len );
1009         switch (ret) {
1010         case GNUTLS_E_INTERRUPTED:
1011         case GNUTLS_E_AGAIN:
1012                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1013                 sock_errset(EWOULDBLOCK);
1014                 ret = 0;
1015                 break;
1016         case GNUTLS_E_REHANDSHAKE:
1017                 for ( ret = gnutls_handshake ( p->session->session );
1018                       ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
1019                       ret = gnutls_handshake ( p->session->session ) );
1020                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1021                 ret = 0;
1022                 break;
1023         default:
1024                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1025         }
1026         return ret;
1027 }
1028
1029 static ber_slen_t
1030 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1031 {
1032         struct tls_data         *p;
1033         ber_slen_t              ret;
1034
1035         assert( sbiod != NULL );
1036         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1037
1038         p = (struct tls_data *)sbiod->sbiod_pvt;
1039
1040         ret = gnutls_record_send ( p->session->session, (char *)buf, len );
1041
1042         if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
1043                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1044                 sock_errset(EWOULDBLOCK);
1045                 ret = 0;
1046         } else {
1047                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1048         }
1049         return ret;
1050 }
1051
1052 static Sockbuf_IO tlsg_sbio =
1053 {
1054         tlsg_sb_setup,          /* sbi_setup */
1055         tlsg_sb_remove,         /* sbi_remove */
1056         tlsg_sb_ctrl,           /* sbi_ctrl */
1057         tlsg_sb_read,           /* sbi_read */
1058         tlsg_sb_write,          /* sbi_write */
1059         tlsg_sb_close           /* sbi_close */
1060 };
1061
1062 /* Certs are not automatically varified during the handshake */
1063 static int
1064 tlsg_cert_verify( tlsg_session *ssl )
1065 {
1066         unsigned int status = 0;
1067         int err;
1068         time_t now = time(0);
1069         time_t peertime;
1070
1071         err = gnutls_certificate_verify_peers2( ssl->session, &status );
1072         if ( err < 0 ) {
1073                 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
1074                         err,0,0 );
1075                 return -1;
1076         }
1077         if ( status ) {
1078                 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
1079                         status, 0,0 );
1080                 return -1;
1081         }
1082         peertime = gnutls_certificate_expiration_time_peers( ssl->session );
1083         if ( peertime == (time_t) -1 ) {
1084                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
1085                         0, 0, 0 );
1086                 return -1;
1087         }
1088         if ( peertime < now ) {
1089                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
1090                         0, 0, 0 );
1091                 return -1;
1092         }
1093         peertime = gnutls_certificate_activation_time_peers( ssl->session );
1094         if ( peertime == (time_t) -1 ) {
1095                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
1096                         0, 0, 0 );
1097                 return -1;
1098         }
1099         if ( peertime > now ) {
1100                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
1101                         0, 0, 0 );
1102                 return -1;
1103         }
1104         return 0;
1105 }
1106
1107 tls_impl ldap_int_tls_impl = {
1108         "GnuTLS",
1109
1110         tlsg_init,
1111         tlsg_destroy,
1112
1113         tlsg_ctx_new,
1114         tlsg_ctx_ref,
1115         tlsg_ctx_free,
1116         tlsg_ctx_init,
1117
1118         tlsg_session_new,
1119         tlsg_session_connect,
1120         tlsg_session_accept,
1121         tlsg_session_upflags,
1122         tlsg_session_errmsg,
1123         tlsg_session_my_dn,
1124         tlsg_session_peer_dn,
1125         tlsg_session_chkhost,
1126         tlsg_session_strength,
1127
1128         &tlsg_sbio,
1129
1130 #ifdef LDAP_R_COMPILE
1131         tlsg_thr_init,
1132 #else
1133         NULL,
1134 #endif
1135
1136         0
1137 };
1138
1139 #endif /* HAVE_GNUTLS */