Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Socket array length to avoid possible out of bounds errors #1031

Merged
merged 2 commits into from
Apr 14, 2021
Merged
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 @@ -327,7 +327,13 @@ private static Socket Connect(string serverName, int port, TimeSpan timeout, boo
string IPv4String = null;
string IPv6String = null;

Socket[] sockets = new Socket[2];
// Returning null socket is handled by the caller function.
if(ipAddresses == null || ipAddresses.Length == 0)
{
return null;
}

Socket[] sockets = new Socket[ipAddresses.Length];
cheenamalhotra marked this conversation as resolved.
Show resolved Hide resolved
JRahnama marked this conversation as resolved.
Show resolved Hide resolved
AddressFamily[] preferedIPFamilies = new AddressFamily[] { AddressFamily.InterNetwork, AddressFamily.InterNetworkV6 };

CancellationTokenSource cts = null;
Expand Down Expand Up @@ -360,6 +366,8 @@ void Cancel()
Socket availableSocket = null;
try
{
int n = 0; // Socket index

// We go through the IP list twice.
// In the first traversal, we only try to connect with the preferedIPFamilies[0].
// In the second traversal, we only try to connect with the preferedIPFamilies[1].
Expand All @@ -371,18 +379,18 @@ void Cancel()
{
if (ipAddress != null && ipAddress.AddressFamily == preferedIPFamilies[i])
{
sockets[i] = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets[n] = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

// enable keep-alive on socket
SetKeepAliveValues(ref sockets[i]);
SetKeepAliveValues(ref sockets[n]);

SqlClientEventSource.Log.TrySNITraceEvent(s_className, EventType.INFO, "Connecting to IP address {0} and port {1}", args0: ipAddress, args1: port);
sockets[i].Connect(ipAddress, port);
if (sockets[i] != null) // sockets[i] can be null if cancel callback is executed during connect()
sockets[n].Connect(ipAddress, port);
if (sockets[n] != null) // sockets[i] can be null if cancel callback is executed during connect()
{
if (sockets[i].Connected)
if (sockets[n].Connected)
{
availableSocket = sockets[i];
availableSocket = sockets[n];

if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
Expand All @@ -397,10 +405,11 @@ void Cancel()
}
else
{
sockets[i].Dispose();
sockets[i] = null;
sockets[n].Dispose();
sockets[n] = null;
}
}
n++;
}
}
catch (Exception e)
Expand Down