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