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