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