public void SSLEstablishing() { string msgToSend = "Hello World!"; string msgReceived = ""; bool success = false; int port = 0; var t1 = Task.Run(() => { var listener = new TcpListener(IPAddress.Any, 0); listener.Start(); port = ((IPEndPoint)listener.LocalEndpoint).Port; try { listener.Start(); var cert = SecurityUtils.BuildSelfSignedCertificate("crycrawler"); var cl = listener.AcceptTcpClient(); var str = cl.GetStream(); var ssl = SecurityUtils.ServerEstablishSSL(str, cert); var bfr = new byte[1024]; var rd = ssl.Read(bfr, 0, bfr.Length); var txt = Encoding.UTF8.GetString(bfr, 0, rd); success = true; msgReceived = txt; } finally { listener.Stop(); } }); Task.Delay(1000).Wait(); var t2 = Task.Run(() => { var cl = new TcpClient(); cl.Connect(IPAddress.Loopback, port); var str = cl.GetStream(); var ssl = SecurityUtils.ClientEstablishSSL(str); var bfr = Encoding.UTF8.GetBytes(msgToSend); ssl.Write(bfr, 0, bfr.Length); }); Task.WhenAll(t1, t2).Wait(); Assert.True(success); Assert.Equal(msgToSend, msgReceived); }
void ConnectionLoop(CancellationToken token) { new Task(() => { while (!token.IsCancellationRequested) { ManualResetEvent reset = new ManualResetEvent(false); try { client = new TcpClient(); client.Connect(new IPEndPoint(Address, Port)); Logger.Log($"Connecting to host...", Logger.LogSeverity.Debug); var stream = client.GetStream(); Logger.Log($"Establishing secure connection...", Logger.LogSeverity.Debug); // setup SSL here var sslstream = SecurityUtils.ClientEstablishSSL(stream); // message handler here MessageHandler = new NetworkMessageHandler <NetworkMessage>(sslstream, w => { if (w.MessageType == NetworkMessageType.ConfigUpdate || w.MessageType == NetworkMessageType.WorkLimitUpdate || (!token.IsCancellationRequested && IsConnected)) { // do not log status checks because they happen too frequently /* * if (w.MessageType != NetworkMessageType.StatusCheck) * Logger.Log("Received message -> " + w.MessageType.ToString(), Logger.LogSeverity.Debug); */ if (w.MessageType == NetworkMessageType.Disconnect) { client.ProperlyClose(); } MessageReceived?.Invoke(w, MessageHandler); } }); // if message handler throws an exception, dispose it MessageHandler.ExceptionThrown += (a, b) => { Logger.Log("[MessageHandler] " + b.GetDetailedMessage(), Logger.LogSeverity.Debug); MessageHandler.Dispose(); reset.Set(); }; Logger.Log($"Validating host...", Logger.LogSeverity.Debug); // handshake ClientId = SecurityUtils.DoHandshake(MessageHandler, PasswordHash, true, ClientId); // wait a bit (to make sure message handler callbacks don't get early messages) Task.Delay(100).Wait(); IsConnected = true; Logger.Log($"Connected to host. (Id: {ClientId})"); Connected?.Invoke(ClientId); // wait here until exception is thrown on message handler reset.WaitOne(); } catch (Exception ex) { Logger.Log("Host connection error. " + ex.Message, Logger.LogSeverity.Debug); } finally { if (IsConnected) { Logger.Log("Disconnected from host"); Disconnected?.Invoke(ClientId); IsConnected = false; } client.ProperlyClose(); } Task.Delay(300).Wait(); } }, token, TaskCreationOptions.LongRunning).Start(); }
public void SSLWithMessageHandler() { string clMessage = "Ping!"; string srMessage = "Pong!"; string clReceived = ""; string srReceived = ""; string clMessage2 = "Ping Ping!"; string srMessage2 = "Pong Pong!"; string clReceived2 = ""; string srReceived2 = ""; int port = 0; var t1 = Task.Run(() => { var listener = new TcpListener(IPAddress.Any, 0); listener.Start(); port = ((IPEndPoint)listener.LocalEndpoint).Port; try { listener.Start(); var cert = SecurityUtils.BuildSelfSignedCertificate("crycrawler"); var cl = listener.AcceptTcpClient(); var str = cl.GetStream(); var ssl = SecurityUtils.ServerEstablishSSL(str, cert); // create message handler var msgHandler = new NetworkMessageHandler <NetworkMessage>(ssl); msgHandler.ExceptionThrown += (a, b) => { }; var response = msgHandler.WaitForResponse(5000).Result; srReceived = response.Data as string; Task.Delay(3000).Wait(); msgHandler.SendMessage(new NetworkMessage(NetworkMessageType.Join, srMessage)); response = msgHandler.WaitForResponse(5000).Result; srReceived2 = response.Data as string; msgHandler.SendMessage(new NetworkMessage(NetworkMessageType.Join, srMessage2)); Task.Delay(1000).Wait(); ssl.Close(); str.Close(); } finally { listener.Stop(); } }); Task.Delay(1000).Wait(); var t2 = Task.Run(() => { var cl = new TcpClient(); cl.Connect(IPAddress.Loopback, port); var str = cl.GetStream(); var ssl = SecurityUtils.ClientEstablishSSL(str); // create message handler var msgHandler = new NetworkMessageHandler <NetworkMessage>(ssl); msgHandler.ExceptionThrown += (a, b) => { }; msgHandler.SendMessage(new NetworkMessage(NetworkMessageType.Join, clMessage)); var response = msgHandler.WaitForResponse(5000).Result; clReceived = response.Data as string; msgHandler.SendMessage(new NetworkMessage(NetworkMessageType.Join, clMessage2)); response = msgHandler.WaitForResponse(5000).Result; clReceived2 = response.Data as string; Task.Delay(1000).Wait(); ssl.Close(); str.Close(); }); Task.WhenAll(t1, t2).Wait(); Assert.Equal(clMessage, srReceived); Assert.Equal(srMessage, clReceived); Assert.Equal(clMessage2, srReceived2); Assert.Equal(srMessage2, clReceived2); }