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 <vlc_common.h>
33 #include <vlc_plugin.h>
37 #include <sys/types.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
44 # include <wincrypt.h>
52 #include <vlc_charset.h>
54 #include <vlc_block.h>
57 #include <gnutls/gnutls.h>
58 #include <gnutls/x509.h>
60 #include <vlc_gcrypt.h>
65 /*****************************************************************************
67 *****************************************************************************/
68 static int OpenClient (vlc_object_t *);
69 static void CloseClient (vlc_object_t *);
70 static int OpenServer (vlc_object_t *);
71 static void CloseServer (vlc_object_t *);
73 #define PRIORITIES_TEXT N_("TLS cipher priorities")
74 #define PRIORITIES_LONGTEXT N_("Ciphers, key exchange methods, " \
75 "hash functions and compression methods can be selected. " \
76 "Refer to GNU TLS documentation for detailed syntax.")
77 static const char *const priorities_values[] = {
84 static const char *const priorities_text[] = {
85 N_("Performance (prioritize faster ciphers)"),
87 N_("Secure 128-bits (exclude 256-bits ciphers)"),
88 N_("Secure 256-bits (prioritize 256-bits ciphers)"),
89 N_("Export (include insecure ciphers)"),
93 set_shortname( "GNU TLS" )
94 set_description( N_("GNU TLS transport layer security") )
95 set_capability( "tls client", 1 )
96 set_callbacks( OpenClient, CloseClient )
97 set_category( CAT_ADVANCED )
98 set_subcategory( SUBCAT_ADVANCED_MISC )
101 set_description( N_("GNU TLS server") )
102 set_capability( "tls server", 1 )
103 set_category( CAT_ADVANCED )
104 set_subcategory( SUBCAT_ADVANCED_MISC )
105 set_callbacks( OpenServer, CloseServer )
107 add_string ("gnutls-priorities", "NORMAL", PRIORITIES_TEXT,
108 PRIORITIES_LONGTEXT, false)
109 change_string_list (priorities_values, priorities_text, NULL)
112 static vlc_mutex_t gnutls_mutex = VLC_STATIC_MUTEX;
115 * Initializes GnuTLS with proper locking.
116 * @return VLC_SUCCESS on success, a VLC error code otherwise.
118 static int gnutls_Init (vlc_object_t *p_this)
120 int ret = VLC_EGENERIC;
122 vlc_gcrypt_init (); /* GnuTLS depends on gcrypt */
124 vlc_mutex_lock (&gnutls_mutex);
125 if (gnutls_global_init ())
127 msg_Err (p_this, "cannot initialize GnuTLS");
131 const char *psz_version = gnutls_check_version ("2.0.0");
132 if (psz_version == NULL)
134 msg_Err (p_this, "unsupported GnuTLS version");
135 gnutls_global_deinit ();
139 msg_Dbg (p_this, "GnuTLS v%s initialized", psz_version);
143 vlc_mutex_unlock (&gnutls_mutex);
149 * Deinitializes GnuTLS.
151 static void gnutls_Deinit (vlc_object_t *p_this)
153 vlc_mutex_lock (&gnutls_mutex);
155 gnutls_global_deinit ();
156 msg_Dbg (p_this, "GnuTLS deinitialized");
157 vlc_mutex_unlock (&gnutls_mutex);
161 static int gnutls_Error (vlc_object_t *obj, int val)
167 WSASetLastError (WSAEWOULDBLOCK);
173 case GNUTLS_E_INTERRUPTED:
175 WSASetLastError (WSAEINTR);
182 msg_Err (obj, "%s", gnutls_strerror (val));
184 if (!gnutls_error_is_fatal (val))
185 msg_Err (obj, "Error above should be handled");
188 WSASetLastError (WSAECONNRESET);
197 struct tls_session_sys_t
199 gnutls_session_t session;
206 * Sends data through a TLS session.
209 gnutls_Send( void *p_session, const void *buf, int i_length )
212 tls_session_sys_t *p_sys;
214 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
216 val = gnutls_record_send( p_sys->session, buf, i_length );
217 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
222 * Receives data through a TLS session.
225 gnutls_Recv( void *p_session, void *buf, int i_length )
228 tls_session_sys_t *p_sys;
230 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
232 val = gnutls_record_recv( p_sys->session, buf, i_length );
233 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
238 * Starts or continues the TLS handshake.
240 * @return -1 on fatal error, 0 on successful handshake completion,
241 * 1 if more would-be blocking recv is needed,
242 * 2 if more would-be blocking send is required.
245 gnutls_ContinueHandshake (tls_session_t *p_session)
247 tls_session_sys_t *p_sys = p_session->p_sys;
251 WSASetLastError( 0 );
253 val = gnutls_handshake( p_sys->session );
254 if( ( val == GNUTLS_E_AGAIN ) || ( val == GNUTLS_E_INTERRUPTED ) )
255 return 1 + gnutls_record_get_direction( p_sys->session );
260 msg_Dbg( p_session, "Winsock error %d", WSAGetLastError( ) );
262 msg_Err( p_session, "TLS handshake error: %s",
263 gnutls_strerror( val ) );
267 p_sys->b_handshaked = true;
278 static const error_msg_t cert_errors[] =
280 { GNUTLS_CERT_INVALID,
281 "Certificate could not be verified" },
282 { GNUTLS_CERT_REVOKED,
283 "Certificate was revoked" },
284 { GNUTLS_CERT_SIGNER_NOT_FOUND,
285 "Certificate's signer was not found" },
286 { GNUTLS_CERT_SIGNER_NOT_CA,
287 "Certificate's signer is not a CA" },
288 { GNUTLS_CERT_INSECURE_ALGORITHM,
289 "Insecure certificate signature algorithm" },
295 gnutls_HandshakeAndValidate( tls_session_t *session )
297 int val = gnutls_ContinueHandshake( session );
301 tls_session_sys_t *p_sys = (tls_session_sys_t *)(session->p_sys);
303 /* certificates chain verification */
305 val = gnutls_certificate_verify_peers2( p_sys->session, &status );
309 msg_Err( session, "Certificate verification failed: %s",
310 gnutls_strerror( val ) );
316 msg_Err( session, "TLS session: access denied" );
317 for( const error_msg_t *e = cert_errors; e->flag; e++ )
319 if( status & e->flag )
321 msg_Err( session, "%s", e->msg );
328 "unknown certificate error (you found a bug in VLC)" );
333 /* certificate (host)name verification */
334 const gnutls_datum_t *data;
335 data = gnutls_certificate_get_peers (p_sys->session, &(unsigned){0});
338 msg_Err( session, "Peer certificate not available" );
342 gnutls_x509_crt_t cert;
343 val = gnutls_x509_crt_init( &cert );
346 msg_Err( session, "x509 fatal error: %s", gnutls_strerror( val ) );
350 val = gnutls_x509_crt_import( cert, data, GNUTLS_X509_FMT_DER );
353 msg_Err( session, "Certificate import error: %s",
354 gnutls_strerror( val ) );
358 assert( p_sys->psz_hostname != NULL );
359 if ( !gnutls_x509_crt_check_hostname( cert, p_sys->psz_hostname ) )
361 msg_Err( session, "Certificate does not match \"%s\"",
362 p_sys->psz_hostname );
366 if( gnutls_x509_crt_get_expiration_time( cert ) < time( NULL ) )
368 msg_Err( session, "Certificate expired" );
372 if( gnutls_x509_crt_get_activation_time( cert ) > time ( NULL ) )
374 msg_Err( session, "Certificate not yet valid" );
378 gnutls_x509_crt_deinit( cert );
379 msg_Dbg( session, "TLS/x509 certificate verified" );
383 gnutls_x509_crt_deinit( cert );
388 * Sets the operating system file descriptor backend for the TLS sesison.
390 * @param fd stream socket already connected with the peer.
393 gnutls_SetFD (tls_session_t *p_session, int fd)
395 gnutls_transport_set_ptr (p_session->p_sys->session,
396 (gnutls_transport_ptr_t)(intptr_t)fd);
400 gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
402 char *priorities = var_InheritString (obj, "gnutls-priorities");
403 if (unlikely(priorities == NULL))
407 int val = gnutls_priority_set_direct (session, priorities, &errp);
410 msg_Err (obj, "cannot set TLS priorities \"%s\": %s", errp,
411 gnutls_strerror (val));
422 gnutls_Addx509File( vlc_object_t *p_this,
423 gnutls_certificate_credentials_t cred,
424 const char *psz_path, bool b_priv );
426 static int gnutls_loadOSCAList(vlc_object_t *p_this,
427 gnutls_certificate_credentials_t cred);
431 gnutls_Addx509Directory( vlc_object_t *p_this,
432 gnutls_certificate_credentials_t cred,
433 const char *psz_dirname,
438 if( *psz_dirname == '\0' )
441 dir = vlc_opendir( psz_dirname );
446 msg_Err (p_this, "cannot open directory (%s): %m", psz_dirname);
450 msg_Dbg (p_this, "creating empty certificate directory: %s",
452 vlc_mkdir (psz_dirname, b_priv ? 0700 : 0755);
458 struct stat st1, st2;
459 int fd = dirfd( dir );
462 * Gets stats for the directory path, checks that it is not a
463 * symbolic link (to avoid possibly infinite recursion), and verifies
464 * that the inode is still the same, to avoid TOCTOU race condition.
467 || fstat( fd, &st1 ) || vlc_lstat( psz_dirname, &st2 )
468 || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
478 char *ent = vlc_readdir (dir);
482 if ((strcmp (ent, ".") == 0) || (strcmp (ent, "..") == 0))
488 char path[strlen (psz_dirname) + strlen (ent) + 2];
489 sprintf (path, "%s"DIR_SEP"%s", psz_dirname, ent);
492 gnutls_Addx509File( p_this, cred, path, b_priv );
501 gnutls_Addx509File( vlc_object_t *p_this,
502 gnutls_certificate_credentials cred,
503 const char *psz_path, bool b_priv )
507 int fd = vlc_open (psz_path, O_RDONLY);
511 block_t *block = block_File (fd);
516 gnutls_datum data = {
517 .data = block->p_buffer,
518 .size = block->i_buffer,
521 ? gnutls_certificate_set_x509_key_mem (cred, &data, &data,
523 : gnutls_certificate_set_x509_trust_mem (cred, &data,
524 GNUTLS_X509_FMT_PEM);
525 block_Release (block);
529 msg_Warn (p_this, "cannot add x509 credentials (%s): %s",
530 psz_path, gnutls_strerror (res));
533 msg_Dbg (p_this, "added x509 credentials (%s)", psz_path);
537 if (!fstat (fd, &st) && S_ISDIR (st.st_mode))
540 msg_Dbg (p_this, "looking recursively for x509 credentials in %s",
542 return gnutls_Addx509Directory (p_this, cred, psz_path, b_priv);
546 msg_Warn (p_this, "cannot add x509 credentials (%s): %m", psz_path);
554 gnutls_loadOSCAList( vlc_object_t *p_this,
555 gnutls_certificate_credentials cred)
557 HCERTSTORE hCertStore = CertOpenSystemStoreA((HCRYPTPROV)NULL, "ROOT");
560 msg_Warn (p_this, "could not open the Cert SystemStore");
564 PCCERT_CONTEXT pCertContext = CertEnumCertificatesInStore(hCertStore, NULL);
565 while( pCertContext )
567 gnutls_datum data = {
568 .data = pCertContext->pbCertEncoded,
569 .size = pCertContext->cbCertEncoded,
572 if(!gnutls_certificate_set_x509_trust_mem(cred, &data, GNUTLS_X509_FMT_DER))
574 msg_Warn (p_this, "cannot add x509 credential");
578 pCertContext = CertEnumCertificatesInStore(hCertStore, pCertContext);
584 /** TLS client session data */
585 typedef struct tls_client_sys_t
587 struct tls_session_sys_t session;
588 gnutls_certificate_credentials_t x509_cred;
593 * Initializes a client-side TLS session.
595 static int OpenClient (vlc_object_t *obj)
597 tls_session_t *p_session = (tls_session_t *)obj;
600 if (gnutls_Init (obj))
603 tls_client_sys_t *p_sys = malloc (sizeof (*p_sys));
610 p_session->p_sys = &p_sys->session;
611 p_session->sock.p_sys = p_session;
612 p_session->sock.pf_send = gnutls_Send;
613 p_session->sock.pf_recv = gnutls_Recv;
614 p_session->pf_set_fd = gnutls_SetFD;
616 p_sys->session.b_handshaked = false;
618 i_val = gnutls_certificate_allocate_credentials (&p_sys->x509_cred);
621 msg_Err (obj, "cannot allocate X509 credentials: %s",
622 gnutls_strerror (i_val));
626 char *userdir = config_GetUserDir ( VLC_DATA_DIR );
629 char path[strlen (userdir) + sizeof ("/ssl/private")];
630 sprintf (path, "%s/ssl", userdir);
631 vlc_mkdir (path, 0755);
633 sprintf (path, "%s/ssl/certs", userdir);
634 gnutls_Addx509Directory (VLC_OBJECT (p_session),
635 p_sys->x509_cred, path, false);
636 sprintf (path, "%s/ssl/private", userdir);
637 gnutls_Addx509Directory (VLC_OBJECT (p_session), p_sys->x509_cred,
642 const char *confdir = config_GetConfDir ();
644 char path[strlen (confdir)
645 + sizeof ("/ssl/certs/ca-certificates.crt")];
646 sprintf (path, "%s/ssl/certs/ca-certificates.crt", confdir);
648 gnutls_loadOSCAList (VLC_OBJECT (p_session),
651 gnutls_Addx509File (VLC_OBJECT (p_session),
652 p_sys->x509_cred, path, false);
655 p_session->pf_handshake = gnutls_HandshakeAndValidate;
656 /*p_session->pf_handshake = gnutls_ContinueHandshake;*/
658 i_val = gnutls_init (&p_sys->session.session, GNUTLS_CLIENT);
661 msg_Err (obj, "cannot initialize TLS session: %s",
662 gnutls_strerror (i_val));
663 gnutls_certificate_free_credentials (p_sys->x509_cred);
667 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session),
668 p_sys->session.session))
671 /* minimum DH prime bits */
672 gnutls_dh_set_prime_bits (p_sys->session.session, 1024);
674 i_val = gnutls_credentials_set (p_sys->session.session,
675 GNUTLS_CRD_CERTIFICATE,
679 msg_Err (obj, "cannot set TLS session credentials: %s",
680 gnutls_strerror (i_val));
684 char *servername = var_GetNonEmptyString (p_session, "tls-server-name");
685 if (servername == NULL )
686 msg_Err (p_session, "server name missing for TLS session");
688 gnutls_server_name_set (p_sys->session.session, GNUTLS_NAME_DNS,
689 servername, strlen (servername));
691 p_sys->session.psz_hostname = servername;
696 gnutls_deinit (p_sys->session.session);
697 gnutls_certificate_free_credentials (p_sys->x509_cred);
705 static void CloseClient (vlc_object_t *obj)
707 tls_session_t *client = (tls_session_t *)obj;
708 tls_client_sys_t *p_sys = (tls_client_sys_t *)(client->p_sys);
710 if (p_sys->session.b_handshaked)
711 gnutls_bye (p_sys->session.session, GNUTLS_SHUT_WR);
712 gnutls_deinit (p_sys->session.session);
713 /* credentials must be free'd *after* gnutls_deinit() */
714 gnutls_certificate_free_credentials (p_sys->x509_cred);
717 free (p_sys->session.psz_hostname);
725 struct tls_server_sys_t
727 gnutls_certificate_credentials_t x509_cred;
728 gnutls_dh_params_t dh_params;
729 int (*pf_handshake) (tls_session_t *);
734 * Terminates TLS session and releases session data.
735 * You still have to close the socket yourself.
738 gnutls_SessionClose (tls_server_t *p_server, tls_session_t *p_session)
740 tls_session_sys_t *p_sys = p_session->p_sys;
743 if( p_sys->b_handshaked )
744 gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
745 gnutls_deinit( p_sys->session );
747 vlc_object_release( p_session );
754 * Initializes a server-side TLS session.
756 static tls_session_t *
757 gnutls_ServerSessionPrepare( tls_server_t *p_server )
759 tls_session_t *p_session;
760 tls_server_sys_t *p_server_sys;
761 gnutls_session_t session;
764 p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
765 if( p_session == NULL )
768 p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
769 if( p_session->p_sys == NULL )
771 vlc_object_release( p_session );
775 p_server_sys = p_server->p_sys;
776 p_session->sock.p_sys = p_session;
777 p_session->sock.pf_send = gnutls_Send;
778 p_session->sock.pf_recv = gnutls_Recv;
779 p_session->pf_set_fd = gnutls_SetFD;
780 p_session->pf_handshake = p_server_sys->pf_handshake;
782 p_session->p_sys->b_handshaked = false;
783 p_session->p_sys->psz_hostname = NULL;
785 i_val = gnutls_init( &session, GNUTLS_SERVER );
788 msg_Err( p_server, "cannot initialize TLS session: %s",
789 gnutls_strerror( i_val ) );
793 p_session->p_sys->session = session;
795 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session), session))
797 gnutls_deinit( session );
801 i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
802 p_server_sys->x509_cred );
805 msg_Err( p_server, "cannot set TLS session credentials: %s",
806 gnutls_strerror( i_val ) );
807 gnutls_deinit( session );
811 if (p_session->pf_handshake == gnutls_HandshakeAndValidate)
812 gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUIRE);
817 free( p_session->p_sys );
818 vlc_object_release( p_session );
824 * Adds one or more certificate authorities.
826 * @param psz_ca_path (Unicode) path to an x509 certificates list.
828 * @return -1 on error, 0 on success.
831 gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
833 tls_server_sys_t *p_sys;
834 char *psz_local_path;
837 p_sys = (tls_server_sys_t *)(p_server->p_sys);
839 psz_local_path = ToLocale( psz_ca_path );
840 val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
842 GNUTLS_X509_FMT_PEM );
843 LocaleFree( psz_local_path );
846 msg_Err( p_server, "cannot add trusted CA (%s): %s", psz_ca_path,
847 gnutls_strerror( val ) );
850 msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
852 /* enables peer's certificate verification */
853 p_sys->pf_handshake = gnutls_HandshakeAndValidate;
860 * Adds a certificates revocation list to be sent to TLS clients.
862 * @param psz_crl_path (Unicode) path of the CRL file.
864 * @return -1 on error, 0 on success.
867 gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
870 char *psz_local_path = ToLocale( psz_crl_path );
872 val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
873 (p_server->p_sys))->x509_cred,
875 GNUTLS_X509_FMT_PEM );
876 LocaleFree( psz_crl_path );
879 msg_Err( p_server, "cannot add CRL (%s): %s", psz_crl_path,
880 gnutls_strerror( val ) );
883 msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );
889 * Allocates a whole server's TLS credentials.
891 static int OpenServer (vlc_object_t *obj)
893 tls_server_t *p_server = (tls_server_t *)obj;
894 tls_server_sys_t *p_sys;
897 if (gnutls_Init (obj))
900 msg_Dbg (obj, "creating TLS server");
902 p_sys = (tls_server_sys_t *)malloc( sizeof(struct tls_server_sys_t) );
906 p_server->p_sys = p_sys;
907 p_server->pf_add_CA = gnutls_ServerAddCA;
908 p_server->pf_add_CRL = gnutls_ServerAddCRL;
909 p_server->pf_open = gnutls_ServerSessionPrepare;
910 p_server->pf_close = gnutls_SessionClose;
912 /* No certificate validation by default */
913 p_sys->pf_handshake = gnutls_ContinueHandshake;
915 /* Sets server's credentials */
916 val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
919 msg_Err( p_server, "cannot allocate X509 credentials: %s",
920 gnutls_strerror( val ) );
924 char *psz_cert_path = var_GetNonEmptyString (obj, "tls-x509-cert");
925 char *psz_key_path = var_GetNonEmptyString (obj, "tls-x509-key");
926 const char *psz_local_cert = ToLocale (psz_cert_path);
927 const char *psz_local_key = ToLocale (psz_key_path);
928 val = gnutls_certificate_set_x509_key_file (p_sys->x509_cred,
929 psz_local_cert, psz_local_key,
930 GNUTLS_X509_FMT_PEM );
931 LocaleFree (psz_local_key);
933 LocaleFree (psz_local_cert);
934 free (psz_cert_path);
938 msg_Err( p_server, "cannot set certificate chain or private key: %s",
939 gnutls_strerror( val ) );
940 gnutls_certificate_free_credentials( p_sys->x509_cred );
945 * - support other ciper suites
947 val = gnutls_dh_params_init (&p_sys->dh_params);
950 const gnutls_datum_t data = {
951 .data = (unsigned char *)dh_params,
952 .size = sizeof (dh_params) - 1,
955 val = gnutls_dh_params_import_pkcs3 (p_sys->dh_params, &data,
956 GNUTLS_X509_FMT_PEM);
958 gnutls_certificate_set_dh_params (p_sys->x509_cred,
963 msg_Err (p_server, "cannot initialize DHE cipher suites: %s",
964 gnutls_strerror (val));
975 * Destroys a TLS server object.
977 static void CloseServer (vlc_object_t *p_server)
979 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
981 /* all sessions depending on the server are now deinitialized */
982 gnutls_certificate_free_credentials (p_sys->x509_cred);
983 gnutls_dh_params_deinit (p_sys->dh_params);
986 gnutls_Deinit (p_server);