Пример #1
0
 public void Dispose()
 {
     ClientCertificateList.Clear();
     CAChain.Dispose();
     ServerCertificate.Dispose();
     ClientCertificate.Dispose();
 }
Пример #2
0
        public virtual void Close()
        {
            Monitor.Stop();

            if (sslCert != null)
            {
                sslCert.Dispose();
                sslCert = null;
            }

            if (sslStream != null)
            {
                sslStream.Dispose();
                sslStream = null;
            }

            if (stream != null)
            {
                stream.Dispose();
                stream = null;
            }

            Socket.Destroy();

            sending   = false;
            receiving = false;
        }
        public void ClientCertNotRequiredCheckTest()
        {
            var serverName = "TestServer";

            using (X509Certificate serverCert = MakeCert(serverName))
            {
                var server = new EncryptionTestTcpServer();
                server.ErrorEvent += Server_ErrorEvent;

                var epList = new List <TcpServerLocalEndpoint>();
                var ipEp1  = (new TcpServerLocalEndpoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234), 1));

                epList.Add(ipEp1);
                server.Start(epList, serverCert, false, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                X509Certificate clientCert = MakeCert(serverName);
                var             client     = new TcpClient();

                server.ClientCertificate = null;
                client.Start(ipEp1.EndPoint, serverName, clientCert, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                Thread.Sleep(5000);
                Assert.IsNull(server.ClientCertificate);

                client.Stop();
                server.Stop();

                server.Dispose();
                client.Dispose();
                clientCert.Dispose();
            }
        }
Пример #4
0
        private void HandleClient(TcpClient connectionSocket)
        {
            string       serverCertificateFile = @"C:\Certificates\ServerSSL.cer";
            SslProtocols protocol = SslProtocols.Tls12;


            using (SslStream sslStream = new SslStream(connectionSocket.GetStream(),
                                                       false))
                using (StreamReader sr = new StreamReader(sslStream))
                    using (StreamWriter sw = new StreamWriter(sslStream))
                    {
                        X509Certificate serverCertificate =
                            new X509Certificate(serverCertificateFile, "why");
                        sslStream.AuthenticateAsServer(serverCertificate,
                                                       false,
                                                       protocol,
                                                       true);
                        serverCertificate.Dispose();
                        Console.WriteLine("Server activated");
                        sw.AutoFlush = true;            // enable automatic flushing

                        string message = sr.ReadLine(); // read string from client
                        string answer  = "";
                        while (!string.IsNullOrEmpty(message))
                        {
                            Console.WriteLine("Client: " + message);
                            answer = message.ToUpper(); // convert string to upper case
                            sw.WriteLine(answer);       // send back upper case string
                            message = sr.ReadLine();
                        }
                    }
        }
        protected static async Task WithServerCertificate(X509Certificate serverCertificate, Func <X509Certificate, string, Task> func)
        {
            X509Certificate certificate = serverCertificate ?? Configuration.Certificates.GetServerCertificate();

            try
            {
                string name;
                if (certificate is X509Certificate2 cert2)
                {
                    name = cert2.GetNameInfo(X509NameType.SimpleName, forIssuer: false);
                }
                else
                {
                    using (cert2 = new X509Certificate2(certificate))
                    {
                        name = cert2.GetNameInfo(X509NameType.SimpleName, forIssuer: false);
                    }
                }

                await func(certificate, name).ConfigureAwait(false);
            }
            finally
            {
                if (certificate != serverCertificate)
                {
                    certificate.Dispose();
                }
            }
        }
Пример #6
0
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            if (_cancelAccept != null)
            {
                _cancelAccept.Cancel();
                _cancelAccept.Dispose();
            }

            _disposed = true;
            if (_server != null)
            {
                _server.Stop();
            }

            if (_serverCert != null)
            {
                _serverCert.Dispose();
                _serverCert = null;
            }
        }
Пример #7
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            if (_sessionAdapter != null)
            {
                _sessionAdapter.Dispose();
            }

            if (_clientStream != null)
            {
                _clientStream.Dispose();
                _clientStream = null;
            }

            if (_certificate != null)
            {
                _certificate.Dispose();
                _certificate = null;
            }

            if (_chain != null)
            {
                _chain.Dispose();
                _chain = null;
            }

            _isDisposed = true;
        }
