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