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