Пример #8
0
 public override void Dispose()
 {
     base.Dispose();
     if (ownsCertificate)
     {
         certificate.Dispose();
     }
 }
        public async Task SslStream_StreamToStream_Authentication_Success(X509Certificate serverCert = null, X509Certificate clientCert = null)
        {
            (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams();
            using (var client = new SslStream(stream1, false, AllowAnyServerCertificate))
                using (var server = new SslStream(stream2, false, delegate { return(true); }))
                {
                    await DoHandshake(client, server, serverCert, clientCert);

                    Assert.True(client.IsAuthenticated);
                    Assert.True(server.IsAuthenticated);
                }

            clientCert?.Dispose();
            serverCert?.Dispose();
        }
Пример #10
0
        public async Task SslStream_StreamToStream_Authentication_Success(X509Certificate serverCert = null, X509Certificate clientCert = null)
        {
            var network = new VirtualNetwork();

            using (var client = new SslStream(new VirtualNetworkStream(network, isServer: false), false, AllowAnyServerCertificate))
                using (var server = new SslStream(new VirtualNetworkStream(network, isServer: true), false, delegate { return(true); }))
                {
                    await DoHandshake(client, server, serverCert, clientCert);

                    Assert.True(client.IsAuthenticated);
                    Assert.True(server.IsAuthenticated);
                }

            clientCert?.Dispose();
            serverCert?.Dispose();
        }
Пример #11
0
        public void TestCase()
        {
            string serverCertPath           = @"/certs/server.pfx";
            string serverPrivateKeyPassword = "******";
            string caFilePath               = "/certs/ca_chain.pem";
            string clientCertPath           = "/certs/client.pfx";
            string clientPrivateKeyPassword = "******";
            string projDir = Directory.GetParent(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName).FullName;

            // Initialize OpenSSL for multithreaded use
            ThreadInitialization.InitializeThreads();
            try {
                // Intitialize server certificates
                serverCAChain     = LoadCACertificateChain(projDir + caFilePath);
                serverCertificate = LoadPKCS12Certificate(projDir + serverCertPath, serverPrivateKeyPassword);

                // Kick the server thread
                Thread serverThread = new Thread(new ThreadStart(ServerTestThreadProc));
                serverThread.Start();

                // Intialize the client certificates
                clientCAChain = LoadCACertificateChain(projDir + caFilePath);
                X509Certificate clientCert = LoadPKCS12Certificate(projDir + clientCertPath, clientPrivateKeyPassword);
                // Add the cert to the client certificate list
                clientCertificateList = new X509List();
                clientCertificateList.Add(clientCert);

                // Kick the client thread
                Thread clientThread = new Thread(new ThreadStart(ClientTestThreadProc));
                clientThread.Start();

                // Wait for the threads to exit
                serverThread.Join();
                clientThread.Join();

                // Cleanup
                serverCertificate.Dispose();
                serverCAChain.Dispose();
                clientCAChain.Dispose();
                clientCert.Dispose();
            }
            catch (Exception ex) {
                Console.WriteLine("Server test failed with exception: {0}", ex.Message);
            }
            ThreadInitialization.UninitializeThreads();
        }
Пример #12
0
        internal static uint SNISecGetServerCertificate(SNIHandle pConnectionObject, ref X509Certificate2 certificate)
        {
            System.UInt32   ret;
            CredHandle      pSecHandle;
            X509Certificate pCertContext = null;

            // provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions
            bool mustRelease = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                pConnectionObject.DangerousAddRef(ref mustRelease);
                Debug.Assert(mustRelease, "AddRef Failed!");

                IntPtr secHandlePtr = Marshal.AllocHGlobal(Marshal.SizeOf <CredHandle>());

                ret = SNIGetInfoWrapper(pConnectionObject, QTypes.SNI_QUERY_CONN_SSL_SECCTXTHANDLE, ref secHandlePtr);
                //ERROR_SUCCESS
                if (0 == ret)
                {
                    // Cast an unmanaged block to pSecHandle;
                    pSecHandle = Marshal.PtrToStructure <CredHandle>(secHandlePtr);

                    // SEC_E_OK
                    if (0 == (ret = QueryContextAttributes(ref pSecHandle, ContextAttribute.SECPKG_ATTR_REMOTE_CERT_CONTEXT, pCertContext.Handle)))
                    {
                        certificate = new X509Certificate2(pCertContext.Handle);
                    }
                }
                Marshal.FreeHGlobal(secHandlePtr);
            }
            finally
            {
                if (pCertContext != null)
                {
                    pCertContext.Dispose();
                }
                if (mustRelease)
                {
                    pConnectionObject.DangerousRelease();
                }
            }
            return(ret);
        }
