]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_g.c
Happy New Year
[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-2018 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         for ( rc = gnutls_handshake ( s->session );
362               rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN;
363               rc = gnutls_handshake ( s->session ) );
364         if ( rc == 0 && s->ctx->reqcert != LDAP_OPT_X_TLS_NEVER ) {
365                 const gnutls_datum_t *peer_cert_list;
366                 unsigned int list_size;
367
368                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
369                                                 &list_size );
370                 if ( !peer_cert_list && s->ctx->reqcert == LDAP_OPT_X_TLS_TRY )
371                         rc = 0;
372                 else {
373                         rc = tlsg_cert_verify( s );
374                         if ( rc && s->ctx->reqcert == LDAP_OPT_X_TLS_ALLOW )
375                                 rc = 0;
376                 }
377         }
378         return rc;
379 }
380
381 static int
382 tlsg_session_connect( LDAP *ld, tls_session *session )
383 {
384         return tlsg_session_accept( session);
385 }
386
387 static int
388 tlsg_session_upflags( Sockbuf *sb, tls_session *session, int rc )
389 {
390         tlsg_session *s = (tlsg_session *)session;
391
392         if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
393                 return 0;
394
395         switch (gnutls_record_get_direction (s->session)) {
396         case 0: 
397                 sb->sb_trans_needs_read = 1;
398                 return 1;
399         case 1:
400                 sb->sb_trans_needs_write = 1;
401                 return 1;
402         }
403         return 0;
404 }
405
406 static char *
407 tlsg_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
408 {
409         return (char *)gnutls_strerror( rc );
410 }
411
412 static void
413 tlsg_x509_cert_dn( struct berval *cert, struct berval *dn, int get_subject )
414 {
415         BerElementBuffer berbuf;
416         BerElement *ber = (BerElement *)&berbuf;
417         ber_tag_t tag;
418         ber_len_t len;
419         ber_int_t i;
420
421         ber_init2( ber, cert, LBER_USE_DER );
422         tag = ber_skip_tag( ber, &len );        /* Sequence */
423         tag = ber_skip_tag( ber, &len );        /* Sequence */
424         tag = ber_peek_tag( ber, &len );        /* Context + Constructed (version) */
425         if ( tag == 0xa0 ) {    /* Version is optional */
426                 tag = ber_skip_tag( ber, &len );
427                 tag = ber_get_int( ber, &i );   /* Int: Version */
428         }
429         tag = ber_skip_tag( ber, &len );        /* Int: Serial (can be longer than ber_int_t) */
430         ber_skip_data( ber, len );
431         tag = ber_skip_tag( ber, &len );        /* Sequence: Signature */
432         ber_skip_data( ber, len );
433         if ( !get_subject ) {
434                 tag = ber_peek_tag( ber, &len );        /* Sequence: Issuer DN */
435         } else {
436                 tag = ber_skip_tag( ber, &len );
437                 ber_skip_data( ber, len );
438                 tag = ber_skip_tag( ber, &len );        /* Sequence: Validity */
439                 ber_skip_data( ber, len );
440                 tag = ber_peek_tag( ber, &len );        /* Sequence: Subject DN */
441         }
442         len = ber_ptrlen( ber );
443         dn->bv_val = cert->bv_val + len;
444         dn->bv_len = cert->bv_len - len;
445 }
446
447 static int
448 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
449 {
450         tlsg_session *s = (tlsg_session *)session;
451         const gnutls_datum_t *x;
452         struct berval bv;
453
454         x = gnutls_certificate_get_ours( s->session );
455
456         if (!x) return LDAP_INVALID_CREDENTIALS;
457         
458         bv.bv_val = (char *) x->data;
459         bv.bv_len = x->size;
460
461         tlsg_x509_cert_dn( &bv, der_dn, 1 );
462         return 0;
463 }
464
465 static int
466 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
467 {
468         tlsg_session *s = (tlsg_session *)session;
469         if ( !s->peer_der_dn.bv_val ) {
470                 const gnutls_datum_t *peer_cert_list;
471                 unsigned int list_size;
472                 struct berval bv;
473
474                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
475                                                         &list_size );
476                 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
477
478                 bv.bv_len = peer_cert_list->size;
479                 bv.bv_val = (char *) peer_cert_list->data;
480
481                 tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
482         }
483         *der_dn = s->peer_der_dn;
484         return 0;
485 }
486
487 /* what kind of hostname were we given? */
488 #define IS_DNS  0
489 #define IS_IP4  1
490 #define IS_IP6  2
491
492 #define CN_OID  "2.5.4.3"
493
494 static int
495 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
496 {
497         tlsg_session *s = (tlsg_session *)session;
498         int i, ret;
499         const gnutls_datum_t *peer_cert_list;
500         unsigned int list_size;
501         char altname[NI_MAXHOST];
502         size_t altnamesize;
503
504         gnutls_x509_crt_t cert;
505         const char *name;
506         char *ptr;
507         char *domain = NULL;
508 #ifdef LDAP_PF_INET6
509         struct in6_addr addr;
510 #else
511         struct in_addr addr;
512 #endif
513         int len1 = 0, len2 = 0;
514         int ntype = IS_DNS;
515
516         if( ldap_int_hostname &&
517                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
518         {
519                 name = ldap_int_hostname;
520         } else {
521                 name = name_in;
522         }
523
524         peer_cert_list = gnutls_certificate_get_peers( s->session, 
525                                                 &list_size );
526         if ( !peer_cert_list ) {
527                 Debug( LDAP_DEBUG_ANY,
528                         "TLS: unable to get peer certificate.\n",
529                         0, 0, 0 );
530                 /* If this was a fatal condition, things would have
531                  * aborted long before now.
532                  */
533                 return LDAP_SUCCESS;
534         }
535         ret = gnutls_x509_crt_init( &cert );
536         if ( ret < 0 )
537                 return LDAP_LOCAL_ERROR;
538         ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
539         if ( ret ) {
540                 gnutls_x509_crt_deinit( cert );
541                 return LDAP_LOCAL_ERROR;
542         }
543
544 #ifdef LDAP_PF_INET6
545         if (inet_pton(AF_INET6, name, &addr)) {
546                 ntype = IS_IP6;
547         } else 
548 #endif
549         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
550                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
551         }
552         
553         if (ntype == IS_DNS) {
554                 len1 = strlen(name);
555                 domain = strchr(name, '.');
556                 if (domain) {
557                         len2 = len1 - (domain-name);
558                 }
559         }
560
561         for ( i=0, ret=0; ret >= 0; i++ ) {
562                 altnamesize = sizeof(altname);
563                 ret = gnutls_x509_crt_get_subject_alt_name( cert, i, 
564                         altname, &altnamesize, NULL );
565                 if ( ret < 0 ) break;
566
567                 /* ignore empty */
568                 if ( altnamesize == 0 ) continue;
569
570                 if ( ret == GNUTLS_SAN_DNSNAME ) {
571                         if (ntype != IS_DNS) continue;
572         
573                         /* Is this an exact match? */
574                         if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
575                                 break;
576                         }
577
578                         /* Is this a wildcard match? */
579                         if (domain && (altname[0] == '*') && (altname[1] == '.') &&
580                                 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
581                         {
582                                 break;
583                         }
584                 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
585                         if (ntype == IS_DNS) continue;
586
587 #ifdef LDAP_PF_INET6
588                         if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
589                                 continue;
590                         } else
591 #endif
592                         if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
593                                 continue;
594                         }
595                         if (!memcmp(altname, &addr, altnamesize)) {
596                                 break;
597                         }
598                 }
599         }
600         if ( ret >= 0 ) {
601                 ret = LDAP_SUCCESS;
602         } else {
603                 /* find the last CN */
604                 i=0;
605                 do {
606                         altnamesize = 0;
607                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
608                                 i, 1, altname, &altnamesize );
609                         if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
610                                 i++;
611                         else
612                                 break;
613                 } while ( 1 );
614
615                 if ( i ) {
616                         altnamesize = sizeof(altname);
617                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
618                                 i-1, 0, altname, &altnamesize );
619                 }
620
621                 if ( ret < 0 ) {
622                         Debug( LDAP_DEBUG_ANY,
623                                 "TLS: unable to get common name from peer certificate.\n",
624                                 0, 0, 0 );
625                         ret = LDAP_CONNECT_ERROR;
626                         if ( ld->ld_error ) {
627                                 LDAP_FREE( ld->ld_error );
628                         }
629                         ld->ld_error = LDAP_STRDUP(
630                                 _("TLS: unable to get CN from peer certificate"));
631
632                 } else {
633                         ret = LDAP_LOCAL_ERROR;
634                         if ( !len1 ) len1 = strlen( name );
635                         if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
636                                 ret = LDAP_SUCCESS;
637
638                         } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
639                                         /* Is this a wildcard match? */
640                                 if( domain &&
641                                         (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
642                                         ret = LDAP_SUCCESS;
643                                 }
644                         }
645                 }
646
647                 if( ret == LDAP_LOCAL_ERROR ) {
648                         altname[altnamesize] = '\0';
649                         Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
650                                 "common name in certificate (%s).\n", 
651                                 name, altname, 0 );
652                         ret = LDAP_CONNECT_ERROR;
653                         if ( ld->ld_error ) {
654                                 LDAP_FREE( ld->ld_error );
655                         }
656                         ld->ld_error = LDAP_STRDUP(
657                                 _("TLS: hostname does not match CN in peer certificate"));
658                 }
659         }
660         gnutls_x509_crt_deinit( cert );
661         return ret;
662 }
663
664 static int
665 tlsg_session_strength( tls_session *session )
666 {
667         tlsg_session *s = (tlsg_session *)session;
668         gnutls_cipher_algorithm_t c;
669
670         c = gnutls_cipher_get( s->session );
671         return gnutls_cipher_get_key_size( c ) * 8;
672 }
673
674 /* suites is a string of colon-separated cipher suite names. */
675 static int
676 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
677 {
678         const char *err;
679         int rc = gnutls_priority_init( &ctx->prios, suites, &err );
680         if ( rc )
681                 ctx->prios = NULL;
682         return rc;
683 }
684
685 /*
686  * TLS support for LBER Sockbufs
687  */
688
689 struct tls_data {
690         tlsg_session            *session;
691         Sockbuf_IO_Desc         *sbiod;
692 };
693
694 static ssize_t
695 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
696 {
697         struct tls_data         *p;
698
699         if ( buf == NULL || len <= 0 ) return 0;
700
701         p = (struct tls_data *)ptr;
702
703         if ( p == NULL || p->sbiod == NULL ) {
704                 return 0;
705         }
706
707         return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
708 }
709
710 static ssize_t
711 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
712 {
713         struct tls_data         *p;
714         
715         if ( buf == NULL || len <= 0 ) return 0;
716         
717         p = (struct tls_data *)ptr;
718
719         if ( p == NULL || p->sbiod == NULL ) {
720                 return 0;
721         }
722
723         return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
724 }
725
726 static int
727 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
728 {
729         struct tls_data         *p;
730         tlsg_session    *session = arg;
731
732         assert( sbiod != NULL );
733
734         p = LBER_MALLOC( sizeof( *p ) );
735         if ( p == NULL ) {
736                 return -1;
737         }
738         
739         gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr)p );
740         gnutls_transport_set_pull_function( session->session, tlsg_recv );
741         gnutls_transport_set_push_function( session->session, tlsg_send );
742         p->session = session;
743         p->sbiod = sbiod;
744         sbiod->sbiod_pvt = p;
745         return 0;
746 }
747
748 static int
749 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
750 {
751         struct tls_data         *p;
752         
753         assert( sbiod != NULL );
754         assert( sbiod->sbiod_pvt != NULL );
755
756         p = (struct tls_data *)sbiod->sbiod_pvt;
757         gnutls_deinit ( p->session->session );
758         LBER_FREE( p->session );
759         LBER_FREE( sbiod->sbiod_pvt );
760         sbiod->sbiod_pvt = NULL;
761         return 0;
762 }
763
764 static int
765 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
766 {
767         struct tls_data         *p;
768         
769         assert( sbiod != NULL );
770         assert( sbiod->sbiod_pvt != NULL );
771
772         p = (struct tls_data *)sbiod->sbiod_pvt;
773         gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
774         return 0;
775 }
776
777 static int
778 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
779 {
780         struct tls_data         *p;
781         
782         assert( sbiod != NULL );
783         assert( sbiod->sbiod_pvt != NULL );
784
785         p = (struct tls_data *)sbiod->sbiod_pvt;
786         
787         if ( opt == LBER_SB_OPT_GET_SSL ) {
788                 *((tlsg_session **)arg) = p->session;
789                 return 1;
790                 
791         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
792                 if( gnutls_record_check_pending( p->session->session ) > 0 ) {
793                         return 1;
794                 }
795         }
796         
797         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
798 }
799
800 static ber_slen_t
801 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
802 {
803         struct tls_data         *p;
804         ber_slen_t              ret;
805
806         assert( sbiod != NULL );
807         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
808
809         p = (struct tls_data *)sbiod->sbiod_pvt;
810
811         ret = gnutls_record_recv ( p->session->session, buf, len );
812         switch (ret) {
813         case GNUTLS_E_INTERRUPTED:
814         case GNUTLS_E_AGAIN:
815                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
816                 sock_errset(EWOULDBLOCK);
817                 ret = 0;
818                 break;
819         case GNUTLS_E_REHANDSHAKE:
820                 for ( ret = gnutls_handshake ( p->session->session );
821                       ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
822                       ret = gnutls_handshake ( p->session->session ) );
823                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
824                 ret = 0;
825                 break;
826         default:
827                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
828         }
829         return ret;
830 }
831
832 static ber_slen_t
833 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
834 {
835         struct tls_data         *p;
836         ber_slen_t              ret;
837
838         assert( sbiod != NULL );
839         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
840
841         p = (struct tls_data *)sbiod->sbiod_pvt;
842
843         ret = gnutls_record_send ( p->session->session, (char *)buf, len );
844
845         if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
846                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
847                 sock_errset(EWOULDBLOCK);
848                 ret = 0;
849         } else {
850                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
851         }
852         return ret;
853 }
854
855 static Sockbuf_IO tlsg_sbio =
856 {
857         tlsg_sb_setup,          /* sbi_setup */
858         tlsg_sb_remove,         /* sbi_remove */
859         tlsg_sb_ctrl,           /* sbi_ctrl */
860         tlsg_sb_read,           /* sbi_read */
861         tlsg_sb_write,          /* sbi_write */
862         tlsg_sb_close           /* sbi_close */
863 };
864
865 /* Certs are not automatically varified during the handshake */
866 static int
867 tlsg_cert_verify( tlsg_session *ssl )
868 {
869         unsigned int status = 0;
870         int err;
871         time_t now = time(0);
872         time_t peertime;
873
874         err = gnutls_certificate_verify_peers2( ssl->session, &status );
875         if ( err < 0 ) {
876                 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
877                         err,0,0 );
878                 return -1;
879         }
880         if ( status ) {
881                 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
882                         status, 0,0 );
883                 return -1;
884         }
885         peertime = gnutls_certificate_expiration_time_peers( ssl->session );
886         if ( peertime == (time_t) -1 ) {
887                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
888                         0, 0, 0 );
889                 return -1;
890         }
891         if ( peertime < now ) {
892                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
893                         0, 0, 0 );
894                 return -1;
895         }
896         peertime = gnutls_certificate_activation_time_peers( ssl->session );
897         if ( peertime == (time_t) -1 ) {
898                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
899                         0, 0, 0 );
900                 return -1;
901         }
902         if ( peertime > now ) {
903                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
904                         0, 0, 0 );
905                 return -1;
906         }
907         return 0;
908 }
909
910 tls_impl ldap_int_tls_impl = {
911         "GnuTLS",
912
913         tlsg_init,
914         tlsg_destroy,
915
916         tlsg_ctx_new,
917         tlsg_ctx_ref,
918         tlsg_ctx_free,
919         tlsg_ctx_init,
920
921         tlsg_session_new,
922         tlsg_session_connect,
923         tlsg_session_accept,
924         tlsg_session_upflags,
925         tlsg_session_errmsg,
926         tlsg_session_my_dn,
927         tlsg_session_peer_dn,
928         tlsg_session_chkhost,
929         tlsg_session_strength,
930
931         &tlsg_sbio,
932
933 #ifdef LDAP_R_COMPILE
934         tlsg_thr_init,
935 #else
936         NULL,
937 #endif
938
939         0
940 };
941
942 #endif /* HAVE_GNUTLS */