]> git.sesse.net Git - vlc/blob - modules/misc/gnutls.c
GnuTLS: remove server-side support for session resumption
[vlc] / modules / misc / gnutls.c
1 /*****************************************************************************
2  * gnutls.c
3  *****************************************************************************
4  * Copyright (C) 2004-2006 Rémi Denis-Courmont
5  * $Id$
6  *
7  * Authors: Rémi Denis-Courmont <rem # videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <errno.h>
35 #include <time.h>
36
37 #include <sys/types.h>
38 #include <errno.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
41 #endif
42 #ifdef WIN32
43 # include <io.h>
44 # include <wincrypt.h>
45 #else
46 # include <unistd.h>
47 #endif
48 # include <fcntl.h>
49
50
51 #include <vlc_tls.h>
52 #include <vlc_charset.h>
53 #include <vlc_fs.h>
54 #include <vlc_block.h>
55
56 #include <gcrypt.h>
57 #include <gnutls/gnutls.h>
58 #include <gnutls/x509.h>
59
60 #include <vlc_gcrypt.h>
61 #include "dhparams.h"
62
63 #include <assert.h>
64
65 /*****************************************************************************
66  * Module descriptor
67  *****************************************************************************/
68 static int  OpenClient  (vlc_object_t *);
69 static void CloseClient (vlc_object_t *);
70 static int  OpenServer  (vlc_object_t *);
71 static void CloseServer (vlc_object_t *);
72
73 #define PRIORITIES_TEXT N_("TLS cipher priorities")
74 #define PRIORITIES_LONGTEXT N_("Ciphers, key exchange methods, " \
75     "hash functions and compression methods can be selected. " \
76     "Refer to GNU TLS documentation for detailed syntax.")
77 static const char *const priorities_values[] = {
78     "PERFORMANCE",
79     "NORMAL",
80     "SECURE128",
81     "SECURE256",
82     "EXPORT",
83 };
84 static const char *const priorities_text[] = {
85     N_("Performance (prioritize faster ciphers)"),
86     N_("Normal"),
87     N_("Secure 128-bits (exclude 256-bits ciphers)"),
88     N_("Secure 256-bits (prioritize 256-bits ciphers)"),
89     N_("Export (include insecure ciphers)"),
90 };
91
92 vlc_module_begin ()
93     set_shortname( "GNU TLS" )
94     set_description( N_("GNU TLS transport layer security") )
95     set_capability( "tls client", 1 )
96     set_callbacks( OpenClient, CloseClient )
97     set_category( CAT_ADVANCED )
98     set_subcategory( SUBCAT_ADVANCED_MISC )
99
100     add_submodule ()
101         set_description( N_("GNU TLS server") )
102         set_capability( "tls server", 1 )
103         set_category( CAT_ADVANCED )
104         set_subcategory( SUBCAT_ADVANCED_MISC )
105         set_callbacks( OpenServer, CloseServer )
106
107         add_string ("gnutls-priorities", "NORMAL", PRIORITIES_TEXT,
108                     PRIORITIES_LONGTEXT, false)
109             change_string_list (priorities_values, priorities_text, NULL)
110 vlc_module_end ()
111
112 static vlc_mutex_t gnutls_mutex = VLC_STATIC_MUTEX;
113
114 /**
115  * Initializes GnuTLS with proper locking.
116  * @return VLC_SUCCESS on success, a VLC error code otherwise.
117  */
118 static int gnutls_Init (vlc_object_t *p_this)
119 {
120     int ret = VLC_EGENERIC;
121
122     vlc_gcrypt_init (); /* GnuTLS depends on gcrypt */
123
124     vlc_mutex_lock (&gnutls_mutex);
125     if (gnutls_global_init ())
126     {
127         msg_Err (p_this, "cannot initialize GnuTLS");
128         goto error;
129     }
130
131     const char *psz_version = gnutls_check_version ("2.0.0");
132     if (psz_version == NULL)
133     {
134         msg_Err (p_this, "unsupported GnuTLS version");
135         gnutls_global_deinit ();
136         goto error;
137     }
138
139     msg_Dbg (p_this, "GnuTLS v%s initialized", psz_version);
140     ret = VLC_SUCCESS;
141
142 error:
143     vlc_mutex_unlock (&gnutls_mutex);
144     return ret;
145 }
146
147
148 /**
149  * Deinitializes GnuTLS.
150  */
151 static void gnutls_Deinit (vlc_object_t *p_this)
152 {
153     vlc_mutex_lock (&gnutls_mutex);
154
155     gnutls_global_deinit ();
156     msg_Dbg (p_this, "GnuTLS deinitialized");
157     vlc_mutex_unlock (&gnutls_mutex);
158 }
159
160
161 static int gnutls_Error (vlc_object_t *obj, int val)
162 {
163     switch (val)
164     {
165         case GNUTLS_E_AGAIN:
166 #ifdef WIN32
167             WSASetLastError (WSAEWOULDBLOCK);
168 #else
169             errno = EAGAIN;
170 #endif
171             break;
172
173         case GNUTLS_E_INTERRUPTED:
174 #ifdef WIN32
175             WSASetLastError (WSAEINTR);
176 #else
177             errno = EINTR;
178 #endif
179             break;
180
181         default:
182             msg_Err (obj, "%s", gnutls_strerror (val));
183 #ifndef NDEBUG
184             if (!gnutls_error_is_fatal (val))
185                 msg_Err (obj, "Error above should be handled");
186 #endif
187 #ifdef WIN32
188             WSASetLastError (WSAECONNRESET);
189 #else
190             errno = ECONNRESET;
191 #endif
192     }
193     return -1;
194 }
195
196
197 struct tls_session_sys_t
198 {
199     gnutls_session_t session;
200     char            *psz_hostname;
201     bool       b_handshaked;
202 };
203
204
205 /**
206  * Sends data through a TLS session.
207  */
208 static int
209 gnutls_Send( void *p_session, const void *buf, int i_length )
210 {
211     int val;
212     tls_session_sys_t *p_sys;
213
214     p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
215
216     val = gnutls_record_send( p_sys->session, buf, i_length );
217     return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
218 }
219
220
221 /**
222  * Receives data through a TLS session.
223  */
224 static int
225 gnutls_Recv( void *p_session, void *buf, int i_length )
226 {
227     int val;
228     tls_session_sys_t *p_sys;
229
230     p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
231
232     val = gnutls_record_recv( p_sys->session, buf, i_length );
233     return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
234 }
235
236
237 /**
238  * Starts or continues the TLS handshake.
239  *
240  * @return -1 on fatal error, 0 on successful handshake completion,
241  * 1 if more would-be blocking recv is needed,
242  * 2 if more would-be blocking send is required.
243  */
244 static int
245 gnutls_ContinueHandshake (tls_session_t *p_session)
246 {
247     tls_session_sys_t *p_sys = p_session->p_sys;
248     int val;
249
250 #ifdef WIN32
251     WSASetLastError( 0 );
252 #endif
253     val = gnutls_handshake( p_sys->session );
254     if( ( val == GNUTLS_E_AGAIN ) || ( val == GNUTLS_E_INTERRUPTED ) )
255         return 1 + gnutls_record_get_direction( p_sys->session );
256
257     if( val < 0 )
258     {
259 #ifdef WIN32
260         msg_Dbg( p_session, "Winsock error %d", WSAGetLastError( ) );
261 #endif
262         msg_Err( p_session, "TLS handshake error: %s",
263                  gnutls_strerror( val ) );
264         return -1;
265     }
266
267     p_sys->b_handshaked = true;
268     return 0;
269 }
270
271
272 typedef struct
273 {
274     int flag;
275     const char *msg;
276 } error_msg_t;
277
278 static const error_msg_t cert_errors[] =
279 {
280     { GNUTLS_CERT_INVALID,
281         "Certificate could not be verified" },
282     { GNUTLS_CERT_REVOKED,
283         "Certificate was revoked" },
284     { GNUTLS_CERT_SIGNER_NOT_FOUND,
285         "Certificate's signer was not found" },
286     { GNUTLS_CERT_SIGNER_NOT_CA,
287         "Certificate's signer is not a CA" },
288     { GNUTLS_CERT_INSECURE_ALGORITHM,
289         "Insecure certificate signature algorithm" },
290     { 0, NULL }
291 };
292
293
294 static int
295 gnutls_HandshakeAndValidate( tls_session_t *session )
296 {
297     int val = gnutls_ContinueHandshake( session );
298     if( val )
299         return val;
300
301     tls_session_sys_t *p_sys = (tls_session_sys_t *)(session->p_sys);
302
303     /* certificates chain verification */
304     unsigned status;
305     val = gnutls_certificate_verify_peers2( p_sys->session, &status );
306
307     if( val )
308     {
309         msg_Err( session, "Certificate verification failed: %s",
310                  gnutls_strerror( val ) );
311         return -1;
312     }
313
314     if( status )
315     {
316         msg_Err( session, "TLS session: access denied" );
317         for( const error_msg_t *e = cert_errors; e->flag; e++ )
318         {
319             if( status & e->flag )
320             {
321                 msg_Err( session, "%s", e->msg );
322                 status &= ~e->flag;
323             }
324         }
325
326         if( status )
327             msg_Err( session,
328                      "unknown certificate error (you found a bug in VLC)" );
329
330         return -1;
331     }
332
333     /* certificate (host)name verification */
334     const gnutls_datum_t *data;
335     data = gnutls_certificate_get_peers (p_sys->session, &(unsigned){0});
336     if( data == NULL )
337     {
338         msg_Err( session, "Peer certificate not available" );
339         return -1;
340     }
341
342     gnutls_x509_crt_t cert;
343     val = gnutls_x509_crt_init( &cert );
344     if( val )
345     {
346         msg_Err( session, "x509 fatal error: %s", gnutls_strerror( val ) );
347         return -1;
348     }
349
350     val = gnutls_x509_crt_import( cert, data, GNUTLS_X509_FMT_DER );
351     if( val )
352     {
353         msg_Err( session, "Certificate import error: %s",
354                  gnutls_strerror( val ) );
355         goto error;
356     }
357
358     assert( p_sys->psz_hostname != NULL );
359     if ( !gnutls_x509_crt_check_hostname( cert, p_sys->psz_hostname ) )
360     {
361         msg_Err( session, "Certificate does not match \"%s\"",
362                  p_sys->psz_hostname );
363         goto error;
364     }
365
366     if( gnutls_x509_crt_get_expiration_time( cert ) < time( NULL ) )
367     {
368         msg_Err( session, "Certificate expired" );
369         goto error;
370     }
371
372     if( gnutls_x509_crt_get_activation_time( cert ) > time ( NULL ) )
373     {
374         msg_Err( session, "Certificate not yet valid" );
375         goto error;
376     }
377
378     gnutls_x509_crt_deinit( cert );
379     msg_Dbg( session, "TLS/x509 certificate verified" );
380     return 0;
381
382 error:
383     gnutls_x509_crt_deinit( cert );
384     return -1;
385 }
386
387 /**
388  * Sets the operating system file descriptor backend for the TLS sesison.
389  *
390  * @param fd stream socket already connected with the peer.
391  */
392 static void
393 gnutls_SetFD (tls_session_t *p_session, int fd)
394 {
395     gnutls_transport_set_ptr (p_session->p_sys->session,
396                               (gnutls_transport_ptr_t)(intptr_t)fd);
397 }
398
399 static int
400 gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
401 {
402     char *priorities = var_InheritString (obj, "gnutls-priorities");
403     if (unlikely(priorities == NULL))
404         return VLC_ENOMEM;
405
406     const char *errp;
407     int val = gnutls_priority_set_direct (session, priorities, &errp);
408     if (val < 0)
409     {
410         msg_Err (obj, "cannot set TLS priorities \"%s\": %s", errp,
411                  gnutls_strerror (val));
412         val = VLC_EGENERIC;
413     }
414     else
415         val = VLC_SUCCESS;
416     free (priorities);
417     return val;
418 }
419
420
421 static int
422 gnutls_Addx509File( vlc_object_t *p_this,
423                     gnutls_certificate_credentials_t cred,
424                     const char *psz_path, bool b_priv );
425 #ifdef WIN32
426 static int gnutls_loadOSCAList(vlc_object_t *p_this,
427                                gnutls_certificate_credentials_t cred);
428 #endif
429
430 static int
431 gnutls_Addx509Directory( vlc_object_t *p_this,
432                          gnutls_certificate_credentials_t cred,
433                          const char *psz_dirname,
434                          bool b_priv )
435 {
436     DIR* dir;
437
438     if( *psz_dirname == '\0' )
439         psz_dirname = ".";
440
441     dir = vlc_opendir( psz_dirname );
442     if( dir == NULL )
443     {
444         if (errno != ENOENT)
445         {
446             msg_Err (p_this, "cannot open directory (%s): %m", psz_dirname);
447             return VLC_EGENERIC;
448         }
449
450         msg_Dbg (p_this, "creating empty certificate directory: %s",
451                  psz_dirname);
452         vlc_mkdir (psz_dirname, b_priv ? 0700 : 0755);
453         return VLC_SUCCESS;
454     }
455 #ifdef S_ISLNK
456     else
457     {
458         struct stat st1, st2;
459         int fd = dirfd( dir );
460
461         /*
462          * Gets stats for the directory path, checks that it is not a
463          * symbolic link (to avoid possibly infinite recursion), and verifies
464          * that the inode is still the same, to avoid TOCTOU race condition.
465          */
466         if( ( fd == -1)
467          || fstat( fd, &st1 ) || vlc_lstat( psz_dirname, &st2 )
468          || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
469         {
470             closedir( dir );
471             return VLC_EGENERIC;
472         }
473     }
474 #endif
475
476     for (;;)
477     {
478         char *ent = vlc_readdir (dir);
479         if (ent == NULL)
480             break;
481
482         if ((strcmp (ent, ".") == 0) || (strcmp (ent, "..") == 0))
483         {
484             free( ent );
485             continue;
486         }
487
488         char path[strlen (psz_dirname) + strlen (ent) + 2];
489         sprintf (path, "%s"DIR_SEP"%s", psz_dirname, ent);
490         free (ent);
491
492         gnutls_Addx509File( p_this, cred, path, b_priv );
493     }
494
495     closedir( dir );
496     return VLC_SUCCESS;
497 }
498
499
500 static int
501 gnutls_Addx509File( vlc_object_t *p_this,
502                     gnutls_certificate_credentials cred,
503                     const char *psz_path, bool b_priv )
504 {
505     struct stat st;
506
507     int fd = vlc_open (psz_path, O_RDONLY);
508     if (fd == -1)
509         goto error;
510
511     block_t *block = block_File (fd);
512     if (block != NULL)
513     {
514         close (fd);
515
516         gnutls_datum data = {
517             .data = block->p_buffer,
518             .size = block->i_buffer,
519         };
520         int res = b_priv
521             ? gnutls_certificate_set_x509_key_mem (cred, &data, &data,
522                                                    GNUTLS_X509_FMT_PEM)
523             : gnutls_certificate_set_x509_trust_mem (cred, &data,
524                                                      GNUTLS_X509_FMT_PEM);
525         block_Release (block);
526
527         if (res < 0)
528         {
529             msg_Warn (p_this, "cannot add x509 credentials (%s): %s",
530                       psz_path, gnutls_strerror (res));
531             return VLC_EGENERIC;
532         }
533         msg_Dbg (p_this, "added x509 credentials (%s)", psz_path);
534         return VLC_SUCCESS;
535     }
536
537     if (!fstat (fd, &st) && S_ISDIR (st.st_mode))
538     {
539         close (fd);
540         msg_Dbg (p_this, "looking recursively for x509 credentials in %s",
541                  psz_path);
542         return gnutls_Addx509Directory (p_this, cred, psz_path, b_priv);
543     }
544
545 error:
546     msg_Warn (p_this, "cannot add x509 credentials (%s): %m", psz_path);
547     if (fd != -1)
548         close (fd);
549     return VLC_EGENERIC;
550 }
551
552 #ifdef WIN32
553 static int
554 gnutls_loadOSCAList( vlc_object_t *p_this,
555                      gnutls_certificate_credentials cred)
556 {
557     HCERTSTORE hCertStore = CertOpenSystemStoreA((HCRYPTPROV)NULL, "ROOT");
558     if (!hCertStore)
559     {
560         msg_Warn (p_this, "could not open the Cert SystemStore");
561         return VLC_EGENERIC;
562     }
563
564     PCCERT_CONTEXT pCertContext = CertEnumCertificatesInStore(hCertStore, NULL);
565     while( pCertContext )
566     {
567         gnutls_datum data = {
568             .data = pCertContext->pbCertEncoded,
569             .size = pCertContext->cbCertEncoded,
570         };
571
572         if(!gnutls_certificate_set_x509_trust_mem(cred, &data, GNUTLS_X509_FMT_DER))
573         {
574             msg_Warn (p_this, "cannot add x509 credential");
575             return VLC_EGENERIC;
576         }
577
578         pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext);
579     }
580     return VLC_SUCCESS;
581 }
582 #endif
583
584 /** TLS client session data */
585 typedef struct tls_client_sys_t
586 {
587     struct tls_session_sys_t         session;
588     gnutls_certificate_credentials_t x509_cred;
589 } tls_client_sys_t;
590
591
592 /**
593  * Initializes a client-side TLS session.
594  */
595 static int OpenClient (vlc_object_t *obj)
596 {
597     tls_session_t *p_session = (tls_session_t *)obj;
598     int i_val;
599
600     if (gnutls_Init (obj))
601         return VLC_EGENERIC;
602
603     tls_client_sys_t *p_sys = malloc (sizeof (*p_sys));
604     if (p_sys == NULL)
605     {
606         gnutls_Deinit (obj);
607         return VLC_ENOMEM;
608     }
609
610     p_session->p_sys = &p_sys->session;
611     p_session->sock.p_sys = p_session;
612     p_session->sock.pf_send = gnutls_Send;
613     p_session->sock.pf_recv = gnutls_Recv;
614     p_session->pf_set_fd = gnutls_SetFD;
615
616     p_sys->session.b_handshaked = false;
617
618     i_val = gnutls_certificate_allocate_credentials (&p_sys->x509_cred);
619     if (i_val != 0)
620     {
621         msg_Err (obj, "cannot allocate X509 credentials: %s",
622                  gnutls_strerror (i_val));
623         goto error;
624     }
625
626     char *userdir = config_GetUserDir ( VLC_DATA_DIR );
627     if (userdir != NULL)
628     {
629         char path[strlen (userdir) + sizeof ("/ssl/private")];
630         sprintf (path, "%s/ssl", userdir);
631         vlc_mkdir (path, 0755);
632
633         sprintf (path, "%s/ssl/certs", userdir);
634         gnutls_Addx509Directory (VLC_OBJECT (p_session),
635                                  p_sys->x509_cred, path, false);
636         sprintf (path, "%s/ssl/private", userdir);
637         gnutls_Addx509Directory (VLC_OBJECT (p_session), p_sys->x509_cred,
638                                  path, true);
639         free (userdir);
640     }
641
642     const char *confdir = config_GetConfDir ();
643     {
644         char path[strlen (confdir)
645                    + sizeof ("/ssl/certs/ca-certificates.crt")];
646         sprintf (path, "%s/ssl/certs/ca-certificates.crt", confdir);
647 #ifdef WIN32
648         gnutls_loadOSCAList (VLC_OBJECT (p_session),
649                              p_sys->x509_cred);
650 #else
651         gnutls_Addx509File (VLC_OBJECT (p_session),
652                             p_sys->x509_cred, path, false);
653 #endif
654     }
655     p_session->pf_handshake = gnutls_HandshakeAndValidate;
656     /*p_session->pf_handshake = gnutls_ContinueHandshake;*/
657
658     i_val = gnutls_init (&p_sys->session.session, GNUTLS_CLIENT);
659     if (i_val != 0)
660     {
661         msg_Err (obj, "cannot initialize TLS session: %s",
662                  gnutls_strerror (i_val));
663         gnutls_certificate_free_credentials (p_sys->x509_cred);
664         goto error;
665     }
666
667     if (gnutls_SessionPrioritize (VLC_OBJECT (p_session),
668                                   p_sys->session.session))
669         goto s_error;
670
671     /* minimum DH prime bits */
672     gnutls_dh_set_prime_bits (p_sys->session.session, 1024);
673
674     i_val = gnutls_credentials_set (p_sys->session.session,
675                                     GNUTLS_CRD_CERTIFICATE,
676                                     p_sys->x509_cred);
677     if (i_val < 0)
678     {
679         msg_Err (obj, "cannot set TLS session credentials: %s",
680                  gnutls_strerror (i_val));
681         goto s_error;
682     }
683
684     char *servername = var_GetNonEmptyString (p_session, "tls-server-name");
685     if (servername == NULL )
686         msg_Err (p_session, "server name missing for TLS session");
687     else
688         gnutls_server_name_set (p_sys->session.session, GNUTLS_NAME_DNS,
689                                 servername, strlen (servername));
690
691     p_sys->session.psz_hostname = servername;
692
693     return VLC_SUCCESS;
694
695 s_error:
696     gnutls_deinit (p_sys->session.session);
697     gnutls_certificate_free_credentials (p_sys->x509_cred);
698 error:
699     gnutls_Deinit (obj);
700     free (p_sys);
701     return VLC_EGENERIC;
702 }
703
704
705 static void CloseClient (vlc_object_t *obj)
706 {
707     tls_session_t *client = (tls_session_t *)obj;
708     tls_client_sys_t *p_sys = (tls_client_sys_t *)(client->p_sys);
709
710     if (p_sys->session.b_handshaked)
711         gnutls_bye (p_sys->session.session, GNUTLS_SHUT_WR);
712     gnutls_deinit (p_sys->session.session);
713     /* credentials must be free'd *after* gnutls_deinit() */
714     gnutls_certificate_free_credentials (p_sys->x509_cred);
715
716     gnutls_Deinit (obj);
717     free (p_sys->session.psz_hostname);
718     free (p_sys);
719 }
720
721
722 /**
723  * Server-side TLS
724  */
725 struct tls_server_sys_t
726 {
727     gnutls_certificate_credentials_t x509_cred;
728     gnutls_dh_params_t               dh_params;
729     int                            (*pf_handshake) (tls_session_t *);
730 };
731
732
733 /**
734  * Terminates TLS session and releases session data.
735  * You still have to close the socket yourself.
736  */
737 static void
738 gnutls_SessionClose (tls_server_t *p_server, tls_session_t *p_session)
739 {
740     tls_session_sys_t *p_sys = p_session->p_sys;
741     (void)p_server;
742
743     if( p_sys->b_handshaked )
744         gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
745     gnutls_deinit( p_sys->session );
746
747     vlc_object_release( p_session );
748
749     free( p_sys );
750 }
751
752
753 /**
754  * Initializes a server-side TLS session.
755  */
756 static tls_session_t *
757 gnutls_ServerSessionPrepare( tls_server_t *p_server )
758 {
759     tls_session_t *p_session;
760     tls_server_sys_t *p_server_sys;
761     gnutls_session_t session;
762     int i_val;
763
764     p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
765     if( p_session == NULL )
766         return NULL;
767
768     p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
769     if( p_session->p_sys == NULL )
770     {
771         vlc_object_release( p_session );
772         return NULL;
773     }
774
775     p_server_sys = p_server->p_sys;
776     p_session->sock.p_sys = p_session;
777     p_session->sock.pf_send = gnutls_Send;
778     p_session->sock.pf_recv = gnutls_Recv;
779     p_session->pf_set_fd = gnutls_SetFD;
780     p_session->pf_handshake = p_server_sys->pf_handshake;
781
782     p_session->p_sys->b_handshaked = false;
783     p_session->p_sys->psz_hostname = NULL;
784
785     i_val = gnutls_init( &session, GNUTLS_SERVER );
786     if( i_val != 0 )
787     {
788         msg_Err( p_server, "cannot initialize TLS session: %s",
789                  gnutls_strerror( i_val ) );
790         goto error;
791     }
792
793     p_session->p_sys->session = session;
794
795     if (gnutls_SessionPrioritize (VLC_OBJECT (p_session), session))
796     {
797         gnutls_deinit( session );
798         goto error;
799     }
800
801     i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
802                                     p_server_sys->x509_cred );
803     if( i_val < 0 )
804     {
805         msg_Err( p_server, "cannot set TLS session credentials: %s",
806                  gnutls_strerror( i_val ) );
807         gnutls_deinit( session );
808         goto error;
809     }
810
811     if (p_session->pf_handshake == gnutls_HandshakeAndValidate)
812         gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUIRE);
813
814     return p_session;
815
816 error:
817     free( p_session->p_sys );
818     vlc_object_release( p_session );
819     return NULL;
820 }
821
822
823 /**
824  * Adds one or more certificate authorities.
825  *
826  * @param psz_ca_path (Unicode) path to an x509 certificates list.
827  *
828  * @return -1 on error, 0 on success.
829  */
830 static int
831 gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
832 {
833     tls_server_sys_t *p_sys;
834     char *psz_local_path;
835     int val;
836
837     p_sys = (tls_server_sys_t *)(p_server->p_sys);
838
839     psz_local_path = ToLocale( psz_ca_path );
840     val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
841                                                   psz_local_path,
842                                                   GNUTLS_X509_FMT_PEM );
843     LocaleFree( psz_local_path );
844     if( val < 0 )
845     {
846         msg_Err( p_server, "cannot add trusted CA (%s): %s", psz_ca_path,
847                  gnutls_strerror( val ) );
848         return VLC_EGENERIC;
849     }
850     msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
851
852     /* enables peer's certificate verification */
853     p_sys->pf_handshake = gnutls_HandshakeAndValidate;
854
855     return VLC_SUCCESS;
856 }
857
858
859 /**
860  * Adds a certificates revocation list to be sent to TLS clients.
861  *
862  * @param psz_crl_path (Unicode) path of the CRL file.
863  *
864  * @return -1 on error, 0 on success.
865  */
866 static int
867 gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
868 {
869     int val;
870     char *psz_local_path = ToLocale( psz_crl_path );
871
872     val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
873                                                 (p_server->p_sys))->x509_cred,
874                                                 psz_local_path,
875                                                 GNUTLS_X509_FMT_PEM );
876     LocaleFree( psz_crl_path );
877     if( val < 0 )
878     {
879         msg_Err( p_server, "cannot add CRL (%s): %s", psz_crl_path,
880                  gnutls_strerror( val ) );
881         return VLC_EGENERIC;
882     }
883     msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );
884     return VLC_SUCCESS;
885 }
886
887
888 /**
889  * Allocates a whole server's TLS credentials.
890  */
891 static int OpenServer (vlc_object_t *obj)
892 {
893     tls_server_t *p_server = (tls_server_t *)obj;
894     tls_server_sys_t *p_sys;
895     int val;
896
897     if (gnutls_Init (obj))
898         return VLC_EGENERIC;
899
900     msg_Dbg (obj, "creating TLS server");
901
902     p_sys = (tls_server_sys_t *)malloc( sizeof(struct tls_server_sys_t) );
903     if( p_sys == NULL )
904         return VLC_ENOMEM;
905
906     p_server->p_sys = p_sys;
907     p_server->pf_add_CA  = gnutls_ServerAddCA;
908     p_server->pf_add_CRL = gnutls_ServerAddCRL;
909     p_server->pf_open    = gnutls_ServerSessionPrepare;
910     p_server->pf_close   = gnutls_SessionClose;
911
912     /* No certificate validation by default */
913     p_sys->pf_handshake  = gnutls_ContinueHandshake;
914
915     /* Sets server's credentials */
916     val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
917     if( val != 0 )
918     {
919         msg_Err( p_server, "cannot allocate X509 credentials: %s",
920                  gnutls_strerror( val ) );
921         goto error;
922     }
923
924     char *psz_cert_path = var_GetNonEmptyString (obj, "tls-x509-cert");
925     char *psz_key_path = var_GetNonEmptyString (obj, "tls-x509-key");
926     const char *psz_local_cert = ToLocale (psz_cert_path);
927     const char *psz_local_key = ToLocale (psz_key_path);
928     val = gnutls_certificate_set_x509_key_file (p_sys->x509_cred,
929                                                 psz_local_cert, psz_local_key,
930                                                 GNUTLS_X509_FMT_PEM );
931     LocaleFree (psz_local_key);
932     free (psz_key_path);
933     LocaleFree (psz_local_cert);
934     free (psz_cert_path);
935
936     if( val < 0 )
937     {
938         msg_Err( p_server, "cannot set certificate chain or private key: %s",
939                  gnutls_strerror( val ) );
940         gnutls_certificate_free_credentials( p_sys->x509_cred );
941         goto error;
942     }
943
944     /* FIXME:
945      * - support other ciper suites
946      */
947     val = gnutls_dh_params_init (&p_sys->dh_params);
948     if (val >= 0)
949     {
950         const gnutls_datum_t data = {
951             .data = (unsigned char *)dh_params,
952             .size = sizeof (dh_params) - 1,
953         };
954
955         val = gnutls_dh_params_import_pkcs3 (p_sys->dh_params, &data,
956                                              GNUTLS_X509_FMT_PEM);
957         if (val == 0)
958             gnutls_certificate_set_dh_params (p_sys->x509_cred,
959                                               p_sys->dh_params);
960     }
961     if (val < 0)
962     {
963         msg_Err (p_server, "cannot initialize DHE cipher suites: %s",
964                  gnutls_strerror (val));
965     }
966
967     return VLC_SUCCESS;
968
969 error:
970     free (p_sys);
971     return VLC_EGENERIC;
972 }
973
974 /**
975  * Destroys a TLS server object.
976  */
977 static void CloseServer (vlc_object_t *p_server)
978 {
979     tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
980
981     /* all sessions depending on the server are now deinitialized */
982     gnutls_certificate_free_credentials (p_sys->x509_cred);
983     gnutls_dh_params_deinit (p_sys->dh_params);
984     free (p_sys);
985
986     gnutls_Deinit (p_server);
987 }