- Support for adding a single file rather than a directory as CA path
[vlc.git] / modules / misc / gnutls.c
1 /*****************************************************************************
2  * gnutls.c
3  *****************************************************************************
4  * Copyright (C) 2004-2006 Rémi Denis-Courmont
5  * $Id$
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*
25  * TODO:
26  * - fix FIXMEs
27  */
28
29
30 /*****************************************************************************
31  * Preamble
32  *****************************************************************************/
33 #include <stdlib.h>
34 #include <errno.h>
35 #include <vlc/vlc.h>
36
37 #include <sys/types.h>
38 #include <errno.h>
39 #ifdef HAVE_DIRENT_H
40 # include <dirent.h>
41 #endif
42 #ifdef HAVE_SYS_STAT_H
43 # include <sys/stat.h>
44 # ifdef HAVE_UNISTD_H
45 #  include <unistd.h>
46 # endif
47 #endif
48
49
50 #include "vlc_tls.h"
51 #include "charset.h"
52
53 #include <gcrypt.h>
54 #include <gnutls/gnutls.h>
55 #include <gnutls/x509.h>
56
57 #define DH_BITS             1024
58 #define CACHE_EXPIRATION    3600
59 #define CACHE_SIZE          64
60
61 /*****************************************************************************
62  * Module descriptor
63  *****************************************************************************/
64 static int  Open ( vlc_object_t * );
65 static void Close( vlc_object_t * );
66
67 #define DH_BITS_TEXT N_("Diffie-Hellman prime bits")
68 #define DH_BITS_LONGTEXT N_( \
69     "Allows you to modify the Diffie-Hellman prime's number of bits " \
70     "(used for TLS or SSL-based server-side encryption)." )
71
72 #define CACHE_EXPIRATION_TEXT N_("Expiration time for resumed TLS sessions")
73 #define CACHE_EXPIRATION_LONGTEXT N_( \
74     "Defines the delay before resumed TLS sessions will be expired " \
75     "(in seconds)." )
76
77 #define CACHE_SIZE_TEXT N_("Number of resumed TLS sessions")
78 #define CACHE_SIZE_LONGTEXT N_( \
79     "Allows you to modify the maximum number of resumed TLS sessions that " \
80     "the cache will hold." )
81
82 #define CHECK_CERT_TEXT N_("Check TLS/SSL server certificate validity")
83 #define CHECK_CERT_LONGTEXT N_( \
84     "Ensures that server certificate is valid " \
85     "(i.e. signed by an approved Certificate Authority)." )
86
87 #define CHECK_HOSTNAME_TEXT N_("Check TLS/SSL server hostname in certificate")
88 #define CHECK_HOSTNAME_LONGTEXT N_( \
89     "Ensures that server hostname in certificate match requested host name." )
90
91 #if defined (WIN32) || defined (UNDER_CE)
92 # undef HOST_CA_PATH
93 #else
94 # define HOST_CA_PATH "/etc/ssl/certs/ca-certificates.crt"
95 #endif
96
97 vlc_module_begin();
98     set_shortname( "GnuTLS" );
99     set_description( _("GnuTLS TLS encryption layer") );
100     set_capability( "tls", 1 );
101     set_callbacks( Open, Close );
102     set_category( CAT_ADVANCED );
103     set_subcategory( SUBCAT_ADVANCED_MISC );
104
105     add_bool( "tls-check-cert", VLC_TRUE, NULL, CHECK_CERT_TEXT,
106               CHECK_CERT_LONGTEXT, VLC_FALSE );
107     add_bool( "tls-check-hostname", VLC_TRUE, NULL, CHECK_HOSTNAME_TEXT,
108               CHECK_HOSTNAME_LONGTEXT, VLC_FALSE );
109
110     add_integer( "gnutls-dh-bits", DH_BITS, NULL, DH_BITS_TEXT,
111                  DH_BITS_LONGTEXT, VLC_TRUE );
112     add_integer( "gnutls-cache-expiration", CACHE_EXPIRATION, NULL,
113                  CACHE_EXPIRATION_TEXT, CACHE_EXPIRATION_LONGTEXT, VLC_TRUE );
114     add_integer( "gnutls-cache-size", CACHE_SIZE, NULL, CACHE_SIZE_TEXT,
115                  CACHE_SIZE_LONGTEXT, VLC_TRUE );
116 vlc_module_end();
117
118
119 #define MAX_SESSION_ID    32
120 #define MAX_SESSION_DATA  1024
121
122 typedef struct saved_session_t
123 {
124     char id[MAX_SESSION_ID];
125     char data[MAX_SESSION_DATA];
126
127     unsigned i_idlen;
128     unsigned i_datalen;
129 } saved_session_t;
130
131
132 typedef struct tls_server_sys_t
133 {
134     gnutls_certificate_credentials  x509_cred;
135     gnutls_dh_params                dh_params;
136
137     struct saved_session_t          *p_cache;
138     struct saved_session_t          *p_store;
139     int                             i_cache_size;
140     vlc_mutex_t                     cache_lock;
141
142     int                             (*pf_handshake2)( tls_session_t * );
143 } tls_server_sys_t;
144
145
146 typedef struct tls_session_sys_t
147 {
148     gnutls_session  session;
149     char            *psz_hostname;
150     vlc_bool_t      b_handshaked;
151 } tls_session_sys_t;
152
153
154 typedef struct tls_client_sys_t
155 {
156     struct tls_session_sys_t       session;
157     gnutls_certificate_credentials x509_cred;
158 } tls_client_sys_t;
159
160
161 static int
162 _get_Int( vlc_object_t *p_this, const char *var )
163 {
164     vlc_value_t value;
165
166     if( var_Get( p_this, var, &value ) != VLC_SUCCESS )
167     {
168         var_Create( p_this, var, VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
169         var_Get( p_this, var, &value );
170     }
171
172     return value.i_int;
173 }
174
175 static int
176 _get_Bool( vlc_object_t *p_this, const char *var )
177 {
178     vlc_value_t value;
179
180     if( var_Get( p_this, var, &value ) != VLC_SUCCESS )
181     {
182         var_Create( p_this, var, VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
183         var_Get( p_this, var, &value );
184     }
185
186     return value.b_bool;
187 }
188
189 #define get_Int( a, b ) _get_Int( (vlc_object_t *)(a), (b) )
190 #define get_Bool( a, b ) _get_Bool( (vlc_object_t *)(a), (b) )
191
192
193 /*****************************************************************************
194  * tls_Send:
195  *****************************************************************************
196  * Sends data through a TLS session.
197  *****************************************************************************/
198 static int
199 gnutls_Send( void *p_session, const void *buf, int i_length )
200 {
201     int val;
202     tls_session_sys_t *p_sys;
203
204     p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
205
206     val = gnutls_record_send( p_sys->session, buf, i_length );
207     /* TODO: handle fatal error */
208     return val < 0 ? -1 : val;
209 }
210
211
212 /*****************************************************************************
213  * tls_Recv:
214  *****************************************************************************
215  * Receives data through a TLS session.
216  *****************************************************************************/
217 static int
218 gnutls_Recv( void *p_session, void *buf, int i_length )
219 {
220     int val;
221     tls_session_sys_t *p_sys;
222
223     p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
224
225     val = gnutls_record_recv( p_sys->session, buf, i_length );
226     /* TODO: handle fatal error */
227     return val < 0 ? -1 : val;
228 }
229
230
231 /*****************************************************************************
232  * tls_Session(Continue)?Handshake:
233  *****************************************************************************
234  * Establishes TLS session with a peer through socket <fd>.
235  * Returns -1 on error (you need not and must not call tls_SessionClose)
236  * 0 on succesful handshake completion, 1 if more would-be blocking recv is
237  * needed, 2 if more would-be blocking send is required.
238  *****************************************************************************/
239 static int
240 gnutls_ContinueHandshake( tls_session_t *p_session)
241 {
242     tls_session_sys_t *p_sys;
243     int val;
244
245     p_sys = (tls_session_sys_t *)(p_session->p_sys);
246
247      /* TODO: handle fatal error */
248     val = gnutls_handshake( p_sys->session );
249     if( ( val == GNUTLS_E_AGAIN ) || ( val == GNUTLS_E_INTERRUPTED ) )
250         return 1 + gnutls_record_get_direction( p_sys->session );
251
252     if( val < 0 )
253     {
254         msg_Err( p_session, "TLS handshake failed: %s",
255                  gnutls_strerror( val ) );
256         p_session->pf_close( p_session );
257         return -1;
258     }
259
260     p_sys->b_handshaked = VLC_TRUE;
261     return 0;
262 }
263
264 static int
265 gnutls_VerifyHostname( vlc_object_t *p_this, gnutls_session session,
266                        const char *psz_hostname )
267 {
268     const gnutls_datum *p_data;
269     gnutls_x509_crt cert;
270     unsigned status;
271     int val;
272
273     /* certificate (host)name verification */
274     p_data = gnutls_certificate_get_peers( session, &status );
275     if( p_data == NULL )
276     {
277         msg_Err( p_this, "TLS peer certificate not available" );
278         return -1;
279     }
280
281     val = gnutls_x509_crt_init( &cert );
282     if( val )
283     {
284         msg_Err( p_this, "x509 fatal error: %s", gnutls_strerror( val ) );
285         return -1;
286     }
287
288     val = gnutls_x509_crt_import( cert, p_data, GNUTLS_X509_FMT_DER );
289     if( val )
290     {
291         msg_Err( p_this, "x509 certificate import error: %s",
292                 gnutls_strerror( val ) );
293         gnutls_x509_crt_deinit( cert );
294         return -1;
295     }
296
297     if( gnutls_x509_crt_check_hostname( cert, psz_hostname ) == 0 )
298     {
299         msg_Err( p_this, "x509 certificate does not match \"%s\"",
300                 psz_hostname );
301         gnutls_x509_crt_deinit( cert );
302         return -1;
303     }
304
305     gnutls_x509_crt_deinit( cert );
306     msg_Dbg( p_this, "x509 hostname matches %s", psz_hostname );
307     return 0;
308 }
309
310 static int
311 gnutls_HandshakeAndValidate( tls_session_t *p_session )
312 {
313     int val;
314
315     val = gnutls_ContinueHandshake( p_session );
316     if( val == 0 )
317     {
318         unsigned status;
319         tls_session_sys_t *p_sys;
320
321         p_sys = (tls_session_sys_t *)(p_session->p_sys);
322         /* certificates chain verification */
323         val = gnutls_certificate_verify_peers2( p_sys->session, &status );
324
325         if( val )
326         {
327             msg_Err( p_session, "TLS certificate verification failed: %s",
328                      gnutls_strerror( val ) );
329             p_session->pf_close( p_session );
330             return -1;
331         }
332
333         if( status )
334         {
335             msg_Warn( p_session, "TLS session: access denied" );
336             if( status & GNUTLS_CERT_INVALID )
337                 msg_Dbg( p_session, "certificate could not be verified" );
338             if( status & GNUTLS_CERT_REVOKED )
339                 msg_Dbg( p_session, "certificate was revoked" );
340             if( status & GNUTLS_CERT_SIGNER_NOT_FOUND )
341                 msg_Dbg( p_session, "certificate's signer was not found" );
342             if( status & GNUTLS_CERT_SIGNER_NOT_CA )
343                 msg_Dbg( p_session, "certificate's signer is not a CA" );
344             p_session->pf_close( p_session );
345             return -1;
346         }
347
348         msg_Dbg( p_session, "TLS certificate verified" );
349         if( ( p_sys->psz_hostname != NULL )
350          && gnutls_VerifyHostname( (vlc_object_t *)p_session, p_sys->session,
351                                    p_sys->psz_hostname ) )
352         {
353             p_session->pf_close( p_session );
354             return -1;
355         }
356         return 0;
357     }
358
359     return val;
360 }
361
362 static int
363 gnutls_BeginHandshake( tls_session_t *p_session, int fd,
364                          const char *psz_hostname )
365 {
366     tls_session_sys_t *p_sys;
367
368     p_sys = (tls_session_sys_t *)(p_session->p_sys);
369
370     gnutls_transport_set_ptr (p_sys->session, (gnutls_transport_ptr)(intptr_t)fd);
371
372     if( psz_hostname != NULL )
373     {
374         gnutls_server_name_set( p_sys->session, GNUTLS_NAME_DNS, psz_hostname,
375                                 strlen( psz_hostname ) );
376         if( get_Bool( p_session, "tls-check-hostname" ) )
377         {
378             p_sys->psz_hostname = strdup( psz_hostname );
379             if( p_sys->psz_hostname == NULL )
380             {
381                 p_session->pf_close( p_session );
382                 return -1;
383             }
384         }
385     }
386
387     return p_session->pf_handshake2( p_session );
388 }
389
390 /*****************************************************************************
391  * tls_SessionClose:
392  *****************************************************************************
393  * Terminates TLS session and releases session data.
394  *****************************************************************************/
395 static void
396 gnutls_SessionClose( tls_session_t *p_session )
397 {
398     tls_session_sys_t *p_sys;
399
400     p_sys = (tls_session_sys_t *)(p_session->p_sys);
401
402     if( p_sys->b_handshaked == VLC_TRUE )
403         gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
404     gnutls_deinit( p_sys->session );
405
406     if( p_sys->psz_hostname != NULL )
407         free( p_sys->psz_hostname );
408
409     vlc_object_detach( p_session );
410     vlc_object_destroy( p_session );
411
412     free( p_sys );
413 }
414
415 static void
416 gnutls_ClientDelete( tls_session_t *p_session )
417 {
418     /* On the client-side, credentials are re-allocated per session */
419     gnutls_certificate_credentials x509_cred =
420                         ((tls_client_sys_t *)(p_session->p_sys))->x509_cred;
421
422     gnutls_SessionClose( p_session );
423
424     /* credentials must be free'd *after* gnutls_deinit() */
425     gnutls_certificate_free_credentials( x509_cred );
426 }
427
428
429 static int
430 gnutls_Addx509File( vlc_object_t *p_this,
431                     gnutls_certificate_credentials cred,
432                     const char *psz_path, vlc_bool_t b_priv );
433
434 static int
435 gnutls_Addx509Directory( vlc_object_t *p_this,
436                          gnutls_certificate_credentials cred,
437                          const char *psz_dirname,
438                          vlc_bool_t b_priv )
439 {
440     DIR* dir;
441     const char *psz_dirent;
442
443     if( *psz_dirname == '\0' )
444         psz_dirname = ".";
445
446     dir = utf8_opendir( psz_dirname );
447     if( dir == NULL )
448     {
449         msg_Warn( p_this, "Cannot open directory (%s): %s", psz_dirname,
450                   strerror( errno ) );
451         return VLC_EGENERIC;
452     }
453 #ifdef S_ISLNK
454     else
455     {
456         struct stat st1, st2;
457         int fd = dirfd( dir );
458
459         /*
460          * Gets stats for the directory path, checks that it is not a
461          * symbolic link (to avoid possibly infinite recursion), and verifies
462          * that the inode is still the same, to avoid TOCTOU race condition.
463          */
464         if( ( fd == -1)
465          || fstat( fd, &st1 ) || utf8_lstat( psz_dirname, &st2 )
466          || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
467         {
468             closedir( dir );
469             return VLC_EGENERIC;
470         }
471     }
472 #endif
473
474     while( ( psz_dirent = utf8_readdir( dir ) ) != NULL )
475     {
476         char *psz_filename;
477         int check;
478
479         if( ( strcmp( ".", psz_dirent ) == 0 )
480          || ( strcmp( "..", psz_dirent ) == 0 ) )
481             continue;
482
483         check = asprintf( &psz_filename, "%s/%s", psz_dirname,
484                               psz_dirent );
485         LocaleFree( psz_dirent );
486         if( check == -1 )
487             continue;
488
489         gnutls_Addx509File( p_this, cred, psz_filename, b_priv );
490         free( psz_filename );
491     }
492
493     closedir( dir );
494     return VLC_SUCCESS;
495 }
496
497
498 static int
499 gnutls_Addx509File( vlc_object_t *p_this,
500                     gnutls_certificate_credentials cred,
501                     const char *psz_path, vlc_bool_t b_priv )
502 {
503     struct stat st;
504
505     if( utf8_stat( psz_path, &st ) == 0 )
506     {
507         if( S_ISREG( st.st_mode ) )
508         {
509             char *psz_localname = ToLocale( psz_path );
510             int i = b_priv
511                     ? gnutls_certificate_set_x509_key_file( cred,
512                     psz_localname,  psz_localname, GNUTLS_X509_FMT_PEM )
513                 : gnutls_certificate_set_x509_trust_file( cred,
514                         psz_localname, GNUTLS_X509_FMT_PEM );
515             LocaleFree( psz_localname );
516
517             if( i < 0 )
518             {
519                 msg_Warn( p_this, "Cannot add x509 credentials (%s): %s",
520                           psz_path, gnutls_strerror( i ) );
521                 return VLC_EGENERIC;
522             }
523             else
524             {
525                 msg_Dbg( p_this, "Added x509 credentials (%s)",
526                          psz_path );
527                 return VLC_SUCCESS;
528             }
529         }
530         else if( S_ISDIR( st.st_mode ) )
531         {
532             msg_Dbg( p_this,
533                      "Looking recursively for x509 credentials in %s",
534                      psz_path );
535             return gnutls_Addx509Directory( p_this, cred, psz_path, b_priv);
536         }
537     }
538     return VLC_EGENERIC;
539 }
540
541
542 /*****************************************************************************
543  * tls_ClientCreate:
544  *****************************************************************************
545  * Initializes client-side TLS session data.
546  *****************************************************************************/
547 static tls_session_t *
548 gnutls_ClientCreate( tls_t *p_tls )
549 {
550     tls_session_t *p_session = NULL;
551     tls_client_sys_t *p_sys = NULL;
552     int i_val;
553     const int cert_type_priority[3] =
554     {
555         GNUTLS_CRT_X509,
556         0
557     };
558
559     p_sys = (tls_client_sys_t *)malloc( sizeof(struct tls_client_sys_t) );
560     if( p_sys == NULL )
561         return NULL;
562
563     p_session = (struct tls_session_t *)vlc_object_create ( p_tls, sizeof(struct tls_session_t) );
564     if( p_session == NULL )
565     {
566         free( p_sys );
567         return NULL;
568     }
569
570     p_session->p_sys = p_sys;
571     p_session->sock.p_sys = p_session;
572     p_session->sock.pf_send = gnutls_Send;
573     p_session->sock.pf_recv = gnutls_Recv;
574     p_session->pf_handshake = gnutls_BeginHandshake;
575     p_session->pf_close = gnutls_ClientDelete;
576
577     p_sys->session.b_handshaked = VLC_FALSE;
578     p_sys->session.psz_hostname = NULL;
579
580     vlc_object_attach( p_session, p_tls );
581
582     i_val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
583     if( i_val != 0 )
584     {
585         msg_Err( p_tls, "Cannot allocate X509 credentials: %s",
586                  gnutls_strerror( i_val ) );
587         goto error;
588     }
589
590     if( get_Bool( p_tls, "tls-check-cert" ) )
591     {
592         char *psz_path;
593
594         if( asprintf( &psz_path, "%s/"CONFIG_DIR"/ssl/certs",
595                       p_tls->p_vlc->psz_homedir ) == -1 )
596         {
597             gnutls_certificate_free_credentials( p_sys->x509_cred );
598             goto error;
599         }
600
601         gnutls_Addx509Directory( (vlc_object_t *)p_session, p_sys->x509_cred,
602                                  psz_path, VLC_FALSE );
603 #ifdef HOST_CA_PATH
604         gnutls_Addx509File( (vlc_object_t *)p_session, p_sys->x509_cred,
605                             HOST_CA_PATH, VLC_FALSE );
606 #endif
607
608         free( psz_path );
609         p_session->pf_handshake2 = gnutls_HandshakeAndValidate;
610     }
611     else
612         p_session->pf_handshake2 = gnutls_ContinueHandshake;
613
614     {
615         char *psz_path;
616
617         if( asprintf( &psz_path, "%s/"CONFIG_DIR"/ssl/private",
618                       p_tls->p_vlc->psz_homedir ) == -1 )
619         {
620             gnutls_certificate_free_credentials( p_sys->x509_cred );
621             goto error;
622         }
623
624         gnutls_Addx509Directory( (vlc_object_t *)p_session, p_sys->x509_cred,
625                                  psz_path, VLC_TRUE );
626
627         free( psz_path );
628     }
629
630     i_val = gnutls_init( &p_sys->session.session, GNUTLS_CLIENT );
631     if( i_val != 0 )
632     {
633         msg_Err( p_tls, "Cannot initialize TLS session: %s",
634                  gnutls_strerror( i_val ) );
635         gnutls_certificate_free_credentials( p_sys->x509_cred );
636         goto error;
637     }
638
639     i_val = gnutls_set_default_priority( p_sys->session.session );
640     if( i_val < 0 )
641     {
642         msg_Err( p_tls, "Cannot set ciphers priorities: %s",
643                  gnutls_strerror( i_val ) );
644         gnutls_deinit( p_sys->session.session );
645         gnutls_certificate_free_credentials( p_sys->x509_cred );
646         goto error;
647     }
648
649     i_val = gnutls_certificate_type_set_priority( p_sys->session.session,
650                                                   cert_type_priority );
651     if( i_val < 0 )
652     {
653         msg_Err( p_tls, "Cannot set certificate type priorities: %s",
654                  gnutls_strerror( i_val ) );
655         gnutls_deinit( p_sys->session.session );
656         gnutls_certificate_free_credentials( p_sys->x509_cred );
657         goto error;
658     }
659
660     i_val = gnutls_credentials_set( p_sys->session.session,
661                                     GNUTLS_CRD_CERTIFICATE,
662                                     p_sys->x509_cred );
663     if( i_val < 0 )
664     {
665         msg_Err( p_tls, "Cannot set TLS session credentials: %s",
666                  gnutls_strerror( i_val ) );
667         gnutls_deinit( p_sys->session.session );
668         gnutls_certificate_free_credentials( p_sys->x509_cred );
669         goto error;
670     }
671
672     return p_session;
673
674 error:
675     vlc_object_detach( p_session );
676     vlc_object_destroy( p_session );
677     free( p_sys );
678
679     return NULL;
680 }
681
682
683 /*****************************************************************************
684  * TLS session resumption callbacks
685  *****************************************************************************/
686 static int cb_store( void *p_server, gnutls_datum key, gnutls_datum data )
687 {
688     tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
689
690     if( ( p_sys->i_cache_size == 0 )
691      || ( key.size > MAX_SESSION_ID )
692      || ( data.size > MAX_SESSION_DATA ) )
693         return -1;
694
695     vlc_mutex_lock( &p_sys->cache_lock );
696
697     memcpy( p_sys->p_store->id, key.data, key.size);
698     memcpy( p_sys->p_store->data, data.data, data.size );
699     p_sys->p_store->i_idlen = key.size;
700     p_sys->p_store->i_datalen = data.size;
701
702     p_sys->p_store++;
703     if( ( p_sys->p_store - p_sys->p_cache ) == p_sys->i_cache_size )
704         p_sys->p_store = p_sys->p_cache;
705
706     vlc_mutex_unlock( &p_sys->cache_lock );
707
708     return 0;
709 }
710
711
712 static const gnutls_datum err_datum = { NULL, 0 };
713
714 static gnutls_datum cb_fetch( void *p_server, gnutls_datum key )
715 {
716     tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
717     saved_session_t *p_session, *p_end;
718
719     p_session = p_sys->p_cache;
720     p_end = p_session + p_sys->i_cache_size;
721
722     vlc_mutex_lock( &p_sys->cache_lock );
723
724     while( p_session < p_end )
725     {
726         if( ( p_session->i_idlen == key.size )
727          && !memcmp( p_session->id, key.data, key.size ) )
728         {
729             gnutls_datum data;
730
731             data.size = p_session->i_datalen;
732
733             data.data = gnutls_malloc( data.size );
734             if( data.data == NULL )
735             {
736                 vlc_mutex_unlock( &p_sys->cache_lock );
737                 return err_datum;
738             }
739
740             memcpy( data.data, p_session->data, data.size );
741             vlc_mutex_unlock( &p_sys->cache_lock );
742             return data;
743         }
744         p_session++;
745     }
746
747     vlc_mutex_unlock( &p_sys->cache_lock );
748
749     return err_datum;
750 }
751
752
753 static int cb_delete( void *p_server, gnutls_datum key )
754 {
755     tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
756     saved_session_t *p_session, *p_end;
757
758     p_session = p_sys->p_cache;
759     p_end = p_session + p_sys->i_cache_size;
760
761     vlc_mutex_lock( &p_sys->cache_lock );
762
763     while( p_session < p_end )
764     {
765         if( ( p_session->i_idlen == key.size )
766          && !memcmp( p_session->id, key.data, key.size ) )
767         {
768             p_session->i_datalen = p_session->i_idlen = 0;
769             vlc_mutex_unlock( &p_sys->cache_lock );
770             return 0;
771         }
772         p_session++;
773     }
774
775     vlc_mutex_unlock( &p_sys->cache_lock );
776
777     return -1;
778 }
779
780
781 /*****************************************************************************
782  * tls_ServerSessionPrepare:
783  *****************************************************************************
784  * Initializes server-side TLS session data.
785  *****************************************************************************/
786 static tls_session_t *
787 gnutls_ServerSessionPrepare( tls_server_t *p_server )
788 {
789     tls_session_t *p_session;
790     tls_server_sys_t *p_server_sys;
791     gnutls_session session;
792     int i_val;
793
794     p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
795     if( p_session == NULL )
796         return NULL;
797
798     p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
799     if( p_session->p_sys == NULL )
800     {
801         vlc_object_destroy( p_session );
802         return NULL;
803     }
804
805     vlc_object_attach( p_session, p_server );
806
807     p_server_sys = (tls_server_sys_t *)p_server->p_sys;
808     p_session->sock.p_sys = p_session;
809     p_session->sock.pf_send = gnutls_Send;
810     p_session->sock.pf_recv = gnutls_Recv;
811     p_session->pf_handshake = gnutls_BeginHandshake;
812     p_session->pf_handshake2 = p_server_sys->pf_handshake2;
813     p_session->pf_close = gnutls_SessionClose;
814
815     ((tls_session_sys_t *)p_session->p_sys)->b_handshaked = VLC_FALSE;
816     ((tls_session_sys_t *)p_session->p_sys)->psz_hostname = NULL;
817
818     i_val = gnutls_init( &session, GNUTLS_SERVER );
819     if( i_val != 0 )
820     {
821         msg_Err( p_server, "Cannot initialize TLS session: %s",
822                  gnutls_strerror( i_val ) );
823         goto error;
824     }
825
826     ((tls_session_sys_t *)p_session->p_sys)->session = session;
827
828     i_val = gnutls_set_default_priority( session );
829     if( i_val < 0 )
830     {
831         msg_Err( p_server, "Cannot set ciphers priorities: %s",
832                  gnutls_strerror( i_val ) );
833         gnutls_deinit( session );
834         goto error;
835     }
836
837     i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
838                                     p_server_sys->x509_cred );
839     if( i_val < 0 )
840     {
841         msg_Err( p_server, "Cannot set TLS session credentials: %s",
842                  gnutls_strerror( i_val ) );
843         gnutls_deinit( session );
844         goto error;
845     }
846
847     if( p_session->pf_handshake2 == gnutls_HandshakeAndValidate )
848         gnutls_certificate_server_set_request( session, GNUTLS_CERT_REQUIRE );
849
850     gnutls_dh_set_prime_bits( session, get_Int( p_server, "gnutls-dh-bits" ) );
851
852     /* Session resumption support */
853     gnutls_db_set_cache_expiration( session, get_Int( p_server,
854                                     "gnutls-cache-expiration" ) );
855     gnutls_db_set_retrieve_function( session, cb_fetch );
856     gnutls_db_set_remove_function( session, cb_delete );
857     gnutls_db_set_store_function( session, cb_store );
858     gnutls_db_set_ptr( session, p_server );
859
860     return p_session;
861
862 error:
863     free( p_session->p_sys );
864     vlc_object_detach( p_session );
865     vlc_object_destroy( p_session );
866     return NULL;
867 }
868
869
870 /*****************************************************************************
871  * tls_ServerDelete:
872  *****************************************************************************
873  * Releases data allocated with tls_ServerCreate.
874  *****************************************************************************/
875 static void
876 gnutls_ServerDelete( tls_server_t *p_server )
877 {
878     tls_server_sys_t *p_sys;
879     p_sys = (tls_server_sys_t *)p_server->p_sys;
880
881     vlc_mutex_destroy( &p_sys->cache_lock );
882     free( p_sys->p_cache );
883
884     vlc_object_detach( p_server );
885     vlc_object_destroy( p_server );
886
887     /* all sessions depending on the server are now deinitialized */
888     gnutls_certificate_free_credentials( p_sys->x509_cred );
889     gnutls_dh_params_deinit( p_sys->dh_params );
890     free( p_sys );
891 }
892
893
894 /*****************************************************************************
895  * tls_ServerAddCA:
896  *****************************************************************************
897  * Adds one or more certificate authorities.
898  * Returns -1 on error, 0 on success.
899  *****************************************************************************/
900 static int
901 gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
902 {
903     tls_server_sys_t *p_sys;
904     char *psz_local_path;
905     int val;
906
907     p_sys = (tls_server_sys_t *)(p_server->p_sys);
908
909     psz_local_path = ToLocale( psz_ca_path );
910     val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
911                                                   psz_local_path,
912                                                   GNUTLS_X509_FMT_PEM );
913     LocaleFree( psz_local_path );
914     if( val < 0 )
915     {
916         msg_Err( p_server, "Cannot add trusted CA (%s): %s", psz_ca_path,
917                  gnutls_strerror( val ) );
918         return VLC_EGENERIC;
919     }
920     msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
921
922     /* enables peer's certificate verification */
923     p_sys->pf_handshake2 = gnutls_HandshakeAndValidate;
924
925     return VLC_SUCCESS;
926 }
927
928
929 /*****************************************************************************
930  * tls_ServerAddCRL:
931  *****************************************************************************
932  * Adds a certificates revocation list to be sent to TLS clients.
933  * Returns -1 on error, 0 on success.
934  *****************************************************************************/
935 static int
936 gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
937 {
938     int val;
939     char *psz_local_path = ToLocale( psz_crl_path );
940
941     val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
942                                                 (p_server->p_sys))->x509_cred,
943                                                 psz_local_path,
944                                                 GNUTLS_X509_FMT_PEM );
945     LocaleFree( psz_crl_path );
946     if( val < 0 )
947     {
948         msg_Err( p_server, "Cannot add CRL (%s): %s", psz_crl_path,
949                  gnutls_strerror( val ) );
950         return VLC_EGENERIC;
951     }
952     msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );
953     return VLC_SUCCESS;
954 }
955
956
957 /*****************************************************************************
958  * tls_ServerCreate:
959  *****************************************************************************
960  * Allocates a whole server's TLS credentials.
961  * Returns NULL on error.
962  *****************************************************************************/
963 static tls_server_t *
964 gnutls_ServerCreate( tls_t *p_tls, const char *psz_cert_path,
965                      const char *psz_key_path )
966 {
967     tls_server_t *p_server;
968     tls_server_sys_t *p_sys;
969     char *psz_local_key, *psz_local_cert;
970     int val;
971
972     msg_Dbg( p_tls, "Creating TLS server" );
973
974     p_sys = (tls_server_sys_t *)malloc( sizeof(struct tls_server_sys_t) );
975     if( p_sys == NULL )
976         return NULL;
977
978     p_sys->i_cache_size = get_Int( p_tls, "gnutls-cache-size" );
979     p_sys->p_cache = (struct saved_session_t *)calloc( p_sys->i_cache_size,
980                                            sizeof( struct saved_session_t ) );
981     if( p_sys->p_cache == NULL )
982     {
983         free( p_sys );
984         return NULL;
985     }
986     p_sys->p_store = p_sys->p_cache;
987
988     p_server = vlc_object_create( p_tls, sizeof(struct tls_server_t) );
989     if( p_server == NULL )
990     {
991         free( p_sys->p_cache );
992         free( p_sys );
993         return NULL;
994     }
995
996     vlc_object_attach( p_server, p_tls );
997
998     p_server->p_sys = p_sys;
999     p_server->pf_delete = gnutls_ServerDelete;
1000     p_server->pf_add_CA = gnutls_ServerAddCA;
1001     p_server->pf_add_CRL = gnutls_ServerAddCRL;
1002     p_server->pf_session_prepare = gnutls_ServerSessionPrepare;
1003
1004     /* No certificate validation by default */
1005     p_sys->pf_handshake2 = gnutls_ContinueHandshake;
1006
1007     /* FIXME: check for errors */
1008     vlc_mutex_init( p_server, &p_sys->cache_lock );
1009
1010     /* Sets server's credentials */
1011     val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
1012     if( val != 0 )
1013     {
1014         msg_Err( p_server, "Cannot allocate X509 credentials: %s",
1015                  gnutls_strerror( val ) );
1016         goto error;
1017     }
1018
1019     psz_local_cert = ToLocale( psz_cert_path );
1020     psz_local_key = ToLocale( psz_key_path );
1021     val = gnutls_certificate_set_x509_key_file( p_sys->x509_cred,
1022                                                 psz_local_cert, psz_local_key,
1023                                                 GNUTLS_X509_FMT_PEM );
1024     LocaleFree( psz_cert_path );
1025     LocaleFree( psz_key_path );
1026     if( val < 0 )
1027     {
1028         msg_Err( p_server, "Cannot set certificate chain or private key: %s",
1029                  gnutls_strerror( val ) );
1030         gnutls_certificate_free_credentials( p_sys->x509_cred );
1031         goto error;
1032     }
1033
1034     /* FIXME:
1035      * - regenerate these regularly
1036      * - support other ciper suites
1037      */
1038     val = gnutls_dh_params_init( &p_sys->dh_params );
1039     if( val >= 0 )
1040     {
1041         msg_Dbg( p_server, "Computing Diffie Hellman ciphers parameters" );
1042         val = gnutls_dh_params_generate2( p_sys->dh_params,
1043                                           get_Int( p_tls, "gnutls-dh-bits" ) );
1044     }
1045     if( val < 0 )
1046     {
1047         msg_Err( p_server, "Cannot initialize DH cipher suites: %s",
1048                  gnutls_strerror( val ) );
1049         gnutls_certificate_free_credentials( p_sys->x509_cred );
1050         goto error;
1051     }
1052     msg_Dbg( p_server, "Ciphers parameters computed" );
1053
1054     gnutls_certificate_set_dh_params( p_sys->x509_cred, p_sys->dh_params);
1055
1056     return p_server;
1057
1058 error:
1059     vlc_mutex_destroy( &p_sys->cache_lock );
1060     vlc_object_detach( p_server );
1061     vlc_object_destroy( p_server );
1062     free( p_sys );
1063     return NULL;
1064 }
1065
1066
1067 /*****************************************************************************
1068  * gcrypt thread option VLC implementation:
1069  *****************************************************************************/
1070 vlc_object_t *__p_gcry_data;
1071
1072 static int gcry_vlc_mutex_init( void **p_sys )
1073 {
1074     int i_val;
1075     vlc_mutex_t *p_lock = (vlc_mutex_t *)malloc( sizeof( vlc_mutex_t ) );
1076
1077     if( p_lock == NULL)
1078         return ENOMEM;
1079
1080     i_val = vlc_mutex_init( __p_gcry_data, p_lock );
1081     if( i_val )
1082         free( p_lock );
1083     else
1084         *p_sys = p_lock;
1085     return i_val;
1086 }
1087
1088 static int gcry_vlc_mutex_destroy( void **p_sys )
1089 {
1090     int i_val;
1091     vlc_mutex_t *p_lock = (vlc_mutex_t *)*p_sys;
1092
1093     i_val = vlc_mutex_destroy( p_lock );
1094     free( p_lock );
1095     return i_val;
1096 }
1097
1098 static int gcry_vlc_mutex_lock( void **p_sys )
1099 {
1100     return vlc_mutex_lock( (vlc_mutex_t *)*p_sys );
1101 }
1102
1103 static int gcry_vlc_mutex_unlock( void **lock )
1104 {
1105     return vlc_mutex_unlock( (vlc_mutex_t *)*lock );
1106 }
1107
1108 static struct gcry_thread_cbs gcry_threads_vlc =
1109 {
1110     GCRY_THREAD_OPTION_USER,
1111     NULL,
1112     gcry_vlc_mutex_init,
1113     gcry_vlc_mutex_destroy,
1114     gcry_vlc_mutex_lock,
1115     gcry_vlc_mutex_unlock
1116 };
1117
1118
1119 /*****************************************************************************
1120  * Module initialization
1121  *****************************************************************************/
1122 static int
1123 Open( vlc_object_t *p_this )
1124 {
1125     tls_t *p_tls = (tls_t *)p_this;
1126
1127     vlc_value_t lock, count;
1128
1129     var_Create( p_this->p_libvlc, "gnutls_mutex", VLC_VAR_MUTEX );
1130     var_Get( p_this->p_libvlc, "gnutls_mutex", &lock );
1131     vlc_mutex_lock( lock.p_address );
1132
1133     /* Initialize GnuTLS only once */
1134     var_Create( p_this->p_libvlc, "gnutls_count", VLC_VAR_INTEGER );
1135     var_Get( p_this->p_libvlc, "gnutls_count", &count);
1136
1137     if( count.i_int == 0)
1138     {
1139         const char *psz_version;
1140
1141         __p_gcry_data = VLC_OBJECT( p_this->p_vlc );
1142
1143         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_vlc);
1144         if( gnutls_global_init( ) )
1145         {
1146             msg_Warn( p_this, "cannot initialize GnuTLS" );
1147             vlc_mutex_unlock( lock.p_address );
1148             return VLC_EGENERIC;
1149         }
1150         /*
1151          * FIXME: in fact, we currently depends on 1.0.17, but it breaks on
1152          * Debian which as a patched 1.0.16 (which we can use).
1153          */
1154         psz_version = gnutls_check_version( "1.0.16" );
1155         if( psz_version == NULL )
1156         {
1157             gnutls_global_deinit( );
1158             vlc_mutex_unlock( lock.p_address );
1159             msg_Err( p_this, "unsupported GnuTLS version" );
1160             return VLC_EGENERIC;
1161         }
1162         msg_Dbg( p_this, "GnuTLS v%s initialized", psz_version );
1163     }
1164
1165     count.i_int++;
1166     var_Set( p_this->p_libvlc, "gnutls_count", count);
1167     vlc_mutex_unlock( lock.p_address );
1168
1169     p_tls->pf_server_create = gnutls_ServerCreate;
1170     p_tls->pf_client_create = gnutls_ClientCreate;
1171     return VLC_SUCCESS;
1172 }
1173
1174
1175 /*****************************************************************************
1176  * Module deinitialization
1177  *****************************************************************************/
1178 static void
1179 Close( vlc_object_t *p_this )
1180 {
1181     /*tls_t *p_tls = (tls_t *)p_this;
1182     tls_sys_t *p_sys = (tls_sys_t *)(p_this->p_sys);*/
1183
1184     vlc_value_t lock, count;
1185
1186     var_Create( p_this->p_libvlc, "gnutls_mutex", VLC_VAR_MUTEX );
1187     var_Get( p_this->p_libvlc, "gnutls_mutex", &lock );
1188     vlc_mutex_lock( lock.p_address );
1189
1190     var_Create( p_this->p_libvlc, "gnutls_count", VLC_VAR_INTEGER );
1191     var_Get( p_this->p_libvlc, "gnutls_count", &count);
1192     count.i_int--;
1193     var_Set( p_this->p_libvlc, "gnutls_count", count);
1194
1195     if( count.i_int == 0 )
1196     {
1197         gnutls_global_deinit( );
1198         msg_Dbg( p_this, "GnuTLS deinitialized" );
1199     }
1200
1201     vlc_mutex_unlock( lock.p_address );
1202 }