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