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