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