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