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