Skip to content
This repository was archived by the owner on Jan 23, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
Expand All @@ -25,7 +27,6 @@ internal class SNITCPHandle : SNIHandle
private readonly TaskFactory _writeTaskFactory;

private Stream _stream;
private TcpClient _tcpClient;
private SslStream _sslStream;
private SslOverTdsStream _sslOverTdsStream;
private SNIAsyncCallback _receiveCallback;
Expand Down Expand Up @@ -56,12 +57,6 @@ public override void Dispose()
_sslStream.Dispose();
_sslStream = null;
}

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

Expand Down Expand Up @@ -103,8 +98,6 @@ public SNITCPHandle(string serverName, int port, long timerExpire, object callba

try
{
_tcpClient = new TcpClient();

TimeSpan ts;

// In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
Expand All @@ -116,7 +109,7 @@ public SNITCPHandle(string serverName, int port, long timerExpire, object callba
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
}

Task connectTask;
Task<Socket> connectTask;
if (parallel)
{
Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(serverName);
Expand All @@ -130,11 +123,11 @@ public SNITCPHandle(string serverName, int port, long timerExpire, object callba
return;
}

connectTask = _tcpClient.ConnectAsync(serverAddresses, port);
connectTask = ConnectAsync(serverAddresses, port);
}
else
{
connectTask = _tcpClient.ConnectAsync(serverName, port);
connectTask = ConnectAsync(serverName, port);
}

if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts)))
Expand All @@ -143,9 +136,9 @@ public SNITCPHandle(string serverName, int port, long timerExpire, object callba
return;
}

_tcpClient.NoDelay = true;
_tcpStream = _tcpClient.GetStream();
_socket = _tcpClient.Client;
_socket = connectTask.Result;
_socket.NoDelay = true;
_tcpStream = new NetworkStream(_socket, true);

_sslOverTdsStream = new SslOverTdsStream(_tcpStream);
_sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
Expand All @@ -165,6 +158,70 @@ public SNITCPHandle(string serverName, int port, long timerExpire, object callba
_status = TdsEnums.SNI_SUCCESS;
}

private static async Task<Socket> ConnectAsync(string serverName, int port)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await socket.ConnectAsync(serverName, port).ConfigureAwait(false);
return socket;
}

// On unix we can't use the instance Socket methods that take multiple endpoints

IPAddress[] addresses = await Dns.GetHostAddressesAsync(serverName).ConfigureAwait(false);
return await ConnectAsync(addresses, port).ConfigureAwait(false);
}

private static async Task<Socket> ConnectAsync(IPAddress[] serverAddresses, int port)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
await socket.ConnectAsync(serverAddresses, port).ConfigureAwait(false);
return socket;
}

// On unix we can't use the instance Socket methods that take multiple endpoints

if (serverAddresses == null)
{
throw new ArgumentNullException("serverAddresses");
}
if (serverAddresses.Length == 0)
{
throw new ArgumentOutOfRangeException("serverAddresses");
}

// Try each address in turn, and return the socket opened for the first one that works.
ExceptionDispatchInfo lastException = null;
foreach (IPAddress address in serverAddresses)
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
await socket.ConnectAsync(address, port).ConfigureAwait(false);
return socket;
}
catch (Exception exc)
{
socket.Dispose();
lastException = ExceptionDispatchInfo.Capture(exc);
}
}

// Propagate the last failure that occurrred
if (lastException != null)
{
lastException.Throw();
}

// Should never get here. Either there will have been no addresses and we'll have thrown
// at the beginning, or one of the addresses will have worked and we'll have returned, or
// at least one of the addresses will failed, in which case we will have propagated that.
throw new ArgumentException();
}

