From c838dabd8d926a874996707a5374990949cd4185 Mon Sep 17 00:00:00 2001 From: priyankatiwari08 Date: Tue, 3 Nov 2026 23:08:49 +0530 Subject: [PATCH] Validate PRELOGIN option offsets before reading option data (#4902) * Validate PRELOGIN option offsets before reading option data ConsumePreLoginHandshake read the VERSION, ENCRYPT, INSTANCE, MARS and FEDAUTHREQUIRED option headers and data without checking that they lie within the received PRELOGIN response. A malformed response could cause an IndexOutOfRangeException to escape from SqlConnection.Open/OpenAsync. Read each option header through a helper that verifies the 4-byte header and the option data it points to are within the response, and report a CorruptedTdsStream parsing error otherwise. Responses that were previously accepted are unaffected. Add simulated-server tests covering out-of-range offsets, data truncated at the end of the response, and truncated option headers for each option, on both sync and async open paths, plus a well-formed control. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7ef2b899-d3ce-43cc-91d5-a321d447d1d4 * Validate declared PRELOGIN option lengths and all option headers Options the client reads must declare exactly their defined data length (VERSION 6 bytes; ENCRYPT, INSTANCE, MARS and FEDAUTHREQUIRED 1 byte), so a short option can no longer be read together with the bytes of the option that follows it. Every other option header (THREADID, TRACEID, unknown options and ENCRYPT under TDS 8) is now validated as well: the header and the declared data must lie within the response. Rename the helper parameter to expectedBytes and add tests for length mismatches, a short option overlapping the next option's data, and bounds violations in options the client does not read. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7ef2b899-d3ce-43cc-91d5-a321d447d1d4 * Validate PRELOGIN total size and simplify option header parsing - Read and validate each option header once, before dispatching on the option, using ReadPreLoginOptionHeader, which returns the data offset and length instead of advancing a ref offset. - Treat THREADID, TRACEID and unrecognized options in a single branch that skips the option after its header is validated; drop Debug.Fail. - Require the option tokens, headers, data and terminator to describe exactly the bytes of the response, rejecting undescribed bytes, data claimed by more than one option without a gap, and a missing terminator. - Make the test TDS server write ENCRYPT and TRACEID data only when it writes the matching option header. - Add tests for unknown options and for the total-size check. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7ef2b899-d3ce-43cc-91d5-a321d447d1d4 --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 7ef2b899-d3ce-43cc-91d5-a321d447d1d4 --- .../Data/SqlClient/Parser/TdsParser.cs | 175 +++-- .../PreLoginOptionBoundsTests.cs | 602 ++++++++++++++++++ .../TDS/TDS/PreLogin/TDSPreLoginToken.cs | 16 +- 3 files changed, 737 insertions(+), 56 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/PreLoginOptionBoundsTests.cs diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs index e8baed41fd..e5a3523223 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs @@ -995,6 +995,87 @@ private void EnableSsl(uint info, SqlConnectionEncryptOption encrypt, bool integ _physicalStateObj.ClearAllWritePackets(); } + /// + /// The size of a PRELOGIN option header that follows the option token: a 2-byte data + /// offset and a 2-byte data length. + /// + private const int PreLoginOptionHeaderSize = 4; + + /// + /// Returns the exact data length the server must declare for a PRELOGIN option whose + /// value the client reads, or for options whose value the client + /// does not read (including unknown options), which may declare any length. + /// + private static int? GetExpectedPreLoginOptionLength(int option) => option switch + { + // UL_VERSION (4 bytes) followed by US_SUBBUILD (2 bytes). + (int)PreLoginOptions.VERSION => 6, + (int)PreLoginOptions.ENCRYPT => 1, + (int)PreLoginOptions.INSTANCE => 1, + (int)PreLoginOptions.MARS => 1, + (int)PreLoginOptions.FEDAUTHREQUIRED => 1, + _ => null, + }; + + /// + /// Reads and validates the PRELOGIN option header that starts at + /// : a big-endian 2-byte data offset followed by a + /// big-endian 2-byte data length. The header must lie within + /// , the declared length must equal + /// when one is given, and the option data the header + /// describes must lie within . + /// + /// The PRELOGIN response. + /// The offset of the option header. + /// + /// The exact data length the option must declare, or to accept + /// any declared length for options whose data the client does not read. + /// + /// + /// The offset and length of the option data within + /// . + /// + private (int DataOffset, int DataLength) ReadPreLoginOptionHeader( + byte[] preLoginResponse, + int headerOffset, + int? expectedBytes) + { + if (headerOffset + PreLoginOptionHeaderSize > preLoginResponse.Length) + { + SqlClientEventSource.Log.TryTraceEvent( + " {0}, " + + "PreLogin option header at offset {1} exceeds response length {2}.", + ObjectID, headerOffset, preLoginResponse.Length); + throw SQL.ParsingErrorOffset(ParsingErrorState.CorruptedTdsStream, headerOffset); + } + + int dataOffset = preLoginResponse[headerOffset] << 8 + | preLoginResponse[headerOffset + 1]; + int dataLength = preLoginResponse[headerOffset + 2] << 8 + | preLoginResponse[headerOffset + 3]; + + if (expectedBytes.HasValue && dataLength != expectedBytes.Value) + { + SqlClientEventSource.Log.TryTraceEvent( + " {0}, " + + "PreLogin option length {1} does not match expected length {2}.", + ObjectID, dataLength, expectedBytes.Value); + throw SQL.ParsingErrorLength(ParsingErrorState.CorruptedTdsStream, dataLength); + } + + if (dataOffset + dataLength > preLoginResponse.Length) + { + SqlClientEventSource.Log.TryTraceEvent( + " {0}, " + + "PreLogin option data at offset {1} with length {2} exceeds response " + + "length {3}.", + ObjectID, dataOffset, dataLength, preLoginResponse.Length); + throw SQL.ParsingErrorOffset(ParsingErrorState.CorruptedTdsStream, dataOffset); + } + + return (dataOffset, dataLength); + } + private PreLoginHandshakeStatus ConsumePreLoginHandshake( SqlConnectionEncryptOption encrypt, bool trustServerCert, @@ -1048,37 +1129,47 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake( } int offset = 0; - int payloadOffset = 0; - int payloadLength = 0; int option = payload[offset++]; bool serverSupportsEncryption = false; + bool terminatorFound = false; + + // The number of response bytes described by the option tokens, option headers and + // option data read so far. A well-formed response is fully described by its options + // and the terminator, so any mismatch with the response length means bytes that + // belong to no option, or bytes claimed by more than one option. + int describedBytes = 0; - while (option != (byte)PreLoginOptions.LASTOPT) + while (true) { + if (option == (byte)PreLoginOptions.LASTOPT) + { + terminatorFound = true; + describedBytes++; + break; + } + + (int dataOffset, int dataLength) = ReadPreLoginOptionHeader( + payload, offset, GetExpectedPreLoginOptionLength(option)); + offset += PreLoginOptionHeaderSize; + describedBytes += 1 + PreLoginOptionHeaderSize + dataLength; + switch (option) { case (int)PreLoginOptions.VERSION: - payloadOffset = payload[offset++] << 8 | payload[offset++]; - payloadLength = payload[offset++] << 8 | payload[offset++]; - - byte majorVersion = payload[payloadOffset]; - byte minorVersion = payload[payloadOffset + 1]; - int level = (payload[payloadOffset + 2] << 8) | - payload[payloadOffset + 3]; + byte majorVersion = payload[dataOffset]; + byte minorVersion = payload[dataOffset + 1]; + int level = (payload[dataOffset + 2] << 8) | + payload[dataOffset + 3]; break; case (int)PreLoginOptions.ENCRYPT: if (tlsFirst) { - // Can skip/ignore this option if we are doing TDS 8. - offset += 4; + // Can skip/ignore this option's value if we are doing TDS 8. break; } - payloadOffset = payload[offset++] << 8 | payload[offset++]; - payloadLength = payload[offset++] << 8 | payload[offset++]; - - EncryptionOptions serverOption = ((EncryptionOptions)payload[payloadOffset]) & EncryptionOptions.OPTIONS_MASK; + EncryptionOptions serverOption = ((EncryptionOptions)payload[dataOffset]) & EncryptionOptions.OPTIONS_MASK; /* internal enum EncryptionOptions { OFF, @@ -1132,11 +1223,8 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake( break; case (int)PreLoginOptions.INSTANCE: - payloadOffset = payload[offset++] << 8 | payload[offset++]; - payloadLength = payload[offset++] << 8 | payload[offset++]; - byte ERROR_INST = 0x1; - byte instanceResult = payload[payloadOffset]; + byte instanceResult = payload[dataOffset]; if (instanceResult == ERROR_INST) { @@ -1148,35 +1236,19 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake( break; - case (int)PreLoginOptions.THREADID: - // DO NOTHING FOR THREADID - offset += 4; - break; - case (int)PreLoginOptions.MARS: - payloadOffset = payload[offset++] << 8 | payload[offset++]; - payloadLength = payload[offset++] << 8 | payload[offset++]; - - marsCapable = (payload[payloadOffset] == 0 ? false : true); + marsCapable = (payload[dataOffset] == 0 ? false : true); - Debug.Assert(payload[payloadOffset] == 0 || payload[payloadOffset] == 1, "Value for Mars PreLoginHandshake option not equal to 1 or 0!"); - break; - - case (int)PreLoginOptions.TRACEID: - // DO NOTHING FOR TRACEID - offset += 4; + Debug.Assert(payload[dataOffset] == 0 || payload[dataOffset] == 1, "Value for Mars PreLoginHandshake option not equal to 1 or 0!"); break; case (int)PreLoginOptions.FEDAUTHREQUIRED: - payloadOffset = payload[offset++] << 8 | payload[offset++]; - payloadLength = payload[offset++] << 8 | payload[offset++]; - // Only 0x00 and 0x01 are accepted values from the server. - if (payload[payloadOffset] != 0x00 && payload[payloadOffset] != 0x01) + if (payload[dataOffset] != 0x00 && payload[dataOffset] != 0x01) { SqlClientEventSource.Log.TryTraceEvent(" {0}, " + - "Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {1}.", ObjectID, (int)payload[payloadOffset]); - throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[payloadOffset]); + "Server sent an unexpected value for FedAuthRequired PreLogin Option. Value was {1}.", ObjectID, (int)payload[dataOffset]); + throw SQL.ParsingErrorValue(ParsingErrorState.FedAuthRequiredPreLoginResponseInvalidValue, (int)payload[dataOffset]); } // We must NOT use the response for the FEDAUTHREQUIRED PreLogin option, if the connection string option @@ -1186,16 +1258,15 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake( && _connHandler.ConnectionOptions.Authentication != SqlAuthenticationMethod.NotSpecified) || _connHandler.IsAccessTokenProvided) { - fedAuthRequired = payload[payloadOffset] == 0x01 ? true : false; + fedAuthRequired = payload[dataOffset] == 0x01 ? true : false; } break; + case (int)PreLoginOptions.THREADID: + case (int)PreLoginOptions.TRACEID: default: - Debug.Fail("UNKNOWN option in ConsumePreLoginHandshake, option:" + option); - - // DO NOTHING FOR THESE UNKNOWN OPTIONS - offset += 4; - + // The client does not use the value of this option, and skips options it + // does not recognize. The header has already been validated above. break; } @@ -1209,6 +1280,16 @@ private PreLoginHandshakeStatus ConsumePreLoginHandshake( } } + if (!terminatorFound || describedBytes != payload.Length) + { + SqlClientEventSource.Log.TryTraceEvent( + " {0}, " + + "PreLogin options describe {1} bytes but the response length is {2}. " + + "Terminator found: {3}.", + ObjectID, describedBytes, payload.Length, terminatorFound); + throw SQL.ParsingErrorLength(ParsingErrorState.CorruptedTdsStream, payload.Length); + } + if (_encryptionOption == EncryptionOptions.ON || _encryptionOption == EncryptionOptions.LOGIN) { diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/PreLoginOptionBoundsTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/PreLoginOptionBoundsTests.cs new file mode 100644 index 0000000000..dc3ffc5a02 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/PreLoginOptionBoundsTests.cs @@ -0,0 +1,602 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.SqlServer.TDS; +using Microsoft.SqlServer.TDS.EndPoint; +using Microsoft.SqlServer.TDS.PreLogin; +using Microsoft.SqlServer.TDS.Servers; +using Xunit; + +namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests; + +/// +/// Tests that the client validates every option header in a PRELOGIN response and reports a +/// parsing error, rather than reading outside the response buffer or across option +/// boundaries, when an option header or the option data it describes lies beyond the end of +/// the response, when an option the client reads declares an unexpected data length, or when +/// the options and terminator do not describe exactly the bytes of the response. +/// +[Collection(SimulatedServerTestCollection.Name)] +public class PreLoginOptionBoundsTests : IDisposable +{ + private const byte Version = 0x00; + private const byte Encrypt = 0x01; + private const byte Instance = 0x02; + private const byte ThreadId = 0x03; + private const byte Mars = 0x04; + private const byte TraceId = 0x05; + private const byte FedAuthRequired = 0x06; + + // An option token the client does not define; such options are validated and skipped. + private const byte UnknownOption = 0x10; + private const byte Terminator = 0xFF; + + private readonly PreLoginOverrideTdsServer _server; + private readonly string _connectionString; + + public PreLoginOptionBoundsTests() + { + _server = new PreLoginOverrideTdsServer(); + _server.Start(); + SqlConnectionStringBuilder builder = new() + { + DataSource = $"localhost,{_server.EndPoint.Port}", + Encrypt = SqlConnectionEncryptOption.Optional, + Pooling = false + }; + _connectionString = builder.ConnectionString; + } + + public void Dispose() => _server.Dispose(); + + /// + /// Control: a well-formed PRELOGIN response containing every option the client reads + /// is accepted and the connection opens. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task WellFormedResponse_Connects(bool useAsync) + { + _server.BuildResponse = encryption => BuildValidResponse(encryption); + + using SqlConnection connection = new(_connectionString); + if (useAsync) + { + await connection.OpenAsync(); + } + else + { + connection.Open(); + } + + Assert.Equal(System.Data.ConnectionState.Open, connection.State); + } + + /// + /// An option whose data offset points far beyond the end of the response is rejected + /// with a parsing error. + /// + [Theory] + [InlineData(Version, false)] + [InlineData(Version, true)] + [InlineData(Encrypt, false)] + [InlineData(Encrypt, true)] + [InlineData(Instance, false)] + [InlineData(Instance, true)] + [InlineData(Mars, false)] + [InlineData(Mars, true)] + [InlineData(FedAuthRequired, false)] + [InlineData(FedAuthRequired, true)] + public async Task OptionOffsetBeyondResponse_ThrowsParsingError(byte option, bool useAsync) + { + _server.BuildResponse = encryption => + { + byte[] response = BuildValidResponse(encryption); + SetOptionOffset(response, option, 0xFFFF); + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex, expectedOffset: 0xFFFF); + } + + /// + /// An option whose data starts inside the response but does not fit before the end of + /// the response is rejected. This checks the boundary: VERSION declares 6 bytes, so an + /// offset 3 bytes from the end is too short; single-byte options at an offset equal to + /// the response length are just past the end. + /// + [Theory] + [InlineData(Version, 3, false)] + [InlineData(Version, 3, true)] + [InlineData(Encrypt, 0, false)] + [InlineData(Encrypt, 0, true)] + [InlineData(Instance, 0, false)] + [InlineData(Instance, 0, true)] + [InlineData(Mars, 0, false)] + [InlineData(Mars, 0, true)] + [InlineData(FedAuthRequired, 0, false)] + [InlineData(FedAuthRequired, 0, true)] + public async Task OptionDataTruncatedAtEndOfResponse_ThrowsParsingError(byte option, int bytesAvailable, bool useAsync) + { + int expectedOffset = 0; + _server.BuildResponse = encryption => + { + byte[] response = BuildValidResponse(encryption); + expectedOffset = response.Length - bytesAvailable; + SetOptionOffset(response, option, (ushort)expectedOffset); + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex, expectedOffset); + } + + /// + /// A response that ends in the middle of an option header is rejected. + /// + [Theory] + [InlineData(Version, false)] + [InlineData(Version, true)] + [InlineData(Encrypt, false)] + [InlineData(Encrypt, true)] + [InlineData(Instance, false)] + [InlineData(Instance, true)] + [InlineData(ThreadId, false)] + [InlineData(ThreadId, true)] + [InlineData(Mars, false)] + [InlineData(Mars, true)] + [InlineData(TraceId, false)] + [InlineData(TraceId, true)] + [InlineData(FedAuthRequired, false)] + [InlineData(FedAuthRequired, true)] + public async Task OptionHeaderTruncated_ThrowsParsingError(byte option, bool useAsync) + { + // Option token followed by only 2 of the 4 header bytes. + _server.BuildResponse = _ => new byte[] { option, 0x00, 0x05 }; + + Exception ex = await OpenExpectingFailure(useAsync); + + // The header begins immediately after the option token, at offset 1. + AssertCorruptedStream(ex, expectedOffset: 1); + } + + /// + /// An option the client reads whose header declares a data length other than the length + /// defined for that option is rejected, even when the declared data lies within the + /// response. + /// + [Theory] + [InlineData(Version, 0, false)] + [InlineData(Version, 4, false)] + [InlineData(Version, 4, true)] + [InlineData(Version, 7, false)] + [InlineData(Encrypt, 0, false)] + [InlineData(Encrypt, 0, true)] + [InlineData(Encrypt, 2, false)] + [InlineData(Instance, 0, false)] + [InlineData(Instance, 0, true)] + [InlineData(Instance, 2, false)] + [InlineData(Mars, 0, false)] + [InlineData(Mars, 0, true)] + [InlineData(Mars, 2, false)] + [InlineData(FedAuthRequired, 0, false)] + [InlineData(FedAuthRequired, 0, true)] + [InlineData(FedAuthRequired, 2, false)] + public async Task OptionLengthMismatch_ThrowsParsingError( + byte option, + ushort declaredLength, + bool useAsync) + { + _server.BuildResponse = encryption => + { + byte[] response = BuildValidResponse(encryption); + SetOptionLength(response, option, declaredLength); + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex); + Assert.Contains($"Length: {declaredLength}", ex.Message); + } + + /// + /// A VERSION option that declares only 2 bytes of data, placed so that the 6 bytes the + /// client expects would run into the data of the following options, is rejected rather + /// than being read together with the other options' bytes. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task OptionDataShorterThanExpectedOverlapsNextOption_ThrowsParsingError( + bool useAsync) + { + _server.BuildResponse = encryption => + { + byte[] response = BuildValidResponse(encryption); + ushort encryptOffset = GetOptionOffset(response, Encrypt); + SetOptionOffset(response, Version, (ushort)(encryptOffset - 2)); + SetOptionLength(response, Version, 2); + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex); + Assert.Contains("Length: 2", ex.Message); + } + + /// + /// An option the client does not read (THREADID, TRACEID, or an option the client does + /// not recognize) is still validated: data that starts beyond the end of the response is + /// rejected. + /// + [Theory] + [InlineData(ThreadId, false)] + [InlineData(ThreadId, true)] + [InlineData(TraceId, false)] + [InlineData(TraceId, true)] + [InlineData(UnknownOption, false)] + [InlineData(UnknownOption, true)] + public async Task UnreadOptionOffsetBeyondResponse_ThrowsParsingError( + byte option, + bool useAsync) + { + _server.BuildResponse = encryption => + { + byte[] response = BuildValidResponse( + encryption, includeTraceId: true, includeUnknownOption: true); + SetOptionOffset(response, option, 0xFFFF); + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex, expectedOffset: 0xFFFF); + } + + /// + /// An option the client does not read (THREADID, TRACEID, or an option the client does + /// not recognize) is still validated: a declared length that runs past the end of the + /// response is rejected. + /// + [Theory] + [InlineData(ThreadId, false)] + [InlineData(ThreadId, true)] + [InlineData(TraceId, false)] + [InlineData(TraceId, true)] + [InlineData(UnknownOption, false)] + [InlineData(UnknownOption, true)] + public async Task UnreadOptionLengthBeyondResponse_ThrowsParsingError( + byte option, + bool useAsync) + { + int expectedOffset = 0; + _server.BuildResponse = encryption => + { + byte[] response = BuildValidResponse( + encryption, includeTraceId: true, includeUnknownOption: true); + expectedOffset = GetOptionOffset(response, option); + SetOptionLength(response, option, (ushort)(response.Length - expectedOffset + 1)); + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex, expectedOffset); + } + + /// + /// A response that ends in the middle of the header of an option the client does not + /// recognize is rejected. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task UnknownOptionHeaderTruncated_ThrowsParsingError(bool useAsync) + { + // Option token followed by only 2 of the 4 header bytes. + _server.BuildResponse = _ => new byte[] { UnknownOption, 0x00, 0x05 }; + + Exception ex = await OpenExpectingFailure(useAsync); + + // The header begins immediately after the option token, at offset 1. + AssertCorruptedStream(ex, expectedOffset: 1); + } + + /// + /// Control: options the client does not read (THREADID, TRACEID, or an option the client + /// does not recognize) may declare any length, provided the data lies within the response + /// and the options still describe every byte of the response. The option is skipped and + /// the connection opens. + /// + [Theory] + [InlineData(ThreadId, 0, false)] + [InlineData(ThreadId, 0, true)] + [InlineData(ThreadId, 7, false)] + [InlineData(TraceId, 0, false)] + [InlineData(TraceId, 0, true)] + [InlineData(TraceId, 40, false)] + [InlineData(UnknownOption, 0, false)] + [InlineData(UnknownOption, 0, true)] + [InlineData(UnknownOption, 3, false)] + [InlineData(UnknownOption, 3, true)] + public async Task UnreadOptionAnyLengthWithinResponse_Connects( + byte option, + int dataLength, + bool useAsync) + { + _server.BuildResponse = encryption => BuildResponse( + GetValidOptions(encryption, includeTraceId: true, includeUnknownOption: true) + .Select(o => o.Option == option ? (o.Option, new byte[dataLength]) : o)); + + using SqlConnection connection = new(_connectionString); + if (useAsync) + { + await connection.OpenAsync(); + } + else + { + connection.Open(); + } + + Assert.Equal(System.Data.ConnectionState.Open, connection.State); + } + + /// + /// A response that contains bytes after the data of its last option, which no option + /// describes, is rejected. + /// + [Theory] + [InlineData(1, false)] + [InlineData(1, true)] + [InlineData(8, false)] + public async Task UndescribedTrailingBytes_ThrowsParsingError(int extraBytes, bool useAsync) + { + int responseLength = 0; + _server.BuildResponse = encryption => + { + byte[] valid = BuildValidResponse(encryption); + byte[] response = new byte[valid.Length + extraBytes]; + Buffer.BlockCopy(valid, 0, response, 0, valid.Length); + responseLength = response.Length; + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex); + Assert.Contains($"Length: {responseLength}", ex.Message); + } + + /// + /// A response in which two options point at the same data byte, so that together the + /// options describe more bytes than the response contains, is rejected. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task OptionsShareDataBytes_ThrowsParsingError(bool useAsync) + { + int responseLength = 0; + _server.BuildResponse = encryption => + { + // FEDAUTHREQUIRED data is the last byte of the response. Point it at the MARS data + // byte instead and drop the now-unused last byte, so every offset and length + // stays within the response. + byte[] valid = BuildValidResponse(encryption); + SetOptionOffset(valid, FedAuthRequired, GetOptionOffset(valid, Mars)); + byte[] response = valid.Take(valid.Length - 1).ToArray(); + responseLength = response.Length; + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex); + Assert.Contains($"Length: {responseLength}", ex.Message); + } + + /// + /// A response whose option list is not closed by the terminator before the response + /// ends is rejected. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task MissingTerminator_ThrowsParsingError(bool useAsync) + { + int responseLength = 0; + _server.BuildResponse = _ => + { + // A single MARS option whose header is the whole response: the data byte is the + // last header byte, and the response ends before any terminator. + byte[] response = new byte[] { Mars, 0x00, 0x04, 0x00, 0x01 }; + responseLength = response.Length; + return response; + }; + + Exception ex = await OpenExpectingFailure(useAsync); + + AssertCorruptedStream(ex); + Assert.Contains($"Length: {responseLength}", ex.Message); + } + + private async Task OpenExpectingFailure(bool useAsync) + { + using SqlConnection connection = new(_connectionString); + if (useAsync) + { + return await Assert.ThrowsAnyAsync(connection.OpenAsync); + } + + return Assert.ThrowsAny(connection.Open); + } + + private static void AssertCorruptedStream(Exception ex) + { + Assert.IsNotType(ex); + Assert.Contains("Error state: 18", ex.Message); // ParsingErrorState.CorruptedTdsStream + } + + private static void AssertCorruptedStream(Exception ex, int expectedOffset) + { + AssertCorruptedStream(ex); + Assert.Contains($"Offset: {expectedOffset}", ex.Message); + } + + /// + /// Builds a well-formed PRELOGIN response containing VERSION, ENCRYPT, INSTANCE, + /// THREADID, MARS and FEDAUTHREQUIRED options, and optionally TRACEID and an option the + /// client does not recognize. + /// + private static byte[] BuildValidResponse( + TDSPreLoginTokenEncryptionType encryption, + bool includeTraceId = false, + bool includeUnknownOption = false) => + BuildResponse(GetValidOptions(encryption, includeTraceId, includeUnknownOption)); + + /// + /// Returns the options of a well-formed PRELOGIN response, in response order. The + /// FEDAUTHREQUIRED data is the last data in the response. + /// + private static List<(byte Option, byte[] Data)> GetValidOptions( + TDSPreLoginTokenEncryptionType encryption, + bool includeTraceId, + bool includeUnknownOption) + { + // The test server omits ENCRYPT when it has no encryption preference; NOT_SUP is the + // equivalent wire value and keeps the client in agreement with the server session. + byte encryptValue = encryption == TDSPreLoginTokenEncryptionType.None + ? (byte)TDSPreLoginTokenEncryptionType.NotSupported + : (byte)encryption; + + List<(byte Option, byte[] Data)> options = new() + { + (Version, new byte[] { 0x10, 0x00, 0x00, 0x00, 0x00, 0x00 }), + (Encrypt, new byte[] { encryptValue }), + (Instance, new byte[] { 0x00 }), + (ThreadId, new byte[] { 0x00, 0x00, 0x00, 0x00 }), + }; + + if (includeTraceId) + { + options.Add((TraceId, new byte[36])); + } + + if (includeUnknownOption) + { + options.Add((UnknownOption, new byte[] { 0x01, 0x02 })); + } + + options.Add((Mars, new byte[] { 0x00 })); + options.Add((FedAuthRequired, new byte[] { 0x00 })); + return options; + } + + /// + /// Builds a PRELOGIN response from the given options: one header per option, the + /// terminator, then the option data in the same order with no gaps. + /// + private static byte[] BuildResponse(IEnumerable<(byte Option, byte[] Data)> optionSequence) + { + List<(byte Option, byte[] Data)> options = optionSequence.ToList(); + int headerLength = options.Count * 5 + 1; + byte[] response = new byte[headerLength + options.Sum(o => o.Data.Length)]; + + int headerPosition = 0; + int dataPosition = headerLength; + foreach ((byte option, byte[] data) in options) + { + response[headerPosition++] = option; + response[headerPosition++] = (byte)(dataPosition >> 8); + response[headerPosition++] = (byte)dataPosition; + response[headerPosition++] = (byte)(data.Length >> 8); + response[headerPosition++] = (byte)data.Length; + + Buffer.BlockCopy(data, 0, response, dataPosition, data.Length); + dataPosition += data.Length; + } + + response[headerPosition] = Terminator; + return response; + } + + private static int FindOptionHeader(byte[] response, byte option) + { + for (int position = 0; response[position] != Terminator; position += 5) + { + if (response[position] == option) + { + return position; + } + } + + throw new ArgumentException( + $"Option {option} not found in PRELOGIN response.", nameof(option)); + } + + private static ushort GetOptionOffset(byte[] response, byte option) + { + int position = FindOptionHeader(response, option); + return (ushort)(response[position + 1] << 8 | response[position + 2]); + } + + private static void SetOptionOffset(byte[] response, byte option, ushort offset) + { + int position = FindOptionHeader(response, option); + response[position + 1] = (byte)(offset >> 8); + response[position + 2] = (byte)offset; + } + + private static void SetOptionLength(byte[] response, byte option, ushort length) + { + int position = FindOptionHeader(response, option); + response[position + 3] = (byte)(length >> 8); + response[position + 4] = (byte)length; + } + + /// + /// A TDS server that replaces its PRELOGIN response with caller-supplied raw bytes. + /// + private sealed class PreLoginOverrideTdsServer : TdsServer + { + public Func? BuildResponse { get; set; } + + public override TDSMessageCollection OnPreLoginRequest(ITDSServerSession session, TDSMessage request) + { + // Let the base server negotiate so its session state matches a normal handshake. + TDSMessageCollection response = base.OnPreLoginRequest(session, request); + + if (BuildResponse is null) + { + return response; + } + + TDSPreLoginToken token = response[0].OfType().First(); + return new TDSMessageCollection( + new TDSMessage(TDSMessageType.Response, new RawToken(BuildResponse(token.Encryption)))); + } + } + + private sealed class RawToken : TDSPacketToken + { + private readonly byte[] _bytes; + + public RawToken(byte[] bytes) => _bytes = bytes; + + public override bool Inflate(Stream source) => throw new NotSupportedException(); + + public override void Deflate(Stream destination) => destination.Write(_bytes, 0, _bytes.Length); + } +} diff --git a/src/Microsoft.Data.SqlClient/tests/tools/TDS/TDS/PreLogin/TDSPreLoginToken.cs b/src/Microsoft.Data.SqlClient/tests/tools/TDS/TDS/PreLogin/TDSPreLoginToken.cs index f5ca465fc0..1e43dba1a7 100644 --- a/src/Microsoft.Data.SqlClient/tests/tools/TDS/TDS/PreLogin/TDSPreLoginToken.cs +++ b/src/Microsoft.Data.SqlClient/tests/tools/TDS/TDS/PreLogin/TDSPreLoginToken.cs @@ -372,15 +372,10 @@ public override void Deflate(Stream destination) // Write MARS destination.WriteByte((byte)(IsMARS ? 0x01 : 0x00)); - // Write traceID - if (ClientTraceID != null) + // Write traceID and ActivityID only when the TraceID option header was added above + if (ActivityID != null && ClientTraceID != null) { destination.Write(ClientTraceID, 0, ClientTraceID.Length); - } - - // Write ActivityID - if (ActivityID != null) - { destination.Write(ActivityID, 0, ActivityID.Length); } @@ -396,8 +391,11 @@ public override void Deflate(Stream destination) destination.Write(Nonce, 0, Nonce.Length); } - // Write Encryption - destination.WriteByte((byte)Encryption); + // Write Encryption only when the Encryption option header was added above + if (Encryption != TDSPreLoginTokenEncryptionType.None) + { + destination.WriteByte((byte)Encryption); + } } } }