60f7a5b175088c6f617c6ca54cf4ff6cc049f0d6
[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"
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_HandshakeAndValidate( tls_session_t *p_session )
266 {
267     int val;
268
269     val = gnutls_ContinueHandshake( p_session );
270     if( val == 0 )
271     {
272         unsigned status;
273         gnutls_x509_crt cert;
274         const gnutls_datum *p_data;
275         tls_session_sys_t *p_sys;
276
277         p_sys = (tls_session_sys_t *)(p_session->p_sys);
278         /* certificates chain verification */
279         val = gnutls_certificate_verify_peers2( p_sys->session, &status );
280
281         if( val )
282         {
283             msg_Err( p_session, "TLS certificate verification failed: %s",
284                      gnutls_strerror( val ) );
285             p_session->pf_close( p_session );
286             return -1;
287         }
288
289         if( status )
290         {
291             msg_Warn( p_session, "TLS session: access denied" );
292             if( status & GNUTLS_CERT_INVALID )
293                 msg_Dbg( p_session, "certificate could not be verified" );
294             if( status & GNUTLS_CERT_REVOKED )
295                 msg_Dbg( p_session, "certificate was revoked" );
296             if( status & GNUTLS_CERT_SIGNER_NOT_FOUND )
297                 msg_Dbg( p_session, "certificate's signer was not found" );
298             if( status & GNUTLS_CERT_SIGNER_NOT_CA )
299                 msg_Dbg( p_session, "certificate's signer is not a CA" );
300             p_session->pf_close( p_session );
301             return -1;
302         }
303
304         msg_Dbg( p_session, "TLS certificate verified" );
305         if( p_sys->psz_hostname == NULL )
306             return 0;
307
308         /* certificate (host)name verification */
309         p_data = gnutls_certificate_get_peers( p_sys->session, &status );
310         if( p_data == NULL )
311         {
312             msg_Err( p_session, "TLS peer certificate not available" );
313             p_session->pf_close( p_session );
314             return -1;
315         }
316
317         val = gnutls_x509_crt_init( &cert );
318         if( val )
319         {
320             msg_Err( p_session, "x509 fatal error: %s",
321                      gnutls_strerror( val ) );
322             p_session->pf_close( p_session );
323             return -1;
324         }
325
326         val = gnutls_x509_crt_import( cert, p_data, GNUTLS_X509_FMT_DER );
327         if( val )
328         {
329             msg_Err( p_session, "x509 certificate import error: %s",
330                      gnutls_strerror( val ) );
331             gnutls_x509_crt_deinit( cert );
332             p_session->pf_close( p_session );
333             return -1;
334         }
335
336         if( gnutls_x509_crt_check_hostname( cert, p_sys->psz_hostname ) == 0 )
337         {
338             msg_Err( p_session, "x509 certificate does not match \"%s\"",
339                      p_sys->psz_hostname );
340             gnutls_x509_crt_deinit( cert );
341             p_session->pf_close( p_session );
342             return -1;
343         }
344
345         gnutls_x509_crt_deinit( cert );
346
347         msg_Dbg( p_session, "x509 hostname verified" );
348         return 0;
349     }
350
351     return val;
352 }
353
354 static int
355 gnutls_BeginHandshake( tls_session_t *p_session, int fd,
356                          const char *psz_hostname )
357 {
358     tls_session_sys_t *p_sys;
359
360     p_sys = (tls_session_sys_t *)(p_session->p_sys);
361
362     gnutls_transport_set_ptr (p_sys->session, (gnutls_transport_ptr)(intptr_t)fd);
363
364     if( psz_hostname != NULL )
365     {
366         gnutls_server_name_set( p_sys->session, GNUTLS_NAME_DNS, psz_hostname,
367                                 strlen( psz_hostname ) );
368         if( get_Bool( p_session, "tls-check-hostname" ) )
369         {
370             p_sys->psz_hostname = strdup( psz_hostname );
371             if( p_sys->psz_hostname == NULL )
372             {
373                 p_session->pf_close( p_session );
374                 return -1;
375             }
376         }
377     }
378
379     return p_session->pf_handshake2( p_session );
380 }
381
382 /*****************************************************************************
383  * tls_SessionClose:
384  *****************************************************************************
385  * Terminates TLS session and releases session data.
386  *****************************************************************************/
387 static void
388 gnutls_SessionClose( tls_session_t *p_session )
389 {
390     tls_session_sys_t *p_sys;
391
392     p_sys = (tls_session_sys_t *)(p_session->p_sys);
393
394     if( p_sys->b_handshaked == VLC_TRUE )
395         gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
396     gnutls_deinit( p_sys->session );
397
398     if( p_sys->psz_hostname != NULL )
399         free( p_sys->psz_hostname );
400
401     vlc_object_detach( p_session );
402     vlc_object_destroy( p_session );
403
404     free( p_sys );
405 }
406
407 static void
408 gnutls_ClientDelete( tls_session_t *p_session )
409 {
410     /* On the client-side, credentials are re-allocated per session */
411     gnutls_certificate_credentials x509_cred =
412                         ((tls_client_sys_t *)(p_session->p_sys))->x509_cred;
413
414     gnutls_SessionClose( p_session );
415
416     /* credentials must be free'd *after* gnutls_deinit() */
417     gnutls_certificate_free_credentials( x509_cred );
418 }
419
420 static int
421 gnutls_Addx509Directory( vlc_object_t *p_this,
422                          gnutls_certificate_credentials cred,
423                          const char *psz_dirname,
424                          vlc_bool_t b_priv )
425 {
426     DIR* dir;
427     const char *psz_dirent;
428
429     if( *psz_dirname == '\0' )
430         psz_dirname = ".";
431
432     dir = utf8_opendir( psz_dirname );
433     if( dir == NULL )
434     {
435         msg_Warn( p_this, "Cannot open directory (%s): %s", psz_dirname,
436                   strerror( errno ) );
437         return VLC_EGENERIC;
438     }
439 #ifdef S_ISLNK
440     else
441     {
442         struct stat st1, st2;
443         int fd = dirfd( dir );
444
445         /*
446          * Gets stats for the directory path, checks that it is not a
447          * symbolic link (to avoid possibly infinite recursion), and verifies
448          * that the inode is still the same, to avoid TOCTOU race condition.
449          */
450         if( ( fd == -1)
451          || fstat( fd, &st1 ) || utf8_lstat( psz_dirname, &st2 )
452          || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
453         {
454             closedir( dir );
455             return VLC_EGENERIC;
456         }
457     }
458 #endif
459
460     while( ( psz_dirent = utf8_readdir( dir ) ) != NULL )
461     {
462         struct stat st;
463         char *psz_filename;
464         int check;
465
466         if( ( strcmp( ".", psz_dirent ) == 0 )
467          || ( strcmp( "..", psz_dirent ) == 0 ) )
468             continue;
469
470         check = asprintf( &psz_filename, "%s/%s", psz_dirname,
471                               psz_dirent );
472         LocaleFree( psz_dirent );
473         if( check == -1 )
474             continue;
475
476         if( utf8_stat( psz_filename, &st ) == 0 )
477         {
478             if( S_ISREG( st.st_mode ) )
479             {
480                 char *psz_localname = ToLocale( psz_filename );
481                 int i = b_priv
482                     ? gnutls_certificate_set_x509_key_file( cred,
483                         psz_localname,  psz_localname, GNUTLS_X509_FMT_PEM )
484                     : gnutls_certificate_set_x509_trust_file( cred,
485                             psz_localname, GNUTLS_X509_FMT_PEM );
486                 LocaleFree( psz_localname );
487
488                 if( i < 0 )
489                     msg_Warn( p_this, "Cannot add x509 certificate (%s): %s",
490                             psz_filename, gnutls_strerror( i ) );
491                 else
492                     msg_Dbg( p_this, "Added x509 credentials (%s)",
493                              psz_filename );
494             }
495             else if( S_ISDIR( st.st_mode ) )
496             {
497                 msg_Dbg( p_this,
498                          "Looking recursively for x509 certificates in %s",
499                          psz_filename );
500                 gnutls_Addx509Directory( p_this, cred, psz_filename, b_priv);
501             }
502         }
503         free( psz_filename );
504     }
505
506     closedir( dir );
507     return VLC_SUCCESS;
508 }
509
510 /*****************************************************************************
511  * tls_ClientCreate:
512  *****************************************************************************
513  * Initializes client-side TLS session data.
514  *****************************************************************************/
515 static tls_session_t *
516 gnutls_ClientCreate( tls_t *p_tls )
517 {
518     tls_session_t *p_session = NULL;
519     tls_client_sys_t *p_sys = NULL;
520     int i_val;
521     const int cert_type_priority[3] =
522     {
523         GNUTLS_CRT_X509,
524         0
525     };
526
527     p_sys = (tls_client_sys_t *)malloc( sizeof(struct tls_client_sys_t) );
528     if( p_sys == NULL )
529         return NULL;
530
531     p_session = (struct tls_session_t *)vlc_object_create ( p_tls, sizeof(struct tls_session_t) );
532     if( p_session == NULL )
533     {
534         free( p_sys );
535         return NULL;
536     }
537
538     p_session->p_sys = p_sys;
539     p_session->sock.p_sys = p_session;
540     p_session->sock.pf_send = gnutls_Send;
541     p_session->sock.pf_recv = gnutls_Recv;
542     p_session->pf_handshake = gnutls_BeginHandshake;
543     p_session->pf_close = gnutls_ClientDelete;
544
545     p_sys->session.b_handshaked = VLC_FALSE;
546     p_sys->session.psz_hostname = NULL;
547
548     vlc_object_attach( p_session, p_tls );
549
550     i_val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
551     if( i_val != 0 )
552     {
553         msg_Err( p_tls, "Cannot allocate X509 credentials: %s",
554                  gnutls_strerror( i_val ) );
555         goto error;
556     }
557
558     if( get_Bool( p_tls, "tls-check-cert" ) )
559     {
560         char *psz_path;
561
562         if( asprintf( &psz_path, "%s/"CONFIG_DIR"/ssl/certs",
563                       p_tls->p_vlc->psz_homedir ) == -1 )
564         {
565             gnutls_certificate_free_credentials( p_sys->x509_cred );
566             goto error;
567         }
568
569         gnutls_Addx509Directory( (vlc_object_t *)p_session, p_sys->x509_cred,
570                                  psz_path, VLC_FALSE );
571 #ifdef HOST_CA_PATH
572         gnutls_Addx509Directory( (vlc_object_t *)p_session, p_sys->x509_cred,
573                                  HOST_CA_PATH, VLC_FALSE );
574 #endif
575
576         free( psz_path );
577         p_session->pf_handshake2 = gnutls_HandshakeAndValidate;
578     }
579     else
580         p_session->pf_handshake2 = gnutls_ContinueHandshake;
581
582     {
583         char *psz_path;
584
585         if( asprintf( &psz_path, "%s/"CONFIG_DIR"/ssl/private",
586                       p_tls->p_vlc->psz_homedir ) == -1 )
587         {
588             gnutls_certificate_free_credentials( p_sys->x509_cred );
589             goto error;
590         }
591
592         gnutls_Addx509Directory( (vlc_object_t *)p_session, p_sys->x509_cred,
593                                  psz_path, VLC_TRUE );
594
595         free( psz_path );
596     }
597
598     i_val = gnutls_init( &p_sys->session.session, GNUTLS_CLIENT );
599     if( i_val != 0 )
600     {
601         msg_Err( p_tls, "Cannot initialize TLS session: %s",
602                  gnutls_strerror( i_val ) );
603         gnutls_certificate_free_credentials( p_sys->x509_cred );
604         goto error;
605     }
606
607     i_val = gnutls_set_default_priority( p_sys->session.session );
608     if( i_val < 0 )
609     {
610         msg_Err( p_tls, "Cannot set ciphers priorities: %s",
611                  gnutls_strerror( i_val ) );
612         gnutls_deinit( p_sys->session.session );
613         gnutls_certificate_free_credentials( p_sys->x509_cred );
614         goto error;
615     }
616
617     i_val = gnutls_certificate_type_set_priority( p_sys->session.session,
618                                                   cert_type_priority );
619     if( i_val < 0 )
620     {
621         msg_Err( p_tls, "Cannot set certificate type priorities: %s",
622                  gnutls_strerror( i_val ) );
623         gnutls_deinit( p_sys->session.session );
624         gnutls_certificate_free_credentials( p_sys->x509_cred );
625         goto error;
626     }
627
628     i_val = gnutls_credentials_set( p_sys->session.session,
629                                     GNUTLS_CRD_CERTIFICATE,
630                                     p_sys->x509_cred );
631     if( i_val < 0 )
632     {
633         msg_Err( p_tls, "Cannot set TLS session credentials: %s",
634                  gnutls_strerror( i_val ) );
635         gnutls_deinit( p_sys->session.session );
636         gnutls_certificate_free_credentials( p_sys->x509_cred );
637         goto error;
638     }
639
640     return p_session;
641
642 error:
643     vlc_object_detach( p_session );
644     vlc_object_destroy( p_session );
645     free( p_sys );
646
647     return NULL;
648 }
649
650
651 /*****************************************************************************
652  * TLS session resumption callbacks
653  *****************************************************************************/
654 static int cb_store( void *p_server, gnutls_datum key, gnutls_datum data )
655 {
656     tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
657
658     if( ( p_sys->i_cache_size == 0 )
659      || ( key.size > MAX_SESSION_ID )
660      || ( data.size > MAX_SESSION_DATA ) )
661         return -1;
662
663     vlc_mutex_lock( &p_sys->cache_lock );
664
665     memcpy( p_sys->p_store->id, key.data, key.size);
666     memcpy( p_sys->p_store->data, data.data, data.size );
667     p_sys->p_store->i_idlen = key.size;
668     p_sys->p_store->i_datalen = data.size;
669
670     p_sys->p_store++;
671     if( ( p_sys->p_store - p_sys->p_cache ) == p_sys->i_cache_size )
672         p_sys->p_store = p_sys->p_cache;
673
674     vlc_mutex_unlock( &p_sys->cache_lock );
675
676     return 0;
677 }
678
679
680 static const gnutls_datum err_datum = { NULL, 0 };
681
682 static gnutls_datum cb_fetch( void *p_server, gnutls_datum key )
683 {
684     tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
685     saved_session_t *p_session, *p_end;
686
687     p_session = p_sys->p_cache;
688     p_end = p_session + p_sys->i_cache_size;
689
690     vlc_mutex_lock( &p_sys->cache_lock );
691
692     while( p_session < p_end )
693     {
694         if( ( p_session->i_idlen == key.size )
695          && !memcmp( p_session->id, key.data, key.size ) )
696         {
697             gnutls_datum data;
698
699             data.size = p_session->i_datalen;
700
701             data.data = gnutls_malloc( data.size );
702             if( data.data == NULL )
703             {
704                 vlc_mutex_unlock( &p_sys->cache_lock );
705                 return err_datum;
706             }
707
708             memcpy( data.data, p_session->data, data.size );
709             vlc_mutex_unlock( &p_sys->cache_lock );
710             return data;
711         }
712         p_session++;
713     }
714
715     vlc_mutex_unlock( &p_sys->cache_lock );
716
717     return err_datum;
718 }
719
720
721 static int cb_delete( void *p_server, gnutls_datum key )
722 {
723     tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
724     saved_session_t *p_session, *p_end;
725
726     p_session = p_sys->p_cache;
727     p_end = p_session + p_sys->i_cache_size;
728
729     vlc_mutex_lock( &p_sys->cache_lock );
730
731     while( p_session < p_end )
732     {
733         if( ( p_session->i_idlen == key.size )
734          && !memcmp( p_session->id, key.data, key.size ) )
735         {
736             p_session->i_datalen = p_session->i_idlen = 0;
737             vlc_mutex_unlock( &p_sys->cache_lock );
738             return 0;
739         }
740         p_session++;
741     }
742
743     vlc_mutex_unlock( &p_sys->cache_lock );
744
745     return -1;
746 }
747
748
749 /*****************************************************************************
750  * tls_ServerSessionPrepare:
751  *****************************************************************************
752  * Initializes server-side TLS session data.
753  *****************************************************************************/
754 static tls_session_t *
755 gnutls_ServerSessionPrepare( tls_server_t *p_server )
756 {
757     tls_session_t *p_session;
758     tls_server_sys_t *p_server_sys;
759     gnutls_session session;
760     int i_val;
761
762     p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
763     if( p_session == NULL )
764         return NULL;
765
766     p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
767     if( p_session->p_sys == NULL )
768     {
769         vlc_object_destroy( p_session );
770         return NULL;
771     }
772
773     vlc_object_attach( p_session, p_server );
774
775     p_server_sys = (tls_server_sys_t *)p_server->p_sys;
776     p_session->sock.p_sys = p_session;
777     p_session->sock.pf_send = gnutls_Send;
778     p_session->sock.pf_recv = gnutls_Recv;
779     p_session->pf_handshake = gnutls_BeginHandshake;
780     p_session->pf_handshake2 = p_server_sys->pf_handshake2;
781     p_session->pf_close = gnutls_SessionClose;
782
783     ((tls_session_sys_t *)p_session->p_sys)->b_handshaked = VLC_FALSE;
784     ((tls_session_sys_t *)p_session->p_sys)->psz_hostname = NULL;
785
786     i_val = gnutls_init( &session, GNUTLS_SERVER );
787     if( i_val != 0 )
788     {
789         msg_Err( p_server, "Cannot initialize TLS session: %s",
790                  gnutls_strerror( i_val ) );
791         goto error;
792     }
793
794     ((tls_session_sys_t *)p_session->p_sys)->session = session;
795
796     i_val = gnutls_set_default_priority( session );
797     if( i_val < 0 )
798     {
799         msg_Err( p_server, "Cannot set ciphers priorities: %s",
800                  gnutls_strerror( i_val ) );
801         gnutls_deinit( session );
802         goto error;
803     }
804
805     i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
806                                     p_server_sys->x509_cred );
807     if( i_val < 0 )
808     {
809         msg_Err( p_server, "Cannot set TLS session credentials: %s",
810                  gnutls_strerror( i_val ) );
811         gnutls_deinit( session );
812         goto error;
813     }
814
815     if( p_session->pf_handshake2 == gnutls_HandshakeAndValidate )
816         gnutls_certificate_server_set_request( session, GNUTLS_CERT_REQUIRE );
817
818     gnutls_dh_set_prime_bits( session, get_Int( p_server, "gnutls-dh-bits" ) );
819
820     /* Session resumption support */
821     gnutls_db_set_cache_expiration( session, get_Int( p_server,
822                                     "gnutls-cache-expiration" ) );
823     gnutls_db_set_retrieve_function( session, cb_fetch );
824     gnutls_db_set_remove_function( session, cb_delete );
825     gnutls_db_set_store_function( session, cb_store );
826     gnutls_db_set_ptr( session, p_server );
827
828     return p_session;
829
830 error:
831     free( p_session->p_sys );
832     vlc_object_detach( p_session );
833     vlc_object_destroy( p_session );
834     return NULL;
835 }
836
837
838 /*****************************************************************************
839  * tls_ServerDelete:
840  *****************************************************************************
841  * Releases data allocated with tls_ServerCreate.
842  *****************************************************************************/
843 static void
844 gnutls_ServerDelete( tls_server_t *p_server )
845 {
846     tls_server_sys_t *p_sys;
847     p_sys = (tls_server_sys_t *)p_server->p_sys;
848
849     vlc_mutex_destroy( &p_sys->cache_lock );
850     free( p_sys->p_cache );
851
852     vlc_object_detach( p_server );
853     vlc_object_destroy( p_server );
854
855     /* all sessions depending on the server are now deinitialized */
856     gnutls_certificate_free_credentials( p_sys->x509_cred );
857     gnutls_dh_params_deinit( p_sys->dh_params );
858     free( p_sys );
859 }
860
861
862 /*****************************************************************************
863  * tls_ServerAddCA:
864  *****************************************************************************
865  * Adds one or more certificate authorities.
866  * Returns -1 on error, 0 on success.
867  *****************************************************************************/
868 static int
869 gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
870 {
871     tls_server_sys_t *p_sys;
872     char *psz_local_path;
873     int val;
874
875     p_sys = (tls_server_sys_t *)(p_server->p_sys);
876
877     psz_local_path = ToLocale( psz_ca_path );
878     val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
879                                                   psz_local_path,
880                                                   GNUTLS_X509_FMT_PEM );
881     LocaleFree( psz_local_path );
882     if( val < 0 )
883     {
884         msg_Err( p_server, "Cannot add trusted CA (%s): %s", psz_ca_path,
885                  gnutls_strerror( val ) );
886         return VLC_EGENERIC;
887     }
888     msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
889
890     /* enables peer's certificate verification */
891     p_sys->pf_handshake2 = gnutls_HandshakeAndValidate;
892
893     return VLC_SUCCESS;
894 }
895
896
897 /*****************************************************************************
898  * tls_ServerAddCRL:
899  *****************************************************************************
900  * Adds a certificates revocation list to be sent to TLS clients.
901  * Returns -1 on error, 0 on success.
902  *****************************************************************************/
903 static int
904 gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
905 {
906     int val;
907     char *psz_local_path = ToLocale( psz_crl_path );
908
909     val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
910                                                 (p_server->p_sys))->x509_cred,
911                                                 psz_local_path,
912                                                 GNUTLS_X509_FMT_PEM );
913     LocaleFree( psz_crl_path );
914     if( val < 0 )
915     {
916         msg_Err( p_server, "Cannot add CRL (%s): %s", psz_crl_path,
917                  gnutls_strerror( val ) );
918         return VLC_EGENERIC;
919     }
920     msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );
921     return VLC_SUCCESS;
922 }
923
924
925 /*****************************************************************************
926  * tls_ServerCreate:
927  *****************************************************************************
928  * Allocates a whole server's TLS credentials.
929  * Returns NULL on error.
930  *****************************************************************************/
931 static tls_server_t *
932 gnutls_ServerCreate( tls_t *p_tls, const char *psz_cert_path,
933                      const char *psz_key_path )
934 {
935     tls_server_t *p_server;
936     tls_server_sys_t *p_sys;
937     char *psz_local_key, *psz_local_cert;
938     int val;
939
940     msg_Dbg( p_tls, "Creating TLS server" );
941
942     p_sys = (tls_server_sys_t *)malloc( sizeof(struct tls_server_sys_t) );
943     if( p_sys == NULL )
944         return NULL;
945
946     p_sys->i_cache_size = get_Int( p_tls, "gnutls-cache-size" );
947     p_sys->p_cache = (struct saved_session_t *)calloc( p_sys->i_cache_size,
948                                            sizeof( struct saved_session_t ) );
949     if( p_sys->p_cache == NULL )
950     {
951         free( p_sys );
952         return NULL;
953     }
954     p_sys->p_store = p_sys->p_cache;
955
956     p_server = vlc_object_create( p_tls, sizeof(struct tls_server_t) );
957     if( p_server == NULL )
958     {
959         free( p_sys->p_cache );
960         free( p_sys );
961         return NULL;
962     }
963
964     vlc_object_attach( p_server, p_tls );
965
966     p_server->p_sys = p_sys;
967     p_server->pf_delete = gnutls_ServerDelete;
968     p_server->pf_add_CA = gnutls_ServerAddCA;
969     p_server->pf_add_CRL = gnutls_ServerAddCRL;
970     p_server->pf_session_prepare = gnutls_ServerSessionPrepare;
971
972     /* No certificate validation by default */
973     p_sys->pf_handshake2 = gnutls_ContinueHandshake;
974
975     /* FIXME: check for errors */
976     vlc_mutex_init( p_server, &p_sys->cache_lock );
977
978     /* Sets server's credentials */
979     val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
980     if( val != 0 )
981     {
982         msg_Err( p_server, "Cannot allocate X509 credentials: %s",
983                  gnutls_strerror( val ) );
984         goto error;
985     }
986
987     psz_local_cert = ToLocale( psz_cert_path );
988     psz_local_key = ToLocale( psz_key_path );
989     val = gnutls_certificate_set_x509_key_file( p_sys->x509_cred,
990                                                 psz_local_cert, psz_local_key,
991                                                 GNUTLS_X509_FMT_PEM );
992     LocaleFree( psz_cert_path );
993     LocaleFree( psz_key_path );
994     if( val < 0 )
995     {
996         msg_Err( p_server, "Cannot set certificate chain or private key: %s",
997                  gnutls_strerror( val ) );
998         gnutls_certificate_free_credentials( p_sys->x509_cred );
999         goto error;
1000     }
1001
1002     /* FIXME:
1003      * - regenerate these regularly
1004      * - support other ciper suites
1005      */
1006     val = gnutls_dh_params_init( &p_sys->dh_params );
1007     if( val >= 0 )
1008     {
1009         msg_Dbg( p_server, "Computing Diffie Hellman ciphers parameters" );
1010         val = gnutls_dh_params_generate2( p_sys->dh_params,
1011                                           get_Int( p_tls, "gnutls-dh-bits" ) );
1012     }
1013     if( val < 0 )
1014     {
1015         msg_Err( p_server, "Cannot initialize DH cipher suites: %s",
1016                  gnutls_strerror( val ) );
1017         gnutls_certificate_free_credentials( p_sys->x509_cred );
1018         goto error;
1019     }
1020     msg_Dbg( p_server, "Ciphers parameters computed" );
1021
1022     gnutls_certificate_set_dh_params( p_sys->x509_cred, p_sys->dh_params);
1023
1024     return p_server;
1025
1026 error:
1027     vlc_mutex_destroy( &p_sys->cache_lock );
1028     vlc_object_detach( p_server );
1029     vlc_object_destroy( p_server );
1030     free( p_sys );
1031     return NULL;
1032 }
1033
1034
1035 /*****************************************************************************
1036  * gcrypt thread option VLC implementation:
1037  *****************************************************************************/
1038 vlc_object_t *__p_gcry_data;
1039
1040 static int gcry_vlc_mutex_init( void **p_sys )
1041 {
1042     int i_val;
1043     vlc_mutex_t *p_lock = (vlc_mutex_t *)malloc( sizeof( vlc_mutex_t ) );
1044
1045     if( p_lock == NULL)
1046         return ENOMEM;
1047
1048     i_val = vlc_mutex_init( __p_gcry_data, p_lock );
1049     if( i_val )
1050         free( p_lock );
1051     else
1052         *p_sys = p_lock;
1053     return i_val;
1054 }
1055
1056 static int gcry_vlc_mutex_destroy( void **p_sys )
1057 {
1058     int i_val;
1059     vlc_mutex_t *p_lock = (vlc_mutex_t *)*p_sys;
1060
1061     i_val = vlc_mutex_destroy( p_lock );
1062     free( p_lock );
1063     return i_val;
1064 }
1065
1066 static int gcry_vlc_mutex_lock( void **p_sys )
1067 {
1068     return vlc_mutex_lock( (vlc_mutex_t *)*p_sys );
1069 }
1070
1071 static int gcry_vlc_mutex_unlock( void **lock )
1072 {
1073     return vlc_mutex_unlock( (vlc_mutex_t *)*lock );
1074 }
1075
1076 static struct gcry_thread_cbs gcry_threads_vlc =
1077 {
1078     GCRY_THREAD_OPTION_USER,
1079     NULL,
1080     gcry_vlc_mutex_init,
1081     gcry_vlc_mutex_destroy,
1082     gcry_vlc_mutex_lock,
1083     gcry_vlc_mutex_unlock
1084 };
1085
1086
1087 /*****************************************************************************
1088  * Module initialization
1089  *****************************************************************************/
1090 static int
1091 Open( vlc_object_t *p_this )
1092 {
1093     tls_t *p_tls = (tls_t *)p_this;
1094
1095     vlc_value_t lock, count;
1096
1097     var_Create( p_this->p_libvlc, "gnutls_mutex", VLC_VAR_MUTEX );
1098     var_Get( p_this->p_libvlc, "gnutls_mutex", &lock );
1099     vlc_mutex_lock( lock.p_address );
1100
1101     /* Initialize GnuTLS only once */
1102     var_Create( p_this->p_libvlc, "gnutls_count", VLC_VAR_INTEGER );
1103     var_Get( p_this->p_libvlc, "gnutls_count", &count);
1104
1105     if( count.i_int == 0)
1106     {
1107         const char *psz_version;
1108
1109         __p_gcry_data = VLC_OBJECT( p_this->p_vlc );
1110
1111         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_vlc);
1112         if( gnutls_global_init( ) )
1113         {
1114             msg_Warn( p_this, "cannot initialize GnuTLS" );
1115             vlc_mutex_unlock( lock.p_address );
1116             return VLC_EGENERIC;
1117         }
1118         /*
1119          * FIXME: in fact, we currently depends on 1.0.17, but it breaks on
1120          * Debian which as a patched 1.0.16 (which we can use).
1121          */
1122         psz_version = gnutls_check_version( "1.0.16" );
1123         if( psz_version == NULL )
1124         {
1125             gnutls_global_deinit( );
1126             vlc_mutex_unlock( lock.p_address );
1127             msg_Err( p_this, "unsupported GnuTLS version" );
1128             return VLC_EGENERIC;
1129         }
1130         msg_Dbg( p_this, "GnuTLS v%s initialized", psz_version );
1131     }
1132
1133     count.i_int++;
1134     var_Set( p_this->p_libvlc, "gnutls_count", count);
1135     vlc_mutex_unlock( lock.p_address );
1136
1137     p_tls->pf_server_create = gnutls_ServerCreate;
1138     p_tls->pf_client_create = gnutls_ClientCreate;
1139     return VLC_SUCCESS;
1140 }
1141
1142
1143 /*****************************************************************************
1144  * Module deinitialization
1145  *****************************************************************************/
1146 static void
1147 Close( vlc_object_t *p_this )
1148 {
1149     /*tls_t *p_tls = (tls_t *)p_this;
1150     tls_sys_t *p_sys = (tls_sys_t *)(p_this->p_sys);*/
1151
1152     vlc_value_t lock, count;
1153
1154     var_Create( p_this->p_libvlc, "gnutls_mutex", VLC_VAR_MUTEX );
1155     var_Get( p_this->p_libvlc, "gnutls_mutex", &lock );
1156     vlc_mutex_lock( lock.p_address );
1157
1158     var_Create( p_this->p_libvlc, "gnutls_count", VLC_VAR_INTEGER );
1159     var_Get( p_this->p_libvlc, "gnutls_count", &count);
1160     count.i_int--;
1161     var_Set( p_this->p_libvlc, "gnutls_count", count);
1162
1163     if( count.i_int == 0 )
1164     {
1165         gnutls_global_deinit( );
1166         msg_Dbg( p_this, "GnuTLS deinitialized" );
1167     }
1168
1169     vlc_mutex_unlock( lock.p_address );
1170 }