/// <summary>
/// Enable SSL
/// </summary>
Expand Down Expand Up @@ -276,11 +333,11 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
{
if (timeoutInMilliseconds > 0)
{
_tcpClient.ReceiveTimeout = timeoutInMilliseconds;
_socket.ReceiveTimeout = timeoutInMilliseconds;
}
else if (timeoutInMilliseconds == -1)
{ // SqlCient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0
_tcpClient.ReceiveTimeout = 0;
_socket.ReceiveTimeout = 0;
}
else
{
Expand Down Expand Up @@ -320,7 +377,7 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
}
finally
{
_tcpClient.ReceiveTimeout = 0;
_socket.ReceiveTimeout = 0;
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,8 @@ private async Task ClientAsyncSslHelper(
Assert.True(((IAsyncResult)async).AsyncWaitHandle.WaitOne(TestConfiguration.PassingTestTimeoutMilliseconds), "Timed Out");
async.GetAwaiter().GetResult();

_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);
_log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
server.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");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ public async Task ClientDefaultEncryption_ServerRequireEncryption_ConnectWithEnc
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null))
{
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);
_log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
serverRequireEncryption.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");
}
Expand All @@ -66,9 +65,8 @@ public async Task ClientDefaultEncryption_ServerAllowNoEncryption_ConnectWithEnc
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null))
{
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);
_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");
}
Expand Down
11 changes: 4 additions & 7 deletions src/System.Net.Security/tests/FunctionalTests/DummyTcpServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,7 @@ private void OnAuthenticate(Task result, ClientState state)
try
{
result.GetAwaiter().GetResult();
_log.WriteLine("Server({0}) authenticated to client({1}) with encryption cipher: {2} {3}-bit strength",
state.TcpClient.Client.LocalEndPoint, state.TcpClient.Client.RemoteEndPoint,
_log.WriteLine("Server authenticated to client with encryption cipher: {0} {1}-bit strength",
sslStream.CipherAlgorithm, sslStream.CipherStrength);

// Start listening for data from the client connection.
Expand All @@ -106,15 +105,13 @@ private void OnAuthenticate(Task result, ClientState state)
catch (AuthenticationException authEx)
{
_log.WriteLine(
"Server({0}) disconnecting from client({1}) during authentication. No shared SSL/TLS algorithm. ({2})",
state.TcpClient.Client.LocalEndPoint,
state.TcpClient.Client.RemoteEndPoint,
"Server disconnecting from client during authentication. No shared SSL/TLS algorithm. ({0})",
authEx);
}
catch (Exception ex)
{
_log.WriteLine("Server({0}) disconnecting from client({1}) during authentication. Exception: {2}",
state.TcpClient.Client.LocalEndPoint, state.TcpClient.Client.RemoteEndPoint, ex.Message);
_log.WriteLine("Server disconnecting from client during authentication. Exception: {0}",
ex.Message);
}
finally
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ public async Task ServerAllowNoEncryption_ClientRequireEncryption_ConnectWithEnc
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);
_log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
serverAllowNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength);
Assert.NotEqual(CipherAlgorithmType.Null, sslStream.CipherAlgorithm);
Assert.True(sslStream.CipherStrength > 0);
}
Expand All @@ -65,9 +64,8 @@ public async Task ServerAllowNoEncryption_ClientAllowNoEncryption_ConnectWithEnc
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption))
{
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);
_log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
serverAllowNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength);
Assert.NotEqual(CipherAlgorithmType.Null, sslStream.CipherAlgorithm);
Assert.True(sslStream.CipherStrength > 0, "Cipher strength should be greater than 0");
}
Expand All @@ -87,9 +85,8 @@ public async Task ServerAllowNoEncryption_ClientNoEncryption_ConnectWithNoEncryp
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
{
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);
_log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
serverAllowNoEncryption.RemoteEndPoint, sslStream.CipherAlgorithm, sslStream.CipherStrength);

CipherAlgorithmType expected = CipherAlgorithmType.Null;
Assert.Equal(expected, sslStream.CipherAlgorithm);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,8 @@ private async Task ServerAsyncSslHelper(
}

_log.WriteLine(
"Server({0}) authenticated client({1}) with encryption cipher: {2} {3}-bit strength",
serverConnection.Client.LocalEndPoint,
serverConnection.Client.RemoteEndPoint,
"Server({0}) authenticated with encryption cipher: {1} {2}-bit strength",
serverEndPoint,
sslServerStream.CipherAlgorithm,
sslServerStream.CipherStrength);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,8 @@ public async Task ServerNoEncryption_ClientAllowNoEncryption_ConnectWithNoEncryp
{
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);
_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);
Expand All @@ -87,9 +86,8 @@ public async Task ServerNoEncryption_ClientNoEncryption_ConnectWithNoEncryption(
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.NoEncryption))
{
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);
_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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,8 @@ public async Task ServerRequireEncryption_ClientRequireEncryption_ConnectWithEnc
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);
_log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
serverRequireEncryption.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");
}
Expand All @@ -65,9 +64,8 @@ public async Task ServerRequireEncryption_ClientAllowNoEncryption_ConnectWithEnc
using (var sslStream = new SslStream(client.GetStream(), false, AllowAnyServerCertificate, null, EncryptionPolicy.AllowNoEncryption))
{
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);
_log.WriteLine("Client authenticated to server({0}) with encryption cipher: {1} {2}-bit strength",
serverRequireEncryption.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");
}
Expand Down
Loading