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