Пример #13
0
        public void Execute(string[] args)
        {
            string serverCertPath           = @"../../test/certs/server.pfx";
            string serverPrivateKeyPassword = "******";
            string caFilePath               = "../../test/certs/ca_chain.pem";
            string clientCertPath           = "../../test/certs/client.pfx";
            string clientPrivateKeyPassword = "******";

            // Initialize OpenSSL for multithreaded use
            ThreadInitialization.InitializeThreads();
            try {
                // Intitialize server certificates
                serverCAChain     = LoadCACertificateChain(caFilePath);
                serverCertificate = LoadPKCS12Certificate(serverCertPath, serverPrivateKeyPassword);

                // Kick the server thread
                Thread serverThread = new Thread(new ThreadStart(ServerTestThreadProc));
                serverThread.Start();

                // Intialize the client certificates
                clientCAChain = LoadCACertificateChain(caFilePath);
                X509Certificate clientCert = LoadPKCS12Certificate(clientCertPath, clientPrivateKeyPassword);
                // Add the cert to the client certificate list
                clientCertificateList = new X509List();
                clientCertificateList.Add(clientCert);

                // Kick the client thread
                Thread clientThread = new Thread(new ThreadStart(ClientTestThreadProc));
                clientThread.Start();

                // Wait for the threads to exit
                serverThread.Join();
                clientThread.Join();

                // Cleanup
                serverCertificate.Dispose();
                serverCAChain.Dispose();
                clientCAChain.Dispose();
                clientCert.Dispose();
            }
            catch (Exception ex) {
                Console.WriteLine("Server test failed with exception: {0}", ex.Message);
            }
            ThreadInitialization.UninitializeThreads();
        }
        public async Task SslStream_StreamToStream_Authentication_Success(X509Certificate serverCert = null, X509Certificate clientCert = null)
        {
            if (PlatformDetection.IsWindows10Version20348OrGreater)
            {
                // [ActiveIssue("https://github.com/dotnet/runtime/issues/58927")]
                throw new SkipTestException("Unstable on Windows 11");
            }

            (Stream stream1, Stream stream2) = TestHelper.GetConnectedStreams();
            using (var client = new SslStream(stream1, false, AllowAnyServerCertificate))
                using (var server = new SslStream(stream2, false, delegate { return(true); }))
                {
                    await DoHandshake(client, server, serverCert, clientCert);

                    Assert.True(client.IsAuthenticated);
                    Assert.True(server.IsAuthenticated);
                }

            clientCert?.Dispose();
            serverCert?.Dispose();
        }
        public void DisconnectClient_Tests()
        {
            var serverName = "TestServer";

            using (X509Certificate serverCert = MakeCert(serverName))
            {
                var server = new TcpServer();
                server.ErrorEvent += Server_ErrorEvent;

                server.ConnectedEvent    += Server_ConnectedEvent;
                server.DisconnectedEvent += Server_DisconnectedEvent;

                var epList = new List <TcpServerLocalEndpoint>();
                var ipEp1  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777);
                var ipEp2  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
                var ipEp3  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

                epList.Add(new TcpServerLocalEndpoint(ipEp1, 1));
                epList.Add(new TcpServerLocalEndpoint(ipEp2, 1));
                epList.Add(new TcpServerLocalEndpoint(ipEp3, 1));

                server.Start(epList, serverCert, false, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);

                var client = new TcpClient();
                client.ConnectedEvent    += Client_ConnectedEvent;
                client.DisconnectedEvent += Client_DisconnectedEvent;

                X509Certificate clientCert = MakeCert(serverName);

                DisconnectClientTest(client, server, ipEp1, serverName, clientCert, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                DisconnectClientTest(client, server, ipEp2, serverName, clientCert, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                DisconnectClientTest(client, server, ipEp3, serverName, clientCert, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);

                server.Dispose();

                client.Dispose();

                clientCert.Dispose();
            }
        }
        public void ClientCertRequiredCheckTest()
        {
            var serverName = "TestServer";

            using (X509Certificate serverCert = MakeCert(serverName))
            {
                var server = new EncryptionTestTcpServer();
                server.ErrorEvent += Server_ErrorEvent;

                var epList = new List <TcpServerLocalEndpoint>();
                var ipEp1  = (new TcpServerLocalEndpoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234), 1));

                epList.Add(ipEp1);
                server.Start(epList, serverCert, true, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                X509Certificate clientCert = MakeCert(serverName);
                var             client     = new TcpClient();

                server.ClientCertificate = null;
                client.Start(ipEp1.EndPoint, serverName, clientCert, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                var waitStart = DateTime.Now;
                while (server.ClientCertificate == null)
                {
                    var delta = DateTime.Now - waitStart;
                    if (delta.TotalSeconds > 5)
                    {
                        Assert.Fail("Wait Timeout");
                    }
                }
                Assert.IsNotNull(server.ClientCertificate);
                Assert.AreEqual(clientCert, server.ClientCertificate);

                client.Stop();
                server.Stop();

                server.Dispose();
                client.Dispose();
                clientCert.Dispose();
            }
        }
Пример #17
0
        public void PollTest()
        {
            var serverName = "TestServer";

            using (X509Certificate serverCert = MakeCert(serverName))
            {
                var server = new TcpServer();
                var epList = new List <TcpServerLocalEndpoint>();
                var ipEp1  = (new TcpServerLocalEndpoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 0192), 1));
                epList.Add(ipEp1);
                server.DataReceivedEvent += Server_DataReceivedEvent;
                server.Start(epList, serverCert, false, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);

                X509Certificate clientCert = MakeCert(serverName);
                var             client     = new TcpClientTestClass();
                client.ErrorEvent        += Client_ErrorEvent;
                client.DisconnectedEvent += Client_DisconnectedEvent;
                client.ConnectedEvent    += Client_ConnectedEvent;
                client.Start(ipEp1.EndPoint, serverName, clientCert, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);

                Thread.Sleep(200);

                CheckPollInterval(client, server, 100);
                CheckPollInterval(client, server, 500);
                CheckPollInterval(client, server, 1000);
                CheckPollInterval(client, server, 2000);

                CheckPollFailCount(client, server, 1);
                CheckPollFailCount(client, server, 3);
                CheckPollFailCount(client, server, 5);
                CheckPollFailCount(client, server, 10);

                client.Dispose();
                server.Dispose();
                clientCert.Dispose();
            }
        }
