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