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