Typos
[vlc/asuraparaju-public.git] / modules / misc / gnutls.c
blob5b7a82b63011e5255923a6c3751ae2b0378eec33
1 /*****************************************************************************
2 * gnutls.c
3 *****************************************************************************
4 * Copyright (C) 2004-2006 Rémi Denis-Courmont
5 * $Id$
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
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.
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.
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 *****************************************************************************/
24 /*****************************************************************************
25 * Preamble
26 *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <errno.h>
35 #include <time.h>
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>
53 #include <vlc_tls.h>
54 #include <vlc_charset.h>
55 #include <vlc_fs.h>
56 #include <vlc_block.h>
58 #include <gcrypt.h>
59 #include <gnutls/gnutls.h>
60 #include <gnutls/x509.h>
62 #include <vlc_gcrypt.h>
64 #define CACHE_TIMEOUT 3600
65 #define CACHE_SIZE 64
67 #include "dhparams.h"
69 #include <assert.h>
71 /*****************************************************************************
72 * Module descriptor
73 *****************************************************************************/
74 static int OpenClient (vlc_object_t *);
75 static void CloseClient (vlc_object_t *);
76 static int OpenServer (vlc_object_t *);
77 static void CloseServer (vlc_object_t *);
79 #define CACHE_TIMEOUT_TEXT N_("Expiration time for resumed TLS sessions")
80 #define CACHE_TIMEOUT_LONGTEXT N_( \
81 "It is possible to cache the resumed TLS sessions. This is the expiration "\
82 "time of the sessions stored in this cache, in seconds." )
84 #define CACHE_SIZE_TEXT N_("Number of resumed TLS sessions")
85 #define CACHE_SIZE_LONGTEXT N_( \
86 "This is the maximum number of resumed TLS sessions that " \
87 "the cache will hold." )
89 vlc_module_begin ()
90 set_shortname( "GnuTLS" )
91 set_description( N_("GnuTLS transport layer security") )
92 set_capability( "tls client", 1 )
93 set_callbacks( OpenClient, CloseClient )
94 set_category( CAT_ADVANCED )
95 set_subcategory( SUBCAT_ADVANCED_MISC )
97 add_obsolete_bool( "tls-check-cert" )
98 add_obsolete_bool( "tls-check-hostname" )
100 add_submodule ()
101 set_description( N_("GnuTLS server") )
102 set_capability( "tls server", 1 )
103 set_category( CAT_ADVANCED )
104 set_subcategory( SUBCAT_ADVANCED_MISC )
105 set_callbacks( OpenServer, CloseServer )
107 add_obsolete_integer( "gnutls-dh-bits" )
108 add_integer( "gnutls-cache-timeout", CACHE_TIMEOUT, NULL,
109 CACHE_TIMEOUT_TEXT, CACHE_TIMEOUT_LONGTEXT, true )
110 add_integer( "gnutls-cache-size", CACHE_SIZE, NULL, CACHE_SIZE_TEXT,
111 CACHE_SIZE_LONGTEXT, true )
112 vlc_module_end ()
114 static vlc_mutex_t gnutls_mutex = VLC_STATIC_MUTEX;
117 * Initializes GnuTLS with proper locking.
118 * @return VLC_SUCCESS on success, a VLC error code otherwise.
120 static int gnutls_Init (vlc_object_t *p_this)
122 int ret = VLC_EGENERIC;
124 vlc_gcrypt_init (); /* GnuTLS depends on gcrypt */
126 vlc_mutex_lock (&gnutls_mutex);
127 if (gnutls_global_init ())
129 msg_Err (p_this, "cannot initialize GnuTLS");
130 goto error;
133 const char *psz_version = gnutls_check_version ("1.3.3");
134 if (psz_version == NULL)
136 msg_Err (p_this, "unsupported GnuTLS version");
137 gnutls_global_deinit ();
138 goto error;
141 msg_Dbg (p_this, "GnuTLS v%s initialized", psz_version);
142 ret = VLC_SUCCESS;
144 error:
145 vlc_mutex_unlock (&gnutls_mutex);
146 return ret;
151 * Deinitializes GnuTLS.
153 static void gnutls_Deinit (vlc_object_t *p_this)
155 vlc_mutex_lock (&gnutls_mutex);
157 gnutls_global_deinit ();
158 msg_Dbg (p_this, "GnuTLS deinitialized");
159 vlc_mutex_unlock (&gnutls_mutex);
163 static int gnutls_Error (vlc_object_t *obj, int val)
165 switch (val)
167 case GNUTLS_E_AGAIN:
168 #ifdef WIN32
169 WSASetLastError (WSAEWOULDBLOCK);
170 #else
171 errno = EAGAIN;
172 #endif
173 break;
175 case GNUTLS_E_INTERRUPTED:
176 #ifdef WIN32
177 WSASetLastError (WSAEINTR);
178 #else
179 errno = EINTR;
180 #endif
181 break;
183 default:
184 msg_Err (obj, "%s", gnutls_strerror (val));
185 #ifndef NDEBUG
186 if (!gnutls_error_is_fatal (val))
187 msg_Err (obj, "Error above should be handled");
188 #endif
189 #ifdef WIN32
190 WSASetLastError (WSAECONNRESET);
191 #else
192 errno = ECONNRESET;
193 #endif
195 return -1;
199 struct tls_session_sys_t
201 gnutls_session_t session;
202 char *psz_hostname;
203 bool b_handshaked;
208 * Sends data through a TLS session.
210 static int
211 gnutls_Send( void *p_session, const void *buf, int i_length )
213 int val;
214 tls_session_sys_t *p_sys;
216 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
218 val = gnutls_record_send( p_sys->session, buf, i_length );
219 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
224 * Receives data through a TLS session.
226 static int
227 gnutls_Recv( void *p_session, void *buf, int i_length )
229 int val;
230 tls_session_sys_t *p_sys;
232 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
234 val = gnutls_record_recv( p_sys->session, buf, i_length );
235 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
240 * Starts or continues the TLS handshake.
242 * @return -1 on fatal error, 0 on successful handshake completion,
243 * 1 if more would-be blocking recv is needed,
244 * 2 if more would-be blocking send is required.
246 static int
247 gnutls_ContinueHandshake (tls_session_t *p_session)
249 tls_session_sys_t *p_sys = p_session->p_sys;
250 int val;
252 #ifdef WIN32
253 WSASetLastError( 0 );
254 #endif
255 val = gnutls_handshake( p_sys->session );
256 if( ( val == GNUTLS_E_AGAIN ) || ( val == GNUTLS_E_INTERRUPTED ) )
257 return 1 + gnutls_record_get_direction( p_sys->session );
259 if( val < 0 )
261 #ifdef WIN32
262 msg_Dbg( p_session, "Winsock error %d", WSAGetLastError( ) );
263 #endif
264 msg_Err( p_session, "TLS handshake error: %s",
265 gnutls_strerror( val ) );
266 return -1;
269 p_sys->b_handshaked = true;
270 return 0;
274 typedef struct
276 int flag;
277 const char *msg;
278 } error_msg_t;
280 static const error_msg_t cert_errors[] =
282 { GNUTLS_CERT_INVALID,
283 "Certificate could not be verified" },
284 { GNUTLS_CERT_REVOKED,
285 "Certificate was revoked" },
286 { GNUTLS_CERT_SIGNER_NOT_FOUND,
287 "Certificate's signer was not found" },
288 { GNUTLS_CERT_SIGNER_NOT_CA,
289 "Certificate's signer is not a CA" },
290 { GNUTLS_CERT_INSECURE_ALGORITHM,
291 "Insecure certificate signature algorithm" },
292 { 0, NULL }
296 static int
297 gnutls_HandshakeAndValidate( tls_session_t *session )
299 int val = gnutls_ContinueHandshake( session );
300 if( val )
301 return val;
303 tls_session_sys_t *p_sys = (tls_session_sys_t *)(session->p_sys);
305 /* certificates chain verification */
306 unsigned status;
307 val = gnutls_certificate_verify_peers2( p_sys->session, &status );
309 if( val )
311 msg_Err( session, "Certificate verification failed: %s",
312 gnutls_strerror( val ) );
313 return -1;
316 if( status )
318 msg_Err( session, "TLS session: access denied" );
319 for( const error_msg_t *e = cert_errors; e->flag; e++ )
321 if( status & e->flag )
323 msg_Err( session, "%s", e->msg );
324 status &= ~e->flag;
328 if( status )
329 msg_Err( session,
330 "unknown certificate error (you found a bug in VLC)" );
332 return -1;
335 /* certificate (host)name verification */
336 const gnutls_datum_t *data;
337 data = gnutls_certificate_get_peers (p_sys->session, &(unsigned){0});
338 if( data == NULL )
340 msg_Err( session, "Peer certificate not available" );
341 return -1;
344 gnutls_x509_crt_t cert;
345 val = gnutls_x509_crt_init( &cert );
346 if( val )
348 msg_Err( session, "x509 fatal error: %s", gnutls_strerror( val ) );
349 return -1;
352 val = gnutls_x509_crt_import( cert, data, GNUTLS_X509_FMT_DER );
353 if( val )
355 msg_Err( session, "Certificate import error: %s",
356 gnutls_strerror( val ) );
357 goto error;
360 assert( p_sys->psz_hostname != NULL );
361 if ( !gnutls_x509_crt_check_hostname( cert, p_sys->psz_hostname ) )
363 msg_Err( session, "Certificate does not match \"%s\"",
364 p_sys->psz_hostname );
365 goto error;
368 if( gnutls_x509_crt_get_expiration_time( cert ) < time( NULL ) )
370 msg_Err( session, "Certificate expired" );
371 goto error;
374 if( gnutls_x509_crt_get_activation_time( cert ) > time ( NULL ) )
376 msg_Err( session, "Certificate not yet valid" );
377 goto error;
380 gnutls_x509_crt_deinit( cert );
381 msg_Dbg( session, "TLS/x509 certificate verified" );
382 return 0;
384 error:
385 gnutls_x509_crt_deinit( cert );
386 return -1;
390 * Sets the operating system file descriptor backend for the TLS sesison.
392 * @param fd stream socket already connected with the peer.
394 static void
395 gnutls_SetFD (tls_session_t *p_session, int fd)
397 gnutls_transport_set_ptr (p_session->p_sys->session,
398 (gnutls_transport_ptr_t)(intptr_t)fd);
401 typedef int (*tls_prio_func) (gnutls_session_t, const int *);
403 static int
404 gnutls_SetPriority (vlc_object_t *restrict obj, const char *restrict name,
405 tls_prio_func func, gnutls_session_t session,
406 const int *restrict values)
408 int val = func (session, values);
409 if (val < 0)
411 msg_Err (obj, "cannot set %s priorities: %s", name,
412 gnutls_strerror (val));
413 return VLC_EGENERIC;
415 return VLC_SUCCESS;
419 static int
420 gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
422 /* Note that ordering matters (on the client side) */
423 static const int protos[] =
425 /*GNUTLS_TLS1_2, as of GnuTLS 2.6.5, still not ratified */
426 GNUTLS_TLS1_1,
427 GNUTLS_TLS1_0,
428 GNUTLS_SSL3,
431 static const int comps[] =
433 GNUTLS_COMP_DEFLATE,
434 GNUTLS_COMP_NULL,
437 static const int macs[] =
439 GNUTLS_MAC_SHA512,
440 GNUTLS_MAC_SHA384,
441 GNUTLS_MAC_SHA256,
442 GNUTLS_MAC_SHA1,
443 GNUTLS_MAC_RMD160, // RIPEMD
444 GNUTLS_MAC_MD5,
445 //GNUTLS_MAC_MD2,
446 //GNUTLS_MAC_NULL,
449 static const int ciphers[] =
451 GNUTLS_CIPHER_AES_256_CBC,
452 GNUTLS_CIPHER_AES_128_CBC,
453 GNUTLS_CIPHER_3DES_CBC,
454 GNUTLS_CIPHER_ARCFOUR_128,
455 // TODO? Camellia ciphers?
456 //GNUTLS_CIPHER_DES_CBC,
457 //GNUTLS_CIPHER_ARCFOUR_40,
458 //GNUTLS_CIPHER_RC2_40_CBC,
459 //GNUTLS_CIPHER_NULL,
462 static const int kx[] =
464 GNUTLS_KX_DHE_RSA,
465 GNUTLS_KX_DHE_DSS,
466 GNUTLS_KX_RSA,
467 //GNUTLS_KX_RSA_EXPORT,
468 //GNUTLS_KX_DHE_PSK, TODO
469 //GNUTLS_KX_PSK, TODO
470 //GNUTLS_KX_SRP_RSA, TODO
471 //GNUTLS_KX_SRP_DSS, TODO
472 //GNUTLS_KX_SRP, TODO
473 //GNUTLS_KX_ANON_DH,
476 static const int cert_types[] =
478 GNUTLS_CRT_X509,
479 //GNUTLS_CRT_OPENPGP, TODO
483 int val = gnutls_set_default_priority (session);
484 if (val < 0)
486 msg_Err (obj, "cannot set default TLS priorities: %s",
487 gnutls_strerror (val));
488 return VLC_EGENERIC;
491 if (gnutls_SetPriority (obj, "protocols",
492 gnutls_protocol_set_priority, session, protos)
493 || gnutls_SetPriority (obj, "compression algorithms",
494 gnutls_compression_set_priority, session, comps)
495 || gnutls_SetPriority (obj, "MAC algorithms",
496 gnutls_mac_set_priority, session, macs)
497 || gnutls_SetPriority (obj, "ciphers",
498 gnutls_cipher_set_priority, session, ciphers)
499 || gnutls_SetPriority (obj, "key exchange algorithms",
500 gnutls_kx_set_priority, session, kx)
501 || gnutls_SetPriority (obj, "certificate types",
502 gnutls_certificate_type_set_priority, session,
503 cert_types))
504 return VLC_EGENERIC;
506 return VLC_SUCCESS;
510 static int
511 gnutls_Addx509File( vlc_object_t *p_this,
512 gnutls_certificate_credentials_t cred,
513 const char *psz_path, bool b_priv );
515 static int
516 gnutls_Addx509Directory( vlc_object_t *p_this,
517 gnutls_certificate_credentials_t cred,
518 const char *psz_dirname,
519 bool b_priv )
521 DIR* dir;
523 if( *psz_dirname == '\0' )
524 psz_dirname = ".";
526 dir = vlc_opendir( psz_dirname );
527 if( dir == NULL )
529 if (errno != ENOENT)
531 msg_Err (p_this, "cannot open directory (%s): %m", psz_dirname);
532 return VLC_EGENERIC;
535 msg_Dbg (p_this, "creating empty certificate directory: %s",
536 psz_dirname);
537 vlc_mkdir (psz_dirname, b_priv ? 0700 : 0755);
538 return VLC_SUCCESS;
540 #ifdef S_ISLNK
541 else
543 struct stat st1, st2;
544 int fd = dirfd( dir );
547 * Gets stats for the directory path, checks that it is not a
548 * symbolic link (to avoid possibly infinite recursion), and verifies
549 * that the inode is still the same, to avoid TOCTOU race condition.
551 if( ( fd == -1)
552 || fstat( fd, &st1 ) || vlc_lstat( psz_dirname, &st2 )
553 || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
555 closedir( dir );
556 return VLC_EGENERIC;
559 #endif
561 for (;;)
563 char *ent = vlc_readdir (dir);
564 if (ent == NULL)
565 break;
567 if ((strcmp (ent, ".") == 0) || (strcmp (ent, "..") == 0))
569 free( ent );
570 continue;
573 char path[strlen (psz_dirname) + strlen (ent) + 2];
574 sprintf (path, "%s"DIR_SEP"%s", psz_dirname, ent);
575 free (ent);
577 gnutls_Addx509File( p_this, cred, path, b_priv );
580 closedir( dir );
581 return VLC_SUCCESS;
585 static int
586 gnutls_Addx509File( vlc_object_t *p_this,
587 gnutls_certificate_credentials cred,
588 const char *psz_path, bool b_priv )
590 struct stat st;
592 int fd = vlc_open (psz_path, O_RDONLY);
593 if (fd == -1)
594 goto error;
596 block_t *block = block_File (fd);
597 if (block != NULL)
599 close (fd);
601 gnutls_datum data = {
602 .data = block->p_buffer,
603 .size = block->i_buffer,
605 int res = b_priv
606 ? gnutls_certificate_set_x509_key_mem (cred, &data, &data,
607 GNUTLS_X509_FMT_PEM)
608 : gnutls_certificate_set_x509_trust_mem (cred, &data,
609 GNUTLS_X509_FMT_PEM);
610 block_Release (block);
612 if (res < 0)
614 msg_Warn (p_this, "cannot add x509 credentials (%s): %s",
615 psz_path, gnutls_strerror (res));
616 return VLC_EGENERIC;
618 msg_Dbg (p_this, "added x509 credentials (%s)", psz_path);
619 return VLC_SUCCESS;
622 if (!fstat (fd, &st) && S_ISDIR (st.st_mode))
624 close (fd);
625 msg_Dbg (p_this, "looking recursively for x509 credentials in %s",
626 psz_path);
627 return gnutls_Addx509Directory (p_this, cred, psz_path, b_priv);
630 error:
631 msg_Warn (p_this, "cannot add x509 credentials (%s): %m", psz_path);
632 if (fd != -1)
633 close (fd);
634 return VLC_EGENERIC;
638 /** TLS client session data */
639 typedef struct tls_client_sys_t
641 struct tls_session_sys_t session;
642 gnutls_certificate_credentials_t x509_cred;
643 } tls_client_sys_t;
647 * Initializes a client-side TLS session.
649 static int OpenClient (vlc_object_t *obj)
651 tls_session_t *p_session = (tls_session_t *)obj;
652 int i_val;
654 if (gnutls_Init (obj))
655 return VLC_EGENERIC;
657 tls_client_sys_t *p_sys = malloc (sizeof (*p_sys));
658 if (p_sys == NULL)
660 gnutls_Deinit (obj);
661 return VLC_ENOMEM;
664 p_session->p_sys = &p_sys->session;
665 p_session->sock.p_sys = p_session;
666 p_session->sock.pf_send = gnutls_Send;
667 p_session->sock.pf_recv = gnutls_Recv;
668 p_session->pf_set_fd = gnutls_SetFD;
670 p_sys->session.b_handshaked = false;
672 i_val = gnutls_certificate_allocate_credentials (&p_sys->x509_cred);
673 if (i_val != 0)
675 msg_Err (obj, "cannot allocate X509 credentials: %s",
676 gnutls_strerror (i_val));
677 goto error;
680 char *userdir = config_GetUserDir ( VLC_DATA_DIR );
681 if (userdir != NULL)
683 char path[strlen (userdir) + sizeof ("/ssl/private")];
684 sprintf (path, "%s/ssl", userdir);
685 vlc_mkdir (path, 0755);
687 sprintf (path, "%s/ssl/certs", userdir);
688 gnutls_Addx509Directory (VLC_OBJECT (p_session),
689 p_sys->x509_cred, path, false);
690 sprintf (path, "%s/ssl/private", userdir);
691 gnutls_Addx509Directory (VLC_OBJECT (p_session), p_sys->x509_cred,
692 path, true);
693 free (userdir);
696 const char *confdir = config_GetConfDir ();
698 char path[strlen (confdir)
699 + sizeof ("/ssl/certs/ca-certificates.crt")];
700 sprintf (path, "%s/ssl/certs/ca-certificates.crt", confdir);
701 gnutls_Addx509File (VLC_OBJECT (p_session),
702 p_sys->x509_cred, path, false);
704 p_session->pf_handshake = gnutls_HandshakeAndValidate;
705 /*p_session->pf_handshake = gnutls_ContinueHandshake;*/
707 i_val = gnutls_init (&p_sys->session.session, GNUTLS_CLIENT);
708 if (i_val != 0)
710 msg_Err (obj, "cannot initialize TLS session: %s",
711 gnutls_strerror (i_val));
712 gnutls_certificate_free_credentials (p_sys->x509_cred);
713 goto error;
716 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session),
717 p_sys->session.session))
718 goto s_error;
720 /* minimum DH prime bits */
721 gnutls_dh_set_prime_bits (p_sys->session.session, 1024);
723 i_val = gnutls_credentials_set (p_sys->session.session,
724 GNUTLS_CRD_CERTIFICATE,
725 p_sys->x509_cred);
726 if (i_val < 0)
728 msg_Err (obj, "cannot set TLS session credentials: %s",
729 gnutls_strerror (i_val));
730 goto s_error;
733 char *servername = var_GetNonEmptyString (p_session, "tls-server-name");
734 if (servername == NULL )
735 msg_Err (p_session, "server name missing for TLS session");
736 else
737 gnutls_server_name_set (p_sys->session.session, GNUTLS_NAME_DNS,
738 servername, strlen (servername));
740 p_sys->session.psz_hostname = servername;
742 return VLC_SUCCESS;
744 s_error:
745 gnutls_deinit (p_sys->session.session);
746 gnutls_certificate_free_credentials (p_sys->x509_cred);
747 error:
748 gnutls_Deinit (obj);
749 free (p_sys);
750 return VLC_EGENERIC;
754 static void CloseClient (vlc_object_t *obj)
756 tls_session_t *client = (tls_session_t *)obj;
757 tls_client_sys_t *p_sys = (tls_client_sys_t *)(client->p_sys);
759 if (p_sys->session.b_handshaked == true)
760 gnutls_bye (p_sys->session.session, GNUTLS_SHUT_WR);
761 gnutls_deinit (p_sys->session.session);
762 /* credentials must be free'd *after* gnutls_deinit() */
763 gnutls_certificate_free_credentials (p_sys->x509_cred);
765 gnutls_Deinit (obj);
766 free (p_sys->session.psz_hostname);
767 free (p_sys);
772 * Server-side TLS
774 struct tls_server_sys_t
776 gnutls_certificate_credentials_t x509_cred;
777 gnutls_dh_params_t dh_params;
779 struct saved_session_t *p_cache;
780 struct saved_session_t *p_store;
781 int i_cache_size;
782 vlc_mutex_t cache_lock;
784 int (*pf_handshake) (tls_session_t *);
789 * TLS session resumption callbacks (server-side)
791 #define MAX_SESSION_ID 32
792 #define MAX_SESSION_DATA 1024
794 typedef struct saved_session_t
796 char id[MAX_SESSION_ID];
797 char data[MAX_SESSION_DATA];
799 unsigned i_idlen;
800 unsigned i_datalen;
801 } saved_session_t;
804 static int cb_store( void *p_server, gnutls_datum key, gnutls_datum data )
806 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
808 if( ( p_sys->i_cache_size == 0 )
809 || ( key.size > MAX_SESSION_ID )
810 || ( data.size > MAX_SESSION_DATA ) )
811 return -1;
813 vlc_mutex_lock( &p_sys->cache_lock );
815 memcpy( p_sys->p_store->id, key.data, key.size);
816 memcpy( p_sys->p_store->data, data.data, data.size );
817 p_sys->p_store->i_idlen = key.size;
818 p_sys->p_store->i_datalen = data.size;
820 p_sys->p_store++;
821 if( ( p_sys->p_store - p_sys->p_cache ) == p_sys->i_cache_size )
822 p_sys->p_store = p_sys->p_cache;
824 vlc_mutex_unlock( &p_sys->cache_lock );
826 return 0;
830 static gnutls_datum cb_fetch( void *p_server, gnutls_datum key )
832 static const gnutls_datum_t err_datum = { NULL, 0 };
833 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
834 saved_session_t *p_session, *p_end;
836 p_session = p_sys->p_cache;
837 p_end = p_session + p_sys->i_cache_size;
839 vlc_mutex_lock( &p_sys->cache_lock );
841 while( p_session < p_end )
843 if( ( p_session->i_idlen == key.size )
844 && !memcmp( p_session->id, key.data, key.size ) )
846 gnutls_datum_t data;
848 data.size = p_session->i_datalen;
850 data.data = gnutls_malloc( data.size );
851 if( data.data == NULL )
853 vlc_mutex_unlock( &p_sys->cache_lock );
854 return err_datum;
857 memcpy( data.data, p_session->data, data.size );
858 vlc_mutex_unlock( &p_sys->cache_lock );
859 return data;
861 p_session++;
864 vlc_mutex_unlock( &p_sys->cache_lock );
866 return err_datum;
870 static int cb_delete( void *p_server, gnutls_datum key )
872 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
873 saved_session_t *p_session, *p_end;
875 p_session = p_sys->p_cache;
876 p_end = p_session + p_sys->i_cache_size;
878 vlc_mutex_lock( &p_sys->cache_lock );
880 while( p_session < p_end )
882 if( ( p_session->i_idlen == key.size )
883 && !memcmp( p_session->id, key.data, key.size ) )
885 p_session->i_datalen = p_session->i_idlen = 0;
886 vlc_mutex_unlock( &p_sys->cache_lock );
887 return 0;
889 p_session++;
892 vlc_mutex_unlock( &p_sys->cache_lock );
894 return -1;
899 * Terminates TLS session and releases session data.
900 * You still have to close the socket yourself.
902 static void
903 gnutls_SessionClose (tls_server_t *p_server, tls_session_t *p_session)
905 tls_session_sys_t *p_sys = p_session->p_sys;
906 (void)p_server;
908 if( p_sys->b_handshaked == true )
909 gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
910 gnutls_deinit( p_sys->session );
912 vlc_object_release( p_session );
914 free( p_sys );
919 * Initializes a server-side TLS session.
921 static tls_session_t *
922 gnutls_ServerSessionPrepare( tls_server_t *p_server )
924 tls_session_t *p_session;
925 tls_server_sys_t *p_server_sys;
926 gnutls_session_t session;
927 int i_val;
929 p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
930 if( p_session == NULL )
931 return NULL;
933 p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
934 if( p_session->p_sys == NULL )
936 vlc_object_release( p_session );
937 return NULL;
940 p_server_sys = p_server->p_sys;
941 p_session->sock.p_sys = p_session;
942 p_session->sock.pf_send = gnutls_Send;
943 p_session->sock.pf_recv = gnutls_Recv;
944 p_session->pf_set_fd = gnutls_SetFD;
945 p_session->pf_handshake = p_server_sys->pf_handshake;
947 p_session->p_sys->b_handshaked = false;
948 p_session->p_sys->psz_hostname = NULL;
950 i_val = gnutls_init( &session, GNUTLS_SERVER );
951 if( i_val != 0 )
953 msg_Err( p_server, "cannot initialize TLS session: %s",
954 gnutls_strerror( i_val ) );
955 goto error;
958 p_session->p_sys->session = session;
960 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session), session))
962 gnutls_deinit( session );
963 goto error;
966 i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
967 p_server_sys->x509_cred );
968 if( i_val < 0 )
970 msg_Err( p_server, "cannot set TLS session credentials: %s",
971 gnutls_strerror( i_val ) );
972 gnutls_deinit( session );
973 goto error;
976 if (p_session->pf_handshake == gnutls_HandshakeAndValidate)
977 gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUIRE);
979 /* Session resumption support */
980 i_val = var_InheritInteger (p_server, "gnutls-cache-timeout");
981 if (i_val >= 0)
982 gnutls_db_set_cache_expiration (session, i_val);
983 gnutls_db_set_retrieve_function( session, cb_fetch );
984 gnutls_db_set_remove_function( session, cb_delete );
985 gnutls_db_set_store_function( session, cb_store );
986 gnutls_db_set_ptr( session, p_server );
988 return p_session;
990 error:
991 free( p_session->p_sys );
992 vlc_object_release( p_session );
993 return NULL;
998 * Adds one or more certificate authorities.
1000 * @param psz_ca_path (Unicode) path to an x509 certificates list.
1002 * @return -1 on error, 0 on success.
1004 static int
1005 gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
1007 tls_server_sys_t *p_sys;
1008 char *psz_local_path;
1009 int val;
1011 p_sys = (tls_server_sys_t *)(p_server->p_sys);
1013 psz_local_path = ToLocale( psz_ca_path );
1014 val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
1015 psz_local_path,
1016 GNUTLS_X509_FMT_PEM );
1017 LocaleFree( psz_local_path );
1018 if( val < 0 )
1020 msg_Err( p_server, "cannot add trusted CA (%s): %s", psz_ca_path,
1021 gnutls_strerror( val ) );
1022 return VLC_EGENERIC;
1024 msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
1026 /* enables peer's certificate verification */
1027 p_sys->pf_handshake = gnutls_HandshakeAndValidate;
1029 return VLC_SUCCESS;
1034 * Adds a certificates revocation list to be sent to TLS clients.
1036 * @param psz_crl_path (Unicode) path of the CRL file.
1038 * @return -1 on error, 0 on success.
1040 static int
1041 gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
1043 int val;
1044 char *psz_local_path = ToLocale( psz_crl_path );
1046 val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
1047 (p_server->p_sys))->x509_cred,
1048 psz_local_path,
1049 GNUTLS_X509_FMT_PEM );
1050 LocaleFree( psz_crl_path );
1051 if( val < 0 )
1053 msg_Err( p_server, "cannot add CRL (%s): %s", psz_crl_path,
1054 gnutls_strerror( val ) );
1055 return VLC_EGENERIC;
1057 msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );
1058 return VLC_SUCCESS;
1063 * Allocates a whole server's TLS credentials.
1065 static int OpenServer (vlc_object_t *obj)
1067 tls_server_t *p_server = (tls_server_t *)obj;
1068 tls_server_sys_t *p_sys;
1069 int val;
1071 if (gnutls_Init (obj))
1072 return VLC_EGENERIC;
1074 msg_Dbg (obj, "creating TLS server");
1076 p_sys = (tls_server_sys_t *)malloc( sizeof(struct tls_server_sys_t) );
1077 if( p_sys == NULL )
1078 return VLC_ENOMEM;
1080 p_sys->i_cache_size = var_InheritInteger (obj, "gnutls-cache-size");
1081 if (p_sys->i_cache_size == -1) /* Duh, config subsystem exploded?! */
1082 p_sys->i_cache_size = 0;
1083 p_sys->p_cache = calloc (p_sys->i_cache_size,
1084 sizeof (struct saved_session_t));
1085 if (p_sys->p_cache == NULL)
1087 free (p_sys);
1088 return VLC_ENOMEM;
1091 p_sys->p_store = p_sys->p_cache;
1092 p_server->p_sys = p_sys;
1093 p_server->pf_add_CA = gnutls_ServerAddCA;
1094 p_server->pf_add_CRL = gnutls_ServerAddCRL;
1095 p_server->pf_open = gnutls_ServerSessionPrepare;
1096 p_server->pf_close = gnutls_SessionClose;
1098 /* No certificate validation by default */
1099 p_sys->pf_handshake = gnutls_ContinueHandshake;
1101 vlc_mutex_init( &p_sys->cache_lock );
1103 /* Sets server's credentials */
1104 val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
1105 if( val != 0 )
1107 msg_Err( p_server, "cannot allocate X509 credentials: %s",
1108 gnutls_strerror( val ) );
1109 goto error;
1112 char *psz_cert_path = var_GetNonEmptyString (obj, "tls-x509-cert");
1113 char *psz_key_path = var_GetNonEmptyString (obj, "tls-x509-key");
1114 const char *psz_local_cert = ToLocale (psz_cert_path);
1115 const char *psz_local_key = ToLocale (psz_key_path);
1116 val = gnutls_certificate_set_x509_key_file (p_sys->x509_cred,
1117 psz_local_cert, psz_local_key,
1118 GNUTLS_X509_FMT_PEM );
1119 LocaleFree (psz_local_key);
1120 free (psz_key_path);
1121 LocaleFree (psz_local_cert);
1122 free (psz_cert_path);
1124 if( val < 0 )
1126 msg_Err( p_server, "cannot set certificate chain or private key: %s",
1127 gnutls_strerror( val ) );
1128 gnutls_certificate_free_credentials( p_sys->x509_cred );
1129 goto error;
1132 /* FIXME:
1133 * - support other ciper suites
1135 val = gnutls_dh_params_init (&p_sys->dh_params);
1136 if (val >= 0)
1138 const gnutls_datum_t data = {
1139 .data = (unsigned char *)dh_params,
1140 .size = sizeof (dh_params) - 1,
1143 val = gnutls_dh_params_import_pkcs3 (p_sys->dh_params, &data,
1144 GNUTLS_X509_FMT_PEM);
1145 if (val == 0)
1146 gnutls_certificate_set_dh_params (p_sys->x509_cred,
1147 p_sys->dh_params);
1149 if (val < 0)
1151 msg_Err (p_server, "cannot initialize DHE cipher suites: %s",
1152 gnutls_strerror (val));
1155 return VLC_SUCCESS;
1157 error:
1158 vlc_mutex_destroy (&p_sys->cache_lock);
1159 free (p_sys->p_cache);
1160 free (p_sys);
1161 return VLC_EGENERIC;
1165 * Destroys a TLS server object.
1167 static void CloseServer (vlc_object_t *p_server)
1169 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
1171 vlc_mutex_destroy (&p_sys->cache_lock);
1172 free (p_sys->p_cache);
1174 /* all sessions depending on the server are now deinitialized */
1175 gnutls_certificate_free_credentials (p_sys->x509_cred);
1176 gnutls_dh_params_deinit (p_sys->dh_params);
1177 free (p_sys);
1179 gnutls_Deinit (p_server);