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