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