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