Пример #18
0
 protected override void Dispose(bool disposing)
 {
     try {
         if (disposed)
         {
             return;
         }
         if (disposing)
         {
             disposed = true;
             if (serverIdentity != null)
             {
                 serverIdentity.Dispose();
                 serverIdentity = null;
             }
             if (clientIdentity != null)
             {
                 clientIdentity.Dispose();
                 clientIdentity = null;
             }
             if (remoteCertificate != null)
             {
                 remoteCertificate.Dispose();
                 remoteCertificate = null;
             }
         }
     } finally {
         disposed = true;
         if (context != IntPtr.Zero)
         {
             CFObject.CFRelease(context);
             context = IntPtr.Zero;
         }
         base.Dispose(disposing);
     }
 }
Пример #19
0
        public override void Dispose(bool disposing)
        {
            try
            {
                if (disposing)
                {
                    Shutdown();

                    // reset states
                    localClientCertificate = null;
                    remoteCertificate      = null;

                    if (localClientCertificate != null)
                    {
                        localClientCertificate.Dispose();
                        localClientCertificate = null;
                    }

                    if (remoteCertificate != null)
                    {
                        remoteCertificate.Dispose();
                        remoteCertificate = null;
                    }

                    connectioninfo  = null;
                    isAuthenticated = false;
                    hasContext      = false;
                }

                handle.Free();
            }
            finally
            {
                base.Dispose(disposing);
            }
        }
        /* Retrieve CA Information */
        /// <summary>
        /// Retrieves the Root CA JSON file with the latest details of the Certificate
        /// </summary>
        /// <remarks>Sets the Certificate Details For Launcher Comparison</remarks>
        public static void Latest()
        {
            if (!UnixOS.Detected())
            {
                Log.Checking("CERTIFICATE STORE: Is Installed or Not");
                DiscordLauncherPresence.Status("Start Up", "Checking Root Certificate Authority");

                try
                {
                    Uri URLCall = new Uri("http://crl.carboncrew.org/RCA-Info.json");
                    ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                    var Client = new WebClient
                    {
                        Encoding = Encoding.UTF8
                    };
                    if (!WebCalls.Alternative())
                    {
                        Client = new WebClientWithTimeout {
                            Encoding = Encoding.UTF8
                        };
                    }
                    else
                    {
                        Client.Headers.Add("user-agent", "SBRW Launcher " +
                                           Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                    }

                    try
                    {
                        /* Download Up to Date Certificate Status */
                        RootCAJson = Client.DownloadString(URLCall);
                    }
                    catch (WebException Error)
                    {
                        APIChecker.StatusCodes(URLCall.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped),
                                               Error, (HttpWebResponse)Error.Response);
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true);
                    }
                    finally
                    {
                        if (Client != null)
                        {
                            Client.Dispose();
                        }
                    }

                    if (IsJSONValid.ValidJson(RootCAJson))
                    {
                        JsonRootCA API = JsonConvert.DeserializeObject <JsonRootCA>(RootCAJson);

                        if (API.CN != null)
                        {
                            Log.Info("CERTIFICATE STORE: Setting Common Name -> " + API.CN);
                            RootCACommonName = API.CN;
                        }

                        if (API.Subject != null)
                        {
                            Log.Info("CERTIFICATE STORE: Setting Subject Name -> " + API.Subject);
                            RootCASubjectName = API.Subject;
                        }

                        if (API.Ids != null)
                        {
                            foreach (IdsModel entries in API.Ids)
                            {
                                if (entries.Serial != null)
                                {
                                    Log.Info("CERTIFICATE STORE: Setting Serial Number -> " + entries.Serial);
                                    RootCASerial = entries.Serial;
                                }
                            }
                        }

                        if (API.File != null)
                        {
                            foreach (FileModel entries in API.File)
                            {
                                if (entries.Name != null)
                                {
                                    Log.Info("CERTIFICATE STORE: Setting Root CA File Name -> " + entries.Name);
                                    RootCAFileName = entries.Name;
                                }

                                if (entries.Cer != null)
                                {
                                    Log.Info("CERTIFICATE STORE: Setting Root CA File URL -> " + entries.Cer);
                                    RootCAFileURL = entries.Cer;
                                }
                            }
                        }

                        if (API != null)
                        {
                            API = null;
                        }
                    }
                    else
                    {
                        Log.Warning("CERTIFICATE STORE: Received Invalid JSON Data");
                    }
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true);
                }
                finally
                {
                    if (RootCAJson != null)
                    {
                        RootCAJson = null;
                    }
                }

                /* Install Custom Root Certificate (If Default Values aren't used) */
                if (RootCASerial != "7449A8EB07C997A6")
                {
                    try
                    {
                        X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                        store.Open(OpenFlags.ReadWrite);

                        var certificatesThumbPrint = store.Certificates.Find(X509FindType.FindByThumbprint,
                                                                             RootCASerial, false);

                        for (int i = 0; i < store.Certificates.Count; i++)
                        {
                            if (store.Certificates[i].SerialNumber == RootCASerial)
                            {
                                Log.Info("CERTIFICATE STORE: Found Root CA [" + store.Certificates[i].Subject + "]");
                                Log.Info("CERTIFICATE STORE: Serial Number [" + store.Certificates[i].SerialNumber + "]");
                                IsROOTCAInstalled = true;
                            }
                            else if (store.Certificates[i].SerialNumber != RootCASerial && store.Certificates[i].Subject == RootCASubjectName)
                            {
                                Log.Info("CERTIFICATE STORE: Removing OLD Root CA [" + store.Certificates[i].Subject + "]");
                                Log.Info("CERTIFICATE STORE: Serial Number [" + store.Certificates[i].SerialNumber + "]");
                                store.Remove(store.Certificates[i]);
                            }
                        }
                        store.Close();
                        store.Dispose();
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true);
                    }

                    string CertSaveLocation = Strings.Encode(Path.Combine(Locations.LauncherFolder, RootCAFileName + ".cer"));

                    try
                    {
                        if (!IsROOTCAInstalled)
                        {
                            Uri URLCall = new Uri(RootCAFileURL);
                            ServicePointManager.FindServicePoint(URLCall).ConnectionLeaseTimeout = (int)TimeSpan.FromMinutes(1).TotalMilliseconds;
                            var Client = new WebClient
                            {
                                Encoding = Encoding.UTF8
                            };
                            if (!WebCalls.Alternative())
                            {
                                Client = new WebClientWithTimeout {
                                    Encoding = Encoding.UTF8
                                };
                            }
                            else
                            {
                                Client.Headers.Add("user-agent", "SBRW Launcher " +
                                                   Application.ProductVersion + " (+https://github.com/SoapBoxRaceWorld/GameLauncher_NFSW)");
                            }

                            try
                            {
                                /* Download Up to Date Certificate Status */
                                Client.DownloadFile(URLCall, CertSaveLocation);
                            }
                            catch (WebException Error)
                            {
                                APIChecker.StatusCodes(RootCAFileURL, Error, (HttpWebResponse)Error.Response);
                            }
                            catch (Exception Error)
                            {
                                LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true);
                            }
                            finally
                            {
                                if (Client != null)
                                {
                                    Client.Dispose();
                                }
                            }

                            if (File.Exists(CertSaveLocation))
                            {
                                X509Store Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                                Store.Open(OpenFlags.ReadWrite);
                                X509Certificate2Collection collection = new X509Certificate2Collection();
                                X509Certificate2           cert       = new X509Certificate2(CertSaveLocation);
                                byte[] encodedCert = cert.GetRawCertData();
                                Log.Info("CERTIFICATE STORE: We are now installing [" + RootCACommonName + "] certificate into the Trusted Root Certificate store ...");
                                Store.Add(cert);
                                Log.Info("CERTIFICATE STORE: Done! [" + RootCACommonName + "] certificate was installed successfully.");
                                Store.Close();
                                Store.Dispose();
                            }
                        }
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true);
                    }

                    try
                    {
                        if (File.Exists(CertSaveLocation))
                        {
                            Log.Info("CERTIFICATE STORE: Removed [" + RootCACommonName + "] certificate from launcher folder.");
                            File.Delete(CertSaveLocation);
                        }
                    }
                    catch (Exception Error)
                    {
                        LogToFileAddons.OpenLog("CERTIFICATE STORE", null, Error, null, true);
                    }
                }
                else
                {
                    Log.Warning("CERTIFICATE STORE: Default Information was detected. Not running additional Function Calls");
                }

                Log.Completed("CERTIFICATE STORE: Done");
            }

            Log.Checking("CERTIFICATE CHECK: Is Signed or Not");
            try
            {
                X509Certificate certificate = null;

                try
                {
                    Assembly assembly = Assembly.LoadFrom(Strings.Encode(Path.Combine(Locations.LauncherFolder, Locations.NameLauncher)));
                    Module   module   = assembly.GetModules().First();
                    certificate = module.GetSignerCertificate();

                    if (certificate != null)
                    {
                        LauncherSerial = certificate.GetSerialNumberString();
                    }
                }
                catch (Exception Error)
                {
                    LogToFileAddons.OpenLog("CERTIFICATE CHECK", null, Error, null, true);
                }
                finally
                {
                    if (certificate != null)
                    {
                        certificate.Dispose();
                    }
                }
            }
            catch (Exception Error)
            {
                LogToFileAddons.OpenLog("CERTIFICATE CHECK", null, Error, null, true);
            }
            Log.Completed("CERTIFICATE CHECK: Done");

            Log.Info("VERIFIED: Moved to Function");
            /* (Start Process) Check if Launcher Is Signed or Not */
            IsExeVerified.Check();
        }
        public void ConnectDisconnectServerTests()
        {
            var serverName = "TestServer";

            using (X509Certificate serverCert = MakeCert(serverName))
            {
                var server = new TcpServer();
                server.ErrorEvent += Server_ErrorEvent;

                server.ConnectedEvent    += Server_ConnectedEvent;
                server.DisconnectedEvent += Server_DisconnectedEvent;

                var epList = new List <TcpServerLocalEndpoint>();
                var ipEp1  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777);
                var ipEp2  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888);
                var ipEp3  = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);

                epList.Add(new TcpServerLocalEndpoint(ipEp1, 1));
                epList.Add(new TcpServerLocalEndpoint(ipEp2, 1));
                epList.Add(new TcpServerLocalEndpoint(ipEp3, 1));

                server.Start(epList, serverCert, false, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);

                var client = new TcpClient();
                client.ConnectedEvent    += Client_ConnectedEvent;
                client.DisconnectedEvent += Client_DisconnectedEvent;

                X509Certificate clientCert1 = MakeCert(serverName);
                X509Certificate clientCert2 = MakeCert(serverName);
                X509Certificate clientCert3 = MakeCert(serverName);

                ConnectionTest(client, ipEp1, serverName, clientCert1, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                ConnectionTest(client, ipEp2, serverName, clientCert2, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                ConnectionTest(client, ipEp3, serverName, clientCert3, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);

                while (server.GetConnections().Count != 0)
                {
                }
                ;

                ServerConnectedEventArgs    = null;
                ServerDisconnectedEventArgs = null;
                Assert.IsNull(ServerConnectedEventArgs);
                Assert.IsNull(ServerDisconnectedEventArgs);
                client.Start(ipEp1, serverName, clientCert1, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                var waitStart = DateTime.Now;
                while (ServerConnectedEventArgs == null)
                {
                    var delta = DateTime.Now - waitStart;
                    if (delta.TotalSeconds > 5)
                    {
                        Assert.Fail("Wait Timeout");
                    }
                }
                Assert.IsNotNull(ServerConnectedEventArgs);
                Assert.IsNull(ServerDisconnectedEventArgs);
                Assert.AreEqual(ipEp1, ServerConnectedEventArgs.LocalEndPoint);

                var remoteIp = ServerConnectedEventArgs.RemoteEndPoint;

                ServerConnectedEventArgs    = null;
                ServerDisconnectedEventArgs = null;
                Assert.IsNull(ServerConnectedEventArgs);
                Assert.IsNull(ServerDisconnectedEventArgs);
                client.Dispose();
                waitStart = DateTime.Now;
                while (ServerDisconnectedEventArgs == null)
                {
                    var delta = DateTime.Now - waitStart;
                    if (delta.TotalSeconds > 5)
                    {
                        Assert.Fail("Wait Timeout");
                    }
                }
                Assert.IsNull(ServerConnectedEventArgs);
                Assert.IsNotNull(ServerDisconnectedEventArgs);
                Assert.AreEqual(ipEp1, ServerDisconnectedEventArgs.LocalEndPoint);
                Assert.AreEqual(remoteIp, ServerDisconnectedEventArgs.RemoteEndPoint);

                var client1 = new TcpClient();
                var client2 = new TcpClient();
                var client3 = new TcpClient();

                ServerConnectedEventArgs    = null;
                ServerDisconnectedEventArgs = null;
                Assert.IsNull(ServerConnectedEventArgs);
                Assert.IsNull(ServerDisconnectedEventArgs);
                client1.Start(ipEp1, serverName, clientCert1, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                waitStart = DateTime.Now;
                while (ServerConnectedEventArgs == null)
                {
                    var delta = DateTime.Now - waitStart;
                    if (delta.TotalSeconds > 5)
                    {
                        Assert.Fail("Wait Timeout");
                    }
                }
                Assert.IsNull(ServerDisconnectedEventArgs);
                Assert.AreEqual(ipEp1, ServerConnectedEventArgs.LocalEndPoint);

                ServerConnectedEventArgs    = null;
                ServerDisconnectedEventArgs = null;
                Assert.IsNull(ServerConnectedEventArgs);
                Assert.IsNull(ServerDisconnectedEventArgs);
                client2.Start(ipEp2, serverName, clientCert2, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                waitStart = DateTime.Now;
                while (ServerConnectedEventArgs == null)
                {
                    var delta = DateTime.Now - waitStart;
                    if (delta.TotalSeconds > 5)
                    {
                        Assert.Fail("Wait Timeout");
                    }
                }
                Assert.IsNull(ServerDisconnectedEventArgs);
                Assert.AreEqual(ipEp2, ServerConnectedEventArgs.LocalEndPoint);

                ServerConnectedEventArgs    = null;
                ServerDisconnectedEventArgs = null;
                Assert.IsNull(ServerConnectedEventArgs);
                Assert.IsNull(ServerDisconnectedEventArgs);
                client3.Start(ipEp3, serverName, clientCert3, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                waitStart = DateTime.Now;
                while (ServerConnectedEventArgs == null)
                {
                    var delta = DateTime.Now - waitStart;
                    if (delta.TotalSeconds > 5)
                    {
                        Assert.Fail("Wait Timeout");
                    }
                }
                Assert.IsNull(ServerDisconnectedEventArgs);
                Assert.AreEqual(ipEp3, ServerConnectedEventArgs.LocalEndPoint);


                client1.DisconnectedEvent += Client1_DisconnectedEvent;
                client2.DisconnectedEvent += Client2_DisconnectedEvent;
                client3.DisconnectedEvent += Client3_DisconnectedEvent;

                Client1DisconnectedEventColled = false;
                Client2DisconnectedEventColled = false;
                Client3DisconnectedEventColled = false;
                Assert.IsFalse(Client1DisconnectedEventColled);
                Assert.IsFalse(Client2DisconnectedEventColled);
                Assert.IsFalse(Client3DisconnectedEventColled);

                server.Stop();

                Thread.Sleep(1500);

                Assert.IsTrue(Client1DisconnectedEventColled);
                Assert.IsTrue(Client2DisconnectedEventColled);
                Assert.IsTrue(Client3DisconnectedEventColled);
                Assert.IsFalse(client1.IsConnected);
                Assert.IsFalse(client2.IsConnected);
                Assert.IsFalse(client3.IsConnected);

                server.Start(epList, serverCert, false, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                Thread.Sleep(1000);

                Assert.IsTrue(client1.IsConnected);
                Assert.IsTrue(client2.IsConnected);
                Assert.IsTrue(client3.IsConnected);


                var conn     = server.GetConnections();
                var contains = false;
                foreach (Connection connection in conn)
                {
                    if (Equals(connection.RemoteEndPoint, client1.ExchangeInterface.LocalEndPoint) &&
                        Equals(connection.LocalEndPoint, client1.ExchangeInterface.RemoteEndPoint))
                    {
                        contains = true;
                        break;
                    }
                }
                Assert.IsTrue(contains);

                contains = false;
                foreach (Connection connection in conn)
                {
                    if (Equals(connection.RemoteEndPoint, client2.ExchangeInterface.LocalEndPoint) &&
                        Equals(connection.LocalEndPoint, client2.ExchangeInterface.RemoteEndPoint))
                    {
                        contains = true;
                        break;
                    }
                }
                Assert.IsTrue(contains);

                contains = false;
                foreach (Connection connection in conn)
                {
                    if (Equals(connection.RemoteEndPoint, client3.ExchangeInterface.LocalEndPoint) &&
                        Equals(connection.LocalEndPoint, client3.ExchangeInterface.RemoteEndPoint))
                    {
                        contains = true;
                        break;
                    }
                }
                Assert.IsTrue(contains);



                Client1DisconnectedEventColled = false;
                Client2DisconnectedEventColled = false;
                Client3DisconnectedEventColled = false;
                Assert.IsFalse(Client1DisconnectedEventColled);
                Assert.IsFalse(Client2DisconnectedEventColled);
                Assert.IsFalse(Client3DisconnectedEventColled);
                Assert.IsTrue(server.IsStarted);
                Assert.IsFalse(server.IsDisposed);
                server.Dispose();

                Thread.Sleep(1500);

                Assert.IsTrue(Client1DisconnectedEventColled);
                Assert.IsTrue(Client2DisconnectedEventColled);
                Assert.IsTrue(Client3DisconnectedEventColled);

                Assert.IsFalse(client1.IsConnected);
                Assert.IsFalse(client2.IsConnected);
                Assert.IsFalse(client3.IsConnected);

                Assert.IsTrue(server.IsDisposed);
                Assert.IsFalse(server.IsStarted);


                client1.Dispose();
                client2.Dispose();
                client3.Dispose();

                clientCert1.Dispose();
                clientCert2.Dispose();
                clientCert3.Dispose();
            }
        }
Пример #22
0
		public void TestCase() {
			string serverCertPath = @"../../test/certs/server.pfx";
			string serverPrivateKeyPassword = "******";
			string caFilePath = "../../test/certs/ca_chain.pem";
			string clientCertPath = "../../test/certs/client.pfx";
			string clientPrivateKeyPassword = "******";

			// Initialize OpenSSL for multithreaded use
			ThreadInitialization.InitializeThreads();
			try {
				// Intitialize server certificates
				serverCAChain = LoadCACertificateChain(caFilePath);
				serverCertificate = LoadPKCS12Certificate(serverCertPath, serverPrivateKeyPassword);

				// Kick the server thread
				Thread serverThread = new Thread(new ThreadStart(ServerTestThreadProc));
				serverThread.Start();

				// Intialize the client certificates
				clientCAChain = LoadCACertificateChain(caFilePath);
				X509Certificate clientCert = LoadPKCS12Certificate(clientCertPath, clientPrivateKeyPassword);
				// Add the cert to the client certificate list
				clientCertificateList = new X509List();
				clientCertificateList.Add(clientCert);

				// Kick the client thread
				Thread clientThread = new Thread(new ThreadStart(ClientTestThreadProc));
				clientThread.Start();

				// Wait for the threads to exit
				serverThread.Join();
				clientThread.Join();

				// Cleanup
				serverCertificate.Dispose();
				serverCAChain.Dispose();
				clientCAChain.Dispose();
				clientCert.Dispose();
			}
			catch (Exception ex) {
				Console.WriteLine("Server test failed with exception: {0}", ex.Message);
			}
			ThreadInitialization.UninitializeThreads();
		}
Пример #23
0
        public void SendReceiveTest()
        {
            var serverName = "TestServer";

            using (X509Certificate serverCert = MakeCert(serverName))
            {
                var server = new TcpServer();

                server.DataReceivedEvent += Server_DataReceivedEvent;

                var epList = new List <TcpServerLocalEndpoint>();
                var ipEp1  = (new TcpServerLocalEndpoint(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234), 1));

                epList.Add(ipEp1);
                server.Start(epList, serverCert, false, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);

                X509Certificate clientCert = MakeCert(serverName);
                var             client     = new TcpClient();
                client.DataReceivedEvent += Client_DataReceivedEvent;
                client.Start(ipEp1.EndPoint, serverName, clientCert, SslProtocols.None, false, EncryptionPolicy.RequireEncryption);
                Thread.Sleep(200);

                for (int i = 1; i < 10; i++)
                {
                    var data = BitConverter.GetBytes(i);
                    ServerDataReceivedEvent.Clear();
                    Assert.AreEqual(0, ServerDataReceivedEvent.Count);
                    client.SendData(data);

                    var waitStart = DateTime.Now;
                    while (ServerDataReceivedEvent.Count == 0)
                    {
                        var delta = DateTime.Now - waitStart;
                        if (delta.TotalMilliseconds > 100)
                        {
                            Assert.Fail("Data not received");
                        }
                    }

                    Assert.AreEqual(1, ServerDataReceivedEvent.Count);
                    Assert.AreEqual(data.Length, ServerDataReceivedEvent[0].Data.Length);
                    for (int j = 0; j < data.Length; j++)
                    {
                        Assert.AreEqual(data[j], ServerDataReceivedEvent[0].Data[j]);
                        Assert.AreEqual(client.ExchangeInterface.LocalEndPoint, ServerDataReceivedEvent[0].RemoteEndPoint);
                        Assert.AreEqual(client.ExchangeInterface.RemoteEndPoint, ServerDataReceivedEvent[0].LocalEndPoint);
                    }
                }

                for (int i = 1; i < 10; i++)
                {
                    var data = BitConverter.GetBytes(i);
                    ClientDataReceivedEvent.Clear();
                    Assert.AreEqual(0, ClientDataReceivedEvent.Count);
                    server.Write(data, client.ExchangeInterface.RemoteEndPoint, client.ExchangeInterface.LocalEndPoint);

                    var waitStart = DateTime.Now;
                    while (ClientDataReceivedEvent.Count == 0)
                    {
                        var delta = DateTime.Now - waitStart;
                        if (delta.TotalMilliseconds > 100)
                        {
                            Assert.Fail("Data not received");
                        }
                    }

                    Assert.AreEqual(1, ClientDataReceivedEvent.Count);
                    Assert.AreEqual(data.Length, ClientDataReceivedEvent[0].Data.Length);
                    for (int j = 0; j < data.Length; j++)
                    {
                        Assert.AreEqual(data[j], ClientDataReceivedEvent[0].Data[j]);
                        Assert.AreEqual(ipEp1.EndPoint, ClientDataReceivedEvent[0].RemoteEndPoint);
                    }
                }

                server.Dispose();
                client.Dispose();
                clientCert.Dispose();
            }
        }
Пример #24
0
 /// <inheritdoc />
 public override void Dispose()
 {
     serverCertificate.Dispose();
     base.Dispose();
 }