Skip to content

Commit 44be992

Browse files
authored
Fix managed SNI TLS handshake ignoring Connect Timeout (#5051)
* Fix managed SNI TLS handshake timeout On managed SNI the TLS handshake ran with no bound: Receive leaves the socket read timeout infinite and AuthenticateAsClient got no token, so a server that stalls after PRELOGIN blocked Open until the OS dropped the socket. EnableSsl now gets a token from the remaining Connect Timeout that closes the transport stream, and reports wait timeout 258 so MultiSubnetFailover keeps retrying within the full timeout. * Stall TLS handshake via TdsServer
1 parent 27e2a3c commit 44be992

24 files changed

Lines changed: 720 additions & 60 deletions

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,10 @@ protected static void AuthenticateAsClient(SslStream sslStream, string serverNam
9090
/// <summary>
9191
/// Enable SSL
9292
/// </summary>
93-
public abstract uint EnableSsl(uint options);
93+
/// <param name="options">SSL options</param>
94+
/// <param name="cancellationToken">Cancelled when the connection's Connect Timeout elapses; aborts a handshake still in progress.</param>
95+
/// <returns>SNI error code</returns>
96+
public abstract uint EnableSsl(uint options, CancellationToken cancellationToken);
9497

9598
/// <summary>
9699
/// Disable SSL

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -384,11 +384,11 @@ public void HandleReceiveComplete(SniPacket packet, uint sniErrorCode)
384384
/// <summary>
385385
/// Enable SSL
386386
/// </summary>
387-
public uint EnableSsl(uint options)
387+
public uint EnableSsl(uint options, CancellationToken cancellationToken)
388388
{
389389
using (SqlClientSNIEventScope.Create(nameof(SniMarsConnection)))
390390
{
391-
return _lowerHandle.EnableSsl(options);
391+
return _lowerHandle.EnableSsl(options, cancellationToken);
392392
}
393393
}
394394

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -566,7 +566,7 @@ public override void SetBufferSize(int bufferSize)
566566
{
567567
}
568568

569-
public override uint EnableSsl(uint options) => _connection.EnableSsl(options);
569+
public override uint EnableSsl(uint options, CancellationToken cancellationToken) => _connection.EnableSsl(options, cancellationToken);
570570

571571
public override void DisableSsl() => _connection.DisableSsl();
572572

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,14 @@ public override void Dispose()
169169

170170
if (_sslStream != null)
171171
{
172-
_sslStream.Dispose();
172+
try
173+
{
174+
_sslStream.Dispose();
175+
}
176+
catch (ObjectDisposedException)
177+
{
178+
// The SSL stream flushes the pipe it leaves open, which a handshake timeout has already closed.
179+
}
173180
_sslStream = null;
174181
}
175182

@@ -329,27 +336,38 @@ public override void SetAsyncCallbacks(SniAsyncCallback receiveCallback, SniAsyn
329336
_sendCallback = sendCallback;
330337
}
331338

332-
public override uint EnableSsl(uint options)
339+
public override uint EnableSsl(uint options, CancellationToken cancellationToken)
333340
{
334341
using (SqlClientSNIEventScope.Create(nameof(SniNpHandle)))
335342
{
336343
_validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
337344
try
338345
{
339-
if (_tlsFirst)
340-
{
341-
AuthenticateAsClient(_sslStream, _targetServer, null);
342-
}
343-
else
346+
// The handshake reads block on the pipe, so closing the transport is what bounds them.
347+
using (cancellationToken.UnsafeRegister(static stream => ((Stream)stream).Dispose(), _pipeStream))
344348
{
345-
// TODO: Resolve whether to send _serverNameIndication or _targetServer. _serverNameIndication currently results in error. Why?
346-
_sslStream.AuthenticateAsClient(_targetServer, null, s_supportedProtocols, false);
349+
if (_tlsFirst)
350+
{
351+
AuthenticateAsClient(_sslStream, _targetServer, null);
352+
}
353+
else
354+
{
355+
// TODO: Resolve whether to send _serverNameIndication or _targetServer. _serverNameIndication currently results in error. Why?
356+
_sslStream.AuthenticateAsClient(_targetServer, null, s_supportedProtocols, false);
357+
}
347358
}
359+
// A timeout landing after the handshake but before the registration ended has already closed the transport.
360+
cancellationToken.ThrowIfCancellationRequested();
348361
if (_sslOverTdsStream is not null)
349362
{
350363
_sslOverTdsStream.FinishHandshake();
351364
}
352365
}
366+
catch (Exception e) when (cancellationToken.IsCancellationRequested)
367+
{
368+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, TLS handshake did not complete within the connection timeout: {1}", args0: ConnectionId, args1: e.Message);
369+
return SniCommon.ReportSNIError(SniProviders.NP_PROV, (int)TdsEnums.SNI_WAIT_TIMEOUT, SniCommon.ConnTimeoutError, Strings.SNI_ERROR_11);
370+
}
353371
catch (AuthenticationException aue)
354372
{
355373
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, AuthenticationException message = {1}.", args0: ConnectionId, args1: aue?.Message);

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs‎

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -752,27 +752,38 @@ internal static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Ti
752752
/// <summary>
753753
/// Enable SSL
754754
/// </summary>
755-
public override uint EnableSsl(uint options)
755+
public override uint EnableSsl(uint options, CancellationToken cancellationToken)
756756
{
757757
using (SqlClientSNIEventScope.Create(nameof(SniHandle)))
758758
{
759759
_validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
760760

761761
try
762762
{
763-
if (_tlsFirst)
763+
// The handshake reads block on the socket, so closing the transport is what bounds them.
764+
using (cancellationToken.UnsafeRegister(static stream => ((Stream)stream).Dispose(), _tcpStream))
764765
{
765-
AuthenticateAsClient(_sslStream, _targetServer, null);
766-
}
767-
else
768-
{
769-
_sslStream.AuthenticateAsClient(_targetServer, null, s_supportedProtocols, false);
766+
if (_tlsFirst)
767+
{
768+
AuthenticateAsClient(_sslStream, _targetServer, null);
769+
}
770+
else
771+
{
772+
_sslStream.AuthenticateAsClient(_targetServer, null, s_supportedProtocols, false);
773+
}
770774
}
775+
// A timeout landing after the handshake but before the registration ended has already closed the transport.
776+
cancellationToken.ThrowIfCancellationRequested();
771777
if (_sslOverTdsStream is not null)
772778
{
773779
_sslOverTdsStream.FinishHandshake();
774780
}
775781
}
782+
catch (Exception e) when (cancellationToken.IsCancellationRequested)
783+
{
784+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, TLS handshake did not complete within the connection timeout: {1}", args0: _connectionId, args1: e.Message);
785+
return ReportTcpSNIError((int)TdsEnums.SNI_WAIT_TIMEOUT, SniCommon.ConnTimeoutError, Strings.SNI_ERROR_11);
786+
}
776787
catch (AuthenticationException aue)
777788
{
778789
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Authentication exception occurred: {1}", args0: _connectionId, args1: aue?.Message);

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,8 @@ internal override uint EnableSsl(ref uint info, bool tlsFirst, string serverCert
379379
try
380380
{
381381
SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.EnableSsl | Info | Session Id {0}", sessionHandle.ConnectionId);
382-
return sessionHandle.EnableSsl(info);
382+
using CancellationTokenSource connectTimeout = new(GetTimeoutRemaining());
383+
return sessionHandle.EnableSsl(info, connectTimeout.Token);
383384
}
384385
catch (Exception e)
385386
{
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
#if NET
6+
7+
using System;
8+
using System.IO.Pipes;
9+
using System.Threading;
10+
using System.Threading.Tasks;
11+
using Microsoft.Data.ProviderBase;
12+
using Microsoft.Data.SqlClient.ManagedSni;
13+
using Microsoft.Data.SqlClient.Parser;
14+
using Xunit;
15+
16+
namespace Microsoft.Data.SqlClient.UnitTests.ManagedSni
17+
{
18+
/// <summary>
19+
/// Tests for <see cref="SniNpHandle"/>.
20+
/// </summary>
21+
public sealed class SniNpHandleTests
22+
{
23+
/// <summary>
24+
/// Upper bound for EnableSsl to return. Generous, so it only separates "honors the token"
25+
/// from "blocks until the peer closes the pipe".
26+
/// </summary>
27+
private static readonly TimeSpan HandshakeBudget = TimeSpan.FromSeconds(30);
28+
29+
/// <summary>
30+
/// When the peer accepts the TLS ClientHello and never answers, EnableSsl must stop the
31+
/// handshake once its token is cancelled and report an SNI timeout error, for both TLS
32+
/// inside TDS and TLS-first (strict encryption). This is what bounds the handshake by
33+
/// Connect Timeout over named pipes (GitHub issues #4834 and #5045).
34+
/// </summary>
35+
/// <param name="tlsFirst">Whether the handle negotiates TLS before any TDS traffic.</param>
36+
[Theory]
37+
[InlineData(false)]
38+
[InlineData(true)]
39+
public async Task EnableSsl_PeerNeverAnswersHandshake_ReturnsTimeoutErrorWhenTokenIsCancelled(bool tlsFirst)
40+
{
41+
// Arrange
42+
// Connect the handle to a local pipe server that will stay silent.
43+
string pipeName = $"SqlClient-{Guid.NewGuid():N}";
44+
using NamedPipeServerStream peer = new(
45+
pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
46+
using CancellationTokenSource acceptTimeout = new(TimeSpan.FromSeconds(5));
47+
Task accept = peer.WaitForConnectionAsync(acceptTimeout.Token);
48+
SniNpHandle handle = new(
49+
".",
50+
pipeName,
51+
TimeoutTimer.StartNew(TimeSpan.FromSeconds(5)),
52+
tlsFirst,
53+
hostNameInCertificate: null,
54+
serverCertificateFilename: null);
55+
await accept;
56+
Assert.Equal(TdsEnums.SNI_SUCCESS, handle.Status);
57+
using CancellationTokenSource handshakeTimeout = new(TimeSpan.FromMilliseconds(500));
58+
59+
try
60+
{
61+
// Act
62+
// SNI errors are thread-static, so read the error on the thread that ran EnableSsl.
63+
Task<(uint Result, SniError Error)> enableSsl = Task.Run(
64+
() => (handle.EnableSsl(0, handshakeTimeout.Token), SniLoadHandle.LastError));
65+
Task settled = await Task.WhenAny(enableSsl, Task.Delay(HandshakeBudget));
66+
67+
// Assert
68+
Assert.True(
69+
ReferenceEquals(enableSsl, settled),
70+
$"EnableSsl did not return within {HandshakeBudget.TotalSeconds:N0}s after its token was cancelled.");
71+
(uint result, SniError error) = await enableSsl;
72+
Assert.Equal(TdsEnums.SNI_ERROR, result);
73+
Assert.Equal(SniProviders.NP_PROV, error.provider);
74+
Assert.Equal((uint)SniCommon.ConnTimeoutError, error.sniError);
75+
Assert.Equal((int)TdsEnums.SNI_WAIT_TIMEOUT, error.nativeError);
76+
}
77+
finally
78+
{
79+
// Cleanup
80+
// Disposing the handle also releases a handshake that ignored the token.
81+
handle.Dispose();
82+
}
83+
}
84+
}
85+
}
86+
87+
#endif

‎src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniPacketTests.cs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using System;
88
using System.IO;
99
using System.Security.Authentication;
10+
using System.Threading;
1011
using System.Threading.Tasks;
1112
using Microsoft.Data.SqlClient.ManagedSni;
1213
using Microsoft.Data.SqlClient.Parser;
@@ -92,7 +93,7 @@ public override void Dispose()
9293
{
9394
}
9495

95-
public override uint EnableSsl(uint options) => TdsEnums.SNI_SUCCESS;
96+
public override uint EnableSsl(uint options, CancellationToken cancellationToken) => TdsEnums.SNI_SUCCESS;
9697

9798
public override SniPacket RentPacket(int headerSize, int dataSize)
9899
{

‎src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniReceiveTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -496,7 +496,7 @@ public override void ReturnPacket(SniPacket packet)
496496

497497
public override void Dispose() => throw new NotSupportedException();
498498

499-
public override uint EnableSsl(uint options) => throw new NotSupportedException();
499+
public override uint EnableSsl(uint options, CancellationToken cancellationToken) => throw new NotSupportedException();
500500

501501
public override uint Receive(out SniPacket packet, int timeoutInMilliseconds)
502502
=> throw new NotSupportedException();
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
#if NET
6+
7+
using System;
8+
using System.Net;
9+
using System.Net.Sockets;
10+
using System.Threading;
11+
using System.Threading.Tasks;
12+
using Microsoft.Data.ProviderBase;
13+
using Microsoft.Data.SqlClient.ManagedSni;
14+
using Microsoft.Data.SqlClient.Parser;
15+
using Xunit;
16+
17+
namespace Microsoft.Data.SqlClient.UnitTests.ManagedSni
18+
{
19+
/// <summary>
20+
/// Tests for <see cref="SniTcpHandle"/>.
21+
/// </summary>
22+
public sealed class SniTcpHandleTests
23+
{
24+
/// <summary>
25+
/// Upper bound for EnableSsl to return. Generous, so it only separates "honors the token"
26+
/// from "blocks until the operating system gives up on the socket".
27+
/// </summary>
28+
private static readonly TimeSpan HandshakeBudget = TimeSpan.FromSeconds(30);
29+
30+
/// <summary>
31+
/// When the peer accepts the TLS ClientHello and never answers, EnableSsl must stop the
32+
/// handshake once its token is cancelled and report an SNI timeout error, for both TLS
33+
/// inside TDS and TLS-first (strict encryption). This is what bounds the handshake by
34+
/// Connect Timeout (GitHub issues #4834 and #5045).
35+
/// </summary>
36+
/// <param name="tlsFirst">Whether the handle negotiates TLS before any TDS traffic.</param>
37+
[Theory]
38+
[InlineData(false)]
39+
[InlineData(true)]
40+
public async Task EnableSsl_PeerNeverAnswersHandshake_ReturnsTimeoutErrorWhenTokenIsCancelled(bool tlsFirst)
41+
{
42+
// Arrange
43+
// Connect the handle to a local peer that will stay silent.
44+
using TcpListener listener = new(IPAddress.Loopback, 0);
45+
listener.Start();
46+
SQLDNSInfo? pendingDnsInfo = null;
47+
SniTcpHandle handle = new(
48+
IPAddress.Loopback.ToString(),
49+
((IPEndPoint)listener.LocalEndpoint).Port,
50+
TimeoutTimer.StartNew(TimeSpan.FromSeconds(5)),
51+
parallel: false,
52+
SqlConnectionIPAddressPreference.IPv4First,
53+
cachedFQDN: nameof(SniTcpHandleTests),
54+
ref pendingDnsInfo,
55+
tlsFirst,
56+
hostNameInCertificate: null,
57+
serverCertificateFilename: null);
58+
using CancellationTokenSource acceptTimeout = new(TimeSpan.FromSeconds(5));
59+
using Socket peer = await listener.AcceptSocketAsync(acceptTimeout.Token);
60+
Assert.Equal(TdsEnums.SNI_SUCCESS, handle.Status);
61+
using CancellationTokenSource handshakeTimeout = new(TimeSpan.FromMilliseconds(500));
62+
63+
try
64+
{
65+
// Act
66+
// SNI errors are thread-static, so read the error on the thread that ran EnableSsl.
67+
Task<(uint Result, SniError Error)> enableSsl = Task.Run(
68+
() => (handle.EnableSsl(0, handshakeTimeout.Token), SniLoadHandle.LastError));
69+
Task settled = await Task.WhenAny(enableSsl, Task.Delay(HandshakeBudget));
70+
71+
// Assert
72+
Assert.True(
73+
ReferenceEquals(enableSsl, settled),
74+
$"EnableSsl did not return within {HandshakeBudget.TotalSeconds:N0}s after its token was cancelled.");
75+
(uint result, SniError error) = await enableSsl;
76+
Assert.Equal(TdsEnums.SNI_ERROR, result);
77+
Assert.Equal(SniProviders.TCP_PROV, error.provider);
78+
Assert.Equal((uint)SniCommon.ConnTimeoutError, error.sniError);
79+
Assert.Equal((int)TdsEnums.SNI_WAIT_TIMEOUT, error.nativeError);
80+
}
81+
finally
82+
{
83+
// Cleanup
84+
// Disposing the handle also releases a handshake that ignored the token.
85+
handle.Dispose();
86+
}
87+
}
88+
}
89+
}
90+
91+
#endif

0 commit comments

Comments
 (0)