1 /*****************************************************************************
3 *****************************************************************************
4 * Copyright (C) 2004-2006 Rémi Denis-Courmont
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 /*****************************************************************************
26 *****************************************************************************/
32 #include <sys/types.h>
37 #ifdef HAVE_SYS_STAT_H
38 # include <sys/stat.h>
46 #include <vlc_charset.h>
49 #include <gnutls/gnutls.h>
50 #include <gnutls/x509.h>
53 #define CACHE_TIMEOUT 3600
56 /*****************************************************************************
58 *****************************************************************************/
59 static int OpenClient (vlc_object_t *);
60 static void CloseClient (vlc_object_t *);
61 static int OpenServer (vlc_object_t *);
62 static void CloseServer (vlc_object_t *);
64 #define DH_BITS_TEXT N_("Diffie-Hellman prime bits")
65 #define DH_BITS_LONGTEXT N_( \
66 "This allows you to modify the Diffie-Hellman prime's number of bits, " \
67 "used for TLS or SSL-based server-side encryption. This is generally " \
70 #define CACHE_TIMEOUT_TEXT N_("Expiration time for resumed TLS sessions")
71 #define CACHE_TIMEOUT_LONGTEXT N_( \
72 "It is possible to cache the resumed TLS sessions. This is the expiration "\
73 "time of the sessions stored in this cache, in seconds." )
75 #define CACHE_SIZE_TEXT N_("Number of resumed TLS sessions")
76 #define CACHE_SIZE_LONGTEXT N_( \
77 "This is the maximum number of resumed TLS sessions that " \
78 "the cache will hold." )
80 #define CHECK_CERT_TEXT N_("Check TLS/SSL server certificate validity")
81 #define CHECK_CERT_LONGTEXT N_( \
82 "This ensures that the server certificate is valid " \
83 "(i.e. signed by an approved Certification Authority)." )
86 set_shortname( "GnuTLS" );
87 set_description( _("GnuTLS transport layer security") );
88 set_capability( "tls client", 1 );
89 set_callbacks( OpenClient, CloseClient );
90 set_category( CAT_ADVANCED );
91 set_subcategory( SUBCAT_ADVANCED_MISC );
93 add_bool( "tls-check-cert", VLC_TRUE, NULL, CHECK_CERT_TEXT,
94 CHECK_CERT_LONGTEXT, VLC_FALSE );
95 add_obsolete_bool( "tls-check-hostname" );
98 set_description( _("GnuTLS server") );
99 set_capability( "tls server", 1 );
100 set_category( CAT_ADVANCED );
101 set_subcategory( SUBCAT_ADVANCED_MISC );
102 set_callbacks( OpenServer, CloseServer );
104 add_integer( "gnutls-dh-bits", DH_BITS, NULL, DH_BITS_TEXT,
105 DH_BITS_LONGTEXT, VLC_TRUE );
106 add_integer( "gnutls-cache-timeout", CACHE_TIMEOUT, NULL,
107 CACHE_TIMEOUT_TEXT, CACHE_TIMEOUT_LONGTEXT, VLC_TRUE );
108 add_integer( "gnutls-cache-size", CACHE_SIZE, NULL, CACHE_SIZE_TEXT,
109 CACHE_SIZE_LONGTEXT, VLC_TRUE );
114 #ifdef LIBVLC_USE_PTHREAD
115 GCRY_THREAD_OPTION_PTHREAD_IMPL;
116 # define gcry_threads_vlc gcry_threads_pthread
119 * gcrypt thread option VLC implementation
122 # define NEED_THREAD_CONTEXT 1
123 static vlc_object_t *__p_gcry_data = NULL;
125 static int gcry_vlc_mutex_init( void **p_sys )
128 vlc_mutex_t *p_lock = (vlc_mutex_t *)malloc( sizeof( vlc_mutex_t ) );
133 i_val = vlc_mutex_init( __p_gcry_data, p_lock );
141 static int gcry_vlc_mutex_destroy( void **p_sys )
144 vlc_mutex_t *p_lock = (vlc_mutex_t *)*p_sys;
146 i_val = vlc_mutex_destroy( p_lock );
151 static int gcry_vlc_mutex_lock( void **p_sys )
153 return vlc_mutex_lock( (vlc_mutex_t *)*p_sys );
156 static int gcry_vlc_mutex_unlock( void **lock )
158 return vlc_mutex_unlock( (vlc_mutex_t *)*lock );
161 static struct gcry_thread_cbs gcry_threads_vlc =
163 GCRY_THREAD_OPTION_USER,
166 gcry_vlc_mutex_destroy,
168 gcry_vlc_mutex_unlock
174 * Initializes GnuTLS with proper locking.
175 * @return VLC_SUCCESS on success, a VLC error code otherwise.
177 static int gnutls_Init (vlc_object_t *p_this)
179 int ret = VLC_EGENERIC;
181 vlc_mutex_t *lock = var_GetGlobalMutex ("gnutls_mutex");
182 vlc_mutex_lock (lock);
184 /* This should probably be removed/fixed. It will screw up with multiple
185 * LibVLC instances. */
186 #ifdef NEED_THREAD_CONTEXT
187 __p_gcry_data = VLC_OBJECT (p_this->p_libvlc);
190 gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_vlc);
191 if (gnutls_global_init ())
193 msg_Err (p_this, "cannot initialize GnuTLS");
197 const char *psz_version = gnutls_check_version ("1.3.3");
198 if (psz_version == NULL)
200 msg_Err (p_this, "unsupported GnuTLS version");
201 gnutls_global_deinit ();
205 msg_Dbg (p_this, "GnuTLS v%s initialized", psz_version);
209 vlc_mutex_unlock (lock);
215 * Deinitializes GnuTLS.
217 static void gnutls_Deinit (vlc_object_t *p_this)
219 vlc_mutex_t *lock = var_GetGlobalMutex( "gnutls_mutex" );
220 vlc_mutex_lock (lock);
222 gnutls_global_deinit ();
223 msg_Dbg (p_this, "GnuTLS deinitialized");
224 vlc_mutex_unlock (lock);
228 static int gnutls_Error (vlc_object_t *obj, int val)
237 /* WinSock does not return EAGAIN, return EINTR instead */
239 case GNUTLS_E_INTERRUPTED:
241 WSASetLastError (WSAEINTR);
248 msg_Err (obj, "%s", gnutls_strerror (val));
250 if (!gnutls_error_is_fatal (val))
251 msg_Err (obj, "Error above should be handled");
254 WSASetLastError (WSAECONNRESET);
263 struct tls_session_sys_t
265 gnutls_session_t session;
267 vlc_bool_t b_handshaked;
272 * Sends data through a TLS session.
275 gnutls_Send( void *p_session, const void *buf, int i_length )
278 tls_session_sys_t *p_sys;
280 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
282 val = gnutls_record_send( p_sys->session, buf, i_length );
283 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
288 * Receives data through a TLS session.
291 gnutls_Recv( void *p_session, void *buf, int i_length )
294 tls_session_sys_t *p_sys;
296 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
298 val = gnutls_record_recv( p_sys->session, buf, i_length );
299 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
304 * Starts or continues the TLS handshake.
306 * @return -1 on fatal error, 0 on succesful handshake completion,
307 * 1 if more would-be blocking recv is needed,
308 * 2 if more would-be blocking send is required.
311 gnutls_ContinueHandshake (tls_session_t *p_session)
313 tls_session_sys_t *p_sys = p_session->p_sys;
317 WSASetLastError( 0 );
319 val = gnutls_handshake( p_sys->session );
320 if( ( val == GNUTLS_E_AGAIN ) || ( val == GNUTLS_E_INTERRUPTED ) )
321 return 1 + gnutls_record_get_direction( p_sys->session );
326 msg_Dbg( p_session, "Winsock error %d", WSAGetLastError( ) );
328 msg_Err( p_session, "TLS handshake error: %s",
329 gnutls_strerror( val ) );
333 p_sys->b_handshaked = VLC_TRUE;
344 static const error_msg_t cert_errors[] =
346 { GNUTLS_CERT_INVALID,
347 "Certificate could not be verified" },
348 { GNUTLS_CERT_REVOKED,
349 "Certificate was revoked" },
350 { GNUTLS_CERT_SIGNER_NOT_FOUND,
351 "Certificate's signer was not found" },
352 { GNUTLS_CERT_SIGNER_NOT_CA,
353 "Certificate's signer is not a CA" },
354 { GNUTLS_CERT_INSECURE_ALGORITHM,
355 "Insecure certificate signature algorithm" },
361 gnutls_HandshakeAndValidate( tls_session_t *session )
363 int val = gnutls_ContinueHandshake( session );
367 tls_session_sys_t *p_sys = (tls_session_sys_t *)(session->p_sys);
369 /* certificates chain verification */
371 val = gnutls_certificate_verify_peers2( p_sys->session, &status );
375 msg_Err( session, "Certificate verification failed: %s",
376 gnutls_strerror( val ) );
382 msg_Err( session, "TLS session: access denied" );
383 for( const error_msg_t *e = cert_errors; e->flag; e++ )
385 if( status & e->flag )
387 msg_Err( session, "%s", e->msg );
394 "unknown certificate error (you found a bug in VLC)" );
399 /* certificate (host)name verification */
400 const gnutls_datum_t *data;
401 data = gnutls_certificate_get_peers (p_sys->session, &(unsigned){0});
404 msg_Err( session, "Peer certificate not available" );
408 gnutls_x509_crt_t cert;
409 val = gnutls_x509_crt_init( &cert );
412 msg_Err( session, "x509 fatal error: %s", gnutls_strerror( val ) );
416 val = gnutls_x509_crt_import( cert, data, GNUTLS_X509_FMT_DER );
419 msg_Err( session, "Certificate import error: %s",
420 gnutls_strerror( val ) );
424 if( p_sys->psz_hostname != NULL )
426 if ( !gnutls_x509_crt_check_hostname( cert, p_sys->psz_hostname ) )
428 msg_Err( session, "Certificate does not match \"%s\"",
429 p_sys->psz_hostname );
434 msg_Warn( session, "Certificate and hostname were not verified" );
436 if( gnutls_x509_crt_get_expiration_time( cert ) < time( NULL ) )
438 msg_Err( session, "Certificate expired" );
442 if( gnutls_x509_crt_get_activation_time( cert ) > time ( NULL ) )
444 msg_Err( session, "Certificate not yet valid" );
448 gnutls_x509_crt_deinit( cert );
449 msg_Dbg( session, "TLS/x509 certificate verified" );
453 gnutls_x509_crt_deinit( cert );
458 * Sets the operating system file descriptor backend for the TLS sesison.
460 * @param fd stream socket already connected with the peer.
463 gnutls_SetFD (tls_session_t *p_session, int fd)
465 gnutls_transport_set_ptr (p_session->p_sys->session,
466 (gnutls_transport_ptr_t)(intptr_t)fd);
469 typedef int (*tls_prio_func) (gnutls_session_t, const int *);
472 gnutls_SetPriority (vlc_object_t *restrict obj, const char *restrict name,
473 tls_prio_func func, gnutls_session_t session,
474 const int *restrict values)
476 int val = func (session, values);
479 msg_Err (obj, "cannot set %s priorities: %s", name,
480 gnutls_strerror (val));
488 gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
490 /* Note that ordering matters (on the client side) */
491 static const int protos[] =
498 static const int comps[] =
504 static const int macs[] =
507 GNUTLS_MAC_RMD160, // RIPEMD
513 static const int ciphers[] =
515 GNUTLS_CIPHER_AES_256_CBC,
516 GNUTLS_CIPHER_AES_128_CBC,
517 GNUTLS_CIPHER_3DES_CBC,
518 GNUTLS_CIPHER_ARCFOUR_128,
519 //GNUTLS_CIPHER_DES_CBC,
520 //GNUTLS_CIPHER_ARCFOUR_40,
521 //GNUTLS_CIPHER_RC2_40_CBC,
522 //GNUTLS_CIPHER_NULL,
525 static const int kx[] =
530 //GNUTLS_KX_RSA_EXPORT,
531 //GNUTLS_KX_DHE_PSK, TODO
532 //GNUTLS_KX_PSK, TODO
533 //GNUTLS_KX_SRP_RSA, TODO
534 //GNUTLS_KX_SRP_DSS, TODO
535 //GNUTLS_KX_SRP, TODO
539 static const int cert_types[] =
542 //GNUTLS_CRT_OPENPGP, TODO
546 int val = gnutls_set_default_priority (session);
549 msg_Err (obj, "cannot set default TLS priorities: %s",
550 gnutls_strerror (val));
554 if (gnutls_SetPriority (obj, "protocols",
555 gnutls_protocol_set_priority, session, protos)
556 || gnutls_SetPriority (obj, "compression algorithms",
557 gnutls_compression_set_priority, session, comps)
558 || gnutls_SetPriority (obj, "MAC algorithms",
559 gnutls_mac_set_priority, session, macs)
560 || gnutls_SetPriority (obj, "ciphers",
561 gnutls_cipher_set_priority, session, ciphers)
562 || gnutls_SetPriority (obj, "key exchange algorithms",
563 gnutls_kx_set_priority, session, kx)
564 || gnutls_SetPriority (obj, "certificate types",
565 gnutls_certificate_type_set_priority, session,
574 gnutls_Addx509File( vlc_object_t *p_this,
575 gnutls_certificate_credentials_t cred,
576 const char *psz_path, vlc_bool_t b_priv );
579 gnutls_Addx509Directory( vlc_object_t *p_this,
580 gnutls_certificate_credentials_t cred,
581 const char *psz_dirname,
586 if( *psz_dirname == '\0' )
589 dir = utf8_opendir( psz_dirname );
594 msg_Err (p_this, "cannot open directory (%s): %m", psz_dirname);
598 msg_Dbg (p_this, "creating empty certificate directory: %s",
600 utf8_mkdir (psz_dirname, b_priv ? 0700 : 0755);
606 struct stat st1, st2;
607 int fd = dirfd( dir );
610 * Gets stats for the directory path, checks that it is not a
611 * symbolic link (to avoid possibly infinite recursion), and verifies
612 * that the inode is still the same, to avoid TOCTOU race condition.
615 || fstat( fd, &st1 ) || utf8_lstat( psz_dirname, &st2 )
616 || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
626 char *ent = utf8_readdir (dir);
630 if ((strcmp (ent, ".") == 0) || (strcmp (ent, "..") == 0))
633 char path[strlen (psz_dirname) + strlen (ent) + 2];
634 sprintf (path, "%s"DIR_SEP"%s", psz_dirname, ent);
637 gnutls_Addx509File( p_this, cred, path, b_priv );
646 gnutls_Addx509File( vlc_object_t *p_this,
647 gnutls_certificate_credentials cred,
648 const char *psz_path, vlc_bool_t b_priv )
652 if( utf8_stat( psz_path, &st ) == 0 )
654 if( S_ISREG( st.st_mode ) )
656 char *psz_localname = ToLocale( psz_path );
658 ? gnutls_certificate_set_x509_key_file( cred,
659 psz_localname, psz_localname, GNUTLS_X509_FMT_PEM )
660 : gnutls_certificate_set_x509_trust_file( cred,
661 psz_localname, GNUTLS_X509_FMT_PEM );
662 LocaleFree( psz_localname );
666 msg_Warn( p_this, "cannot add x509 credentials (%s): %s",
667 psz_path, gnutls_strerror( i ) );
672 msg_Dbg( p_this, "added x509 credentials (%s)",
677 else if( S_ISDIR( st.st_mode ) )
680 "looking recursively for x509 credentials in %s",
682 return gnutls_Addx509Directory( p_this, cred, psz_path, b_priv);
686 msg_Warn( p_this, "cannot add x509 credentials (%s): %m", psz_path );
691 /** TLS client session data */
692 typedef struct tls_client_sys_t
694 struct tls_session_sys_t session;
695 gnutls_certificate_credentials_t x509_cred;
700 * Initializes a client-side TLS session.
702 static int OpenClient (vlc_object_t *obj)
704 tls_session_t *p_session = (tls_session_t *)obj;
707 if (gnutls_Init (obj))
710 tls_client_sys_t *p_sys = malloc (sizeof (*p_sys));
717 p_session->p_sys = &p_sys->session;
718 p_session->sock.p_sys = p_session;
719 p_session->sock.pf_send = gnutls_Send;
720 p_session->sock.pf_recv = gnutls_Recv;
721 p_session->pf_set_fd = gnutls_SetFD;
723 p_sys->session.b_handshaked = VLC_FALSE;
724 p_sys->session.psz_hostname = NULL;
726 const char *homedir = obj->p_libvlc->psz_datadir,
727 *datadir = config_GetDataDir ();
728 size_t l1 = strlen (homedir), l2 = strlen (datadir);
729 char path[((l1 > l2) ? l1 : l2) + sizeof ("/ca-certificates.crt")];
730 // > sizeof ("/ssl/private")
731 // > sizeof ("/ssl/certs")
733 i_val = gnutls_certificate_allocate_credentials (&p_sys->x509_cred);
736 msg_Err (obj, "cannot allocate X509 credentials: %s",
737 gnutls_strerror (i_val));
741 sprintf (path, "%s/ssl", homedir);
744 if (var_CreateGetBool (obj, "tls-check-cert"))
746 sprintf (path, "%s/ssl/certs", homedir);
747 gnutls_Addx509Directory (VLC_OBJECT (p_session),
748 p_sys->x509_cred, path, VLC_FALSE);
750 sprintf (path, "%s/ca-certificates.crt", datadir);
751 gnutls_Addx509File (VLC_OBJECT (p_session),
752 p_sys->x509_cred, path, VLC_FALSE);
753 p_session->pf_handshake = gnutls_HandshakeAndValidate;
756 p_session->pf_handshake = gnutls_ContinueHandshake;
758 sprintf (path, "%s/ssl/private", homedir);
759 gnutls_Addx509Directory (VLC_OBJECT (p_session), p_sys->x509_cred,
762 i_val = gnutls_init (&p_sys->session.session, GNUTLS_CLIENT);
765 msg_Err (obj, "cannot initialize TLS session: %s",
766 gnutls_strerror (i_val));
767 gnutls_certificate_free_credentials (p_sys->x509_cred);
771 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session),
772 p_sys->session.session))
775 i_val = gnutls_credentials_set (p_sys->session.session,
776 GNUTLS_CRD_CERTIFICATE,
780 msg_Err (obj, "cannot set TLS session credentials: %s",
781 gnutls_strerror (i_val));
785 char *servername = var_GetNonEmptyString (p_session, "tls-server-name");
786 if (servername != NULL )
788 p_sys->session.psz_hostname = servername;
789 gnutls_server_name_set (p_sys->session.session, GNUTLS_NAME_DNS,
790 servername, strlen (servername));
796 gnutls_deinit (p_sys->session.session);
797 gnutls_certificate_free_credentials (p_sys->x509_cred);
805 static void CloseClient (vlc_object_t *obj)
807 tls_session_t *client = (tls_session_t *)obj;
808 tls_client_sys_t *p_sys = (tls_client_sys_t *)(client->p_sys);
810 if (p_sys->session.b_handshaked == VLC_TRUE)
811 gnutls_bye (p_sys->session.session, GNUTLS_SHUT_WR);
812 gnutls_deinit (p_sys->session.session);
813 /* credentials must be free'd *after* gnutls_deinit() */
814 gnutls_certificate_free_credentials (p_sys->x509_cred);
817 free (p_sys->session.psz_hostname);
825 struct tls_server_sys_t
827 gnutls_certificate_credentials_t x509_cred;
828 gnutls_dh_params_t dh_params;
830 struct saved_session_t *p_cache;
831 struct saved_session_t *p_store;
833 vlc_mutex_t cache_lock;
835 int (*pf_handshake) (tls_session_t *);
840 * TLS session resumption callbacks (server-side)
842 #define MAX_SESSION_ID 32
843 #define MAX_SESSION_DATA 1024
845 typedef struct saved_session_t
847 char id[MAX_SESSION_ID];
848 char data[MAX_SESSION_DATA];
855 static int cb_store( void *p_server, gnutls_datum key, gnutls_datum data )
857 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
859 if( ( p_sys->i_cache_size == 0 )
860 || ( key.size > MAX_SESSION_ID )
861 || ( data.size > MAX_SESSION_DATA ) )
864 vlc_mutex_lock( &p_sys->cache_lock );
866 memcpy( p_sys->p_store->id, key.data, key.size);
867 memcpy( p_sys->p_store->data, data.data, data.size );
868 p_sys->p_store->i_idlen = key.size;
869 p_sys->p_store->i_datalen = data.size;
872 if( ( p_sys->p_store - p_sys->p_cache ) == p_sys->i_cache_size )
873 p_sys->p_store = p_sys->p_cache;
875 vlc_mutex_unlock( &p_sys->cache_lock );
881 static gnutls_datum cb_fetch( void *p_server, gnutls_datum key )
883 static const gnutls_datum_t err_datum = { NULL, 0 };
884 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
885 saved_session_t *p_session, *p_end;
887 p_session = p_sys->p_cache;
888 p_end = p_session + p_sys->i_cache_size;
890 vlc_mutex_lock( &p_sys->cache_lock );
892 while( p_session < p_end )
894 if( ( p_session->i_idlen == key.size )
895 && !memcmp( p_session->id, key.data, key.size ) )
899 data.size = p_session->i_datalen;
901 data.data = gnutls_malloc( data.size );
902 if( data.data == NULL )
904 vlc_mutex_unlock( &p_sys->cache_lock );
908 memcpy( data.data, p_session->data, data.size );
909 vlc_mutex_unlock( &p_sys->cache_lock );
915 vlc_mutex_unlock( &p_sys->cache_lock );
921 static int cb_delete( void *p_server, gnutls_datum key )
923 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
924 saved_session_t *p_session, *p_end;
926 p_session = p_sys->p_cache;
927 p_end = p_session + p_sys->i_cache_size;
929 vlc_mutex_lock( &p_sys->cache_lock );
931 while( p_session < p_end )
933 if( ( p_session->i_idlen == key.size )
934 && !memcmp( p_session->id, key.data, key.size ) )
936 p_session->i_datalen = p_session->i_idlen = 0;
937 vlc_mutex_unlock( &p_sys->cache_lock );
943 vlc_mutex_unlock( &p_sys->cache_lock );
950 * Terminates TLS session and releases session data.
951 * You still have to close the socket yourself.
954 gnutls_SessionClose (tls_server_t *p_server, tls_session_t *p_session)
956 tls_session_sys_t *p_sys = p_session->p_sys;
959 if( p_sys->b_handshaked == VLC_TRUE )
960 gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
961 gnutls_deinit( p_sys->session );
963 vlc_object_detach( p_session );
964 vlc_object_destroy( p_session );
971 * Initializes a server-side TLS session.
973 static tls_session_t *
974 gnutls_ServerSessionPrepare( tls_server_t *p_server )
976 tls_session_t *p_session;
977 tls_server_sys_t *p_server_sys;
978 gnutls_session_t session;
981 p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
982 if( p_session == NULL )
985 p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
986 if( p_session->p_sys == NULL )
988 vlc_object_destroy( p_session );
992 p_server_sys = p_server->p_sys;
993 p_session->sock.p_sys = p_session;
994 p_session->sock.pf_send = gnutls_Send;
995 p_session->sock.pf_recv = gnutls_Recv;
996 p_session->pf_set_fd = gnutls_SetFD;
997 p_session->pf_handshake = p_server_sys->pf_handshake;
999 p_session->p_sys->b_handshaked = VLC_FALSE;
1000 p_session->p_sys->psz_hostname = NULL;
1002 i_val = gnutls_init( &session, GNUTLS_SERVER );
1005 msg_Err( p_server, "cannot initialize TLS session: %s",
1006 gnutls_strerror( i_val ) );
1010 p_session->p_sys->session = session;
1012 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session), session))
1014 gnutls_deinit( session );
1018 i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
1019 p_server_sys->x509_cred );
1022 msg_Err( p_server, "cannot set TLS session credentials: %s",
1023 gnutls_strerror( i_val ) );
1024 gnutls_deinit( session );
1028 if (p_session->pf_handshake == gnutls_HandshakeAndValidate)
1029 gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUIRE);
1031 i_val = config_GetInt (p_server, "gnutls-dh-bits");
1032 gnutls_dh_set_prime_bits (session, i_val);
1034 /* Session resumption support */
1035 i_val = config_GetInt (p_server, "gnutls-cache-timeout");
1036 gnutls_db_set_cache_expiration (session, i_val);
1037 gnutls_db_set_retrieve_function( session, cb_fetch );
1038 gnutls_db_set_remove_function( session, cb_delete );
1039 gnutls_db_set_store_function( session, cb_store );
1040 gnutls_db_set_ptr( session, p_server );
1045 free( p_session->p_sys );
1046 vlc_object_detach( p_session );
1047 vlc_object_destroy( p_session );
1053 * Adds one or more certificate authorities.
1055 * @param psz_ca_path (Unicode) path to an x509 certificates list.
1057 * @return -1 on error, 0 on success.
1060 gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
1062 tls_server_sys_t *p_sys;
1063 char *psz_local_path;
1066 p_sys = (tls_server_sys_t *)(p_server->p_sys);
1068 psz_local_path = ToLocale( psz_ca_path );
1069 val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
1071 GNUTLS_X509_FMT_PEM );
1072 LocaleFree( psz_local_path );
1075 msg_Err( p_server, "cannot add trusted CA (%s): %s", psz_ca_path,
1076 gnutls_strerror( val ) );
1077 return VLC_EGENERIC;
1079 msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
1081 /* enables peer's certificate verification */
1082 p_sys->pf_handshake = gnutls_HandshakeAndValidate;
1089 * Adds a certificates revocation list to be sent to TLS clients.
1091 * @param psz_crl_path (Unicode) path of the CRL file.
1093 * @return -1 on error, 0 on success.
1096 gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
1099 char *psz_local_path = ToLocale( psz_crl_path );
1101 val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
1102 (p_server->p_sys))->x509_cred,
1104 GNUTLS_X509_FMT_PEM );
1105 LocaleFree( psz_crl_path );
1108 msg_Err( p_server, "cannot add CRL (%s): %s", psz_crl_path,
1109 gnutls_strerror( val ) );
1110 return VLC_EGENERIC;
1112 msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );
1118 * Allocates a whole server's TLS credentials.
1120 static int OpenServer (vlc_object_t *obj)
1122 tls_server_t *p_server = (tls_server_t *)obj;
1123 tls_server_sys_t *p_sys;
1126 if (gnutls_Init (obj))
1127 return VLC_EGENERIC;
1129 msg_Dbg (obj, "creating TLS server");
1131 p_sys = (tls_server_sys_t *)malloc( sizeof(struct tls_server_sys_t) );
1135 p_sys->i_cache_size = config_GetInt (obj, "gnutls-cache-size");
1136 p_sys->p_cache = calloc (p_sys->i_cache_size,
1137 sizeof (struct saved_session_t));
1138 if (p_sys->p_cache == NULL)
1144 p_sys->p_store = p_sys->p_cache;
1145 p_server->p_sys = p_sys;
1146 p_server->pf_add_CA = gnutls_ServerAddCA;
1147 p_server->pf_add_CRL = gnutls_ServerAddCRL;
1148 p_server->pf_open = gnutls_ServerSessionPrepare;
1149 p_server->pf_close = gnutls_SessionClose;
1151 /* No certificate validation by default */
1152 p_sys->pf_handshake = gnutls_ContinueHandshake;
1154 vlc_mutex_init( p_server, &p_sys->cache_lock );
1156 /* Sets server's credentials */
1157 val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
1160 msg_Err( p_server, "cannot allocate X509 credentials: %s",
1161 gnutls_strerror( val ) );
1165 char *psz_cert_path = var_GetNonEmptyString (obj, "tls-x509-cert");
1166 char *psz_key_path = var_GetNonEmptyString (obj, "tls-x509-key");
1167 const char *psz_local_cert = ToLocale (psz_cert_path);
1168 const char *psz_local_key = ToLocale (psz_key_path);
1169 val = gnutls_certificate_set_x509_key_file (p_sys->x509_cred,
1170 psz_local_cert, psz_local_key,
1171 GNUTLS_X509_FMT_PEM );
1172 LocaleFree (psz_local_key);
1173 free (psz_key_path);
1174 LocaleFree (psz_local_cert);
1175 free (psz_cert_path);
1179 msg_Err( p_server, "cannot set certificate chain or private key: %s",
1180 gnutls_strerror( val ) );
1181 gnutls_certificate_free_credentials( p_sys->x509_cred );
1186 * - regenerate these regularly
1187 * - support other ciper suites
1189 val = gnutls_dh_params_init( &p_sys->dh_params );
1192 msg_Dbg( p_server, "computing DHE ciphers parameters" );
1193 val = gnutls_dh_params_generate2 (p_sys->dh_params,
1194 config_GetInt (obj, "gnutls-dh-bits"));
1196 /* Write the DH parameter to cache */
1197 const char *cachedir = p_server->p_libvlc->psz_cachedir;
1198 char cachefile[strlen (cachedir) + sizeof ("/dh_params.pem")];
1199 sprintf (cachefile, "%s/dh_params.pem", cachedir);
1201 FILE *cache = utf8_fopen (cachefile, "wb");
1205 gnutls_dh_params_export_pkcs3 (p_sys->dh_params,
1206 GNUTLS_X509_FMT_PEM, NULL, &len);
1207 msg_Dbg (p_server, "caching DHE parameters (%u bytes) to %s",
1208 (unsigned)len, cachefile);
1210 unsigned char buf[len];
1211 gnutls_dh_params_export_pkcs3 (p_sys->dh_params,
1212 GNUTLS_X509_FMT_PEM, buf, &len);
1213 if (fwrite (buf, 1, len, cache) != len)
1214 msg_Warn (p_server, "cannot write to %s: %m", cachefile);
1218 msg_Warn (p_server, "cannot open to %s: %m", cachefile);
1223 msg_Err( p_server, "cannot initialize DHE cipher suites: %s",
1224 gnutls_strerror( val ) );
1225 gnutls_certificate_free_credentials( p_sys->x509_cred );
1228 msg_Dbg( p_server, "ciphers parameters computed" );
1230 gnutls_certificate_set_dh_params( p_sys->x509_cred, p_sys->dh_params);
1235 vlc_mutex_destroy (&p_sys->cache_lock);
1236 free (p_sys->p_cache);
1238 return VLC_EGENERIC;
1242 * Destroys a TLS server object.
1244 static void CloseServer (vlc_object_t *p_server)
1246 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
1248 vlc_mutex_destroy (&p_sys->cache_lock);
1249 free (p_sys->p_cache);
1251 /* all sessions depending on the server are now deinitialized */
1252 gnutls_certificate_free_credentials (p_sys->x509_cred);
1253 gnutls_dh_params_deinit (p_sys->dh_params);
1256 gnutls_Deinit (p_server);