]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_g.c
Merge remote-tracking branch 'origin/mdb.RE/0.9'
[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
242         if ( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) {
243                 gnutls_x509_privkey_t key;
244                 gnutls_datum_t buf;
245                 gnutls_x509_crt_t certs[VERIFY_DEPTH];
246                 unsigned int max = VERIFY_DEPTH;
247
248                 rc = gnutls_x509_privkey_init( &key );
249                 if ( rc ) return -1;
250
251                 /* OpenSSL builds the cert chain for us, but GnuTLS
252                  * expects it to be present in the certfile. If it's
253                  * not, we have to build it ourselves. So we have to
254                  * do some special checks here...
255                  */
256                 rc = tlsg_getfile( lt->lt_keyfile, &buf );
257                 if ( rc ) return -1;
258                 rc = gnutls_x509_privkey_import( key, &buf,
259                         GNUTLS_X509_FMT_PEM );
260                 LDAP_FREE( buf.data );
261                 if ( rc < 0 ) return rc;
262
263                 rc = tlsg_getfile( lt->lt_certfile, &buf );
264                 if ( rc ) return -1;
265                 rc = gnutls_x509_crt_list_import( certs, &max, &buf,
266                         GNUTLS_X509_FMT_PEM, 0 );
267                 LDAP_FREE( buf.data );
268                 if ( rc < 0 ) return rc;
269
270                 /* If there's only one cert and it's not self-signed,
271                  * then we have to build the cert chain.
272                  */
273                 if ( max == 1 && !gnutls_x509_crt_check_issuer( certs[0], certs[0] )) {
274                         unsigned int i;
275                         for ( i = 1; i<VERIFY_DEPTH; i++ ) {
276                                 if ( gnutls_certificate_get_issuer( ctx->cred, certs[i-1], &certs[i], 0 ))
277                                         break;
278                                 max++;
279                                 /* If this CA is self-signed, we're done */
280                                 if ( gnutls_x509_crt_check_issuer( certs[i], certs[i] ))
281                                         break;
282                         }
283                 }
284                 rc = gnutls_certificate_set_x509_key( ctx->cred, certs, max, key );
285                 if ( rc ) return -1;
286         } else if ( lo->ldo_tls_certfile || lo->ldo_tls_keyfile ) {
287                 Debug( LDAP_DEBUG_ANY, 
288                        "TLS: only one of certfile and keyfile specified\n",
289                        NULL, NULL, NULL );
290                 return -1;
291         }
292
293         if ( lo->ldo_tls_crlfile ) {
294                 rc = gnutls_certificate_set_x509_crl_file( 
295                         ctx->cred,
296                         lt->lt_crlfile,
297                         GNUTLS_X509_FMT_PEM );
298                 if ( rc < 0 ) return -1;
299                 rc = 0;
300         }
301
302         /* FIXME: ITS#5992 - this should be configurable,
303          * and V1 CA certs should be phased out ASAP.
304          */
305         gnutls_certificate_set_verify_flags( ctx->cred,
306                 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT );
307
308         if ( is_server && lo->ldo_tls_dhfile ) {
309                 gnutls_datum_t buf;
310                 rc = tlsg_getfile( lo->ldo_tls_dhfile, &buf );
311                 if ( rc ) return -1;
312                 rc = gnutls_dh_params_init( &ctx->dh_params );
313                 if ( rc == 0 )
314                         rc = gnutls_dh_params_import_pkcs3( ctx->dh_params, &buf,
315                                 GNUTLS_X509_FMT_PEM );
316                 LDAP_FREE( buf.data );
317                 if ( rc ) return -1;
318                 gnutls_certificate_set_dh_params( ctx->cred, ctx->dh_params );
319         }
320
321         ctx->reqcert = lo->ldo_tls_require_cert;
322
323         return 0;
324 }
325
326 static tls_session *
327 tlsg_session_new ( tls_ctx * ctx, int is_server )
328 {
329         tlsg_ctx *c = (tlsg_ctx *)ctx;
330         tlsg_session *session;
331
332         session = ber_memcalloc ( 1, sizeof (*session) );
333         if ( !session )
334                 return NULL;
335
336         session->ctx = c;
337         gnutls_init( &session->session, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT );
338         gnutls_priority_set( session->session, c->prios );
339         if ( c->cred )
340                 gnutls_credentials_set( session->session, GNUTLS_CRD_CERTIFICATE, c->cred );
341         
342         if ( is_server ) {
343                 int flag = 0;
344                 if ( c->reqcert ) {
345                         flag = GNUTLS_CERT_REQUEST;
346                         if ( c->reqcert == LDAP_OPT_X_TLS_DEMAND ||
347                                 c->reqcert == LDAP_OPT_X_TLS_HARD )
348                                 flag = GNUTLS_CERT_REQUIRE;
349                         gnutls_certificate_server_set_request( session->session, flag );
350                 }
351         }
352         return (tls_session *)session;
353
354
355 static int
356 tlsg_session_accept( tls_session *session )
357 {
358         tlsg_session *s = (tlsg_session *)session;
359         int rc;
360
361         rc = gnutls_handshake( s->session );
362         if ( rc == 0 && s->ctx->reqcert != LDAP_OPT_X_TLS_NEVER ) {
363                 const gnutls_datum_t *peer_cert_list;
364                 unsigned int list_size;
365
366                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
367                                                 &list_size );
368                 if ( !peer_cert_list && s->ctx->reqcert == LDAP_OPT_X_TLS_TRY )
369                         rc = 0;
370                 else {
371                         rc = tlsg_cert_verify( s );
372                         if ( rc && s->ctx->reqcert == LDAP_OPT_X_TLS_ALLOW )
373                                 rc = 0;
374                 }
375         }
376         return rc;
377 }
378
379 static int
380 tlsg_session_connect( LDAP *ld, tls_session *session )
381 {
382         return tlsg_session_accept( session);
383 }
384
385 static int
386 tlsg_session_upflags( Sockbuf *sb, tls_session *session, int rc )
387 {
388         tlsg_session *s = (tlsg_session *)session;
389
390         if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
391                 return 0;
392
393         switch (gnutls_record_get_direction (s->session)) {
394         case 0: 
395                 sb->sb_trans_needs_read = 1;
396                 return 1;
397         case 1:
398                 sb->sb_trans_needs_write = 1;
399                 return 1;
400         }
401         return 0;
402 }
403
404 static char *
405 tlsg_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
406 {
407         return (char *)gnutls_strerror( rc );
408 }
409
410 static void
411 tlsg_x509_cert_dn( struct berval *cert, struct berval *dn, int get_subject )
412 {
413         BerElementBuffer berbuf;
414         BerElement *ber = (BerElement *)&berbuf;
415         ber_tag_t tag;
416         ber_len_t len;
417         ber_int_t i;
418
419         ber_init2( ber, cert, LBER_USE_DER );
420         tag = ber_skip_tag( ber, &len );        /* Sequence */
421         tag = ber_skip_tag( ber, &len );        /* Sequence */
422         tag = ber_peek_tag( ber, &len );        /* Context + Constructed (version) */
423         if ( tag == 0xa0 ) {    /* Version is optional */
424                 tag = ber_skip_tag( ber, &len );
425                 tag = ber_get_int( ber, &i );   /* Int: Version */
426         }
427         tag = ber_skip_tag( ber, &len );        /* Int: Serial (can be longer than ber_int_t) */
428         ber_skip_data( ber, len );
429         tag = ber_skip_tag( ber, &len );        /* Sequence: Signature */
430         ber_skip_data( ber, len );
431         if ( !get_subject ) {
432                 tag = ber_peek_tag( ber, &len );        /* Sequence: Issuer DN */
433         } else {
434                 tag = ber_skip_tag( ber, &len );
435                 ber_skip_data( ber, len );
436                 tag = ber_skip_tag( ber, &len );        /* Sequence: Validity */
437                 ber_skip_data( ber, len );
438                 tag = ber_peek_tag( ber, &len );        /* Sequence: Subject DN */
439         }
440         len = ber_ptrlen( ber );
441         dn->bv_val = cert->bv_val + len;
442         dn->bv_len = cert->bv_len - len;
443 }
444
445 static int
446 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
447 {
448         tlsg_session *s = (tlsg_session *)session;
449         const gnutls_datum_t *x;
450         struct berval bv;
451
452         x = gnutls_certificate_get_ours( s->session );
453
454         if (!x) return LDAP_INVALID_CREDENTIALS;
455         
456         bv.bv_val = (char *) x->data;
457         bv.bv_len = x->size;
458
459         tlsg_x509_cert_dn( &bv, der_dn, 1 );
460         return 0;
461 }
462
463 static int
464 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
465 {
466         tlsg_session *s = (tlsg_session *)session;
467         if ( !s->peer_der_dn.bv_val ) {
468                 const gnutls_datum_t *peer_cert_list;
469                 unsigned int list_size;
470                 struct berval bv;
471
472                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
473                                                         &list_size );
474                 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
475
476                 bv.bv_len = peer_cert_list->size;
477                 bv.bv_val = (char *) peer_cert_list->data;
478
479                 tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
480         }
481         *der_dn = s->peer_der_dn;
482         return 0;
483 }
484
485 /* what kind of hostname were we given? */
486 #define IS_DNS  0
487 #define IS_IP4  1
488 #define IS_IP6  2
489
490 #define CN_OID  "2.5.4.3"
491
492 static int
493 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
494 {
495         tlsg_session *s = (tlsg_session *)session;
496         int i, ret;
497         const gnutls_datum_t *peer_cert_list;
498         unsigned int list_size;
499         char altname[NI_MAXHOST];
500         size_t altnamesize;
501
502         gnutls_x509_crt_t cert;
503         const char *name;
504         char *ptr;
505         char *domain = NULL;
506 #ifdef LDAP_PF_INET6
507         struct in6_addr addr;
508 #else
509         struct in_addr addr;
510 #endif
511         int len1 = 0, len2 = 0;
512         int ntype = IS_DNS;
513
514         if( ldap_int_hostname &&
515                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
516         {
517                 name = ldap_int_hostname;
518         } else {
519                 name = name_in;
520         }
521
522         peer_cert_list = gnutls_certificate_get_peers( s->session, 
523                                                 &list_size );
524         if ( !peer_cert_list ) {
525                 Debug( LDAP_DEBUG_ANY,
526                         "TLS: unable to get peer certificate.\n",
527                         0, 0, 0 );
528                 /* If this was a fatal condition, things would have
529                  * aborted long before now.
530                  */
531                 return LDAP_SUCCESS;
532         }
533         ret = gnutls_x509_crt_init( &cert );
534         if ( ret < 0 )
535                 return LDAP_LOCAL_ERROR;
536         ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
537         if ( ret ) {
538                 gnutls_x509_crt_deinit( cert );
539                 return LDAP_LOCAL_ERROR;
540         }
541
542 #ifdef LDAP_PF_INET6
543         if (inet_pton(AF_INET6, name, &addr)) {
544                 ntype = IS_IP6;
545         } else 
546 #endif
547         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
548                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
549         }
550         
551         if (ntype == IS_DNS) {
552                 len1 = strlen(name);
553                 domain = strchr(name, '.');
554                 if (domain) {
555                         len2 = len1 - (domain-name);
556                 }
557         }
558
559         for ( i=0, ret=0; ret >= 0; i++ ) {
560                 altnamesize = sizeof(altname);
561                 ret = gnutls_x509_crt_get_subject_alt_name( cert, i, 
562                         altname, &altnamesize, NULL );
563                 if ( ret < 0 ) break;
564
565                 /* ignore empty */
566                 if ( altnamesize == 0 ) continue;
567
568                 if ( ret == GNUTLS_SAN_DNSNAME ) {
569                         if (ntype != IS_DNS) continue;
570         
571                         /* Is this an exact match? */
572                         if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
573                                 break;
574                         }
575
576                         /* Is this a wildcard match? */
577                         if (domain && (altname[0] == '*') && (altname[1] == '.') &&
578                                 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
579                         {
580                                 break;
581                         }
582                 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
583                         if (ntype == IS_DNS) continue;
584
585 #ifdef LDAP_PF_INET6
586                         if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
587                                 continue;
588                         } else
589 #endif
590                         if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
591                                 continue;
592                         }
593                         if (!memcmp(altname, &addr, altnamesize)) {
594                                 break;
595                         }
596                 }
597         }
598         if ( ret >= 0 ) {
599                 ret = LDAP_SUCCESS;
600         } else {
601                 /* find the last CN */
602                 i=0;
603                 do {
604                         altnamesize = 0;
605                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
606                                 i, 1, altname, &altnamesize );
607                         if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
608                                 i++;
609                         else
610                                 break;
611                 } while ( 1 );
612
613                 if ( i ) {
614                         altnamesize = sizeof(altname);
615                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
616                                 i-1, 0, altname, &altnamesize );
617                 }
618
619                 if ( ret < 0 ) {
620                         Debug( LDAP_DEBUG_ANY,
621                                 "TLS: unable to get common name from peer certificate.\n",
622                                 0, 0, 0 );
623                         ret = LDAP_CONNECT_ERROR;
624                         if ( ld->ld_error ) {
625                                 LDAP_FREE( ld->ld_error );
626                         }
627                         ld->ld_error = LDAP_STRDUP(
628                                 _("TLS: unable to get CN from peer certificate"));
629
630                 } else {
631                         ret = LDAP_LOCAL_ERROR;
632                         if ( !len1 ) len1 = strlen( name );
633                         if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
634                                 ret = LDAP_SUCCESS;
635
636                         } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
637                                         /* Is this a wildcard match? */
638                                 if( domain &&
639                                         (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
640                                         ret = LDAP_SUCCESS;
641                                 }
642                         }
643                 }
644
645                 if( ret == LDAP_LOCAL_ERROR ) {
646                         altname[altnamesize] = '\0';
647                         Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
648                                 "common name in certificate (%s).\n", 
649                                 name, altname, 0 );
650                         ret = LDAP_CONNECT_ERROR;
651                         if ( ld->ld_error ) {
652                                 LDAP_FREE( ld->ld_error );
653                         }
654                         ld->ld_error = LDAP_STRDUP(
655                                 _("TLS: hostname does not match CN in peer certificate"));
656                 }
657         }
658         gnutls_x509_crt_deinit( cert );
659         return ret;
660 }
661
662 static int
663 tlsg_session_strength( tls_session *session )
664 {
665         tlsg_session *s = (tlsg_session *)session;
666         gnutls_cipher_algorithm_t c;
667
668         c = gnutls_cipher_get( s->session );
669         return gnutls_cipher_get_key_size( c ) * 8;
670 }
671
672 static int
673 tlsg_session_unique( tls_session *sess, struct berval *buf, int is_server)
674 {
675         tlsg_session *s = (tlsg_session *)sess;
676         gnutls_datum_t cb;
677         int rc;
678
679         rc = gnutls_session_channel_binding( s->session, GNUTLS_CB_TLS_UNIQUE, &cb );
680         if ( rc == 0 ) {
681                 int len = cb.size;
682                 if ( len > buf->bv_len )
683                         len = buf->bv_len;
684                 buf->bv_len = len;
685                 memcpy( buf->bv_val, cb.data, len );
686                 return len;
687         }
688         return 0;
689 }
690
691 static const char *
692 tlsg_session_version( tls_session *sess )
693 {
694         tlsg_session *s = (tlsg_session *)sess;
695         return gnutls_protocol_get_name(gnutls_protocol_get_version( s->session ));
696 }
697
698 static const char *
699 tlsg_session_cipher( tls_session *sess )
700 {
701         tlsg_session *s = (tlsg_session *)sess;
702         return gnutls_cipher_get_name(gnutls_cipher_get( s->session ));
703 }
704
705 static int
706 tlsg_session_peercert( tls_session *sess, struct berval *der )
707 {
708         tlsg_session *s = (tlsg_session *)sess;
709         const gnutls_datum_t *peer_cert_list;
710         unsigned int list_size;
711
712         peer_cert_list = gnutls_certificate_get_peers( s->session, &list_size );
713         if (!peer_cert_list)
714                 return -1;
715         der->bv_len = peer_cert_list[0].size;
716         der->bv_val = LDAP_MALLOC( der->bv_len );
717         if (!der->bv_val)
718                 return -1;
719         memcpy(der->bv_val, peer_cert_list[0].data, der->bv_len);
720         return 0;
721 }
722
723 /* suites is a string of colon-separated cipher suite names. */
724 static int
725 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
726 {
727         const char *err;
728         int rc = gnutls_priority_init( &ctx->prios, suites, &err );
729         if ( rc )
730                 ctx->prios = NULL;
731         return rc;
732 }
733
734 /*
735  * TLS support for LBER Sockbufs
736  */
737
738 struct tls_data {
739         tlsg_session            *session;
740         Sockbuf_IO_Desc         *sbiod;
741 };
742
743 static ssize_t
744 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
745 {
746         struct tls_data         *p;
747
748         if ( buf == NULL || len <= 0 ) return 0;
749
750         p = (struct tls_data *)ptr;
751
752         if ( p == NULL || p->sbiod == NULL ) {
753                 return 0;
754         }
755
756         return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
757 }
758
759 static ssize_t
760 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
761 {
762         struct tls_data         *p;
763         
764         if ( buf == NULL || len <= 0 ) return 0;
765         
766         p = (struct tls_data *)ptr;
767
768         if ( p == NULL || p->sbiod == NULL ) {
769                 return 0;
770         }
771
772         return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
773 }
774
775 static int
776 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
777 {
778         struct tls_data         *p;
779         tlsg_session    *session = arg;
780
781         assert( sbiod != NULL );
782
783         p = LBER_MALLOC( sizeof( *p ) );
784         if ( p == NULL ) {
785                 return -1;
786         }
787         
788         gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
789         gnutls_transport_set_pull_function( session->session, tlsg_recv );
790         gnutls_transport_set_push_function( session->session, tlsg_send );
791         p->session = session;
792         p->sbiod = sbiod;
793         sbiod->sbiod_pvt = p;
794         return 0;
795 }
796
797 static int
798 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
799 {
800         struct tls_data         *p;
801         
802         assert( sbiod != NULL );
803         assert( sbiod->sbiod_pvt != NULL );
804
805         p = (struct tls_data *)sbiod->sbiod_pvt;
806         gnutls_deinit ( p->session->session );
807         LBER_FREE( p->session );
808         LBER_FREE( sbiod->sbiod_pvt );
809         sbiod->sbiod_pvt = NULL;
810         return 0;
811 }
812
813 static int
814 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
815 {
816         struct tls_data         *p;
817         
818         assert( sbiod != NULL );
819         assert( sbiod->sbiod_pvt != NULL );
820
821         p = (struct tls_data *)sbiod->sbiod_pvt;
822         gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
823         return 0;
824 }
825
826 static int
827 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
828 {
829         struct tls_data         *p;
830         
831         assert( sbiod != NULL );
832         assert( sbiod->sbiod_pvt != NULL );
833
834         p = (struct tls_data *)sbiod->sbiod_pvt;
835         
836         if ( opt == LBER_SB_OPT_GET_SSL ) {
837                 *((tlsg_session **)arg) = p->session;
838                 return 1;
839                 
840         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
841                 if( gnutls_record_check_pending( p->session->session ) > 0 ) {
842                         return 1;
843                 }
844         }
845         
846         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
847 }
848
849 static ber_slen_t
850 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
851 {
852         struct tls_data         *p;
853         ber_slen_t              ret;
854
855         assert( sbiod != NULL );
856         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
857
858         p = (struct tls_data *)sbiod->sbiod_pvt;
859
860         ret = gnutls_record_recv ( p->session->session, buf, len );
861         switch (ret) {
862         case GNUTLS_E_INTERRUPTED:
863         case GNUTLS_E_AGAIN:
864                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
865                 sock_errset(EWOULDBLOCK);
866                 ret = 0;
867                 break;
868         case GNUTLS_E_REHANDSHAKE:
869                 for ( ret = gnutls_handshake ( p->session->session );
870                       ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
871                       ret = gnutls_handshake ( p->session->session ) );
872                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
873                 ret = 0;
874                 break;
875         default:
876                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
877         }
878         return ret;
879 }
880
881 static ber_slen_t
882 tlsg_sb_write( 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_send ( p->session->session, (char *)buf, len );
893
894         if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
895                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
896                 sock_errset(EWOULDBLOCK);
897                 ret = 0;
898         } else {
899                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
900         }
901         return ret;
902 }
903
904 static Sockbuf_IO tlsg_sbio =
905 {
906         tlsg_sb_setup,          /* sbi_setup */
907         tlsg_sb_remove,         /* sbi_remove */
908         tlsg_sb_ctrl,           /* sbi_ctrl */
909         tlsg_sb_read,           /* sbi_read */
910         tlsg_sb_write,          /* sbi_write */
911         tlsg_sb_close           /* sbi_close */
912 };
913
914 /* Certs are not automatically varified during the handshake */
915 static int
916 tlsg_cert_verify( tlsg_session *ssl )
917 {
918         unsigned int status = 0;
919         int err;
920         time_t now = time(0);
921         time_t peertime;
922
923         err = gnutls_certificate_verify_peers2( ssl->session, &status );
924         if ( err < 0 ) {
925                 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
926                         err,0,0 );
927                 return -1;
928         }
929         if ( status ) {
930                 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
931                         status, 0,0 );
932                 return -1;
933         }
934         peertime = gnutls_certificate_expiration_time_peers( ssl->session );
935         if ( peertime == (time_t) -1 ) {
936                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
937                         0, 0, 0 );
938                 return -1;
939         }
940         if ( peertime < now ) {
941                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
942                         0, 0, 0 );
943                 return -1;
944         }
945         peertime = gnutls_certificate_activation_time_peers( ssl->session );
946         if ( peertime == (time_t) -1 ) {
947                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
948                         0, 0, 0 );
949                 return -1;
950         }
951         if ( peertime > now ) {
952                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
953                         0, 0, 0 );
954                 return -1;
955         }
956         return 0;
957 }
958
959 tls_impl ldap_int_tls_impl = {
960         "GnuTLS",
961
962         tlsg_init,
963         tlsg_destroy,
964
965         tlsg_ctx_new,
966         tlsg_ctx_ref,
967         tlsg_ctx_free,
968         tlsg_ctx_init,
969
970         tlsg_session_new,
971         tlsg_session_connect,
972         tlsg_session_accept,
973         tlsg_session_upflags,
974         tlsg_session_errmsg,
975         tlsg_session_my_dn,
976         tlsg_session_peer_dn,
977         tlsg_session_chkhost,
978         tlsg_session_strength,
979         tlsg_session_unique,
980         tlsg_session_version,
981         tlsg_session_cipher,
982         tlsg_session_peercert,
983
984         &tlsg_sbio,
985
986 #ifdef LDAP_R_COMPILE
987         tlsg_thr_init,
988 #else
989         NULL,
990 #endif
991
992         0
993 };
994
995 #endif /* HAVE_GNUTLS */