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