From a694bec0cabd3418adcb25619615fa2dbccd3fd1 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Tue, 13 Oct 2026 09:11:33 +0530 Subject: [PATCH 01/12] Connection encryption info: capture Managed SNI server certificate details (Slice C) Capture SHA-256 of the presented leaf certificate, the effective SqlClient validation verdict, and the original callback chain status flags in Managed SNI, and flow them into the per-attempt encryption info capture so both SqlConnection.EncryptionInfo and SqlException.EncryptionInfo report them. No trust decisions, messages, or tracing are changed. Part of #2353 Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../2353-connection-encryption-info.md | 30 +- .../Connection/EncryptionInfoAccumulator.cs | 39 +- .../Connection/ServerCertificateCapture.cs | 61 +++ .../SqlClient/ManagedSni/SniCommon.netcore.cs | 164 +++++- .../SqlClient/ManagedSni/SniHandle.netcore.cs | 8 + .../ManagedSni/SniMarsConnection.netcore.cs | 2 + .../ManagedSni/SniMarsHandle.netcore.cs | 2 + .../ManagedSni/SniNpHandle.netcore.cs | 29 +- .../ManagedSni/SniTcpHandle.netcore.cs | 27 +- .../Data/SqlClient/Parser/TdsParser.cs | 16 + .../SqlClient/Parser/TdsParserStateObject.cs | 7 + .../TdsParserStateObjectManaged.netcore.cs | 2 + .../SniCommonServerCertificateCaptureTest.cs | 494 ++++++++++++++++++ .../ConnectionEncryptionInfoTests.cs | 71 ++- .../ManagedSniCertificateCaptureTests.cs | 318 +++++++++++ 15 files changed, 1229 insertions(+), 41 deletions(-) create mode 100644 src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs create mode 100644 src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs create mode 100644 src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index 3495cafa87..a5f4e26fb6 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -283,10 +283,14 @@ negotiated. When a pooled connection is checked out, its automatic enlistment (` `Enlist`) can fail without a new login; that exception carries the snapshot the physical connection published when it logged in. Exceptions raised before any value was observed, and non-`SqlException` failures, keep `Empty`. -- **Managed SNI** validates the server certificate inside the handshake, so a validation - failure fails `EnableSsl`. In this slice Managed SNI does not capture the negotiated protocol - on a failed handshake, so the exception reports the mode with a `null` protocol. Slice C adds - capture of `SslStream.SslProtocol` from the validation callback. +- **Managed SNI** validates the server certificate inside the handshake, in the + `RemoteCertificateValidationCallback`. `SslStream` agrees the protocol version before it + raises the callback, so the callback records `SslStream.SslProtocol` with the certificate + details. When validation fails `EnableSsl` fails; `TdsParser.EnableSsl` first assigns the + captured protocol and certificate details to the accumulator, so the exception reports the mode + selected at PRELOGIN together with that protocol. A protocol already determined for the attempt + takes precedence over the one reported with the certificate details. Managed SNI is used only on + .NET (`net10.0`). - **Native SNI.** With the current SNI package, native SNI also rejects an untrusted server certificate during the handshake, so this slice reports the mode but no protocol for that failure (the tests assert this for both SNI implementations). If a deferred validation @@ -307,6 +311,24 @@ No transport sets it in this slice, so the property stays `null`; Slice C record SNI contract. On failure an observed cipher suite is kept, like the protocol. A cipher suite is only reported once a ServerHello selected it, so it is not dropped when the protocol is unavailable. + +### Managed SNI certificate capture + +Managed SNI records certificate details from the `RemoteCertificateValidationCallback` +that runs during the TLS handshake. Capture reuses the callback's inputs and SqlClient's +existing verdict; it performs no extra validation or network work and doesn't change +trust decisions, messages, or tracing. Values are reset at the start of every TLS +handshake and recorded whether the handshake succeeds or fails. The callback also records the +TLS protocol agreed for the handshake (see **Failure path** above). + +| Field | Source | `null` when | +| --- | --- | --- | +| `PresentedServerCertificateHash256` | SHA-256 of the presented leaf certificate's DER encoding (`GetRawCertData()`) | No certificate was presented. Captured even when `TrustServerCertificate` bypasses validation. | +| `ServerCertificateValidationErrors` | Effective SqlClient verdict: `ServerCertificateMissing`, `ChainError`, `HostNameMismatch` (after `HostNameInCertificate`), `PinnedCertificateMismatch` (`ServerCertificate`); `None` when validation passed | Validation was bypassed, or the configured `ServerCertificate` file could not be read. | +| `ServerCertificateChainStatus` | Bitwise OR of the original callback chain's `ChainStatus` flags (no chain rebuild); `NoError` when the chain was evaluated cleanly | Validation was bypassed, `ServerCertificate` pinning is used (the chain isn't consulted), no certificate was presented, or the platform reported a chain error without flags. | + +Native SNI does not yet report certificate details; those fields remain `null` there. + ## 5. Scope The API reports negotiated encryption, TLS protocol, the server-selected cipher suite, the diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs index c62453e691..37bcaf289a 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs @@ -6,6 +6,7 @@ using System.Net.Security; #endif using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; #nullable enable @@ -31,6 +32,18 @@ namespace Microsoft.Data.SqlClient.Connection /// internal sealed class EncryptionInfoAccumulator { + /// + /// Gets or sets the SHA-256 hash of the presented server certificate for the current attempt, + /// or if the transport did not observe a presented certificate. + /// + public byte[]? CertificateHash256 { get; set; } + + /// + /// Gets or sets the combined chain status flags for the current attempt, or + /// if the chain was not consulted or is unavailable. + /// + public X509ChainStatusFlags? ChainStatus { get; set; } + #if NET /// /// Gets or sets the TLS cipher suite negotiated for the current attempt, or @@ -62,7 +75,13 @@ public int? CipherSuite /// /// Gets a value indicating whether any value has been recorded for the current attempt. /// - public bool HasValues => Mode is not null || Protocol is not null || CipherSuite is not null; + public bool HasValues => + Mode is not null || + Protocol is not null || + CipherSuite is not null || + CertificateHash256 is not null || + ValidationErrors is not null || + ChainStatus is not null; /// /// Gets or sets the final negotiated encryption mode for the current attempt, or @@ -86,6 +105,12 @@ public SslProtocols? Protocol set => field = value == SslProtocols.None ? null : value; } + /// + /// Gets or sets SqlClient's effective certificate validation verdict for the current attempt, + /// or if SqlClient did not evaluate the certificate. + /// + public SqlServerCertificateValidationErrors? ValidationErrors { get; set; } + /// /// Clears all accumulated values. Called at the start of each physical login attempt. /// @@ -94,6 +119,9 @@ public void Reset() Mode = null; Protocol = null; CipherSuite = null; + CertificateHash256 = null; + ValidationErrors = null; + ChainStatus = null; } /// @@ -101,16 +129,17 @@ public void Reset() /// when nothing was recorded. /// /// - /// Certificate fields are never inferred here; they remain unavailable. + /// Certificate fields are never inferred here; they are published only as recorded by the + /// transport. /// public SqlConnectionEncryptionInfo ToSnapshot() => HasValues ? new SqlConnectionEncryptionInfo( negotiatedEncryptionMode: Mode, negotiatedEncryptionProtocol: Protocol, - presentedServerCertificate: null, - validationErrors: null, - chainStatus: null, + presentedServerCertificate: CertificateHash256, + validationErrors: ValidationErrors, + chainStatus: ChainStatus, negotiatedCipherSuite: CipherSuite) : SqlConnectionEncryptionInfo.Empty; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs new file mode 100644 index 0000000000..119fd3b4de --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs @@ -0,0 +1,61 @@ +// 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.Security.Authentication; +using System.Security.Cryptography.X509Certificates; + +#nullable enable + +namespace Microsoft.Data.SqlClient.Connection +{ + /// + /// Immutable record of the server certificate details observed by the transport during one TLS + /// handshake. Produced by the transport layer and consumed by . + /// + /// + /// Each value is when it is unavailable: no certificate was presented + /// (), SqlClient did not evaluate the certificate + /// (), or the original chain was not consulted or reported no + /// usable status (). This type never carries the certificate itself. + /// + internal sealed class ServerCertificateCapture + { + internal ServerCertificateCapture( + byte[]? hash256, + SqlServerCertificateValidationErrors? validationErrors, + X509ChainStatusFlags? chainStatus, + SslProtocols? protocol = null) + { + Hash256 = hash256; + ValidationErrors = validationErrors; + ChainStatus = chainStatus; + Protocol = protocol; + } + + /// + /// Gets the SHA-256 hash of the DER encoding of the presented leaf certificate, or + /// if no certificate was presented. + /// + public byte[]? Hash256 { get; } + + /// + /// Gets SqlClient's effective validation verdict, or if SqlClient did + /// not evaluate the certificate. + /// + public SqlServerCertificateValidationErrors? ValidationErrors { get; } + + /// + /// Gets the combined status flags of the chain supplied to the certificate validation + /// callback, or if the chain was not consulted or is unavailable. + /// + public X509ChainStatusFlags? ChainStatus { get; } + + /// + /// Gets the TLS protocol the transport reported for this handshake, or + /// if the transport did not report one. Used only when the protocol was not otherwise + /// determined for the attempt (for example, when the handshake failed). + /// + public SslProtocols? Protocol { get; } + } +} diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs index bf72a91bc2..5fca6313cb 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs @@ -8,10 +8,13 @@ using System.Diagnostics; using System.Net; using System.Net.Security; +using System.Security.Authentication; +using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; +using Microsoft.Data.SqlClient.Connection; using Microsoft.Data.SqlClient.Internal; using Microsoft.Data.SqlClient.Parser; @@ -72,14 +75,54 @@ internal class SniCommon /// True if certificate is valid internal static bool ValidateSslServerCertificate(Guid connectionId, string targetServerName, string hostNameInCertificate, X509Certificate serverCert, string validationCertFileName, SslPolicyErrors policyErrors) { + ServerCertificateVerdict verdict = default; + return ValidateSslServerCertificate(connectionId, targetServerName, hostNameInCertificate, serverCert, validationCertFileName, policyErrors, callbackChain: null, ref verdict); + } + + /// + /// Validates the server certificate exactly as + /// + /// does, and additionally records SqlClient's effective verdict in . + /// + /// + /// Recording never changes the trust decision, never performs additional validation or + /// network work, and never alters exception messages or trace text. + /// is written immediately before this method returns or throws its validation exception, so + /// it is observable by the caller in both cases. If validation is aborted for any other + /// reason (for example the ServerCertificate file cannot be loaded), the validation + /// errors are left unavailable because no comparison was completed. + /// + /// is the bitwise OR of the status flags of + /// the original supplied to the TLS validation callback. It is only + /// recorded when that chain is consulted (no ServerCertificate pin and a certificate + /// was presented); it is in pin mode, when no certificate was + /// presented, when no chain was supplied, or when chain errors were reported but the chain + /// carries no status flags. + /// + /// + internal static bool ValidateSslServerCertificate(Guid connectionId, string targetServerName, string hostNameInCertificate, X509Certificate serverCert, string validationCertFileName, SslPolicyErrors policyErrors, X509Chain callbackChain, ref ServerCertificateVerdict verdict) + { + verdict = default; + using (SqlClientSNIEventScope.Create(nameof(SniCommon))) { bool hasHostNameInCertificate = !string.IsNullOrEmpty(hostNameInCertificate); + bool pinConfigured = !string.IsNullOrEmpty(validationCertFileName); + + // The callback chain is only consulted when trust is decided by the platform chain, + // i.e. no ServerCertificate pin is configured and a certificate was presented. + X509ChainStatusFlags? callbackChainStatus = null; + if (!pinConfigured && serverCert is not null && !policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable)) + { + callbackChainStatus = GetChainStatus(callbackChain, policyErrors); + } + if (!hasHostNameInCertificate - && string.IsNullOrEmpty(validationCertFileName) + && !pinConfigured && policyErrors == SslPolicyErrors.None) { SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, targetServerName {1}, SSL Server certificate has no policy errors and no HostNameInCertificate or ServerCertificate was supplied; skipping certificate comparison.", args0: connectionId, args1: targetServerName); + verdict = new ServerCertificateVerdict(SqlServerCertificateValidationErrors.None, callbackChainStatus); return true; } @@ -93,7 +136,7 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ serverNameToValidate = targetServerName; } - if (!string.IsNullOrEmpty(validationCertFileName)) + if (pinConfigured) { // There is no trustworthy certificate to compare against when the server // presented none. SslStream reports that as RemoteCertificateNotAvailable, and @@ -103,6 +146,7 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ if (serverCert is null || policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable)) { SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, ServerCertificate was specified but the server presented no certificate. Certificate validation failed.", args0: connectionId); + verdict = new ServerCertificateVerdict(SqlServerCertificateValidationErrors.ServerCertificateMissing, chainStatus: null); throw ADP.SSLCertificateAuthenticationException(Strings.SQL_ServerCertificateNotAvailable); } @@ -111,26 +155,31 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ if (serverCert.GetRawCertData().AsSpan().SequenceEqual(validationCertificate.GetRawCertData().AsSpan())) { SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, ServerCertificate matches the certificate provided by the server. Certificate validation passed.", args0: connectionId); + verdict = new ServerCertificateVerdict(SqlServerCertificateValidationErrors.None, chainStatus: null); return true; } else { SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, ServerCertificate doesn't match the certificate provided by the server. Certificate validation failed.", args0: connectionId); + verdict = new ServerCertificateVerdict(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, chainStatus: null); throw ADP.SSLCertificateAuthenticationException(Strings.SQL_RemoteCertificateDoesNotMatchServerCertificate); } } + SqlServerCertificateValidationErrors validationErrors = SqlServerCertificateValidationErrors.None; StringBuilder messageBuilder = new(); if (serverCert is null || policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable)) { SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SSL Server certificate not validated as PolicyErrors set to RemoteCertificateNotAvailable.", args0: connectionId, args1: targetServerName); messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNotAvailable); + validationErrors |= SqlServerCertificateValidationErrors.ServerCertificateMissing; } if (serverCert is not null && policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors)) { + validationErrors |= SqlServerCertificateValidationErrors.ChainError; SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {0}, SslPolicyError {1}, SSL Policy certificate chain has errors.", args0: connectionId, args1: targetServerName, args2: policyErrors); // get the chain status from the certificate @@ -162,9 +211,12 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ { SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, serverNameToValidate {1}, Target Server name or HNIC does not match the Subject/SAN in Certificate.", args0: connectionId, args1: serverNameToValidate); messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNameMismatch); + validationErrors |= SqlServerCertificateValidationErrors.HostNameMismatch; } } + verdict = new ServerCertificateVerdict(validationErrors, callbackChainStatus); + if (messageBuilder.Length > 0) { throw ADP.SSLCertificateAuthenticationException(messageBuilder.ToString()); @@ -175,6 +227,97 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ } } + /// + /// Combines the status flags of the chain supplied to the TLS validation callback without + /// building or re-evaluating the chain. + /// + /// The original callback chain, if any. + /// The policy errors supplied to the callback. + /// + /// The bitwise OR of the chain element status flags, + /// for a clean chain, or when the chain is unavailable or chain errors + /// were reported without any status flags. + /// + internal static X509ChainStatusFlags? GetChainStatus(X509Chain chain, SslPolicyErrors policyErrors) + { + return chain is null ? null : CombineChainStatus(chain.ChainStatus, policyErrors); + } + + /// + /// Combines chain status entries into a single set of flags. + /// + /// The chain status entries. + /// The policy errors supplied to the callback. + /// See . + internal static X509ChainStatusFlags? CombineChainStatus(X509ChainStatus[] statuses, SslPolicyErrors policyErrors) + { + X509ChainStatusFlags flags = X509ChainStatusFlags.NoError; + foreach (X509ChainStatus status in statuses ?? Array.Empty()) + { + flags |= status.Status; + } + + if (flags == X509ChainStatusFlags.NoError && policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors)) + { + // A chain error was reported but the chain does not describe it; report the chain + // status as unavailable rather than as a clean chain. + return null; + } + + return flags; + } + + /// + /// Creates the transport-level certificate capture for one TLS validation callback + /// invocation. + /// + /// The certificate presented by the server, if any. + /// The verdict recorded by validation; default when not evaluated. + /// The raising the validation callback, if any. + /// The capture. Never . + internal static ServerCertificateCapture CreateServerCertificateCapture(X509Certificate serverCert, in ServerCertificateVerdict verdict, object sender = null) + { + byte[] hash = null; + if (serverCert is not null) + { + try + { + hash = SHA256.HashData(serverCert.GetRawCertData()); + } + catch (CryptographicException) + { + // Capture must never affect the handshake outcome; leave the hash unavailable. + } + } + + return new ServerCertificateCapture(hash, verdict.ValidationErrors, verdict.ChainStatus, GetHandshakeProtocol(sender)); + } + + /// + /// Reads the TLS protocol version agreed for the handshake in progress. SslStream raises the + /// certificate validation callback after the protocol version has been agreed, so this + /// reflects what was observed for the attempt even if the certificate is then rejected. + /// + /// The protocol, or when it is not available. + private static SslProtocols? GetHandshakeProtocol(object sender) + { + if (sender is not SslStream sslStream) + { + return null; + } + + try + { + SslProtocols protocol = sslStream.SslProtocol; + return protocol == SslProtocols.None ? null : protocol; + } + catch (Exception) + { + // Capture must never affect the handshake outcome. + return null; + } + } + /// /// Loads the certificate specified by the ServerCertificate option, failing closed /// when it cannot be loaded or parsed. @@ -266,6 +409,23 @@ internal static uint ReportSNIError(SniError error) return TdsEnums.SNI_ERROR; } } + + /// + /// SqlClient's effective server certificate validation verdict for one TLS validation callback. + /// Default values (all ) mean the certificate was not evaluated. + /// + internal readonly struct ServerCertificateVerdict + { + internal ServerCertificateVerdict(SqlServerCertificateValidationErrors? validationErrors, X509ChainStatusFlags? chainStatus) + { + ValidationErrors = validationErrors; + ChainStatus = chainStatus; + } + + internal SqlServerCertificateValidationErrors? ValidationErrors { get; } + + internal X509ChainStatusFlags? ChainStatus { get; } + } } #endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs index aedcfcb2c1..9b99491d10 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs @@ -11,6 +11,7 @@ using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; +using Microsoft.Data.SqlClient.Connection; using Microsoft.Data.SqlClient.Parser; namespace Microsoft.Data.SqlClient.ManagedSni @@ -124,6 +125,13 @@ protected static void AuthenticateAsClient(SslStream sslStream, string serverNam /// public virtual SslProtocols ProtocolVersion { get; } = 0; + /// + /// Gets the server certificate details captured during the most recent TLS handshake on + /// this handle, or if the certificate validation callback has not + /// run since TLS was last enabled. + /// + public virtual ServerCertificateCapture ServerCertificateCapture => null; + #if DEBUG /// /// Test handle for killing underlying connection diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs index ef07b3e903..e331bf87af 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs @@ -37,6 +37,8 @@ internal class SniMarsConnection public SslProtocols ProtocolVersion => _lowerHandle.ProtocolVersion; + public Connection.ServerCertificateCapture ServerCertificateCapture => _lowerHandle.ServerCertificateCapture; + internal object DemuxerSync => _sync; /// diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs index 6adb803ddf..e2431b7968 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs @@ -54,6 +54,8 @@ internal sealed class SniMarsHandle : SniHandle public override SslProtocols ProtocolVersion => _connection.ProtocolVersion; + public override Connection.ServerCertificateCapture ServerCertificateCapture => _connection.ServerCertificateCapture; + /// /// Dispose object /// diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs index eb73914c7d..f5246e4076 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs @@ -13,6 +13,7 @@ using System.Security.Cryptography.X509Certificates; using System.Threading; using Microsoft.Data.ProviderBase; +using Microsoft.Data.SqlClient.Connection; using Microsoft.Data.SqlClient.Internal; using Microsoft.Data.SqlClient.Parser; @@ -40,6 +41,7 @@ internal sealed class SniNpHandle : SniPhysicalHandle private SniAsyncCallback _sendCallback; private bool _validateCert = true; + private ServerCertificateCapture _serverCertificateCapture; private readonly uint _status = TdsEnums.SNI_UNINITIALIZED; private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE; private readonly Guid _connectionId = Guid.NewGuid(); @@ -334,6 +336,7 @@ public override uint EnableSsl(uint options) using (SqlClientSNIEventScope.Create(nameof(SniNpHandle))) { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; + Volatile.Write(ref _serverCertificateCapture, null); try { if (_tlsFirst) @@ -385,19 +388,31 @@ public override void DisableSsl() /// true if valid private bool ValidateServerCertificate(object sender, X509Certificate serverCertificate, X509Chain chain, SslPolicyErrors policyErrors) { + ServerCertificateVerdict verdict = default; using (SqlClientSNIEventScope.Create(nameof(SniNpHandle))) { - if (!_validateCert) + try { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Certificate validation not requested.", args0: ConnectionId); - return true; - } + if (!_validateCert) + { + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Certificate validation not requested.", args0: ConnectionId); + return true; + } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Proceeding to SSL certificate validation.", args0: ConnectionId); - return SniCommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors); - } + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Proceeding to SSL certificate validation.", args0: ConnectionId); + return SniCommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors, chain, ref verdict); + } + finally + { + // Recorded for both outcomes so that a failed handshake still reports what was observed. + Volatile.Write(ref _serverCertificateCapture, SniCommon.CreateServerCertificateCapture(serverCertificate, verdict, sender)); + } + } } + /// + public override ServerCertificateCapture ServerCertificateCapture => Volatile.Read(ref _serverCertificateCapture); + /// /// Set buffer size /// diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs index ef8e10256a..b2babc6f3b 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs @@ -16,6 +16,7 @@ using System.Threading; using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; +using Microsoft.Data.SqlClient.Connection; using Microsoft.Data.SqlClient.Internal; using Microsoft.Data.SqlClient.Parser; @@ -41,6 +42,7 @@ internal sealed class SniTcpHandle : SniPhysicalHandle private SniAsyncCallback _sendCallback; private bool _validateCert = true; + private ServerCertificateCapture _serverCertificateCapture; private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE; private uint _status = TdsEnums.SNI_UNINITIALIZED; private Guid _connectionId = Guid.NewGuid(); @@ -757,6 +759,7 @@ public override uint EnableSsl(uint options) using (SqlClientSNIEventScope.Create(nameof(SniHandle))) { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; + Volatile.Write(ref _serverCertificateCapture, null); try { @@ -816,16 +819,28 @@ public override void DisableSsl() /// True if certificate is valid private bool ValidateServerCertificate(object sender, X509Certificate serverCertificate, X509Chain chain, SslPolicyErrors policyErrors) { - if (!_validateCert) + ServerCertificateVerdict verdict = default; + try { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Certificate will not be validated.", args0: _connectionId); - return true; - } + if (!_validateCert) + { + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Certificate will not be validated.", args0: _connectionId); + return true; + } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Certificate will be validated for Target Server name", args0: _connectionId); - return SniCommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Certificate will be validated for Target Server name", args0: _connectionId); + return SniCommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors, chain, ref verdict); + } + finally + { + // Recorded for both outcomes so that a failed handshake still reports what was observed. + Volatile.Write(ref _serverCertificateCapture, SniCommon.CreateServerCertificateCapture(serverCertificate, verdict, sender)); + } } + /// + public override ServerCertificateCapture ServerCertificateCapture => Volatile.Read(ref _serverCertificateCapture); + /// /// Set buffer size /// 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 98112b2533..d43f41feb1 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 @@ -955,6 +955,22 @@ private void EnableSsl(uint info, SqlConnectionEncryptOption encrypt, bool integ #endif error = _physicalStateObj.EnableSsl(ref info, encrypt == SqlConnectionEncryptOption.Strict, serverCertificateFilename); + // The certificate validation callback runs synchronously within EnableSsl, so whatever the + // transport observed is complete here; record it before any failure is reported so that + // the login exception carries it. + ServerCertificateCapture certificateCapture = _physicalStateObj.GetServerCertificateCapture(); + EncryptionInfoAccumulator accumulator = _connHandler?.EncryptionInfoAccumulator; + if (accumulator is not null && certificateCapture is not null) + { + accumulator.CertificateHash256 = certificateCapture.Hash256; + accumulator.ValidationErrors = certificateCapture.ValidationErrors; + accumulator.ChainStatus = certificateCapture.ChainStatus; + + // A protocol already determined for this attempt takes precedence over one reported + // alongside the certificate details. + accumulator.Protocol ??= certificateCapture.Protocol; + } + if (error != TdsEnums.SNI_SUCCESS) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs index 59949d28a1..3570adf8aa 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs @@ -563,6 +563,13 @@ internal abstract void CreatePhysicalSNIHandle( internal abstract uint EnableSsl(ref uint info, bool tlsFirst, string serverCertificateFilename); + /// + /// Gets the server certificate details captured by the transport during the most recent + /// call to , or if the transport does not + /// capture them or no certificate validation callback ran. + /// + internal virtual Connection.ServerCertificateCapture GetServerCertificateCapture() => null; + internal abstract uint CheckConnection(); internal abstract PacketHandle GetResetWritePacket(int dataSize); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs index d0a1a9a093..a95746aca9 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs @@ -388,6 +388,8 @@ internal override uint EnableSsl(ref uint info, bool tlsFirst, string serverCert } } + internal override Connection.ServerCertificateCapture? GetServerCertificateCapture() => _sessionHandle?.ServerCertificateCapture; + internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) { GetSessionSNIHandleHandleOrThrow().SetBufferSize((int)unsignedPacketSize); diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs new file mode 100644 index 0000000000..cbfc48a91b --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -0,0 +1,494 @@ +// 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. + +#if NET + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Security; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using Microsoft.Data.SqlClient.Connection; +using Microsoft.Data.SqlClient.ManagedSni; +using Xunit; + +namespace Microsoft.Data.SqlClient.UnitTests.ManagedSni +{ + /// + /// Tests for the certificate details that managed SNI captures from the TLS validation callback: + /// SqlClient's effective validation verdict, the original callback chain status, and the SHA-256 + /// hash of the presented certificate. + /// + public class SniCommonServerCertificateCaptureTest + { + private const string ServerName = "server.contoso.com"; + + public enum ChainKind + { + // No chain supplied to the callback. + None, + // A chain that was evaluated and found clean. + Clean, + // A chain that was evaluated and found untrusted. + Untrusted, + } + + public enum PinKind + { + None, + Match, + Mismatch, + Unreadable, + } + + public static IEnumerable VerdictCases() + { + // policyErrors, chain, pin, hostNameInCertificate, targetServer, nullCert, expectSuccess, expectedErrors, expectChainFromCallback + const SslPolicyErrors None = SslPolicyErrors.None; + const SslPolicyErrors Chain = SslPolicyErrors.RemoteCertificateChainErrors; + const SslPolicyErrors Name = SslPolicyErrors.RemoteCertificateNameMismatch; + const SslPolicyErrors NotAvailable = SslPolicyErrors.RemoteCertificateNotAvailable; + + // No pin: the platform verdict, refined by SqlClient's host name handling, decides trust. + yield return new object?[] { None, ChainKind.Clean, PinKind.None, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, true }; + yield return new object?[] { None, ChainKind.None, PinKind.None, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, true }; + yield return new object?[] { Chain, ChainKind.Untrusted, PinKind.None, null, ServerName, false, false, SqlServerCertificateValidationErrors.ChainError, true }; + yield return new object?[] { Name, ChainKind.Clean, PinKind.None, null, "other.contoso.com", false, false, SqlServerCertificateValidationErrors.HostNameMismatch, true }; + yield return new object?[] { Chain | Name, ChainKind.Untrusted, PinKind.None, null, "other.contoso.com", false, false, SqlServerCertificateValidationErrors.ChainError | SqlServerCertificateValidationErrors.HostNameMismatch, true }; + // HostNameInCertificate resolves the platform's name mismatch: effective verdict has no host name error. + yield return new object?[] { Name, ChainKind.Clean, PinKind.None, ServerName, "other.contoso.com", false, true, SqlServerCertificateValidationErrors.None, true }; + yield return new object?[] { Chain | Name, ChainKind.Untrusted, PinKind.None, ServerName, "other.contoso.com", false, false, SqlServerCertificateValidationErrors.ChainError, true }; + // HostNameInCertificate that also mismatches is still reported. + yield return new object?[] { Name, ChainKind.Clean, PinKind.None, "third.contoso.com", ServerName, false, false, SqlServerCertificateValidationErrors.HostNameMismatch, true }; + // No certificate presented. + yield return new object?[] { NotAvailable, ChainKind.None, PinKind.None, null, ServerName, true, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; + yield return new object?[] { NotAvailable, ChainKind.Clean, PinKind.None, null, ServerName, false, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; + + // Pin: the exact comparison decides trust and the chain is not consulted. + yield return new object?[] { None, ChainKind.Clean, PinKind.Match, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, false }; + yield return new object?[] { Chain, ChainKind.Untrusted, PinKind.Match, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, false }; + yield return new object?[] { None, ChainKind.Clean, PinKind.Mismatch, null, ServerName, false, false, SqlServerCertificateValidationErrors.PinnedCertificateMismatch, false }; + yield return new object?[] { Chain, ChainKind.Untrusted, PinKind.Mismatch, null, ServerName, false, false, SqlServerCertificateValidationErrors.PinnedCertificateMismatch, false }; + yield return new object?[] { NotAvailable, ChainKind.None, PinKind.Match, null, ServerName, true, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; + yield return new object?[] { NotAvailable, ChainKind.Clean, PinKind.Match, null, ServerName, false, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; + yield return new object?[] { None, ChainKind.None, PinKind.Match, null, ServerName, true, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; + } + + [Theory] + [MemberData(nameof(VerdictCases))] + public void ValidateSslServerCertificate_RecordsEffectiveVerdict( + SslPolicyErrors policyErrors, + ChainKind chainKind, + PinKind pinKind, + string? hostNameInCertificate, + string targetServerName, + bool nullCert, + bool expectSuccess, + SqlServerCertificateValidationErrors expectedErrors, + bool expectChainFromCallback) + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + using X509Certificate2 otherCert = CreateSelfSignedCertificate("other.contoso.com"); + using X509Chain? chain = CreateChain(chainKind, serverCert); + using TempCertFile? pinFile = pinKind switch + { + PinKind.Match => new TempCertFile(serverCert), + PinKind.Mismatch => new TempCertFile(otherCert), + _ => null, + }; + string? pinPath = pinFile?.Path; + + Exception? exception = Validate(targetServerName, hostNameInCertificate, nullCert ? null : serverCert, pinPath, policyErrors, chain, out ServerCertificateVerdict verdict); + + if (expectSuccess) + { + Assert.Null(exception); + } + else + { + Assert.IsType(exception); + } + + Assert.Equal(expectedErrors, verdict.ValidationErrors); + + if (expectChainFromCallback) + { + X509ChainStatusFlags? expectedChain = chain is null ? null : SniCommon.CombineChainStatus(chain.ChainStatus, policyErrors); + Assert.Equal(expectedChain, verdict.ChainStatus); + } + else + { + Assert.Null(verdict.ChainStatus); + } + } + + [Fact] + public void ValidateSslServerCertificate_UntrustedChain_ReportsOriginalCallbackFlags() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + using X509Chain chain = CreateChain(ChainKind.Untrusted, serverCert)!; + + X509ChainStatusFlags expected = X509ChainStatusFlags.NoError; + foreach (X509ChainStatus status in chain.ChainStatus) + { + expected |= status.Status; + } + Assert.NotEqual(X509ChainStatusFlags.NoError, expected); + + Validate(ServerName, null, serverCert, null, SslPolicyErrors.RemoteCertificateChainErrors, chain, out ServerCertificateVerdict verdict); + + Assert.Equal(expected, verdict.ChainStatus); + } + + [Fact] + public void ValidateSslServerCertificate_CleanChain_ReportsNoErrorDistinctFromUnavailable() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + using X509Chain chain = CreateChain(ChainKind.Clean, serverCert)!; + + Validate(ServerName, null, serverCert, null, SslPolicyErrors.None, chain, out ServerCertificateVerdict verdict); + + Assert.Equal(SqlServerCertificateValidationErrors.None, verdict.ValidationErrors); + Assert.Equal(X509ChainStatusFlags.NoError, verdict.ChainStatus); + + Validate(ServerName, null, serverCert, null, SslPolicyErrors.None, callbackChain: null, out ServerCertificateVerdict noChain); + Assert.Equal(SqlServerCertificateValidationErrors.None, noChain.ValidationErrors); + Assert.Null(noChain.ChainStatus); + } + + [Fact] + public void ValidateSslServerCertificate_UnreadablePin_VerdictNotEvaluated() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + string missingPath = Path.Combine(Path.GetTempPath(), "SqlClient_MissingPin_" + Guid.NewGuid().ToString("N") + ".cer"); + + Exception? exception = Validate(ServerName, null, serverCert, missingPath, SslPolicyErrors.None, null, out ServerCertificateVerdict verdict); + + Assert.IsType(exception); + Assert.Null(verdict.ValidationErrors); + Assert.Null(verdict.ChainStatus); + } + + /// + /// Capturing the verdict must not change the outcome or the message of validation. + /// + [Theory] + [MemberData(nameof(VerdictCases))] + public void ValidateSslServerCertificate_CaptureDoesNotChangeOutcomeOrMessage( + SslPolicyErrors policyErrors, + ChainKind chainKind, + PinKind pinKind, + string? hostNameInCertificate, + string targetServerName, + bool nullCert, + bool expectSuccess, + SqlServerCertificateValidationErrors expectedErrors, + bool expectChainFromCallback) + { + _ = expectedErrors; + _ = expectChainFromCallback; + + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + using X509Certificate2 otherCert = CreateSelfSignedCertificate("other.contoso.com"); + using X509Chain? chain = CreateChain(chainKind, serverCert); + using TempCertFile? pinFile = pinKind switch + { + PinKind.Match => new TempCertFile(serverCert), + PinKind.Mismatch => new TempCertFile(otherCert), + _ => null, + }; + X509Certificate2? cert = nullCert ? null : serverCert; + + Exception? legacy = null; + try + { + SniCommon.ValidateSslServerCertificate(Guid.NewGuid(), targetServerName, hostNameInCertificate, cert, pinFile?.Path, policyErrors); + } + catch (Exception e) + { + legacy = e; + } + + Exception? capturing = Validate(targetServerName, hostNameInCertificate, cert, pinFile?.Path, policyErrors, chain, out ServerCertificateVerdict verdict); + + Assert.Equal(expectSuccess, legacy is null); + Assert.Equal(legacy?.GetType(), capturing?.GetType()); + Assert.Equal(legacy?.Message, capturing?.Message); + + if (capturing is not null && cert is not null) + { + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(cert, verdict); + AssertNoLeak(capture.Hash256!, capturing.Message); + AssertNoLeak(capture.Hash256!, capturing.ToString()); + } + } + + [Fact] + public void CreateServerCertificateCapture_HashIsSha256OfDer() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, new ServerCertificateVerdict(SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError)); + + Assert.NotNull(capture.Hash256); + Assert.Equal(32, capture.Hash256!.Length); + + using SHA256 sha256 = SHA256.Create(); + Assert.Equal(sha256.ComputeHash(serverCert.Export(X509ContentType.Cert)), capture.Hash256); + Assert.Equal(SqlServerCertificateValidationErrors.None, capture.ValidationErrors); + Assert.Equal(X509ChainStatusFlags.NoError, capture.ChainStatus); + } + + [Fact] + public void CreateServerCertificateCapture_Bypass_HashOnly() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + + // TrustServerCertificate bypass: validation is never run, so the verdict stays default. + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, default); + + Assert.Equal(SHA256.HashData(serverCert.RawData), capture.Hash256); + Assert.Null(capture.ValidationErrors); + Assert.Null(capture.ChainStatus); + Assert.Null(capture.Protocol); + } + + [Fact] + public void CreateServerCertificateCapture_SenderNotSslStream_ProtocolUnavailable() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, default, new object()); + + Assert.Null(capture.Protocol); + } + + [Fact] + public void CreateServerCertificateCapture_NoCertificate_HashUnavailable() + { + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture( + null!, + new ServerCertificateVerdict(SqlServerCertificateValidationErrors.ServerCertificateMissing, null)); + + Assert.Null(capture.Hash256); + Assert.Equal(SqlServerCertificateValidationErrors.ServerCertificateMissing, capture.ValidationErrors); + Assert.Null(capture.ChainStatus); + } + + public static IEnumerable AllChainStatusFlags() + { + foreach (X509ChainStatusFlags flag in Enum.GetValues()) + { + if (flag != X509ChainStatusFlags.NoError) + { + yield return new object[] { flag }; + } + } + } + + [Theory] + [MemberData(nameof(AllChainStatusFlags))] + public void CombineChainStatus_PreservesEachFlag(X509ChainStatusFlags flag) + { + X509ChainStatus[] statuses = { new() { Status = flag } }; + + Assert.Equal(flag, SniCommon.CombineChainStatus(statuses, SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [Fact] + public void CombineChainStatus_PreservesFullFlagSet() + { + List statuses = new(); + X509ChainStatusFlags all = X509ChainStatusFlags.NoError; + foreach (X509ChainStatusFlags flag in Enum.GetValues()) + { + statuses.Add(new X509ChainStatus { Status = flag }); + all |= flag; + } + + Assert.Equal(all, SniCommon.CombineChainStatus(statuses.ToArray(), SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [Fact] + public void CombineChainStatus_NoEntries_NoErrorUnlessChainErrorsReported() + { + Assert.Equal(X509ChainStatusFlags.NoError, SniCommon.CombineChainStatus(Array.Empty(), SslPolicyErrors.None)); + Assert.Equal(X509ChainStatusFlags.NoError, SniCommon.CombineChainStatus(Array.Empty(), SslPolicyErrors.RemoteCertificateNameMismatch)); + Assert.Null(SniCommon.CombineChainStatus(Array.Empty(), SslPolicyErrors.RemoteCertificateChainErrors)); + } + + [Fact] + public void GetChainStatus_NullChain_Unavailable() + { + Assert.Null(SniCommon.GetChainStatus(null!, SslPolicyErrors.RemoteCertificateChainErrors)); + Assert.Null(SniCommon.GetChainStatus(null!, SslPolicyErrors.None)); + } + + /// + /// Capture reports the chain exactly as supplied to the callback; it does not build or + /// re-evaluate it. A chain that was never built carries no status, so the chain errors reported + /// by the platform cannot be described and the status is unavailable. + /// + [Fact] + public void GetChainStatus_DoesNotBuildChain() + { + using X509Chain unbuilt = new(); + + Assert.Null(SniCommon.GetChainStatus(unbuilt, SslPolicyErrors.RemoteCertificateChainErrors)); + Assert.Empty(unbuilt.ChainElements); + } + + #region EncryptionInfoCapture + + [Fact] + public void EncryptionInfoCapture_RecordServerCertificate_PublishesInSnapshot() + { + byte[] hash = SHA256.HashData(new byte[] { 1, 2, 3 }); + EncryptionInfoCapture capture = new(); + + capture.RecordServerCertificate(new ServerCertificateCapture(hash, SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + + Assert.True(capture.HasValues); + SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); + Assert.False(snapshot.IsEmpty); + Assert.Null(snapshot.NegotiatedEncryptionMode); + Assert.Null(snapshot.NegotiatedEncryptionProtocol); + Assert.Equal(hash, snapshot.PresentedServerCertificateHash256!.Value.ToArray()); + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, snapshot.ValidationErrors); + Assert.Equal(X509ChainStatusFlags.UntrustedRoot, snapshot.ChainStatus); + + capture.Reset(); + Assert.False(capture.HasValues); + Assert.Same(SqlConnectionEncryptionInfo.Empty, capture.ToSnapshot()); + } + + [Fact] + public void EncryptionInfoCapture_ZeroValuesAreAvailable() + { + EncryptionInfoCapture capture = new(); + capture.RecordServerCertificate(new ServerCertificateCapture(null, SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError)); + + Assert.True(capture.HasValues); + SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); + Assert.Equal(SqlServerCertificateValidationErrors.None, snapshot.ValidationErrors); + Assert.Equal(X509ChainStatusFlags.NoError, snapshot.ChainStatus); + Assert.Null(snapshot.PresentedServerCertificateHash256); + } + + [Fact] + public void EncryptionInfoCapture_NullCapture_LeavesCertificateFieldsUnavailable() + { + EncryptionInfoCapture capture = new(); + capture.RecordServerCertificate(null); + + Assert.False(capture.HasValues); + Assert.Same(SqlConnectionEncryptionInfo.Empty, capture.ToSnapshot()); + } + + [Fact] + public void EncryptionInfoCapture_HashNotInSnapshotText() + { + byte[] hash = SHA256.HashData(new byte[] { 4, 5, 6 }); + EncryptionInfoCapture capture = new(); + capture.RecordServerCertificate(new ServerCertificateCapture(hash, SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + + AssertNoLeak(hash, capture.ToSnapshot().ToString() ?? string.Empty); + } + + #endregion + + #region Helpers + + private static Exception? Validate( + string targetServerName, + string? hostNameInCertificate, + X509Certificate? serverCert, + string? pinPath, + SslPolicyErrors policyErrors, + X509Chain? callbackChain, + out ServerCertificateVerdict verdict) + { + verdict = default; + try + { + SniCommon.ValidateSslServerCertificate(Guid.NewGuid(), targetServerName, hostNameInCertificate, serverCert, pinPath, policyErrors, callbackChain, ref verdict); + return null; + } + catch (Exception e) + { + return e; + } + } + + private static X509Chain? CreateChain(ChainKind kind, X509Certificate2 certificate) + { + if (kind == ChainKind.None) + { + return null; + } + + X509Chain chain = new(); + chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; + if (kind == ChainKind.Clean) + { + chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; + chain.ChainPolicy.CustomTrustStore.Add(certificate); + } + + bool valid = chain.Build(certificate); + Assert.Equal(kind == ChainKind.Clean, valid); + return chain; + } + + private static void AssertNoLeak(byte[] hash, string text) + { + Assert.DoesNotContain(Convert.ToHexString(hash), text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(Convert.ToBase64String(hash), text, StringComparison.Ordinal); + Assert.DoesNotContain(BitConverter.ToString(hash), text, StringComparison.OrdinalIgnoreCase); + } + + private static X509Certificate2 CreateSelfSignedCertificate(string subjectCommonName) + { + using RSA rsa = RSA.Create(2048); + CertificateRequest request = new($"CN={subjectCommonName}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + SubjectAlternativeNameBuilder san = new(); + san.AddDnsName(subjectCommonName); + request.CertificateExtensions.Add(san.Build()); + + DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddMinutes(-5); + return request.CreateSelfSigned(notBefore, notBefore.AddHours(1)); + } + + private sealed class TempCertFile : IDisposable + { + public TempCertFile(X509Certificate2 cert) + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SqlClient_CapturePin_" + Guid.NewGuid().ToString("N") + ".cer"); + File.WriteAllBytes(Path, cert.Export(X509ContentType.Cert)); + } + + public string Path { get; } + + public void Dispose() + { + try + { + File.Delete(Path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + } + + #endregion + } +} + +#endif diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs index cec3aad55b..6abea4135a 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs @@ -94,7 +94,7 @@ public void Open_Success_PublishesNegotiatedModeAndProtocol(ServerEncryption ser // Assert Assert.Equal(ConnectionState.Open, connection.State); AssertNegotiated(connection.EncryptionInfo, serverEncryption); - AssertCertificateFieldsNull(connection.EncryptionInfo); + AssertBypassedCertificateFields(connection.EncryptionInfo, serverEncryption); } /// @@ -118,7 +118,7 @@ public async Task OpenAsync_Success_PublishesNegotiatedModeAndProtocol(ServerEnc // Assert Assert.Equal(ConnectionState.Open, connection.State); AssertNegotiated(connection.EncryptionInfo, serverEncryption); - AssertCertificateFieldsNull(connection.EncryptionInfo); + AssertBypassedCertificateFields(connection.EncryptionInfo, serverEncryption); } /// @@ -137,7 +137,7 @@ public void Open_EncryptMandatoryServerOff_PublishesFull() // Assert AssertNegotiated(connection.EncryptionInfo, ServerEncryption.Required); - AssertCertificateFieldsNull(connection.EncryptionInfo); + AssertBypassedCertificateFields(connection.EncryptionInfo, ServerEncryption.Required); } /// @@ -156,7 +156,7 @@ public async Task OpenAsync_EncryptMandatoryServerOff_PublishesFull() // Assert AssertNegotiated(connection.EncryptionInfo, ServerEncryption.Required); - AssertCertificateFieldsNull(connection.EncryptionInfo); + AssertBypassedCertificateFields(connection.EncryptionInfo, ServerEncryption.Required); } /// @@ -457,7 +457,7 @@ public async Task OpenAsync_ServerRejectsEncryptionInPreLogin_ExceptionEncryptio /// /// A synchronous open that fails certificate validation inside the TLS handshake reports - /// the mode selected by pre-login, but no protocol. + /// the mode selected by pre-login. Managed SNI also reports the protocol it observed. /// [Theory] [InlineData(ServerEncryption.Off)] @@ -480,7 +480,7 @@ public void Open_UntrustedServerCertificate_ExceptionReportsModeWithoutProtocol( /// /// An asynchronous open that fails certificate validation inside the TLS handshake reports - /// the mode selected by pre-login, but no protocol. + /// the mode selected by pre-login. Managed SNI also reports the protocol it observed. /// [Theory] [InlineData(ServerEncryption.Off)] @@ -1058,14 +1058,14 @@ private static void AssertNegotiated(SqlConnectionEncryptionInfo info, ServerEnc /// Asserts that a login rejected after pre-login carries the negotiated values on the /// exception only, and not in its message. /// - private static void AssertLoginFailureCarriesNegotiatedValues( + private void AssertLoginFailureCarriesNegotiatedValues( SqlException ex, SqlConnection connection, ServerEncryption serverEncryption) { Assert.Equal(18456, ex.Number); AssertNegotiated(ex.EncryptionInfo, serverEncryption); - AssertCertificateFieldsNull(ex.EncryptionInfo); + AssertBypassedCertificateFields(ex.EncryptionInfo, serverEncryption); AssertEmpty(connection.EncryptionInfo); Assert.DoesNotContain("Tls12", ex.Message); Assert.DoesNotContain("LoginOnly", ex.Message); @@ -1075,28 +1075,65 @@ private static void AssertLoginFailureCarriesNegotiatedValues( /// Asserts the values reported for a certificate-validation failure. The fixture certificate is /// self-signed and untrusted, and the server allows only TLS 1.2. The pre-login response /// selected full encryption, so the mode is reported even though the TLS handshake failed. - /// Both the managed and native SNI implementations reject the certificate inside the TLS - /// handshake, before a protocol is reported, so no protocol or cipher suite is reported. - /// Certificate fields are owned by later slices and are not asserted here. + /// Native SNI rejects the certificate inside the TLS handshake before reporting a protocol, + /// so no protocol or cipher suite is reported. Managed SNI records the protocol and cipher + /// suite SslStream agreed before raising the validation callback. Certificate fields are + /// asserted by ManagedSniCertificateCaptureTests. /// private static void AssertUntrustedCertificateFailure(SqlException ex, SqlConnection connection, TdsServer server) { Assert.True(server.PreLoginCount >= 1); Assert.Equal(SqlConnectionEncryptionMode.Full, ex.EncryptionInfo.NegotiatedEncryptionMode); - Assert.Null(ex.EncryptionInfo.NegotiatedEncryptionProtocol); - Assert.Null(ex.EncryptionInfo.NegotiatedCipherSuiteId); + if (LocalAppContextSwitches.UseManagedNetworking) + { + Assert.Equal(SslProtocols.Tls12, ex.EncryptionInfo.NegotiatedEncryptionProtocol); + Assert.NotNull(ex.EncryptionInfo.NegotiatedCipherSuiteId); + Assert.InRange(ex.EncryptionInfo.NegotiatedCipherSuiteId!.Value, 1, 0xFFFF); + } + else + { + Assert.Null(ex.EncryptionInfo.NegotiatedEncryptionProtocol); + Assert.Null(ex.EncryptionInfo.NegotiatedCipherSuiteId); + } + AssertEmpty(connection.EncryptionInfo); } /// - /// Asserts that no certificate field is populated. + /// Asserts the certificate fields for tests that use TrustServerCertificate=true. + /// SqlClient never evaluates the certificate, so the verdict and chain status are always + /// unavailable. Managed SNI still records the presented certificate and cipher suite whenever + /// a TLS handshake took place; native SNI does not capture certificate details. /// - private static void AssertCertificateFieldsNull(SqlConnectionEncryptionInfo info) + private void AssertBypassedCertificateFields(SqlConnectionEncryptionInfo info, ServerEncryption serverEncryption) { - Assert.Null(info.PresentedServerCertificateRawData); - Assert.Null(info.GetServerCertificate()); + if (serverEncryption != ServerEncryption.NotSupported && LocalAppContextSwitches.UseManagedNetworking) + { + Assert.NotNull(info.PresentedServerCertificateRawData); + Assert.Equal(_certificate.RawData, info.PresentedServerCertificateRawData.Value.ToArray()); + using X509Certificate2? presented = info.GetServerCertificate(); + Assert.NotNull(presented); + Assert.Equal(_certificate.RawData, presented.RawData); + } + else + { + Assert.Null(info.PresentedServerCertificateRawData); + Assert.Null(info.GetServerCertificate()); + } + Assert.Null(info.ValidationErrors); Assert.Null(info.ChainStatus); + + if (serverEncryption == ServerEncryption.NotSupported) + { + // No TLS handshake took place, so no cipher suite was negotiated. + Assert.Null(info.NegotiatedCipherSuiteId); + } + else if (LocalAppContextSwitches.UseManagedNetworking) + { + Assert.NotNull(info.NegotiatedCipherSuiteId); + Assert.InRange(info.NegotiatedCipherSuiteId!.Value, 1, 0xFFFF); + } } /// diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs new file mode 100644 index 0000000000..8d3658d02c --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -0,0 +1,318 @@ +// 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. + +#if NET + +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Security.Authentication; +using System.Security.Cryptography; +using System.Security.Cryptography.X509Certificates; +using System.Threading.Tasks; +using Microsoft.Data.SqlClient.Tests.Common; +using Microsoft.Data.SqlClient.Tests.Common.Fixtures; +using Microsoft.SqlServer.TDS.PreLogin; +using Microsoft.SqlServer.TDS.Servers; +using Xunit; + +namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests +{ + /// + /// Provides untrusted self-signed server certificates for the managed SNI certificate capture tests. + /// + public sealed class ManagedSniCaptureCertificateFixture : CertificateFixtureBase + { + public ManagedSniCaptureCertificateFixture() + { + Localhost = CreateCertificate("localhost", new[] { "localhost" }, new[] { "127.0.0.1" }); + OtherHost = CreateCertificate("other.contoso.com", Array.Empty(), Array.Empty()); + } + + /// A certificate whose names match the "localhost" data source. + public X509Certificate2 Localhost { get; } + + /// A certificate whose names do not match the "localhost" data source. + public X509Certificate2 OtherHost { get; } + } + + /// + /// End-to-end verification, against the simulated TDS server over TLS, that managed SNI publishes the + /// presented server certificate hash, SqlClient's effective validation verdict, and the callback chain + /// status to and . + /// Managed SNI is forced on Windows via the UseManagedNetworkingOnWindows switch. + /// + [Collection(SimulatedServerTestCollection.Name)] + public class ManagedSniCertificateCaptureTests : IClassFixture + { + private readonly ManagedSniCaptureCertificateFixture _fixture; + + public ManagedSniCertificateCaptureTests(ManagedSniCaptureCertificateFixture fixture) + { + _fixture = fixture; + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_TrustServerCertificate_PublishesHashWithoutVerdict(bool async) + { + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); + await OpenAsync(connection, async); + + SqlConnectionEncryptionInfo info = connection.EncryptionInfo; + Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); + Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); + AssertHash(_fixture.Localhost, info); + // The certificate was presented but SqlClient did not evaluate it. + Assert.Null(info.ValidationErrors); + Assert.Null(info.ChainStatus); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_MatchingServerCertificate_PublishesHashAndNoErrors(bool async) + { + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + using TempCertFile pin = new(_fixture.Localhost); + + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + await OpenAsync(connection, async); + + SqlConnectionEncryptionInfo info = connection.EncryptionInfo; + Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); + Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); + AssertHash(_fixture.Localhost, info); + Assert.Equal(SqlServerCertificateValidationErrors.None, info.ValidationErrors); + // The chain is not consulted when a ServerCertificate pin decides trust. + Assert.Null(info.ChainStatus); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndHash(bool async) + { + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); + SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); + + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + AssertHash(_fixture.Localhost, info); + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, info.ValidationErrors); + Assert.NotNull(info.ChainStatus); + Assert.NotEqual(X509ChainStatusFlags.NoError, info.ChainStatus); + // Certificate validation failed after the protocol was agreed; the observed values are kept. + AssertObservedNegotiation(info); + Assert.True(connection.EncryptionInfo.IsEmpty); + AssertNoLeak(ex, info); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_HostNameMismatch_ExceptionCarriesHostNameMismatch(bool async) + { + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.OtherHost); + + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); + SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); + + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + AssertHash(_fixture.OtherHost, info); + Assert.Equal( + SqlServerCertificateValidationErrors.ChainError | SqlServerCertificateValidationErrors.HostNameMismatch, + info.ValidationErrors); + Assert.NotNull(info.ChainStatus); + AssertObservedNegotiation(info); + AssertNoLeak(ex, info); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_HostNameInCertificateOverride_ReportsEffectiveVerdict(bool async) + { + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.OtherHost); + + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, hostNameInCertificate: "other.contoso.com")); + SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); + + // The platform reported a name mismatch, but HostNameInCertificate resolves it; only the + // untrusted chain remains in SqlClient's effective verdict. + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, ex.EncryptionInfo.ValidationErrors); + AssertHash(_fixture.OtherHost, ex.EncryptionInfo); + AssertObservedNegotiation(ex.EncryptionInfo); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch(bool async) + { + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + using TempCertFile pin = new(_fixture.OtherHost); + + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); + + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + AssertHash(_fixture.Localhost, info); + Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, info.ValidationErrors); + Assert.Null(info.ChainStatus); + AssertObservedNegotiation(info); + AssertNoLeak(ex, info); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_FailureThenSuccess_DoesNotCarryPreviousAttemptCertificate(bool async) + { + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer otherServer = StartServer(_fixture.OtherHost); + using TdsServer server = StartServer(_fixture.Localhost); + using TempCertFile pin = new(_fixture.Localhost); + + using SqlConnection failing = new(BuildConnectionString(otherServer.EndPoint.Port, serverCertificate: pin.Path)); + SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(failing, async)); + AssertHash(_fixture.OtherHost, ex.EncryptionInfo); + + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + await OpenAsync(connection, async); + AssertHash(_fixture.Localhost, connection.EncryptionInfo); + Assert.Equal(SqlServerCertificateValidationErrors.None, connection.EncryptionInfo.ValidationErrors); + } + + #region Helpers + + /// + /// Managed SNI records the protocol agreed for the handshake inside the validation callback, so a + /// certificate-validation failure still reports that protocol and the mode being negotiated. + /// + private static void AssertObservedNegotiation(SqlConnectionEncryptionInfo info) + { + Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); + Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); + } + + private static LocalAppContextSwitchesHelper? ForceManagedSni() + { + if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + // Managed SNI is the only implementation off Windows. + return null; + } + + LocalAppContextSwitchesHelper switches = new(); + switches.UseManagedNetworking = true; + return switches; + } + + private static TdsServer StartServer(X509Certificate2 certificate) + { + TdsServer server = new(new TdsServerArguments + { + Encryption = TDSPreLoginTokenEncryptionType.Required, + EncryptionCertificate = certificate, + EncryptionProtocols = SslProtocols.Tls12, + }); + server.Start(); + return server; + } + + private static string BuildConnectionString( + int port, + bool trustServerCertificate = false, + string? serverCertificate = null, + string? hostNameInCertificate = null) + { + SqlConnectionStringBuilder builder = new() + { + DataSource = "localhost," + port, + Encrypt = SqlConnectionEncryptOption.Mandatory, + TrustServerCertificate = trustServerCertificate, + Pooling = false, + ConnectTimeout = 15, + ConnectRetryCount = 0, + }; + if (serverCertificate is not null) + { + builder.ServerCertificate = serverCertificate; + } + if (hostNameInCertificate is not null) + { + builder.HostNameInCertificate = hostNameInCertificate; + } + return builder.ConnectionString; + } + + private static Task OpenAsync(SqlConnection connection, bool async) + { + if (async) + { + return connection.OpenAsync(); + } + + connection.Open(); + return Task.CompletedTask; + } + + private static void AssertHash(X509Certificate2 expected, SqlConnectionEncryptionInfo info) + { + Assert.NotNull(info.PresentedServerCertificateHash256); + Assert.Equal(SHA256.HashData(expected.RawData), info.PresentedServerCertificateHash256.Value.ToArray()); + } + + private static void AssertNoLeak(SqlException ex, SqlConnectionEncryptionInfo info) + { + byte[] hash = info.PresentedServerCertificateHash256!.Value.ToArray(); + string[] encodings = { Convert.ToHexString(hash), Convert.ToBase64String(hash), BitConverter.ToString(hash) }; + foreach (string encoding in encodings) + { + Assert.DoesNotContain(encoding, ex.Message, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(encoding, ex.ToString(), StringComparison.OrdinalIgnoreCase); + } + } + + private sealed class TempCertFile : IDisposable + { + public TempCertFile(X509Certificate2 certificate) + { + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SqlClient_CapturePin_" + Guid.NewGuid().ToString("N") + ".cer"); + File.WriteAllBytes(Path, certificate.Export(X509ContentType.Cert)); + } + + public string Path { get; } + + public void Dispose() + { + try + { + File.Delete(Path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + } + + #endregion + } +} + +#endif From 30d3e4614703c473fed024c8b041c8f91b6463b2 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Mon, 19 Oct 2026 15:03:18 +0530 Subject: [PATCH 02/12] Keep Managed SNI certificate verdict when the host name check throws Named pipes validate against the target '.', which X509Certificate2.MatchesHostname rejects with ArgumentException before the final verdict is recorded. Record the errors already established (e.g. ChainError and callback chain status) before the host name check so the capture survives. The exception is not caught or changed. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../2353-connection-encryption-info.md | 7 +++ .../SqlClient/ManagedSni/SniCommon.netcore.cs | 14 +++++- .../SniCommonServerCertificateCaptureTest.cs | 46 +++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index a5f4e26fb6..f3393a7e7c 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -327,6 +327,13 @@ TLS protocol agreed for the handshake (see **Failure path** above). | `ServerCertificateValidationErrors` | Effective SqlClient verdict: `ServerCertificateMissing`, `ChainError`, `HostNameMismatch` (after `HostNameInCertificate`), `PinnedCertificateMismatch` (`ServerCertificate`); `None` when validation passed | Validation was bypassed, or the configured `ServerCertificate` file could not be read. | | `ServerCertificateChainStatus` | Bitwise OR of the original callback chain's `ChainStatus` flags (no chain rebuild); `NoError` when the chain was evaluated cleanly | Validation was bypassed, `ServerCertificate` pinning is used (the chain isn't consulted), no certificate was presented, or the platform reported a chain error without flags. | +The host name check can throw before the final verdict is recorded. For example, Managed SNI +named pipes validate against the target `.`, which `X509Certificate2.MatchesHostname` rejects +with an `ArgumentException`. Errors established before that check, such as `ChainError` and the +callback chain status, are recorded first so they survive the exception. The exception itself is +unchanged. When no error was established before the check, the fields stay `null` rather than +reporting `None`. + Native SNI does not yet report certificate details; those fields remain `null` there. ## 5. Scope diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs index 5fca6313cb..6d8c1622f9 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs @@ -90,7 +90,10 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ /// is written immediately before this method returns or throws its validation exception, so /// it is observable by the caller in both cases. If validation is aborted for any other /// reason (for example the ServerCertificate file cannot be loaded), the validation - /// errors are left unavailable because no comparison was completed. + /// errors are left unavailable because no comparison was completed. If the host name check + /// throws (for example for the "." named-pipe target), the errors already established before + /// it (such as ) and the chain + /// status remain recorded; the exception itself is not caught or changed. /// /// is the bitwise OR of the status flags of /// the original supplied to the TLS validation callback. It is only @@ -206,6 +209,15 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ (hasHostNameInCertificate || policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))) { + // The host name check can throw before the final verdict is recorded (for + // example MatchesHostname rejects the "." target used by named pipes). Record + // the errors already established so they survive that exception. A provisional + // None is not recorded because it would report a validation that never passed. + if (validationErrors != SqlServerCertificateValidationErrors.None) + { + verdict = new ServerCertificateVerdict(validationErrors, callbackChainStatus); + } + X509Certificate2 cert2 = serverCert as X509Certificate2; if (!cert2.MatchesHostname(serverNameToValidate)) { diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs index cbfc48a91b..c6d5b94d8f 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -172,6 +172,52 @@ public void ValidateSslServerCertificate_UnreadablePin_VerdictNotEvaluated() Assert.Null(verdict.ChainStatus); } + /// + /// Managed SNI named pipes pass "." as the target server name. MatchesHostname rejects it with + /// an , which predates encryption info capture. Errors already + /// established must still be captured, and the exception must stay exactly as it was. + /// + [Theory] + [InlineData(SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch, true)] + [InlineData(SslPolicyErrors.RemoteCertificateNameMismatch, false)] + public void ValidateSslServerCertificate_NamedPipeDotTarget_CapturesKnownErrorsAndKeepsException(SslPolicyErrors policyErrors, bool chainErrors) + { + const string NamedPipeTarget = "."; + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + using X509Chain chain = CreateChain(chainErrors ? ChainKind.Untrusted : ChainKind.Clean, serverCert)!; + + Exception? legacy = null; + try + { + SniCommon.ValidateSslServerCertificate(Guid.NewGuid(), NamedPipeTarget, null, serverCert, null, policyErrors); + } + catch (Exception e) + { + legacy = e; + } + + Exception? capturing = Validate(NamedPipeTarget, null, serverCert, null, policyErrors, chain, out ServerCertificateVerdict verdict); + + // The pre-existing exception is neither caught nor changed. + Assert.IsAssignableFrom(legacy); + Assert.Equal(legacy!.GetType(), capturing?.GetType()); + Assert.Equal(legacy.Message, capturing!.Message); + + if (chainErrors) + { + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, verdict.ValidationErrors); + Assert.Equal(SniCommon.CombineChainStatus(chain.ChainStatus, policyErrors), verdict.ChainStatus); + Assert.NotNull(verdict.ChainStatus); + Assert.NotEqual(X509ChainStatusFlags.NoError, verdict.ChainStatus); + } + else + { + // Nothing was established before the throw; a passing None must not be reported. + Assert.Null(verdict.ValidationErrors); + Assert.Null(verdict.ChainStatus); + } + } + /// /// Capturing the verdict must not change the outcome or the message of validation. /// From 6887dc3c76ecc121685cbe0317c5de82470185f4 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Thu, 22 Oct 2026 14:00:49 +0530 Subject: [PATCH 03/12] Managed SNI: capture negotiated cipher suite Record (int)SslStream.NegotiatedCipherSuite after the handshake (authoritative) and inside the certificate validation callback (adopt-if-none), so failed certificate validation keeps the observed suite. TCP and named-pipe handles; MARS passes through. Reads are exception-safe; 0 is treated as unavailable. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../2353-connection-encryption-info.md | 17 +++++++++ .../Connection/ServerCertificateCapture.cs | 12 +++++- .../SqlClient/ManagedSni/SniCommon.netcore.cs | 37 ++++++++++++++++++- .../SqlClient/ManagedSni/SniHandle.netcore.cs | 6 +++ .../ManagedSni/SniMarsConnection.netcore.cs | 2 + .../ManagedSni/SniMarsHandle.netcore.cs | 2 + .../ManagedSni/SniNpHandle.netcore.cs | 2 + .../ManagedSni/SniTcpHandle.netcore.cs | 2 + .../Data/SqlClient/Parser/TdsParser.cs | 24 +++++++++++- .../SqlClient/Parser/TdsParserStateObject.cs | 6 +++ .../TdsParserStateObjectManaged.netcore.cs | 2 + .../SniCommonServerCertificateCaptureTest.cs | 24 ++++++++++++ .../ManagedSniCertificateCaptureTests.cs | 32 +++++++++++++++- 13 files changed, 162 insertions(+), 6 deletions(-) diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index f3393a7e7c..55c6b08b26 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -336,6 +336,23 @@ reporting `None`. Native SNI does not yet report certificate details; those fields remain `null` there. +**Cipher suite (Managed SNI).** Managed SNI reads `(int)SslStream.NegotiatedCipherSuite` at the +same two points as the protocol, on both the TCP and named-pipe handles (MARS passes through to +the physical handle): + +- **After the handshake completes,** `TdsParser.EnableSsl` records the value from the session + handle into the accumulator's `CipherSuite` property. This read is authoritative for a successful attempt. +- **Inside the validation callback,** the value is stored with the certificate capture. + `SslStream` processes the ServerHello, which selects the suite, before it raises the callback, + so the value is real there. The tests confirm it matches the suite a trusted handshake with the + same server negotiates. It is adopted only when no suite was recorded for the attempt, so a + certificate-validation failure still reports the observed suite. + +Both reads are wrapped in `try`/`catch` so that capture never affects the handshake. A suite of +`0` (`TLS_NULL_WITH_NULL_NULL`, nothing agreed yet) is treated as unavailable. Without TLS, the +property is `null`. Managed SNI runs only on `net10.0`; on `net462` this capture is not compiled +and the property stays `null` until native SNI support (Slice D). + ## 5. Scope The API reports negotiated encryption, TLS protocol, the server-selected cipher suite, the diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs index 119fd3b4de..104f781934 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs @@ -25,12 +25,14 @@ internal ServerCertificateCapture( byte[]? hash256, SqlServerCertificateValidationErrors? validationErrors, X509ChainStatusFlags? chainStatus, - SslProtocols? protocol = null) + SslProtocols? protocol = null, + int? cipherSuite = null) { Hash256 = hash256; ValidationErrors = validationErrors; ChainStatus = chainStatus; Protocol = protocol; + CipherSuite = cipherSuite; } /// @@ -57,5 +59,13 @@ internal ServerCertificateCapture( /// determined for the attempt (for example, when the handshake failed). /// public SslProtocols? Protocol { get; } + + /// + /// Gets the IANA identifier of the cipher suite the transport reported for this handshake, + /// or if the transport did not report one. Used only when the cipher + /// suite was not otherwise determined for the attempt (for example, when the handshake + /// failed). + /// + public int? CipherSuite { get; } } } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs index 6d8c1622f9..d5b88dce88 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs @@ -302,7 +302,42 @@ internal static ServerCertificateCapture CreateServerCertificateCapture(X509Cert } } - return new ServerCertificateCapture(hash, verdict.ValidationErrors, verdict.ChainStatus, GetHandshakeProtocol(sender)); + return new ServerCertificateCapture( + hash, + verdict.ValidationErrors, + verdict.ChainStatus, + GetHandshakeProtocol(sender), + GetNegotiatedCipherSuite(sender as SslStream)); + } + + /// + /// Reads the IANA identifier of the cipher suite agreed for the handshake on + /// . Like the protocol version, the cipher suite is agreed + /// before SslStream raises the certificate validation callback, so this can be read from + /// within the callback as well as after the handshake completes. + /// + /// + /// The cipher suite, or when it is not available. The null cipher + /// suite (TLS_NULL_WITH_NULL_NULL, 0) means none has been agreed and is reported as + /// . + /// + internal static int? GetNegotiatedCipherSuite(SslStream sslStream) + { + if (sslStream is null) + { + return null; + } + + try + { + int cipherSuite = (int)sslStream.NegotiatedCipherSuite; + return cipherSuite == 0 ? null : cipherSuite; + } + catch (Exception) + { + // Capture must never affect the handshake outcome. + return null; + } } /// diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs index 9b99491d10..c2f4c37d95 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs @@ -125,6 +125,12 @@ protected static void AuthenticateAsClient(SslStream sslStream, string serverNam /// public virtual SslProtocols ProtocolVersion { get; } = 0; + /// + /// Gets the IANA identifier of the TLS cipher suite negotiated for this connection, or + /// if none is available. + /// + public virtual int? NegotiatedCipherSuite => null; + /// /// Gets the server certificate details captured during the most recent TLS handshake on /// this handle, or if the certificate validation callback has not diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs index e331bf87af..9fb3740b9c 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs @@ -37,6 +37,8 @@ internal class SniMarsConnection public SslProtocols ProtocolVersion => _lowerHandle.ProtocolVersion; + public int? NegotiatedCipherSuite => _lowerHandle.NegotiatedCipherSuite; + public Connection.ServerCertificateCapture ServerCertificateCapture => _lowerHandle.ServerCertificateCapture; internal object DemuxerSync => _sync; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs index e2431b7968..4c3a92ad73 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs @@ -54,6 +54,8 @@ internal sealed class SniMarsHandle : SniHandle public override SslProtocols ProtocolVersion => _connection.ProtocolVersion; + public override int? NegotiatedCipherSuite => _connection.NegotiatedCipherSuite; + public override Connection.ServerCertificateCapture ServerCertificateCapture => _connection.ServerCertificateCapture; /// diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs index f5246e4076..93cf5c2c5f 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs @@ -142,6 +142,8 @@ public override SslProtocols ProtocolVersion } } + public override int? NegotiatedCipherSuite => SniCommon.GetNegotiatedCipherSuite(_sslStream); + public override uint CheckConnection() { using (SqlClientSNIEventScope.Create(nameof(SniNpHandle))) diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs index b2babc6f3b..2cb75a7207 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs @@ -117,6 +117,8 @@ public override SslProtocols ProtocolVersion } } + public override int? NegotiatedCipherSuite => SniCommon.GetNegotiatedCipherSuite(_sslStream); + /// /// Constructor /// 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 d43f41feb1..437028085e 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 @@ -966,9 +966,18 @@ private void EnableSsl(uint info, SqlConnectionEncryptOption encrypt, bool integ accumulator.ValidationErrors = certificateCapture.ValidationErrors; accumulator.ChainStatus = certificateCapture.ChainStatus; - // A protocol already determined for this attempt takes precedence over one reported - // alongside the certificate details. + // A protocol or cipher suite already determined for this attempt takes precedence over + // one reported alongside the certificate details. accumulator.Protocol ??= certificateCapture.Protocol; + + if (accumulator.CipherSuite is null && certificateCapture.CipherSuite is int capturedCipherSuite) + { +#if NET + accumulator.CipherSuite = (System.Net.Security.TlsCipherSuite)capturedCipherSuite; +#else + accumulator.CipherSuite = capturedCipherSuite; +#endif + } } if (error != TdsEnums.SNI_SUCCESS) @@ -1012,6 +1021,17 @@ private void EnableSsl(uint info, SqlConnectionEncryptOption encrypt, bool integ RecordNegotiatedProtocol(protocol); + // The cipher suite read after the handshake completes is authoritative for the attempt. + if (_physicalStateObj.GetNegotiatedCipherSuite() is int cipherSuite && + _connHandler?.EncryptionInfoAccumulator is EncryptionInfoAccumulator negotiated) + { +#if NET + negotiated.CipherSuite = (System.Net.Security.TlsCipherSuite)cipherSuite; +#else + negotiated.CipherSuite = cipherSuite; +#endif + } + // create a new packet encryption changes the internal packet size Bug# 228403 _physicalStateObj.ClearAllWritePackets(); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs index 3570adf8aa..b994a1751c 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObject.cs @@ -570,6 +570,12 @@ internal abstract void CreatePhysicalSNIHandle( /// internal virtual Connection.ServerCertificateCapture GetServerCertificateCapture() => null; + /// + /// Gets the IANA identifier of the TLS cipher suite negotiated on this session, or + /// if the transport does not report one. + /// + internal virtual int? GetNegotiatedCipherSuite() => null; + internal abstract uint CheckConnection(); internal abstract PacketHandle GetResetWritePacket(int dataSize); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs index a95746aca9..24f8e52720 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Parser/TdsParserStateObjectManaged.netcore.cs @@ -390,6 +390,8 @@ internal override uint EnableSsl(ref uint info, bool tlsFirst, string serverCert internal override Connection.ServerCertificateCapture? GetServerCertificateCapture() => _sessionHandle?.ServerCertificateCapture; + internal override int? GetNegotiatedCipherSuite() => _sessionHandle?.NegotiatedCipherSuite; + internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) { GetSessionSNIHandleHandleOrThrow().SetBufferSize((int)unsignedPacketSize); diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs index c6d5b94d8f..badf4b0cb4 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -310,6 +310,30 @@ public void CreateServerCertificateCapture_SenderNotSslStream_ProtocolUnavailabl ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, default, new object()); Assert.Null(capture.Protocol); + Assert.Null(capture.CipherSuite); + } + + [Fact] + public void GetNegotiatedCipherSuite_NoStreamOrNoHandshake_Unavailable() + { + Assert.Null(SniCommon.GetNegotiatedCipherSuite(null!)); + + // Reading before any handshake must neither throw nor report the null cipher suite (0). + using SslStream sslStream = new(new MemoryStream()); + Assert.Null(SniCommon.GetNegotiatedCipherSuite(sslStream)); + } + + [Fact] + public void RecordServerCertificate_CipherSuite_AdoptedOnlyWhenNotAlreadyRecorded() + { + EncryptionInfoCapture capture = new(); + capture.RecordServerCertificate(new ServerCertificateCapture(null, null, null, cipherSuite: 0xC030)); + Assert.Equal(0xC030, capture.CipherSuite); + + EncryptionInfoCapture alreadyKnown = new(); + alreadyKnown.RecordCipherSuite(0x1301); + alreadyKnown.RecordServerCertificate(new ServerCertificateCapture(null, null, null, cipherSuite: 0xC030)); + Assert.Equal(0x1301, alreadyKnown.CipherSuite); } [Fact] diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs index 8d3658d02c..96e2d747d0 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -6,6 +6,8 @@ using System; using System.IO; +using System.Net.Security; +using System.Reflection; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography; @@ -71,6 +73,9 @@ public async Task Open_TrustServerCertificate_PublishesHashWithoutVerdict(bool a // The certificate was presented but SqlClient did not evaluate it. Assert.Null(info.ValidationErrors); Assert.Null(info.ChainStatus); + // The published cipher suite is the one the client SslStream negotiated. + Assert.NotNull(info.NegotiatedCipherSuite); + Assert.Equal(GetClientSslStreamCipherSuite(connection), info.NegotiatedCipherSuite); } [Theory] @@ -114,6 +119,12 @@ public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndHash(bo AssertObservedNegotiation(info); Assert.True(connection.EncryptionInfo.IsEmpty); AssertNoLeak(ex, info); + + // The suite read inside the validation callback is the real one: a trusted handshake with the + // same server and protocol negotiates the same suite. + using SqlConnection trusted = new(BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); + await OpenAsync(trusted, async); + Assert.Equal(GetClientSslStreamCipherSuite(trusted), info.NegotiatedCipherSuite); } [Theory] @@ -198,13 +209,30 @@ public async Task Open_FailureThenSuccess_DoesNotCarryPreviousAttemptCertificate #region Helpers /// - /// Managed SNI records the protocol agreed for the handshake inside the validation callback, so a - /// certificate-validation failure still reports that protocol and the mode being negotiated. + /// Managed SNI records the protocol and cipher suite agreed for the handshake inside the validation + /// callback, so a certificate-validation failure still reports them and the mode being negotiated. /// private static void AssertObservedNegotiation(SqlConnectionEncryptionInfo info) { Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); + Assert.NotNull(info.NegotiatedCipherSuite); + Assert.InRange(info.NegotiatedCipherSuite.Value, 1, 0xFFFF); + } + + /// + /// Reads the cipher suite directly from the client SslStream of an open managed SNI connection, + /// independently of the encryption info capture. + /// + private static int GetClientSslStreamCipherSuite(SqlConnection connection) + { + global::Microsoft.Data.SqlClient.ManagedSni.SniHandle handle = connection.Parser._physicalStateObj.SessionHandle.ManagedHandle; + Assert.NotNull(handle); + FieldInfo? field = handle.GetType().GetField("_sslStream", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(field); + SslStream? sslStream = field.GetValue(handle) as SslStream; + Assert.NotNull(sslStream); + return (int)sslStream.NegotiatedCipherSuite; } private static LocalAppContextSwitchesHelper? ForceManagedSni() From 393030906fdfd08a0e46ad5c3730f9a2f39dc21c Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Mon, 26 Oct 2026 23:15:13 +0530 Subject: [PATCH 04/12] Mark Managed SNI capture simulator failures as expected TLS handshake failures Main's #4891 makes the TDS simulator rethrow connection faults on Stop. The untrusted, host-name-mismatch and pin-mismatch capture tests now set ExpectTlsHandshakeFailure so the server treats the client's rejection as expected. Test-only change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../ManagedSniCertificateCaptureTests.cs | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs index 96e2d747d0..9792317cc8 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -105,7 +105,7 @@ public async Task Open_MatchingServerCertificate_PublishesHashAndNoErrors(bool a public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndHash(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - using TdsServer server = StartServer(_fixture.Localhost); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); @@ -133,7 +133,7 @@ public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndHash(bo public async Task Open_HostNameMismatch_ExceptionCarriesHostNameMismatch(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - using TdsServer server = StartServer(_fixture.OtherHost); + using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); @@ -154,7 +154,7 @@ public async Task Open_HostNameMismatch_ExceptionCarriesHostNameMismatch(bool as public async Task Open_HostNameInCertificateOverride_ReportsEffectiveVerdict(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - using TdsServer server = StartServer(_fixture.OtherHost); + using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, hostNameInCertificate: "other.contoso.com")); SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); @@ -172,7 +172,7 @@ public async Task Open_HostNameInCertificateOverride_ReportsEffectiveVerdict(boo public async Task Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - using TdsServer server = StartServer(_fixture.Localhost); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); using TempCertFile pin = new(_fixture.OtherHost); using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); @@ -192,7 +192,7 @@ public async Task Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch( public async Task Open_FailureThenSuccess_DoesNotCarryPreviousAttemptCertificate(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - using TdsServer otherServer = StartServer(_fixture.OtherHost); + using TdsServer otherServer = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); using TdsServer server = StartServer(_fixture.Localhost); using TempCertFile pin = new(_fixture.Localhost); @@ -248,13 +248,22 @@ private static int GetClientSslStreamCipherSuite(SqlConnection connection) return switches; } - private static TdsServer StartServer(X509Certificate2 certificate) + /// + /// Starts a TLS 1.2 simulated server that requires encryption. + /// + /// The certificate the server presents. + /// + /// True when the client is expected to reject the certificate, so the server treats the resulting + /// TLS handshake failure as expected rather than reporting it as a fault when it is stopped. + /// + private static TdsServer StartServer(X509Certificate2 certificate, bool expectTlsHandshakeFailure = false) { TdsServer server = new(new TdsServerArguments { Encryption = TDSPreLoginTokenEncryptionType.Required, EncryptionCertificate = certificate, EncryptionProtocols = SslProtocols.Tls12, + ExpectTlsHandshakeFailure = expectTlsHandshakeFailure, }); server.Start(); return server; From 109bc3a4ebdfe39363888b73f0ed12bd2abb77f2 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Wed, 28 Oct 2026 15:09:47 +0530 Subject: [PATCH 05/12] Adapt Slice C tests and design note to NegotiatedCipherSuiteId Assert the public CLS-compliant NegotiatedCipherSuiteId property in the Managed SNI simulator tests and describe the two-property shape in the Managed capture section. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/design-notes/2353-connection-encryption-info.md | 7 +++++-- .../ManagedSniCertificateCaptureTests.cs | 10 +++++----- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index 55c6b08b26..ac64e3be20 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -350,8 +350,11 @@ the physical handle): Both reads are wrapped in `try`/`catch` so that capture never affects the handshake. A suite of `0` (`TLS_NULL_WITH_NULL_NULL`, nothing agreed yet) is treated as unavailable. Without TLS, the -property is `null`. Managed SNI runs only on `net10.0`; on `net462` this capture is not compiled -and the property stays `null` until native SNI support (Slice D). +properties are `null`. The value flows through the SNI handles, `ServerCertificateCapture` and +`EncryptionInfoCapture` as an `int`. `NegotiatedCipherSuiteId` returns it unchanged, and on .NET +`NegotiatedCipherSuite` casts the same value to `TlsCipherSuite`. +Managed SNI runs only on `net10.0`; on `net462` this capture is not compiled +and `NegotiatedCipherSuiteId` stays `null` until native SNI support (Slice D). ## 5. Scope diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs index 9792317cc8..4ed7c22b59 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -74,8 +74,8 @@ public async Task Open_TrustServerCertificate_PublishesHashWithoutVerdict(bool a Assert.Null(info.ValidationErrors); Assert.Null(info.ChainStatus); // The published cipher suite is the one the client SslStream negotiated. - Assert.NotNull(info.NegotiatedCipherSuite); - Assert.Equal(GetClientSslStreamCipherSuite(connection), info.NegotiatedCipherSuite); + Assert.NotNull(info.NegotiatedCipherSuiteId); + Assert.Equal(GetClientSslStreamCipherSuite(connection), info.NegotiatedCipherSuiteId); } [Theory] @@ -124,7 +124,7 @@ public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndHash(bo // same server and protocol negotiates the same suite. using SqlConnection trusted = new(BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); await OpenAsync(trusted, async); - Assert.Equal(GetClientSslStreamCipherSuite(trusted), info.NegotiatedCipherSuite); + Assert.Equal(GetClientSslStreamCipherSuite(trusted), info.NegotiatedCipherSuiteId); } [Theory] @@ -216,8 +216,8 @@ private static void AssertObservedNegotiation(SqlConnectionEncryptionInfo info) { Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); - Assert.NotNull(info.NegotiatedCipherSuite); - Assert.InRange(info.NegotiatedCipherSuite.Value, 1, 0xFFFF); + Assert.NotNull(info.NegotiatedCipherSuiteId); + Assert.InRange(info.NegotiatedCipherSuiteId!.Value, 1, 0xFFFF); } /// From ba2f0ac3c3f470d07c6fafecb2e3b7746ec123a2 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Fri, 30 Oct 2026 13:04:23 +0530 Subject: [PATCH 06/12] Capture the presented server certificate instead of its hash (Managed SNI) Managed SNI now captures a copy of the presented leaf certificate's DER encoding (GetRawCertData) instead of its SHA-256 hash, and passes it to the snapshot so SqlConnectionEncryptionInfo.GetServerCertificate() can return it. Certificates over 64 KiB are not captured, and the first certificate presented in an attempt is kept. Capture still happens in the validation callback's finally block, so it is present on TrustServerCertificate bypass and on validation failure. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../2353-connection-encryption-info.md | 2 +- .../Connection/EncryptionInfoAccumulator.cs | 18 +-- .../Connection/ServerCertificateCapture.cs | 23 ++-- .../SqlClient/ManagedSni/SniCommon.netcore.cs | 51 +++++-- .../ManagedSni/SniNpHandle.netcore.cs | 5 +- .../ManagedSni/SniTcpHandle.netcore.cs | 5 +- .../Data/SqlClient/Parser/TdsParser.cs | 2 +- .../SniCommonServerCertificateCaptureTest.cs | 125 ++++++++++++++---- .../ManagedSniCertificateCaptureTests.cs | 39 +++--- 9 files changed, 189 insertions(+), 81 deletions(-) diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index ac64e3be20..01c840ca0b 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -323,7 +323,7 @@ TLS protocol agreed for the handshake (see **Failure path** above). | Field | Source | `null` when | | --- | --- | --- | -| `PresentedServerCertificateHash256` | SHA-256 of the presented leaf certificate's DER encoding (`GetRawCertData()`) | No certificate was presented. Captured even when `TrustServerCertificate` bypasses validation. | +| `PresentedServerCertificateRawData` / `GetServerCertificate()` | A copy of the presented leaf certificate's DER encoding (`GetRawCertData()`); the first certificate presented in the attempt is kept | No certificate was presented, or its encoding exceeds 64 KiB (`ServerCertificateCapture.MaxRawCertificateSize`). Captured even when `TrustServerCertificate` bypasses validation, and on validation failure. | | `ServerCertificateValidationErrors` | Effective SqlClient verdict: `ServerCertificateMissing`, `ChainError`, `HostNameMismatch` (after `HostNameInCertificate`), `PinnedCertificateMismatch` (`ServerCertificate`); `None` when validation passed | Validation was bypassed, or the configured `ServerCertificate` file could not be read. | | `ServerCertificateChainStatus` | Bitwise OR of the original callback chain's `ChainStatus` flags (no chain rebuild); `NoError` when the chain was evaluated cleanly | Validation was bypassed, `ServerCertificate` pinning is used (the chain isn't consulted), no certificate was presented, or the platform reported a chain error without flags. | diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs index 37bcaf289a..9ad21bae57 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulator.cs @@ -32,12 +32,6 @@ namespace Microsoft.Data.SqlClient.Connection /// internal sealed class EncryptionInfoAccumulator { - /// - /// Gets or sets the SHA-256 hash of the presented server certificate for the current attempt, - /// or if the transport did not observe a presented certificate. - /// - public byte[]? CertificateHash256 { get; set; } - /// /// Gets or sets the combined chain status flags for the current attempt, or /// if the chain was not consulted or is unavailable. @@ -79,7 +73,7 @@ public int? CipherSuite Mode is not null || Protocol is not null || CipherSuite is not null || - CertificateHash256 is not null || + ServerCertificateRawData is not null || ValidationErrors is not null || ChainStatus is not null; @@ -105,6 +99,12 @@ public SslProtocols? Protocol set => field = value == SslProtocols.None ? null : value; } + /// + /// Gets or sets the DER encoding of the presented server certificate for the current attempt, + /// or if the transport did not capture a presented certificate. + /// + public byte[]? ServerCertificateRawData { get; set; } + /// /// Gets or sets SqlClient's effective certificate validation verdict for the current attempt, /// or if SqlClient did not evaluate the certificate. @@ -119,7 +119,7 @@ public void Reset() Mode = null; Protocol = null; CipherSuite = null; - CertificateHash256 = null; + ServerCertificateRawData = null; ValidationErrors = null; ChainStatus = null; } @@ -137,7 +137,7 @@ public SqlConnectionEncryptionInfo ToSnapshot() => ? new SqlConnectionEncryptionInfo( negotiatedEncryptionMode: Mode, negotiatedEncryptionProtocol: Protocol, - presentedServerCertificate: CertificateHash256, + presentedServerCertificate: ServerCertificateRawData, validationErrors: ValidationErrors, chainStatus: ChainStatus, negotiatedCipherSuite: CipherSuite) diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs index 104f781934..ecfd450d63 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs @@ -15,20 +15,26 @@ namespace Microsoft.Data.SqlClient.Connection /// /// /// Each value is when it is unavailable: no certificate was presented - /// (), SqlClient did not evaluate the certificate - /// (), or the original chain was not consulted or reported no - /// usable status (). This type never carries the certificate itself. + /// or it was larger than (), + /// SqlClient did not evaluate the certificate (), or the original + /// chain was not consulted or reported no usable status (). /// internal sealed class ServerCertificateCapture { + /// + /// The largest DER-encoded certificate, in bytes, that is captured. A larger certificate is + /// not captured; the connection is unaffected. + /// + internal const int MaxRawCertificateSize = 64 * 1024; + internal ServerCertificateCapture( - byte[]? hash256, + byte[]? rawCertificate, SqlServerCertificateValidationErrors? validationErrors, X509ChainStatusFlags? chainStatus, SslProtocols? protocol = null, int? cipherSuite = null) { - Hash256 = hash256; + RawCertificate = rawCertificate; ValidationErrors = validationErrors; ChainStatus = chainStatus; Protocol = protocol; @@ -36,10 +42,11 @@ internal ServerCertificateCapture( } /// - /// Gets the SHA-256 hash of the DER encoding of the presented leaf certificate, or - /// if no certificate was presented. + /// Gets the DER encoding of the presented leaf certificate, or if no + /// certificate was presented or it was larger than . + /// The array is owned by this capture and must not be modified. /// - public byte[]? Hash256 { get; } + public byte[]? RawCertificate { get; } /// /// Gets SqlClient's effective validation verdict, or if SqlClient did diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs index d5b88dce88..1b22c575f5 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs @@ -286,30 +286,53 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ /// The certificate presented by the server, if any. /// The verdict recorded by validation; default when not evaluated. /// The raising the validation callback, if any. + /// + /// The capture already recorded for this handshake attempt, if any. The first certificate + /// captured in an attempt is kept; a later callback invocation does not replace it. + /// /// The capture. Never . - internal static ServerCertificateCapture CreateServerCertificateCapture(X509Certificate serverCert, in ServerCertificateVerdict verdict, object sender = null) + internal static ServerCertificateCapture CreateServerCertificateCapture(X509Certificate serverCert, in ServerCertificateVerdict verdict, object sender = null, ServerCertificateCapture previous = null) { - byte[] hash = null; - if (serverCert is not null) - { - try - { - hash = SHA256.HashData(serverCert.GetRawCertData()); - } - catch (CryptographicException) - { - // Capture must never affect the handshake outcome; leave the hash unavailable. - } - } + byte[] rawCertificate = previous?.RawCertificate ?? GetRawCertificate(serverCert); return new ServerCertificateCapture( - hash, + rawCertificate, verdict.ValidationErrors, verdict.ChainStatus, GetHandshakeProtocol(sender), GetNegotiatedCipherSuite(sender as SslStream)); } + /// + /// Copies the DER encoding of the presented certificate for diagnostics. + /// + /// The certificate presented by the server, if any. + /// + /// The DER bytes, or when no certificate was presented, its encoding + /// cannot be read, or it is larger than . + /// + internal static byte[] GetRawCertificate(X509Certificate serverCert) + { + if (serverCert is null) + { + return null; + } + + try + { + // GetRawCertData returns a new array, so the capture owns it. + byte[] rawCertificate = serverCert.GetRawCertData(); + return rawCertificate is { Length: > 0 and <= ServerCertificateCapture.MaxRawCertificateSize } + ? rawCertificate + : null; + } + catch (CryptographicException) + { + // Capture must never affect the handshake outcome; leave the certificate unavailable. + return null; + } + } + /// /// Reads the IANA identifier of the cipher suite agreed for the handshake on /// . Like the protocol version, the cipher suite is agreed diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs index 93cf5c2c5f..1b629dee5a 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs @@ -406,8 +406,9 @@ private bool ValidateServerCertificate(object sender, X509Certificate serverCert } finally { - // Recorded for both outcomes so that a failed handshake still reports what was observed. - Volatile.Write(ref _serverCertificateCapture, SniCommon.CreateServerCertificateCapture(serverCertificate, verdict, sender)); + // Recorded for both outcomes (including when validation is bypassed) so that a failed + // handshake still reports what was observed. The first certificate of the attempt is kept. + Volatile.Write(ref _serverCertificateCapture, SniCommon.CreateServerCertificateCapture(serverCertificate, verdict, sender, Volatile.Read(ref _serverCertificateCapture))); } } } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs index 2cb75a7207..5188429de6 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs @@ -835,8 +835,9 @@ private bool ValidateServerCertificate(object sender, X509Certificate serverCert } finally { - // Recorded for both outcomes so that a failed handshake still reports what was observed. - Volatile.Write(ref _serverCertificateCapture, SniCommon.CreateServerCertificateCapture(serverCertificate, verdict, sender)); + // Recorded for both outcomes (including when validation is bypassed) so that a failed + // handshake still reports what was observed. The first certificate of the attempt is kept. + Volatile.Write(ref _serverCertificateCapture, SniCommon.CreateServerCertificateCapture(serverCertificate, verdict, sender, Volatile.Read(ref _serverCertificateCapture))); } } 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 437028085e..df4812f6d4 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 @@ -962,7 +962,7 @@ private void EnableSsl(uint info, SqlConnectionEncryptOption encrypt, bool integ EncryptionInfoAccumulator accumulator = _connHandler?.EncryptionInfoAccumulator; if (accumulator is not null && certificateCapture is not null) { - accumulator.CertificateHash256 = certificateCapture.Hash256; + accumulator.ServerCertificateRawData = certificateCapture.RawCertificate; accumulator.ValidationErrors = certificateCapture.ValidationErrors; accumulator.ChainStatus = certificateCapture.ChainStatus; diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs index badf4b0cb4..f2bb83a8a6 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -19,8 +19,8 @@ namespace Microsoft.Data.SqlClient.UnitTests.ManagedSni { /// /// Tests for the certificate details that managed SNI captures from the TLS validation callback: - /// SqlClient's effective validation verdict, the original callback chain status, and the SHA-256 - /// hash of the presented certificate. + /// SqlClient's effective validation verdict, the original callback chain status, and the DER + /// encoding of the presented certificate. /// public class SniCommonServerCertificateCaptureTest { @@ -267,36 +267,84 @@ public void ValidateSslServerCertificate_CaptureDoesNotChangeOutcomeOrMessage( if (capturing is not null && cert is not null) { ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(cert, verdict); - AssertNoLeak(capture.Hash256!, capturing.Message); - AssertNoLeak(capture.Hash256!, capturing.ToString()); + AssertNoLeak(capture.RawCertificate!, capturing.Message); + AssertNoLeak(capture.RawCertificate!, capturing.ToString()); } } [Fact] - public void CreateServerCertificateCapture_HashIsSha256OfDer() + public void CreateServerCertificateCapture_CapturesDer() { using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, new ServerCertificateVerdict(SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError)); - Assert.NotNull(capture.Hash256); - Assert.Equal(32, capture.Hash256!.Length); - - using SHA256 sha256 = SHA256.Create(); - Assert.Equal(sha256.ComputeHash(serverCert.Export(X509ContentType.Cert)), capture.Hash256); + Assert.NotNull(capture.RawCertificate); + Assert.Equal(serverCert.Export(X509ContentType.Cert), capture.RawCertificate); Assert.Equal(SqlServerCertificateValidationErrors.None, capture.ValidationErrors); Assert.Equal(X509ChainStatusFlags.NoError, capture.ChainStatus); + + // The capture owns its copy; it is not the certificate's internal buffer. + capture.RawCertificate![0] ^= 0xFF; + Assert.NotEqual(capture.RawCertificate, serverCert.RawData); + } + + [Fact] + public void CreateServerCertificateCapture_OverSizeCap_CertificateUnavailable() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, ServerCertificateCapture.MaxRawCertificateSize); + Assert.True(serverCert.RawData.Length > ServerCertificateCapture.MaxRawCertificateSize); + + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture( + serverCert, + new ServerCertificateVerdict(SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + + // Only the certificate is dropped; the other captured values are unaffected. + Assert.Null(capture.RawCertificate); + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, capture.ValidationErrors); + Assert.Equal(X509ChainStatusFlags.UntrustedRoot, capture.ChainStatus); + } + + [Fact] + public void CreateServerCertificateCapture_AtSizeCap_CertificateCaptured() + { + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, ServerCertificateCapture.MaxRawCertificateSize / 2); + Assert.InRange(serverCert.RawData.Length, 1, ServerCertificateCapture.MaxRawCertificateSize); + + Assert.Equal(serverCert.RawData, SniCommon.GetRawCertificate(serverCert)); + } + + [Fact] + public void CreateServerCertificateCapture_FirstCertificateWins() + { + using X509Certificate2 first = CreateSelfSignedCertificate(ServerName); + using X509Certificate2 second = CreateSelfSignedCertificate("other.contoso.com"); + + ServerCertificateCapture previous = SniCommon.CreateServerCertificateCapture(first, default); + ServerCertificateCapture next = SniCommon.CreateServerCertificateCapture( + second, + new ServerCertificateVerdict(SqlServerCertificateValidationErrors.HostNameMismatch, X509ChainStatusFlags.NoError), + sender: null, + previous: previous); + + // The certificate stays the first one presented in the attempt; the verdict is the latest. + Assert.Equal(first.RawData, next.RawCertificate); + Assert.Equal(SqlServerCertificateValidationErrors.HostNameMismatch, next.ValidationErrors); + + // A previous capture without a certificate does not block capturing a later one. + ServerCertificateCapture empty = SniCommon.CreateServerCertificateCapture(null!, default); + Assert.Equal(second.RawData, SniCommon.CreateServerCertificateCapture(second, default, previous: empty).RawCertificate); } [Fact] - public void CreateServerCertificateCapture_Bypass_HashOnly() + public void CreateServerCertificateCapture_Bypass_CertificateOnly() { using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); // TrustServerCertificate bypass: validation is never run, so the verdict stays default. ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, default); - Assert.Equal(SHA256.HashData(serverCert.RawData), capture.Hash256); + Assert.Equal(serverCert.RawData, capture.RawCertificate); Assert.Null(capture.ValidationErrors); Assert.Null(capture.ChainStatus); Assert.Null(capture.Protocol); @@ -337,13 +385,13 @@ public void RecordServerCertificate_CipherSuite_AdoptedOnlyWhenNotAlreadyRecorde } [Fact] - public void CreateServerCertificateCapture_NoCertificate_HashUnavailable() + public void CreateServerCertificateCapture_NoCertificate_CertificateUnavailable() { ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture( null!, new ServerCertificateVerdict(SqlServerCertificateValidationErrors.ServerCertificateMissing, null)); - Assert.Null(capture.Hash256); + Assert.Null(capture.RawCertificate); Assert.Equal(SqlServerCertificateValidationErrors.ServerCertificateMissing, capture.ValidationErrors); Assert.Null(capture.ChainStatus); } @@ -416,17 +464,24 @@ public void GetChainStatus_DoesNotBuildChain() [Fact] public void EncryptionInfoCapture_RecordServerCertificate_PublishesInSnapshot() { - byte[] hash = SHA256.HashData(new byte[] { 1, 2, 3 }); + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); EncryptionInfoCapture capture = new(); - capture.RecordServerCertificate(new ServerCertificateCapture(hash, SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + capture.RecordServerCertificate(new ServerCertificateCapture(SniCommon.GetRawCertificate(serverCert), SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); Assert.True(capture.HasValues); + Assert.Equal(serverCert.RawData, capture.ServerCertificateRawData); SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); Assert.False(snapshot.IsEmpty); Assert.Null(snapshot.NegotiatedEncryptionMode); Assert.Null(snapshot.NegotiatedEncryptionProtocol); - Assert.Equal(hash, snapshot.PresentedServerCertificateHash256!.Value.ToArray()); + Assert.Equal(serverCert.RawData, snapshot.PresentedServerCertificateRawData!.Value.ToArray()); + using (X509Certificate2? roundTripped = snapshot.GetServerCertificate()) + { + Assert.NotNull(roundTripped); + Assert.Equal(serverCert.RawData, roundTripped.RawData); + Assert.False(roundTripped.HasPrivateKey); + } Assert.Equal(SqlServerCertificateValidationErrors.ChainError, snapshot.ValidationErrors); Assert.Equal(X509ChainStatusFlags.UntrustedRoot, snapshot.ChainStatus); @@ -445,7 +500,8 @@ public void EncryptionInfoCapture_ZeroValuesAreAvailable() SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); Assert.Equal(SqlServerCertificateValidationErrors.None, snapshot.ValidationErrors); Assert.Equal(X509ChainStatusFlags.NoError, snapshot.ChainStatus); - Assert.Null(snapshot.PresentedServerCertificateHash256); + Assert.Null(snapshot.PresentedServerCertificateRawData); + Assert.Null(snapshot.GetServerCertificate()); } [Fact] @@ -459,13 +515,15 @@ public void EncryptionInfoCapture_NullCapture_LeavesCertificateFieldsUnavailable } [Fact] - public void EncryptionInfoCapture_HashNotInSnapshotText() + public void EncryptionInfoCapture_CertificateNotInSnapshotText() { - byte[] hash = SHA256.HashData(new byte[] { 4, 5, 6 }); + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); EncryptionInfoCapture capture = new(); - capture.RecordServerCertificate(new ServerCertificateCapture(hash, SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + capture.RecordServerCertificate(new ServerCertificateCapture(serverCert.RawData, SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); - AssertNoLeak(hash, capture.ToSnapshot().ToString() ?? string.Empty); + string text = capture.ToSnapshot().ToString() ?? string.Empty; + AssertNoLeak(serverCert.RawData, text); + Assert.DoesNotContain(serverCert.Thumbprint, text, StringComparison.OrdinalIgnoreCase); } #endregion @@ -513,20 +571,33 @@ public void EncryptionInfoCapture_HashNotInSnapshotText() return chain; } - private static void AssertNoLeak(byte[] hash, string text) + private static void AssertNoLeak(byte[] certificate, string text) { - Assert.DoesNotContain(Convert.ToHexString(hash), text, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain(Convert.ToBase64String(hash), text, StringComparison.Ordinal); - Assert.DoesNotContain(BitConverter.ToString(hash), text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(Convert.ToHexString(certificate), text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(Convert.ToBase64String(certificate), text, StringComparison.Ordinal); + Assert.DoesNotContain(BitConverter.ToString(certificate), text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(Convert.ToHexString(SHA256.HashData(certificate)), text, StringComparison.OrdinalIgnoreCase); } - private static X509Certificate2 CreateSelfSignedCertificate(string subjectCommonName) + /// The subject and DNS SAN. + /// + /// When non-zero, adds a private, non-critical extension of this many bytes to grow the DER + /// encoding (used to test the capture size cap). + /// + private static X509Certificate2 CreateSelfSignedCertificate(string subjectCommonName, int paddingBytes = 0) { using RSA rsa = RSA.Create(2048); CertificateRequest request = new($"CN={subjectCommonName}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); SubjectAlternativeNameBuilder san = new(); san.AddDnsName(subjectCommonName); request.CertificateExtensions.Add(san.Build()); + if (paddingBytes > 0) + { + // A DER OCTET STRING keeps the extension value well-formed. + System.Formats.Asn1.AsnWriter writer = new(System.Formats.Asn1.AsnEncodingRules.DER); + writer.WriteOctetString(new byte[paddingBytes]); + request.CertificateExtensions.Add(new X509Extension("1.3.6.1.4.1.311.999.1", writer.Encode(), critical: false)); + } DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddMinutes(-5); return request.CreateSelfSigned(notBefore, notBefore.AddHours(1)); diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs index 4ed7c22b59..2b5054fed5 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -41,7 +41,7 @@ public ManagedSniCaptureCertificateFixture() /// /// End-to-end verification, against the simulated TDS server over TLS, that managed SNI publishes the - /// presented server certificate hash, SqlClient's effective validation verdict, and the callback chain + /// presented server certificate, SqlClient's effective validation verdict, and the callback chain /// status to and . /// Managed SNI is forced on Windows via the UseManagedNetworkingOnWindows switch. /// @@ -58,7 +58,7 @@ public ManagedSniCertificateCaptureTests(ManagedSniCaptureCertificateFixture fix [Theory] [InlineData(false)] [InlineData(true)] - public async Task Open_TrustServerCertificate_PublishesHashWithoutVerdict(bool async) + public async Task Open_TrustServerCertificate_PublishesCertificateWithoutVerdict(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.Localhost); @@ -69,7 +69,7 @@ public async Task Open_TrustServerCertificate_PublishesHashWithoutVerdict(bool a SqlConnectionEncryptionInfo info = connection.EncryptionInfo; Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); - AssertHash(_fixture.Localhost, info); + AssertCertificate(_fixture.Localhost, info); // The certificate was presented but SqlClient did not evaluate it. Assert.Null(info.ValidationErrors); Assert.Null(info.ChainStatus); @@ -81,7 +81,7 @@ public async Task Open_TrustServerCertificate_PublishesHashWithoutVerdict(bool a [Theory] [InlineData(false)] [InlineData(true)] - public async Task Open_MatchingServerCertificate_PublishesHashAndNoErrors(bool async) + public async Task Open_MatchingServerCertificate_PublishesCertificateAndNoErrors(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.Localhost); @@ -93,7 +93,7 @@ public async Task Open_MatchingServerCertificate_PublishesHashAndNoErrors(bool a SqlConnectionEncryptionInfo info = connection.EncryptionInfo; Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); - AssertHash(_fixture.Localhost, info); + AssertCertificate(_fixture.Localhost, info); Assert.Equal(SqlServerCertificateValidationErrors.None, info.ValidationErrors); // The chain is not consulted when a ServerCertificate pin decides trust. Assert.Null(info.ChainStatus); @@ -102,7 +102,7 @@ public async Task Open_MatchingServerCertificate_PublishesHashAndNoErrors(bool a [Theory] [InlineData(false)] [InlineData(true)] - public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndHash(bool async) + public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndCertificate(bool async) { using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); @@ -111,7 +111,7 @@ public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndHash(bo SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - AssertHash(_fixture.Localhost, info); + AssertCertificate(_fixture.Localhost, info); Assert.Equal(SqlServerCertificateValidationErrors.ChainError, info.ValidationErrors); Assert.NotNull(info.ChainStatus); Assert.NotEqual(X509ChainStatusFlags.NoError, info.ChainStatus); @@ -139,7 +139,7 @@ public async Task Open_HostNameMismatch_ExceptionCarriesHostNameMismatch(bool as SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - AssertHash(_fixture.OtherHost, info); + AssertCertificate(_fixture.OtherHost, info); Assert.Equal( SqlServerCertificateValidationErrors.ChainError | SqlServerCertificateValidationErrors.HostNameMismatch, info.ValidationErrors); @@ -162,7 +162,7 @@ public async Task Open_HostNameInCertificateOverride_ReportsEffectiveVerdict(boo // The platform reported a name mismatch, but HostNameInCertificate resolves it; only the // untrusted chain remains in SqlClient's effective verdict. Assert.Equal(SqlServerCertificateValidationErrors.ChainError, ex.EncryptionInfo.ValidationErrors); - AssertHash(_fixture.OtherHost, ex.EncryptionInfo); + AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); AssertObservedNegotiation(ex.EncryptionInfo); } @@ -179,7 +179,7 @@ public async Task Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch( SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - AssertHash(_fixture.Localhost, info); + AssertCertificate(_fixture.Localhost, info); Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, info.ValidationErrors); Assert.Null(info.ChainStatus); AssertObservedNegotiation(info); @@ -198,11 +198,11 @@ public async Task Open_FailureThenSuccess_DoesNotCarryPreviousAttemptCertificate using SqlConnection failing = new(BuildConnectionString(otherServer.EndPoint.Port, serverCertificate: pin.Path)); SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(failing, async)); - AssertHash(_fixture.OtherHost, ex.EncryptionInfo); + AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); await OpenAsync(connection, async); - AssertHash(_fixture.Localhost, connection.EncryptionInfo); + AssertCertificate(_fixture.Localhost, connection.EncryptionInfo); Assert.Equal(SqlServerCertificateValidationErrors.None, connection.EncryptionInfo.ValidationErrors); } @@ -306,16 +306,21 @@ private static Task OpenAsync(SqlConnection connection, bool async) return Task.CompletedTask; } - private static void AssertHash(X509Certificate2 expected, SqlConnectionEncryptionInfo info) + private static void AssertCertificate(X509Certificate2 expected, SqlConnectionEncryptionInfo info) { - Assert.NotNull(info.PresentedServerCertificateHash256); - Assert.Equal(SHA256.HashData(expected.RawData), info.PresentedServerCertificateHash256.Value.ToArray()); + Assert.NotNull(info.PresentedServerCertificateRawData); + Assert.Equal(expected.RawData, info.PresentedServerCertificateRawData.Value.ToArray()); + + using X509Certificate2? certificate = info.GetServerCertificate(); + Assert.NotNull(certificate); + Assert.Equal(expected.RawData, certificate.RawData); + Assert.False(certificate.HasPrivateKey); } private static void AssertNoLeak(SqlException ex, SqlConnectionEncryptionInfo info) { - byte[] hash = info.PresentedServerCertificateHash256!.Value.ToArray(); - string[] encodings = { Convert.ToHexString(hash), Convert.ToBase64String(hash), BitConverter.ToString(hash) }; + byte[] der = info.PresentedServerCertificateRawData!.Value.ToArray(); + string[] encodings = { Convert.ToHexString(der), Convert.ToBase64String(der), BitConverter.ToString(der), Convert.ToHexString(SHA256.HashData(der)) }; foreach (string encoding in encodings) { Assert.DoesNotContain(encoding, ex.Message, StringComparison.OrdinalIgnoreCase); From c33a3cd02eac3fce7c6b5607fdbfd406bd0319c9 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Tue, 10 Nov 2026 20:04:04 +0530 Subject: [PATCH 07/12] Address review feedback on Managed SNI certificate capture - Reset the attempt's encryption info capture when Connect retries after an instance-resolution failure, so only the retried attempt's values publish. - Document that an observed protocol is kept after a failure. - Compare capture outcomes against an independent restatement of the validation rules instead of the legacy overload. - Add routed single-login tests proving only the terminal attempt's certificate is published, including a terminal attempt that fails before TLS. - Add XML summaries and Arrange/Act/Assert structure to the capture tests. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../SniCommonServerCertificateCaptureTest.cs | 618 ++++++++++++++---- .../ManagedSniCertificateCaptureTests.cs | 302 ++++++++- 2 files changed, 759 insertions(+), 161 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs index f2bb83a8a6..71e4ef6815 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -11,6 +11,7 @@ using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; +using System.Text; using Microsoft.Data.SqlClient.Connection; using Microsoft.Data.SqlClient.ManagedSni; using Xunit; @@ -26,57 +27,104 @@ public class SniCommonServerCertificateCaptureTest { private const string ServerName = "server.contoso.com"; + /// + /// The chain that a test passes to the validation callback. + /// public enum ChainKind { - // No chain supplied to the callback. + /// No chain supplied to the callback. None, - // A chain that was evaluated and found clean. + /// A chain that was evaluated and found clean. Clean, - // A chain that was evaluated and found untrusted. + /// A chain that was evaluated and found untrusted. Untrusted, } + /// + /// The ServerCertificate pin that a test configures. + /// public enum PinKind { + /// No pin is configured. None, + /// The pin is the presented certificate. Match, + /// The pin is a different certificate. Mismatch, + /// The pin file cannot be loaded. Unreadable, } - public static IEnumerable VerdictCases() + /// + /// Callback inputs and the verdict expected for them: policy errors, callback chain, pin, + /// HostNameInCertificate, target server name, whether no certificate is presented, whether + /// validation succeeds, the expected validation errors, and whether the callback chain + /// status is expected to be reported. + /// + public static TheoryData VerdictCases() { - // policyErrors, chain, pin, hostNameInCertificate, targetServer, nullCert, expectSuccess, expectedErrors, expectChainFromCallback const SslPolicyErrors None = SslPolicyErrors.None; const SslPolicyErrors Chain = SslPolicyErrors.RemoteCertificateChainErrors; const SslPolicyErrors Name = SslPolicyErrors.RemoteCertificateNameMismatch; const SslPolicyErrors NotAvailable = SslPolicyErrors.RemoteCertificateNotAvailable; + const string Other = "other.contoso.com"; - // No pin: the platform verdict, refined by SqlClient's host name handling, decides trust. - yield return new object?[] { None, ChainKind.Clean, PinKind.None, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, true }; - yield return new object?[] { None, ChainKind.None, PinKind.None, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, true }; - yield return new object?[] { Chain, ChainKind.Untrusted, PinKind.None, null, ServerName, false, false, SqlServerCertificateValidationErrors.ChainError, true }; - yield return new object?[] { Name, ChainKind.Clean, PinKind.None, null, "other.contoso.com", false, false, SqlServerCertificateValidationErrors.HostNameMismatch, true }; - yield return new object?[] { Chain | Name, ChainKind.Untrusted, PinKind.None, null, "other.contoso.com", false, false, SqlServerCertificateValidationErrors.ChainError | SqlServerCertificateValidationErrors.HostNameMismatch, true }; - // HostNameInCertificate resolves the platform's name mismatch: effective verdict has no host name error. - yield return new object?[] { Name, ChainKind.Clean, PinKind.None, ServerName, "other.contoso.com", false, true, SqlServerCertificateValidationErrors.None, true }; - yield return new object?[] { Chain | Name, ChainKind.Untrusted, PinKind.None, ServerName, "other.contoso.com", false, false, SqlServerCertificateValidationErrors.ChainError, true }; - // HostNameInCertificate that also mismatches is still reported. - yield return new object?[] { Name, ChainKind.Clean, PinKind.None, "third.contoso.com", ServerName, false, false, SqlServerCertificateValidationErrors.HostNameMismatch, true }; - // No certificate presented. - yield return new object?[] { NotAvailable, ChainKind.None, PinKind.None, null, ServerName, true, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; - yield return new object?[] { NotAvailable, ChainKind.Clean, PinKind.None, null, ServerName, false, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; - - // Pin: the exact comparison decides trust and the chain is not consulted. - yield return new object?[] { None, ChainKind.Clean, PinKind.Match, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, false }; - yield return new object?[] { Chain, ChainKind.Untrusted, PinKind.Match, null, ServerName, false, true, SqlServerCertificateValidationErrors.None, false }; - yield return new object?[] { None, ChainKind.Clean, PinKind.Mismatch, null, ServerName, false, false, SqlServerCertificateValidationErrors.PinnedCertificateMismatch, false }; - yield return new object?[] { Chain, ChainKind.Untrusted, PinKind.Mismatch, null, ServerName, false, false, SqlServerCertificateValidationErrors.PinnedCertificateMismatch, false }; - yield return new object?[] { NotAvailable, ChainKind.None, PinKind.Match, null, ServerName, true, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; - yield return new object?[] { NotAvailable, ChainKind.Clean, PinKind.Match, null, ServerName, false, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; - yield return new object?[] { None, ChainKind.None, PinKind.Match, null, ServerName, true, false, SqlServerCertificateValidationErrors.ServerCertificateMissing, false }; + TheoryData data = new() + { + // No pin: the platform verdict, refined by SqlClient's host name handling, decides + // trust. + { None, ChainKind.Clean, PinKind.None, null, ServerName, false, true, + SqlServerCertificateValidationErrors.None, true }, + { None, ChainKind.None, PinKind.None, null, ServerName, false, true, + SqlServerCertificateValidationErrors.None, true }, + { Chain, ChainKind.Untrusted, PinKind.None, null, ServerName, false, false, + SqlServerCertificateValidationErrors.ChainError, true }, + { Name, ChainKind.Clean, PinKind.None, null, Other, false, false, + SqlServerCertificateValidationErrors.HostNameMismatch, true }, + { Chain | Name, ChainKind.Untrusted, PinKind.None, null, Other, false, false, + SqlServerCertificateValidationErrors.ChainError + | SqlServerCertificateValidationErrors.HostNameMismatch, true }, + // HostNameInCertificate resolves the platform's name mismatch: the effective + // verdict has no host name error. + { Name, ChainKind.Clean, PinKind.None, ServerName, Other, false, true, + SqlServerCertificateValidationErrors.None, true }, + { Chain | Name, ChainKind.Untrusted, PinKind.None, ServerName, Other, false, false, + SqlServerCertificateValidationErrors.ChainError, true }, + // HostNameInCertificate that also mismatches is still reported. + { Name, ChainKind.Clean, PinKind.None, "third.contoso.com", ServerName, false, false, + SqlServerCertificateValidationErrors.HostNameMismatch, true }, + // No certificate presented. + { NotAvailable, ChainKind.None, PinKind.None, null, ServerName, true, false, + SqlServerCertificateValidationErrors.ServerCertificateMissing, false }, + { NotAvailable, ChainKind.Clean, PinKind.None, null, ServerName, false, false, + SqlServerCertificateValidationErrors.ServerCertificateMissing, false }, + + // Pin: the exact comparison decides trust and the chain is not consulted. + { None, ChainKind.Clean, PinKind.Match, null, ServerName, false, true, + SqlServerCertificateValidationErrors.None, false }, + { Chain, ChainKind.Untrusted, PinKind.Match, null, ServerName, false, true, + SqlServerCertificateValidationErrors.None, false }, + { None, ChainKind.Clean, PinKind.Mismatch, null, ServerName, false, false, + SqlServerCertificateValidationErrors.PinnedCertificateMismatch, false }, + { Chain, ChainKind.Untrusted, PinKind.Mismatch, null, ServerName, false, false, + SqlServerCertificateValidationErrors.PinnedCertificateMismatch, false }, + { NotAvailable, ChainKind.None, PinKind.Match, null, ServerName, true, false, + SqlServerCertificateValidationErrors.ServerCertificateMissing, false }, + { NotAvailable, ChainKind.Clean, PinKind.Match, null, ServerName, false, false, + SqlServerCertificateValidationErrors.ServerCertificateMissing, false }, + { None, ChainKind.None, PinKind.Match, null, ServerName, true, false, + SqlServerCertificateValidationErrors.ServerCertificateMissing, false }, + }; + return data; } + /// + /// Validation records SqlClient's effective verdict for each combination of callback + /// inputs: the validation errors after HostNameInCertificate and pin handling, and the + /// original callback chain status only when the chain is consulted. + /// [Theory] [MemberData(nameof(VerdictCases))] public void ValidateSslServerCertificate_RecordsEffectiveVerdict( @@ -90,6 +138,7 @@ public void ValidateSslServerCertificate_RecordsEffectiveVerdict( SqlServerCertificateValidationErrors expectedErrors, bool expectChainFromCallback) { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); using X509Certificate2 otherCert = CreateSelfSignedCertificate("other.contoso.com"); using X509Chain? chain = CreateChain(chainKind, serverCert); @@ -101,8 +150,12 @@ public void ValidateSslServerCertificate_RecordsEffectiveVerdict( }; string? pinPath = pinFile?.Path; - Exception? exception = Validate(targetServerName, hostNameInCertificate, nullCert ? null : serverCert, pinPath, policyErrors, chain, out ServerCertificateVerdict verdict); + // Act + Exception? exception = Validate(targetServerName, hostNameInCertificate, + nullCert ? null : serverCert, pinPath, policyErrors, chain, + out ServerCertificateVerdict verdict); + // Assert if (expectSuccess) { Assert.Null(exception); @@ -116,7 +169,9 @@ public void ValidateSslServerCertificate_RecordsEffectiveVerdict( if (expectChainFromCallback) { - X509ChainStatusFlags? expectedChain = chain is null ? null : SniCommon.CombineChainStatus(chain.ChainStatus, policyErrors); + X509ChainStatusFlags? expectedChain = chain is null + ? null + : SniCommon.CombineChainStatus(chain.ChainStatus, policyErrors); Assert.Equal(expectedChain, verdict.ChainStatus); } else @@ -125,9 +180,14 @@ public void ValidateSslServerCertificate_RecordsEffectiveVerdict( } } + /// + /// An untrusted callback chain is reported as the OR of the chain's own status flags, + /// without rebuilding the chain. + /// [Fact] public void ValidateSslServerCertificate_UntrustedChain_ReportsOriginalCallbackFlags() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); using X509Chain chain = CreateChain(ChainKind.Untrusted, serverCert)!; @@ -138,70 +198,96 @@ public void ValidateSslServerCertificate_UntrustedChain_ReportsOriginalCallbackF } Assert.NotEqual(X509ChainStatusFlags.NoError, expected); - Validate(ServerName, null, serverCert, null, SslPolicyErrors.RemoteCertificateChainErrors, chain, out ServerCertificateVerdict verdict); + // Act + Validate(ServerName, null, serverCert, null, + SslPolicyErrors.RemoteCertificateChainErrors, chain, + out ServerCertificateVerdict verdict); + // Assert Assert.Equal(expected, verdict.ChainStatus); } + /// + /// A clean callback chain is reported as , which + /// is distinct from the null reported when the callback supplies no chain. + /// [Fact] public void ValidateSslServerCertificate_CleanChain_ReportsNoErrorDistinctFromUnavailable() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); using X509Chain chain = CreateChain(ChainKind.Clean, serverCert)!; - Validate(ServerName, null, serverCert, null, SslPolicyErrors.None, chain, out ServerCertificateVerdict verdict); + // Act + Validate(ServerName, null, serverCert, null, SslPolicyErrors.None, chain, + out ServerCertificateVerdict verdict); + Validate(ServerName, null, serverCert, null, SslPolicyErrors.None, callbackChain: null, + out ServerCertificateVerdict noChain); + // Assert Assert.Equal(SqlServerCertificateValidationErrors.None, verdict.ValidationErrors); Assert.Equal(X509ChainStatusFlags.NoError, verdict.ChainStatus); - - Validate(ServerName, null, serverCert, null, SslPolicyErrors.None, callbackChain: null, out ServerCertificateVerdict noChain); Assert.Equal(SqlServerCertificateValidationErrors.None, noChain.ValidationErrors); Assert.Null(noChain.ChainStatus); } + /// + /// When the pinned certificate file cannot be loaded, SqlClient never evaluates the + /// presented certificate, so no verdict is recorded. + /// [Fact] public void ValidateSslServerCertificate_UnreadablePin_VerdictNotEvaluated() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); - string missingPath = Path.Combine(Path.GetTempPath(), "SqlClient_MissingPin_" + Guid.NewGuid().ToString("N") + ".cer"); + string missingPath = Path.Combine(Path.GetTempPath(), + "SqlClient_MissingPin_" + Guid.NewGuid().ToString("N") + ".cer"); - Exception? exception = Validate(ServerName, null, serverCert, missingPath, SslPolicyErrors.None, null, out ServerCertificateVerdict verdict); + // Act + Exception? exception = Validate(ServerName, null, serverCert, missingPath, + SslPolicyErrors.None, null, out ServerCertificateVerdict verdict); + // Assert Assert.IsType(exception); + Assert.Equal( + StringsHelper.GetString(Strings.SQL_ServerCertificateFileLoadFailed, missingPath), + exception!.Message); Assert.Null(verdict.ValidationErrors); Assert.Null(verdict.ChainStatus); } /// - /// Managed SNI named pipes pass "." as the target server name. MatchesHostname rejects it with - /// an , which predates encryption info capture. Errors already - /// established must still be captured, and the exception must stay exactly as it was. + /// Managed SNI named pipes pass "." as the target server name. MatchesHostname rejects it + /// with an , which predates encryption info capture. Errors + /// already established must still be captured, and the exception must be the one that + /// MatchesHostname itself throws. /// [Theory] - [InlineData(SslPolicyErrors.RemoteCertificateChainErrors | SslPolicyErrors.RemoteCertificateNameMismatch, true)] + [InlineData(SslPolicyErrors.RemoteCertificateChainErrors + | SslPolicyErrors.RemoteCertificateNameMismatch, true)] [InlineData(SslPolicyErrors.RemoteCertificateNameMismatch, false)] - public void ValidateSslServerCertificate_NamedPipeDotTarget_CapturesKnownErrorsAndKeepsException(SslPolicyErrors policyErrors, bool chainErrors) + public void ValidateSslServerCertificate_NamedPipeDotTarget_CapturesKnownErrorsAndKeepsException( + SslPolicyErrors policyErrors, bool chainErrors) { + // Arrange const string NamedPipeTarget = "."; using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); - using X509Chain chain = CreateChain(chainErrors ? ChainKind.Untrusted : ChainKind.Clean, serverCert)!; + using X509Chain chain = CreateChain( + chainErrors ? ChainKind.Untrusted : ChainKind.Clean, serverCert)!; - Exception? legacy = null; - try - { - SniCommon.ValidateSslServerCertificate(Guid.NewGuid(), NamedPipeTarget, null, serverCert, null, policyErrors); - } - catch (Exception e) - { - legacy = e; - } + // The exception that the host name check itself throws, independent of SqlClient. + ArgumentException expected = Assert.ThrowsAny( + () => serverCert.MatchesHostname(NamedPipeTarget)); - Exception? capturing = Validate(NamedPipeTarget, null, serverCert, null, policyErrors, chain, out ServerCertificateVerdict verdict); + // Act + Exception? capturing = Validate(NamedPipeTarget, null, serverCert, null, policyErrors, + chain, out ServerCertificateVerdict verdict); + // Assert // The pre-existing exception is neither caught nor changed. - Assert.IsAssignableFrom(legacy); - Assert.Equal(legacy!.GetType(), capturing?.GetType()); - Assert.Equal(legacy.Message, capturing!.Message); + Assert.NotNull(capturing); + Assert.Equal(expected.GetType(), capturing!.GetType()); + Assert.Equal(expected.Message, capturing.Message); if (chainErrors) { @@ -219,7 +305,9 @@ public void ValidateSslServerCertificate_NamedPipeDotTarget_CapturesKnownErrorsA } /// - /// Capturing the verdict must not change the outcome or the message of validation. + /// Capturing the verdict must not change the outcome or the message of validation. The + /// expected outcome is an independent restatement of the validation rules that predate + /// capture, so a change shared by both overloads is still detected. /// [Theory] [MemberData(nameof(VerdictCases))] @@ -237,6 +325,7 @@ public void ValidateSslServerCertificate_CaptureDoesNotChangeOutcomeOrMessage( _ = expectedErrors; _ = expectChainFromCallback; + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); using X509Certificate2 otherCert = CreateSelfSignedCertificate("other.contoso.com"); using X509Chain? chain = CreateChain(chainKind, serverCert); @@ -247,23 +336,25 @@ public void ValidateSslServerCertificate_CaptureDoesNotChangeOutcomeOrMessage( _ => null, }; X509Certificate2? cert = nullCert ? null : serverCert; + string? expectedMessage = ExpectedMessage(targetServerName, hostNameInCertificate, cert, + pinKind, policyErrors); - Exception? legacy = null; - try + // Act + Exception? capturing = Validate(targetServerName, hostNameInCertificate, cert, + pinFile?.Path, policyErrors, chain, out ServerCertificateVerdict verdict); + + // Assert + Assert.Equal(expectSuccess, expectedMessage is null); + if (expectedMessage is null) { - SniCommon.ValidateSslServerCertificate(Guid.NewGuid(), targetServerName, hostNameInCertificate, cert, pinFile?.Path, policyErrors); + Assert.Null(capturing); } - catch (Exception e) + else { - legacy = e; + Assert.IsType(capturing); + Assert.Equal(expectedMessage, capturing!.Message); } - Exception? capturing = Validate(targetServerName, hostNameInCertificate, cert, pinFile?.Path, policyErrors, chain, out ServerCertificateVerdict verdict); - - Assert.Equal(expectSuccess, legacy is null); - Assert.Equal(legacy?.GetType(), capturing?.GetType()); - Assert.Equal(legacy?.Message, capturing?.Message); - if (capturing is not null && cert is not null) { ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(cert, verdict); @@ -272,13 +363,23 @@ public void ValidateSslServerCertificate_CaptureDoesNotChangeOutcomeOrMessage( } } + /// + /// The capture holds its own copy of the DER encoding of the presented certificate, + /// alongside the verdict it was created with. + /// [Fact] public void CreateServerCertificateCapture_CapturesDer() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); + ServerCertificateVerdict verdict = new( + SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError); - ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, new ServerCertificateVerdict(SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError)); + // Act + ServerCertificateCapture capture = + SniCommon.CreateServerCertificateCapture(serverCert, verdict); + // Assert Assert.NotNull(capture.RawCertificate); Assert.Equal(serverCert.Export(X509ContentType.Cert), capture.RawCertificate); Assert.Equal(SqlServerCertificateValidationErrors.None, capture.ValidationErrors); @@ -289,136 +390,221 @@ public void CreateServerCertificateCapture_CapturesDer() Assert.NotEqual(capture.RawCertificate, serverCert.RawData); } + /// + /// A certificate larger than the capture size cap is not captured, while the verdict + /// captured with it is kept. + /// [Fact] public void CreateServerCertificateCapture_OverSizeCap_CertificateUnavailable() { - using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, ServerCertificateCapture.MaxRawCertificateSize); + // Arrange + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, + ServerCertificateCapture.MaxRawCertificateSize); Assert.True(serverCert.RawData.Length > ServerCertificateCapture.MaxRawCertificateSize); + ServerCertificateVerdict verdict = new( + SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot); - ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture( - serverCert, - new ServerCertificateVerdict(SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + // Act + ServerCertificateCapture capture = + SniCommon.CreateServerCertificateCapture(serverCert, verdict); + // Assert // Only the certificate is dropped; the other captured values are unaffected. Assert.Null(capture.RawCertificate); Assert.Equal(SqlServerCertificateValidationErrors.ChainError, capture.ValidationErrors); Assert.Equal(X509ChainStatusFlags.UntrustedRoot, capture.ChainStatus); } + /// + /// A certificate within the capture size cap is captured. + /// [Fact] public void CreateServerCertificateCapture_AtSizeCap_CertificateCaptured() { - using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, ServerCertificateCapture.MaxRawCertificateSize / 2); - Assert.InRange(serverCert.RawData.Length, 1, ServerCertificateCapture.MaxRawCertificateSize); + // Arrange + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, + ServerCertificateCapture.MaxRawCertificateSize / 2); + Assert.InRange(serverCert.RawData.Length, 1, + ServerCertificateCapture.MaxRawCertificateSize); + + // Act + byte[]? rawCertificate = SniCommon.GetRawCertificate(serverCert); - Assert.Equal(serverCert.RawData, SniCommon.GetRawCertificate(serverCert)); + // Assert + Assert.Equal(serverCert.RawData, rawCertificate); } + /// + /// The first certificate presented in an attempt is kept, while the verdict is the most + /// recent one. A previous capture without a certificate does not block a later one. + /// [Fact] public void CreateServerCertificateCapture_FirstCertificateWins() { + // Arrange using X509Certificate2 first = CreateSelfSignedCertificate(ServerName); using X509Certificate2 second = CreateSelfSignedCertificate("other.contoso.com"); - ServerCertificateCapture previous = SniCommon.CreateServerCertificateCapture(first, default); + ServerCertificateCapture empty = SniCommon.CreateServerCertificateCapture(null!, default); + ServerCertificateVerdict verdict = new( + SqlServerCertificateValidationErrors.HostNameMismatch, X509ChainStatusFlags.NoError); + + // Act ServerCertificateCapture next = SniCommon.CreateServerCertificateCapture( - second, - new ServerCertificateVerdict(SqlServerCertificateValidationErrors.HostNameMismatch, X509ChainStatusFlags.NoError), - sender: null, - previous: previous); + second, verdict, sender: null, previous: previous); + ServerCertificateCapture afterEmpty = SniCommon.CreateServerCertificateCapture( + second, default, previous: empty); - // The certificate stays the first one presented in the attempt; the verdict is the latest. + // Assert Assert.Equal(first.RawData, next.RawCertificate); Assert.Equal(SqlServerCertificateValidationErrors.HostNameMismatch, next.ValidationErrors); - - // A previous capture without a certificate does not block capturing a later one. - ServerCertificateCapture empty = SniCommon.CreateServerCertificateCapture(null!, default); - Assert.Equal(second.RawData, SniCommon.CreateServerCertificateCapture(second, default, previous: empty).RawCertificate); + Assert.Equal(second.RawData, afterEmpty.RawCertificate); } + /// + /// With TrustServerCertificate, validation never runs, so only the certificate is + /// captured and the verdict stays unavailable. + /// [Fact] public void CreateServerCertificateCapture_Bypass_CertificateOnly() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); - // TrustServerCertificate bypass: validation is never run, so the verdict stays default. - ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, default); + // Act + ServerCertificateCapture capture = + SniCommon.CreateServerCertificateCapture(serverCert, default); + // Assert Assert.Equal(serverCert.RawData, capture.RawCertificate); Assert.Null(capture.ValidationErrors); Assert.Null(capture.ChainStatus); Assert.Null(capture.Protocol); } + /// + /// When the callback sender is not an , the protocol and cipher + /// suite are unavailable. + /// [Fact] public void CreateServerCertificateCapture_SenderNotSslStream_ProtocolUnavailable() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); - ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(serverCert, default, new object()); + // Act + ServerCertificateCapture capture = + SniCommon.CreateServerCertificateCapture(serverCert, default, new object()); + // Assert Assert.Null(capture.Protocol); Assert.Null(capture.CipherSuite); } + /// + /// Reading the cipher suite without a stream, or before any handshake, neither throws nor + /// reports the null cipher suite (0). + /// [Fact] public void GetNegotiatedCipherSuite_NoStreamOrNoHandshake_Unavailable() { - Assert.Null(SniCommon.GetNegotiatedCipherSuite(null!)); - - // Reading before any handshake must neither throw nor report the null cipher suite (0). + // Arrange using SslStream sslStream = new(new MemoryStream()); - Assert.Null(SniCommon.GetNegotiatedCipherSuite(sslStream)); + + // Act + int? noStream = SniCommon.GetNegotiatedCipherSuite(null!); + int? noHandshake = SniCommon.GetNegotiatedCipherSuite(sslStream); + + // Assert + Assert.Null(noStream); + Assert.Null(noHandshake); } + /// + /// A cipher suite carried by a certificate capture is adopted only when the attempt has + /// not already recorded one. + /// [Fact] public void RecordServerCertificate_CipherSuite_AdoptedOnlyWhenNotAlreadyRecorded() { + // Arrange EncryptionInfoCapture capture = new(); - capture.RecordServerCertificate(new ServerCertificateCapture(null, null, null, cipherSuite: 0xC030)); - Assert.Equal(0xC030, capture.CipherSuite); - EncryptionInfoCapture alreadyKnown = new(); alreadyKnown.RecordCipherSuite(0x1301); - alreadyKnown.RecordServerCertificate(new ServerCertificateCapture(null, null, null, cipherSuite: 0xC030)); + ServerCertificateCapture fromCallback = new(null, null, null, cipherSuite: 0xC030); + + // Act + capture.RecordServerCertificate(fromCallback); + alreadyKnown.RecordServerCertificate(fromCallback); + + // Assert + Assert.Equal(0xC030, capture.CipherSuite); Assert.Equal(0x1301, alreadyKnown.CipherSuite); } + /// + /// When no certificate is presented, the certificate is unavailable and the verdict is + /// kept. + /// [Fact] public void CreateServerCertificateCapture_NoCertificate_CertificateUnavailable() { - ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture( - null!, - new ServerCertificateVerdict(SqlServerCertificateValidationErrors.ServerCertificateMissing, null)); + // Arrange + ServerCertificateVerdict verdict = new( + SqlServerCertificateValidationErrors.ServerCertificateMissing, null); + + // Act + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(null!, verdict); + // Assert Assert.Null(capture.RawCertificate); - Assert.Equal(SqlServerCertificateValidationErrors.ServerCertificateMissing, capture.ValidationErrors); + Assert.Equal(SqlServerCertificateValidationErrors.ServerCertificateMissing, + capture.ValidationErrors); Assert.Null(capture.ChainStatus); } - public static IEnumerable AllChainStatusFlags() + /// + /// Every value other than + /// . + /// + public static TheoryData AllChainStatusFlags() { + TheoryData data = new(); foreach (X509ChainStatusFlags flag in Enum.GetValues()) { if (flag != X509ChainStatusFlags.NoError) { - yield return new object[] { flag }; + data.Add(flag); } } + return data; } + /// + /// Each chain status flag is preserved when combining the callback chain status. + /// [Theory] [MemberData(nameof(AllChainStatusFlags))] public void CombineChainStatus_PreservesEachFlag(X509ChainStatusFlags flag) { + // Arrange X509ChainStatus[] statuses = { new() { Status = flag } }; - Assert.Equal(flag, SniCommon.CombineChainStatus(statuses, SslPolicyErrors.RemoteCertificateChainErrors)); + // Act + X509ChainStatusFlags? combined = SniCommon.CombineChainStatus(statuses, + SslPolicyErrors.RemoteCertificateChainErrors); + + // Assert + Assert.Equal(flag, combined); } + /// + /// All chain status flags are preserved together when combining the callback chain status. + /// [Fact] public void CombineChainStatus_PreservesFullFlagSet() { + // Arrange List statuses = new(); X509ChainStatusFlags all = X509ChainStatusFlags.NoError; foreach (X509ChainStatusFlags flag in Enum.GetValues()) @@ -427,55 +613,100 @@ public void CombineChainStatus_PreservesFullFlagSet() all |= flag; } - Assert.Equal(all, SniCommon.CombineChainStatus(statuses.ToArray(), SslPolicyErrors.RemoteCertificateChainErrors)); + // Act + X509ChainStatusFlags? combined = SniCommon.CombineChainStatus(statuses.ToArray(), + SslPolicyErrors.RemoteCertificateChainErrors); + + // Assert + Assert.Equal(all, combined); } + /// + /// A chain without status entries is reported as clean unless the platform reported chain + /// errors, which the empty chain cannot describe. + /// [Fact] public void CombineChainStatus_NoEntries_NoErrorUnlessChainErrorsReported() { - Assert.Equal(X509ChainStatusFlags.NoError, SniCommon.CombineChainStatus(Array.Empty(), SslPolicyErrors.None)); - Assert.Equal(X509ChainStatusFlags.NoError, SniCommon.CombineChainStatus(Array.Empty(), SslPolicyErrors.RemoteCertificateNameMismatch)); - Assert.Null(SniCommon.CombineChainStatus(Array.Empty(), SslPolicyErrors.RemoteCertificateChainErrors)); + // Act + X509ChainStatusFlags? none = SniCommon.CombineChainStatus( + Array.Empty(), SslPolicyErrors.None); + X509ChainStatusFlags? nameMismatch = SniCommon.CombineChainStatus( + Array.Empty(), SslPolicyErrors.RemoteCertificateNameMismatch); + X509ChainStatusFlags? chainErrors = SniCommon.CombineChainStatus( + Array.Empty(), SslPolicyErrors.RemoteCertificateChainErrors); + + // Assert + Assert.Equal(X509ChainStatusFlags.NoError, none); + Assert.Equal(X509ChainStatusFlags.NoError, nameMismatch); + Assert.Null(chainErrors); } + /// + /// Without a callback chain, the chain status is unavailable. + /// [Fact] public void GetChainStatus_NullChain_Unavailable() { - Assert.Null(SniCommon.GetChainStatus(null!, SslPolicyErrors.RemoteCertificateChainErrors)); - Assert.Null(SniCommon.GetChainStatus(null!, SslPolicyErrors.None)); + // Act + X509ChainStatusFlags? chainErrors = + SniCommon.GetChainStatus(null!, SslPolicyErrors.RemoteCertificateChainErrors); + X509ChainStatusFlags? none = SniCommon.GetChainStatus(null!, SslPolicyErrors.None); + + // Assert + Assert.Null(chainErrors); + Assert.Null(none); } /// /// Capture reports the chain exactly as supplied to the callback; it does not build or - /// re-evaluate it. A chain that was never built carries no status, so the chain errors reported - /// by the platform cannot be described and the status is unavailable. + /// re-evaluate it. A chain that was never built carries no status, so the chain errors + /// reported by the platform cannot be described and the status is unavailable. /// [Fact] public void GetChainStatus_DoesNotBuildChain() { + // Arrange using X509Chain unbuilt = new(); - Assert.Null(SniCommon.GetChainStatus(unbuilt, SslPolicyErrors.RemoteCertificateChainErrors)); + // Act + X509ChainStatusFlags? status = + SniCommon.GetChainStatus(unbuilt, SslPolicyErrors.RemoteCertificateChainErrors); + + // Assert + Assert.Null(status); Assert.Empty(unbuilt.ChainElements); } #region EncryptionInfoCapture + /// + /// A recorded certificate capture is published in the snapshot, round-trips through + /// , and is cleared by + /// . + /// [Fact] public void EncryptionInfoCapture_RecordServerCertificate_PublishesInSnapshot() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); EncryptionInfoCapture capture = new(); - capture.RecordServerCertificate(new ServerCertificateCapture(SniCommon.GetRawCertificate(serverCert), SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + // Act + capture.RecordServerCertificate(new ServerCertificateCapture( + SniCommon.GetRawCertificate(serverCert), + SqlServerCertificateValidationErrors.ChainError, + X509ChainStatusFlags.UntrustedRoot)); + SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); + // Assert Assert.True(capture.HasValues); Assert.Equal(serverCert.RawData, capture.ServerCertificateRawData); - SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); Assert.False(snapshot.IsEmpty); Assert.Null(snapshot.NegotiatedEncryptionMode); Assert.Null(snapshot.NegotiatedEncryptionProtocol); - Assert.Equal(serverCert.RawData, snapshot.PresentedServerCertificateRawData!.Value.ToArray()); + Assert.Equal(serverCert.RawData, + snapshot.PresentedServerCertificateRawData!.Value.ToArray()); using (X509Certificate2? roundTripped = snapshot.GetServerCertificate()) { Assert.NotNull(roundTripped); @@ -485,43 +716,68 @@ public void EncryptionInfoCapture_RecordServerCertificate_PublishesInSnapshot() Assert.Equal(SqlServerCertificateValidationErrors.ChainError, snapshot.ValidationErrors); Assert.Equal(X509ChainStatusFlags.UntrustedRoot, snapshot.ChainStatus); + // Reset clears the attempt. capture.Reset(); Assert.False(capture.HasValues); Assert.Same(SqlConnectionEncryptionInfo.Empty, capture.ToSnapshot()); } + /// + /// Zero values (no errors, a clean chain) are available values, distinct from null. + /// [Fact] public void EncryptionInfoCapture_ZeroValuesAreAvailable() { + // Arrange EncryptionInfoCapture capture = new(); - capture.RecordServerCertificate(new ServerCertificateCapture(null, SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError)); - Assert.True(capture.HasValues); + // Act + capture.RecordServerCertificate(new ServerCertificateCapture(null, + SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError)); SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); + + // Assert + Assert.True(capture.HasValues); Assert.Equal(SqlServerCertificateValidationErrors.None, snapshot.ValidationErrors); Assert.Equal(X509ChainStatusFlags.NoError, snapshot.ChainStatus); Assert.Null(snapshot.PresentedServerCertificateRawData); Assert.Null(snapshot.GetServerCertificate()); } + /// + /// Recording a null capture leaves the certificate fields unavailable. + /// [Fact] public void EncryptionInfoCapture_NullCapture_LeavesCertificateFieldsUnavailable() { + // Arrange EncryptionInfoCapture capture = new(); + + // Act capture.RecordServerCertificate(null); + // Assert Assert.False(capture.HasValues); Assert.Same(SqlConnectionEncryptionInfo.Empty, capture.ToSnapshot()); } + /// + /// The snapshot's text never contains the certificate, any encoding of it, or its + /// thumbprint. + /// [Fact] public void EncryptionInfoCapture_CertificateNotInSnapshotText() { + // Arrange using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); EncryptionInfoCapture capture = new(); - capture.RecordServerCertificate(new ServerCertificateCapture(serverCert.RawData, SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + capture.RecordServerCertificate(new ServerCertificateCapture(serverCert.RawData, + SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); + // Act string text = capture.ToSnapshot().ToString() ?? string.Empty; + + // Assert AssertNoLeak(serverCert.RawData, text); Assert.DoesNotContain(serverCert.Thumbprint, text, StringComparison.OrdinalIgnoreCase); } @@ -530,6 +786,9 @@ public void EncryptionInfoCapture_CertificateNotInSnapshotText() #region Helpers + /// + /// Runs the capturing validation overload and returns the exception it throws, if any. + /// private static Exception? Validate( string targetServerName, string? hostNameInCertificate, @@ -542,7 +801,9 @@ public void EncryptionInfoCapture_CertificateNotInSnapshotText() verdict = default; try { - SniCommon.ValidateSslServerCertificate(Guid.NewGuid(), targetServerName, hostNameInCertificate, serverCert, pinPath, policyErrors, callbackChain, ref verdict); + SniCommon.ValidateSslServerCertificate(Guid.NewGuid(), targetServerName, + hostNameInCertificate, serverCert, pinPath, policyErrors, callbackChain, + ref verdict); return null; } catch (Exception e) @@ -551,6 +812,84 @@ public void EncryptionInfoCapture_CertificateNotInSnapshotText() } } + /// + /// Computes the validation failure message that managed SNI produced before encryption + /// info capture was added, or when validation succeeds. This + /// restates those rules independently of the product code so that a change to the + /// outcome or the message is detected. + /// + private static string? ExpectedMessage( + string targetServerName, + string? hostNameInCertificate, + X509Certificate2? serverCert, + PinKind pinKind, + SslPolicyErrors policyErrors) + { + bool hasHostNameInCertificate = !string.IsNullOrEmpty(hostNameInCertificate); + bool certificateMissing = serverCert is null + || policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable); + + // A pin replaces the platform verdict with an exact comparison. + if (pinKind != PinKind.None) + { + Assert.NotEqual(PinKind.Unreadable, pinKind); + if (certificateMissing) + { + return Strings.SQL_ServerCertificateNotAvailable; + } + return pinKind == PinKind.Match + ? null + : Strings.SQL_RemoteCertificateDoesNotMatchServerCertificate; + } + + if (!hasHostNameInCertificate && policyErrors == SslPolicyErrors.None) + { + return null; + } + + StringBuilder message = new(); + if (certificateMissing) + { + message.AppendLine(Strings.SQL_RemoteCertificateNotAvailable); + } + + if (serverCert is not null + && policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors)) + { + // The message describes a chain rebuilt with offline revocation checking. + using X509Chain chain = new(); + chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline; + StringBuilder chainStatusInformation = new(); + if (!chain.Build(serverCert)) + { + foreach (X509ChainStatus chainStatus in chain.ChainStatus) + { + chainStatusInformation.Append( + $"{chainStatus.StatusInformation}, [Status: {chainStatus.Status}]"); + chainStatusInformation.AppendLine(); + } + } + message.AppendFormat(Strings.SQL_RemoteCertificateChainErrors, + chainStatusInformation); + message.AppendLine(); + } + + if (serverCert is not null + && (hasHostNameInCertificate + || policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch)) + && !serverCert.MatchesHostname( + hasHostNameInCertificate ? hostNameInCertificate! : targetServerName)) + { + message.AppendLine(Strings.SQL_RemoteCertificateNameMismatch); + } + + return message.Length > 0 ? message.ToString() : null; + } + + /// + /// Creates the chain that a test passes to the validation callback, built against the + /// certificate so that its status reflects . + /// private static X509Chain? CreateChain(ChainKind kind, X509Certificate2 certificate) { if (kind == ChainKind.None) @@ -571,23 +910,35 @@ public void EncryptionInfoCapture_CertificateNotInSnapshotText() return chain; } + /// + /// Asserts that the text contains no hexadecimal, Base64, or hash encoding of the + /// certificate. + /// private static void AssertNoLeak(byte[] certificate, string text) { - Assert.DoesNotContain(Convert.ToHexString(certificate), text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(Convert.ToHexString(certificate), text, + StringComparison.OrdinalIgnoreCase); Assert.DoesNotContain(Convert.ToBase64String(certificate), text, StringComparison.Ordinal); - Assert.DoesNotContain(BitConverter.ToString(certificate), text, StringComparison.OrdinalIgnoreCase); - Assert.DoesNotContain(Convert.ToHexString(SHA256.HashData(certificate)), text, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(BitConverter.ToString(certificate), text, + StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(Convert.ToHexString(SHA256.HashData(certificate)), text, + StringComparison.OrdinalIgnoreCase); } + /// + /// Creates a self-signed certificate for . + /// /// The subject and DNS SAN. /// /// When non-zero, adds a private, non-critical extension of this many bytes to grow the DER /// encoding (used to test the capture size cap). /// - private static X509Certificate2 CreateSelfSignedCertificate(string subjectCommonName, int paddingBytes = 0) + private static X509Certificate2 CreateSelfSignedCertificate(string subjectCommonName, + int paddingBytes = 0) { using RSA rsa = RSA.Create(2048); - CertificateRequest request = new($"CN={subjectCommonName}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); + CertificateRequest request = new($"CN={subjectCommonName}", rsa, + HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); SubjectAlternativeNameBuilder san = new(); san.AddDnsName(subjectCommonName); request.CertificateExtensions.Add(san.Build()); @@ -596,23 +947,38 @@ private static X509Certificate2 CreateSelfSignedCertificate(string subjectCommon // A DER OCTET STRING keeps the extension value well-formed. System.Formats.Asn1.AsnWriter writer = new(System.Formats.Asn1.AsnEncodingRules.DER); writer.WriteOctetString(new byte[paddingBytes]); - request.CertificateExtensions.Add(new X509Extension("1.3.6.1.4.1.311.999.1", writer.Encode(), critical: false)); + request.CertificateExtensions.Add( + new X509Extension("1.3.6.1.4.1.311.999.1", writer.Encode(), critical: false)); } DateTimeOffset notBefore = DateTimeOffset.UtcNow.AddMinutes(-5); return request.CreateSelfSigned(notBefore, notBefore.AddHours(1)); } + /// + /// A certificate exported to a temporary file for use as a ServerCertificate pin, + /// deleted on dispose. + /// private sealed class TempCertFile : IDisposable { + /// + /// Exports to a new temporary file. + /// public TempCertFile(X509Certificate2 cert) { - Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SqlClient_CapturePin_" + Guid.NewGuid().ToString("N") + ".cer"); + Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), + "SqlClient_CapturePin_" + Guid.NewGuid().ToString("N") + ".cer"); File.WriteAllBytes(Path, cert.Export(X509ContentType.Cert)); } + /// + /// The path of the temporary file. + /// public string Path { get; } + /// + /// Deletes the temporary file, ignoring failures. + /// public void Dispose() { try diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs index 2b5054fed5..0c74c940f8 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -26,10 +26,15 @@ namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests /// public sealed class ManagedSniCaptureCertificateFixture : CertificateFixtureBase { + /// + /// Creates the "localhost" certificate and a certificate for an unrelated host name. + /// public ManagedSniCaptureCertificateFixture() { - Localhost = CreateCertificate("localhost", new[] { "localhost" }, new[] { "127.0.0.1" }); - OtherHost = CreateCertificate("other.contoso.com", Array.Empty(), Array.Empty()); + Localhost = CreateCertificate( + "localhost", new[] { "localhost" }, new[] { "127.0.0.1" }); + OtherHost = CreateCertificate( + "other.contoso.com", Array.Empty(), Array.Empty()); } /// A certificate whose names match the "localhost" data source. @@ -50,22 +55,32 @@ public class ManagedSniCertificateCaptureTests : IClassFixtureReceives the shared server certificates. public ManagedSniCertificateCaptureTests(ManagedSniCaptureCertificateFixture fixture) { _fixture = fixture; } + /// + /// With TrustServerCertificate, the presented certificate, mode, protocol and the + /// SslStream's cipher suite are published, but no verdict or chain status, because + /// SqlClient did not evaluate the certificate. + /// [Theory] [InlineData(false)] [InlineData(true)] public async Task Open_TrustServerCertificate_PublishesCertificateWithoutVerdict(bool async) { + // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.Localhost); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); - using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); + // Act await OpenAsync(connection, async); + // Assert SqlConnectionEncryptionInfo info = connection.EncryptionInfo; Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); @@ -78,18 +93,26 @@ public async Task Open_TrustServerCertificate_PublishesCertificateWithoutVerdict Assert.Equal(GetClientSslStreamCipherSuite(connection), info.NegotiatedCipherSuiteId); } + /// + /// A matching ServerCertificate pin publishes the certificate with no validation errors + /// and no chain status, because the pin, not the chain, decides trust. + /// [Theory] [InlineData(false)] [InlineData(true)] public async Task Open_MatchingServerCertificate_PublishesCertificateAndNoErrors(bool async) { + // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.Localhost); using TempCertFile pin = new(_fixture.Localhost); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); - using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + // Act await OpenAsync(connection, async); + // Assert SqlConnectionEncryptionInfo info = connection.EncryptionInfo; Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); @@ -99,111 +122,260 @@ public async Task Open_MatchingServerCertificate_PublishesCertificateAndNoErrors Assert.Null(info.ChainStatus); } + /// + /// An untrusted self-signed certificate fails the open; the exception carries the + /// certificate, ChainError, a non-clean chain status and the observed negotiation, the + /// connection itself stays empty, and nothing leaks into the message. + /// [Theory] [InlineData(false)] [InlineData(true)] public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndCertificate(bool async) { + // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); - using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); - SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); + // Act + SqlException ex = await Assert.ThrowsAsync( + () => OpenAsync(connection, async)); + + // Assert SqlConnectionEncryptionInfo info = ex.EncryptionInfo; AssertCertificate(_fixture.Localhost, info); Assert.Equal(SqlServerCertificateValidationErrors.ChainError, info.ValidationErrors); Assert.NotNull(info.ChainStatus); Assert.NotEqual(X509ChainStatusFlags.NoError, info.ChainStatus); - // Certificate validation failed after the protocol was agreed; the observed values are kept. + // Certificate validation failed after the protocol was agreed; the observed values + // are kept. AssertObservedNegotiation(info); Assert.True(connection.EncryptionInfo.IsEmpty); AssertNoLeak(ex, info); - // The suite read inside the validation callback is the real one: a trusted handshake with the - // same server and protocol negotiates the same suite. - using SqlConnection trusted = new(BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); + // The suite read inside the validation callback is the real one: a trusted handshake + // with the same server and protocol negotiates the same suite. + using SqlConnection trusted = new( + BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); await OpenAsync(trusted, async); Assert.Equal(GetClientSslStreamCipherSuite(trusted), info.NegotiatedCipherSuiteId); } + /// + /// A certificate whose names do not match the data source fails the open with both + /// ChainError and HostNameMismatch in the exception's verdict. + /// [Theory] [InlineData(false)] [InlineData(true)] public async Task Open_HostNameMismatch_ExceptionCarriesHostNameMismatch(bool async) { + // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); - using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); - SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); + // Act + SqlException ex = await Assert.ThrowsAsync( + () => OpenAsync(connection, async)); + + // Assert SqlConnectionEncryptionInfo info = ex.EncryptionInfo; AssertCertificate(_fixture.OtherHost, info); Assert.Equal( - SqlServerCertificateValidationErrors.ChainError | SqlServerCertificateValidationErrors.HostNameMismatch, + SqlServerCertificateValidationErrors.ChainError + | SqlServerCertificateValidationErrors.HostNameMismatch, info.ValidationErrors); Assert.NotNull(info.ChainStatus); AssertObservedNegotiation(info); AssertNoLeak(ex, info); } + /// + /// A HostNameInCertificate matching the certificate removes HostNameMismatch from the + /// effective verdict, leaving only ChainError. + /// [Theory] [InlineData(false)] [InlineData(true)] public async Task Open_HostNameInCertificateOverride_ReportsEffectiveVerdict(bool async) { + // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); - - using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, hostNameInCertificate: "other.contoso.com")); - SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); - - // The platform reported a name mismatch, but HostNameInCertificate resolves it; only the - // untrusted chain remains in SqlClient's effective verdict. - Assert.Equal(SqlServerCertificateValidationErrors.ChainError, ex.EncryptionInfo.ValidationErrors); + using SqlConnection connection = new(BuildConnectionString( + server.EndPoint.Port, hostNameInCertificate: "other.contoso.com")); + + // Act + SqlException ex = await Assert.ThrowsAsync( + () => OpenAsync(connection, async)); + + // Assert + // The platform reported a name mismatch, but HostNameInCertificate resolves it; only + // the untrusted chain remains in SqlClient's effective verdict. + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, + ex.EncryptionInfo.ValidationErrors); AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); AssertObservedNegotiation(ex.EncryptionInfo); } + /// + /// A ServerCertificate pin that does not match the presented certificate fails the open + /// with PinnedCertificateMismatch and no chain status. + /// [Theory] [InlineData(false)] [InlineData(true)] public async Task Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch(bool async) { + // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); using TempCertFile pin = new(_fixture.OtherHost); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); - using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); - SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(connection, async)); + // Act + SqlException ex = await Assert.ThrowsAsync( + () => OpenAsync(connection, async)); + // Assert SqlConnectionEncryptionInfo info = ex.EncryptionInfo; AssertCertificate(_fixture.Localhost, info); - Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, info.ValidationErrors); + Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, + info.ValidationErrors); Assert.Null(info.ChainStatus); AssertObservedNegotiation(info); AssertNoLeak(ex, info); } + /// + /// Within one login, a routed connection is a new attempt: the routing server's + /// certificate, presented first, is not published, and the terminal attempt's certificate + /// is. + /// [Theory] [InlineData(false)] [InlineData(true)] - public async Task Open_FailureThenSuccess_DoesNotCarryPreviousAttemptCertificate(bool async) + public async Task Open_Routed_PublishesOnlyTerminalAttemptCertificate(bool async) { + // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - using TdsServer otherServer = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); using TdsServer server = StartServer(_fixture.Localhost); - using TempCertFile pin = new(_fixture.Localhost); + using RoutingTdsServer router = StartRouter(_fixture.OtherHost, server.EndPoint.Port); + using SqlConnection connection = new( + BuildConnectionString(router.EndPoint.Port, trustServerCertificate: true)); - using SqlConnection failing = new(BuildConnectionString(otherServer.EndPoint.Port, serverCertificate: pin.Path)); - SqlException ex = await Assert.ThrowsAsync(() => OpenAsync(failing, async)); - AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); + // Act + await OpenAsync(connection, async); + + // Assert + SqlConnectionEncryptionInfo info = connection.EncryptionInfo; + AssertCertificate(_fixture.Localhost, info); + Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); + Assert.Null(info.ValidationErrors); + Assert.Null(info.ChainStatus); + } + + /// + /// Within one login, when the routing server's certificate passes validation and the + /// routed server's certificate fails it, the exception reports only the terminal + /// attempt's certificate and verdict. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_RoutedTerminalAttemptFails_ExceptionCarriesOnlyTerminalAttempt( + bool async) + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); + using RoutingTdsServer router = StartRouter(_fixture.OtherHost, server.EndPoint.Port); + // The pin matches the routing server's certificate only. + using TempCertFile pin = new(_fixture.OtherHost); + using SqlConnection connection = new( + BuildConnectionString(router.EndPoint.Port, serverCertificate: pin.Path)); + + // Act + SqlException ex = await Assert.ThrowsAsync( + () => OpenAsync(connection, async)); + + // Assert + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + AssertCertificate(_fixture.Localhost, info); + Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, + info.ValidationErrors); + Assert.Null(info.ChainStatus); + AssertObservedNegotiation(info); + } - using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + /// + /// Within one login, when the routed attempt fails in pre-login, before any certificate + /// is presented, the exception carries nothing from the routing server's completed + /// handshake: each attempt starts with a clean capture. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_RoutedTerminalAttemptFailsBeforeTls_ExceptionCarriesNoCertificate( + bool async) + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + // The routed server omits encryption support from its pre-login response while the + // client demands encryption, so the routed attempt fails before TLS starts. + using TdsServer server = new(new TdsServerArguments + { + Encryption = TDSPreLoginTokenEncryptionType.None, + }); + server.Start(); + using RoutingTdsServer router = StartRouter(_fixture.OtherHost, server.EndPoint.Port); + using SqlConnection connection = new( + BuildConnectionString(router.EndPoint.Port, trustServerCertificate: true)); + + // Act + SqlException ex = await Assert.ThrowsAsync( + () => OpenAsync(connection, async)); + + // Assert + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + Assert.Null(info.PresentedServerCertificateRawData); + Assert.Null(info.GetServerCertificate()); + Assert.True(info.IsEmpty); + } + + /// + /// A failed open on one connection does not leak its certificate into a later open on a + /// different connection: each connection publishes only its own certificate. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task Open_FailureThenSuccessOnNewConnection_DoesNotCarryPreviousCertificate( + bool async) + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer otherServer = StartServer(_fixture.OtherHost, + expectTlsHandshakeFailure: true); + using TdsServer server = StartServer(_fixture.Localhost); + using TempCertFile pin = new(_fixture.Localhost); + using SqlConnection failing = new( + BuildConnectionString(otherServer.EndPoint.Port, serverCertificate: pin.Path)); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + + // Act + SqlException ex = await Assert.ThrowsAsync( + () => OpenAsync(failing, async)); await OpenAsync(connection, async); + + // Assert + AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); AssertCertificate(_fixture.Localhost, connection.EncryptionInfo); - Assert.Equal(SqlServerCertificateValidationErrors.None, connection.EncryptionInfo.ValidationErrors); + Assert.Equal(SqlServerCertificateValidationErrors.None, + connection.EncryptionInfo.ValidationErrors); } #region Helpers @@ -226,15 +398,21 @@ private static void AssertObservedNegotiation(SqlConnectionEncryptionInfo info) /// private static int GetClientSslStreamCipherSuite(SqlConnection connection) { - global::Microsoft.Data.SqlClient.ManagedSni.SniHandle handle = connection.Parser._physicalStateObj.SessionHandle.ManagedHandle; + global::Microsoft.Data.SqlClient.ManagedSni.SniHandle handle = + connection.Parser._physicalStateObj.SessionHandle.ManagedHandle; Assert.NotNull(handle); - FieldInfo? field = handle.GetType().GetField("_sslStream", BindingFlags.Instance | BindingFlags.NonPublic); + FieldInfo? field = handle.GetType().GetField( + "_sslStream", BindingFlags.Instance | BindingFlags.NonPublic); Assert.NotNull(field); SslStream? sslStream = field.GetValue(handle) as SslStream; Assert.NotNull(sslStream); return (int)sslStream.NegotiatedCipherSuite; } + /// + /// Forces managed SNI on Windows for the lifetime of the returned helper; returns null + /// elsewhere, where managed SNI is already the only implementation. + /// private static LocalAppContextSwitchesHelper? ForceManagedSni() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) @@ -269,6 +447,31 @@ private static TdsServer StartServer(X509Certificate2 certificate, bool expectTl return server; } + /// + /// Starts a TLS 1.2 simulated routing server that requires encryption and, after login, + /// routes every connection to the given local port. + /// + /// The certificate the routing server presents. + /// The local port of the server to route to. + private static RoutingTdsServer StartRouter(X509Certificate2 certificate, int routedPort) + { + RoutingTdsServer router = new(new RoutingTdsServerArguments + { + Encryption = TDSPreLoginTokenEncryptionType.Required, + EncryptionCertificate = certificate, + EncryptionProtocols = SslProtocols.Tls12, + RoutingTCPHost = "localhost", + RoutingTCPPort = (ushort)routedPort, + RequireReadOnly = false, + }); + router.Start(); + return router; + } + + /// + /// Builds a non-pooled, Encrypt=Mandatory connection string for a local simulated server, + /// with connection retry disabled so each test observes a single login. + /// private static string BuildConnectionString( int port, bool trustServerCertificate = false, @@ -295,6 +498,10 @@ private static string BuildConnectionString( return builder.ConnectionString; } + /// + /// Opens the connection with when + /// is true, otherwise with . + /// private static Task OpenAsync(SqlConnection connection, bool async) { if (async) @@ -306,6 +513,10 @@ private static Task OpenAsync(SqlConnection connection, bool async) return Task.CompletedTask; } + /// + /// Asserts that the published certificate is exactly the expected certificate's DER, both + /// as raw data and as a reconstructed certificate without a private key. + /// private static void AssertCertificate(X509Certificate2 expected, SqlConnectionEncryptionInfo info) { Assert.NotNull(info.PresentedServerCertificateRawData); @@ -317,10 +528,20 @@ private static void AssertCertificate(X509Certificate2 expected, SqlConnectionEn Assert.False(certificate.HasPrivateKey); } + /// + /// Asserts that neither the exception message nor its string form contains the captured + /// certificate in hexadecimal, Base64, dashed hexadecimal, or SHA-256 thumbprint form. + /// private static void AssertNoLeak(SqlException ex, SqlConnectionEncryptionInfo info) { byte[] der = info.PresentedServerCertificateRawData!.Value.ToArray(); - string[] encodings = { Convert.ToHexString(der), Convert.ToBase64String(der), BitConverter.ToString(der), Convert.ToHexString(SHA256.HashData(der)) }; + string[] encodings = + { + Convert.ToHexString(der), + Convert.ToBase64String(der), + BitConverter.ToString(der), + Convert.ToHexString(SHA256.HashData(der)), + }; foreach (string encoding in encodings) { Assert.DoesNotContain(encoding, ex.Message, StringComparison.OrdinalIgnoreCase); @@ -328,16 +549,27 @@ private static void AssertNoLeak(SqlException ex, SqlConnectionEncryptionInfo in } } + /// + /// A temporary DER certificate file usable as a ServerCertificate pin; deleted on + /// dispose. + /// private sealed class TempCertFile : IDisposable { + /// + /// Writes the public part of to a new temporary file. + /// public TempCertFile(X509Certificate2 certificate) { - Path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "SqlClient_CapturePin_" + Guid.NewGuid().ToString("N") + ".cer"); + Path = System.IO.Path.Combine( + System.IO.Path.GetTempPath(), + "SqlClient_CapturePin_" + Guid.NewGuid().ToString("N") + ".cer"); File.WriteAllBytes(Path, certificate.Export(X509ContentType.Cert)); } + /// The full path of the temporary certificate file. public string Path { get; } + /// Deletes the file, ignoring failures. public void Dispose() { try From e068e39eef06072909a4800ee0180c518cb55621 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Tue, 10 Nov 2026 21:29:25 +0530 Subject: [PATCH 08/12] Split Managed SNI capture simulator tests into Open and OpenAsync tests Replace the bool-async theories with separate Open_ and OpenAsync_ tests that call each API directly, sharing setup and scenario assertion helpers. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../ManagedSniCertificateCaptureTests.cs | 626 +++++++++++++----- 1 file changed, 453 insertions(+), 173 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs index 0c74c940f8..37eae4c112 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -60,16 +60,15 @@ public ManagedSniCertificateCaptureTests(ManagedSniCaptureCertificateFixture fix { _fixture = fixture; } + #region Successful opens /// - /// With TrustServerCertificate, the presented certificate, mode, protocol and the - /// SslStream's cipher suite are published, but no verdict or chain status, because - /// SqlClient did not evaluate the certificate. + /// With TrustServerCertificate, a synchronous open publishes the presented certificate, + /// mode, protocol and the SslStream's cipher suite, but no verdict or chain status, + /// because SqlClient did not evaluate the certificate. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_TrustServerCertificate_PublishesCertificateWithoutVerdict(bool async) + [Fact] + public void Open_TrustServerCertificate_PublishesCertificateWithoutVerdict() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -78,29 +77,40 @@ public async Task Open_TrustServerCertificate_PublishesCertificateWithoutVerdict BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); // Act - await OpenAsync(connection, async); + connection.Open(); // Assert - SqlConnectionEncryptionInfo info = connection.EncryptionInfo; - Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); - Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); - AssertCertificate(_fixture.Localhost, info); - // The certificate was presented but SqlClient did not evaluate it. - Assert.Null(info.ValidationErrors); - Assert.Null(info.ChainStatus); - // The published cipher suite is the one the client SslStream negotiated. - Assert.NotNull(info.NegotiatedCipherSuiteId); - Assert.Equal(GetClientSslStreamCipherSuite(connection), info.NegotiatedCipherSuiteId); + AssertTrustedCertificateSnapshot(connection); + } + + /// + /// With TrustServerCertificate, an asynchronous open publishes the presented certificate, + /// mode, protocol and the SslStream's cipher suite, but no verdict or chain status, + /// because SqlClient did not evaluate the certificate. + /// + [Fact] + public async Task OpenAsync_TrustServerCertificate_PublishesCertificateWithoutVerdict() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); + + // Act + await connection.OpenAsync(); + + // Assert + AssertTrustedCertificateSnapshot(connection); } /// - /// A matching ServerCertificate pin publishes the certificate with no validation errors - /// and no chain status, because the pin, not the chain, decides trust. + /// With a matching ServerCertificate pin, a synchronous open publishes the certificate + /// with no validation errors and no chain status, because the pin, not the chain, + /// decides trust. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_MatchingServerCertificate_PublishesCertificateAndNoErrors(bool async) + [Fact] + public void Open_MatchingServerCertificate_PublishesCertificateAndNoErrors() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -110,27 +120,45 @@ public async Task Open_MatchingServerCertificate_PublishesCertificateAndNoErrors BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); // Act - await OpenAsync(connection, async); + connection.Open(); // Assert - SqlConnectionEncryptionInfo info = connection.EncryptionInfo; - Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); - Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); - AssertCertificate(_fixture.Localhost, info); - Assert.Equal(SqlServerCertificateValidationErrors.None, info.ValidationErrors); - // The chain is not consulted when a ServerCertificate pin decides trust. - Assert.Null(info.ChainStatus); + AssertMatchingPinSnapshot(connection.EncryptionInfo); + } + + /// + /// With a matching ServerCertificate pin, an asynchronous open publishes the certificate + /// with no validation errors and no chain status, because the pin, not the chain, + /// decides trust. + /// + [Fact] + public async Task OpenAsync_MatchingServerCertificate_PublishesCertificateAndNoErrors() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + using TempCertFile pin = new(_fixture.Localhost); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + + // Act + await connection.OpenAsync(); + + // Assert + AssertMatchingPinSnapshot(connection.EncryptionInfo); } + #endregion + + #region Certificate validation failures + /// - /// An untrusted self-signed certificate fails the open; the exception carries the - /// certificate, ChainError, a non-clean chain status and the observed negotiation, the - /// connection itself stays empty, and nothing leaks into the message. + /// An untrusted self-signed certificate fails a synchronous open; the exception carries + /// the certificate, ChainError, a non-clean chain status and the observed negotiation, + /// the connection itself stays empty, and nothing leaks into the message. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndCertificate(bool async) + [Fact] + public void Open_UntrustedCertificate_ExceptionCarriesChainErrorAndCertificate() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -138,67 +166,92 @@ public async Task Open_UntrustedCertificate_ExceptionCarriesChainErrorAndCertifi using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); // Act - SqlException ex = await Assert.ThrowsAsync( - () => OpenAsync(connection, async)); + SqlException ex = Assert.Throws(() => connection.Open()); // Assert - SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - AssertCertificate(_fixture.Localhost, info); - Assert.Equal(SqlServerCertificateValidationErrors.ChainError, info.ValidationErrors); - Assert.NotNull(info.ChainStatus); - Assert.NotEqual(X509ChainStatusFlags.NoError, info.ChainStatus); - // Certificate validation failed after the protocol was agreed; the observed values - // are kept. - AssertObservedNegotiation(info); - Assert.True(connection.EncryptionInfo.IsEmpty); - AssertNoLeak(ex, info); + AssertUntrustedCertificateFailure(ex, connection); // The suite read inside the validation callback is the real one: a trusted handshake // with the same server and protocol negotiates the same suite. using SqlConnection trusted = new( BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); - await OpenAsync(trusted, async); - Assert.Equal(GetClientSslStreamCipherSuite(trusted), info.NegotiatedCipherSuiteId); + trusted.Open(); + Assert.Equal( + GetClientSslStreamCipherSuite(trusted), ex.EncryptionInfo.NegotiatedCipherSuiteId); } /// - /// A certificate whose names do not match the data source fails the open with both - /// ChainError and HostNameMismatch in the exception's verdict. + /// An untrusted self-signed certificate fails an asynchronous open; the exception carries + /// the certificate, ChainError, a non-clean chain status and the observed negotiation, + /// the connection itself stays empty, and nothing leaks into the message. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_HostNameMismatch_ExceptionCarriesHostNameMismatch(bool async) + [Fact] + public async Task OpenAsync_UntrustedCertificate_ExceptionCarriesChainErrorAndCertificate() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); // Act - SqlException ex = await Assert.ThrowsAsync( - () => OpenAsync(connection, async)); + SqlException ex = await Assert.ThrowsAsync(() => connection.OpenAsync()); // Assert - SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - AssertCertificate(_fixture.OtherHost, info); + AssertUntrustedCertificateFailure(ex, connection); + + // The suite read inside the validation callback is the real one: a trusted handshake + // with the same server and protocol negotiates the same suite. + using SqlConnection trusted = new( + BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); + await trusted.OpenAsync(); Assert.Equal( - SqlServerCertificateValidationErrors.ChainError - | SqlServerCertificateValidationErrors.HostNameMismatch, - info.ValidationErrors); - Assert.NotNull(info.ChainStatus); - AssertObservedNegotiation(info); - AssertNoLeak(ex, info); + GetClientSslStreamCipherSuite(trusted), ex.EncryptionInfo.NegotiatedCipherSuiteId); + } + + /// + /// A certificate whose names do not match the data source fails a synchronous open with + /// both ChainError and HostNameMismatch in the exception's verdict. + /// + [Fact] + public void Open_HostNameMismatch_ExceptionCarriesHostNameMismatch() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); + + // Act + SqlException ex = Assert.Throws(() => connection.Open()); + + // Assert + AssertHostNameMismatchFailure(ex); + } + + /// + /// A certificate whose names do not match the data source fails an asynchronous open with + /// both ChainError and HostNameMismatch in the exception's verdict. + /// + [Fact] + public async Task OpenAsync_HostNameMismatch_ExceptionCarriesHostNameMismatch() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); + + // Act + SqlException ex = await Assert.ThrowsAsync(() => connection.OpenAsync()); + + // Assert + AssertHostNameMismatchFailure(ex); } /// - /// A HostNameInCertificate matching the certificate removes HostNameMismatch from the - /// effective verdict, leaving only ChainError. + /// On a synchronous open, a HostNameInCertificate matching the certificate removes + /// HostNameMismatch from the effective verdict, leaving only ChainError. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_HostNameInCertificateOverride_ReportsEffectiveVerdict(bool async) + [Fact] + public void Open_HostNameInCertificateOverride_ReportsEffectiveVerdict() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -207,26 +260,38 @@ public async Task Open_HostNameInCertificateOverride_ReportsEffectiveVerdict(boo server.EndPoint.Port, hostNameInCertificate: "other.contoso.com")); // Act - SqlException ex = await Assert.ThrowsAsync( - () => OpenAsync(connection, async)); + SqlException ex = Assert.Throws(() => connection.Open()); // Assert - // The platform reported a name mismatch, but HostNameInCertificate resolves it; only - // the untrusted chain remains in SqlClient's effective verdict. - Assert.Equal(SqlServerCertificateValidationErrors.ChainError, - ex.EncryptionInfo.ValidationErrors); - AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); - AssertObservedNegotiation(ex.EncryptionInfo); + AssertHostNameOverrideFailure(ex); + } + + /// + /// On an asynchronous open, a HostNameInCertificate matching the certificate removes + /// HostNameMismatch from the effective verdict, leaving only ChainError. + /// + [Fact] + public async Task OpenAsync_HostNameInCertificateOverride_ReportsEffectiveVerdict() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.OtherHost, expectTlsHandshakeFailure: true); + using SqlConnection connection = new(BuildConnectionString( + server.EndPoint.Port, hostNameInCertificate: "other.contoso.com")); + + // Act + SqlException ex = await Assert.ThrowsAsync(() => connection.OpenAsync()); + + // Assert + AssertHostNameOverrideFailure(ex); } /// - /// A ServerCertificate pin that does not match the presented certificate fails the open - /// with PinnedCertificateMismatch and no chain status. + /// A ServerCertificate pin that does not match the presented certificate fails a + /// synchronous open with PinnedCertificateMismatch and no chain status. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch(bool async) + [Fact] + public void Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -236,28 +301,46 @@ public async Task Open_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch( BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); // Act - SqlException ex = await Assert.ThrowsAsync( - () => OpenAsync(connection, async)); + SqlException ex = Assert.Throws(() => connection.Open()); // Assert - SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - AssertCertificate(_fixture.Localhost, info); - Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, - info.ValidationErrors); - Assert.Null(info.ChainStatus); - AssertObservedNegotiation(info); - AssertNoLeak(ex, info); + AssertPinnedMismatchFailure(ex, _fixture.Localhost); + AssertNoLeak(ex, ex.EncryptionInfo); + } + + /// + /// A ServerCertificate pin that does not match the presented certificate fails an + /// asynchronous open with PinnedCertificateMismatch and no chain status. + /// + [Fact] + public async Task OpenAsync_ServerCertificateMismatch_ExceptionCarriesPinnedMismatch() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); + using TempCertFile pin = new(_fixture.OtherHost); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + + // Act + SqlException ex = await Assert.ThrowsAsync(() => connection.OpenAsync()); + + // Assert + AssertPinnedMismatchFailure(ex, _fixture.Localhost); + AssertNoLeak(ex, ex.EncryptionInfo); } + #endregion + + #region Per-attempt isolation + /// - /// Within one login, a routed connection is a new attempt: the routing server's - /// certificate, presented first, is not published, and the terminal attempt's certificate - /// is. + /// Within one synchronous login, a routed connection is a new attempt: the routing + /// server's certificate, presented first, is not published, and the terminal attempt's + /// certificate is. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_Routed_PublishesOnlyTerminalAttemptCertificate(bool async) + [Fact] + public void Open_Routed_PublishesOnlyTerminalAttemptCertificate() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -267,26 +350,41 @@ public async Task Open_Routed_PublishesOnlyTerminalAttemptCertificate(bool async BuildConnectionString(router.EndPoint.Port, trustServerCertificate: true)); // Act - await OpenAsync(connection, async); + connection.Open(); // Assert - SqlConnectionEncryptionInfo info = connection.EncryptionInfo; - AssertCertificate(_fixture.Localhost, info); - Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); - Assert.Null(info.ValidationErrors); - Assert.Null(info.ChainStatus); + AssertRoutedTerminalAttemptSnapshot(connection.EncryptionInfo); + } + + /// + /// Within one asynchronous login, a routed connection is a new attempt: the routing + /// server's certificate, presented first, is not published, and the terminal attempt's + /// certificate is. + /// + [Fact] + public async Task OpenAsync_Routed_PublishesOnlyTerminalAttemptCertificate() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + using RoutingTdsServer router = StartRouter(_fixture.OtherHost, server.EndPoint.Port); + using SqlConnection connection = new( + BuildConnectionString(router.EndPoint.Port, trustServerCertificate: true)); + + // Act + await connection.OpenAsync(); + + // Assert + AssertRoutedTerminalAttemptSnapshot(connection.EncryptionInfo); } /// - /// Within one login, when the routing server's certificate passes validation and the - /// routed server's certificate fails it, the exception reports only the terminal + /// Within one synchronous login, when the routing server's certificate passes validation + /// and the routed server's certificate fails it, the exception reports only the terminal /// attempt's certificate and verdict. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_RoutedTerminalAttemptFails_ExceptionCarriesOnlyTerminalAttempt( - bool async) + [Fact] + public void Open_RoutedTerminalAttemptFails_ExceptionCarriesOnlyTerminalAttempt() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -298,62 +396,114 @@ public async Task Open_RoutedTerminalAttemptFails_ExceptionCarriesOnlyTerminalAt BuildConnectionString(router.EndPoint.Port, serverCertificate: pin.Path)); // Act - SqlException ex = await Assert.ThrowsAsync( - () => OpenAsync(connection, async)); + SqlException ex = Assert.Throws(() => connection.Open()); // Assert - SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - AssertCertificate(_fixture.Localhost, info); - Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, - info.ValidationErrors); - Assert.Null(info.ChainStatus); - AssertObservedNegotiation(info); + AssertPinnedMismatchFailure(ex, _fixture.Localhost); } /// - /// Within one login, when the routed attempt fails in pre-login, before any certificate - /// is presented, the exception carries nothing from the routing server's completed - /// handshake: each attempt starts with a clean capture. + /// Within one asynchronous login, when the routing server's certificate passes validation + /// and the routed server's certificate fails it, the exception reports only the terminal + /// attempt's certificate and verdict. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_RoutedTerminalAttemptFailsBeforeTls_ExceptionCarriesNoCertificate( - bool async) + [Fact] + public async Task OpenAsync_RoutedTerminalAttemptFails_ExceptionCarriesOnlyTerminalAttempt() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); - // The routed server omits encryption support from its pre-login response while the - // client demands encryption, so the routed attempt fails before TLS starts. - using TdsServer server = new(new TdsServerArguments - { - Encryption = TDSPreLoginTokenEncryptionType.None, - }); - server.Start(); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); + using RoutingTdsServer router = StartRouter(_fixture.OtherHost, server.EndPoint.Port); + // The pin matches the routing server's certificate only. + using TempCertFile pin = new(_fixture.OtherHost); + using SqlConnection connection = new( + BuildConnectionString(router.EndPoint.Port, serverCertificate: pin.Path)); + + // Act + SqlException ex = await Assert.ThrowsAsync(() => connection.OpenAsync()); + + // Assert + AssertPinnedMismatchFailure(ex, _fixture.Localhost); + } + + /// + /// Within one synchronous login, when the routed attempt fails in pre-login, before any + /// certificate is presented, the exception carries nothing from the routing server's + /// completed handshake: each attempt starts with a clean capture. + /// + [Fact] + public void Open_RoutedTerminalAttemptFailsBeforeTls_ExceptionCarriesNoCertificate() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartUnencryptedServer(); using RoutingTdsServer router = StartRouter(_fixture.OtherHost, server.EndPoint.Port); using SqlConnection connection = new( BuildConnectionString(router.EndPoint.Port, trustServerCertificate: true)); // Act - SqlException ex = await Assert.ThrowsAsync( - () => OpenAsync(connection, async)); + SqlException ex = Assert.Throws(() => connection.Open()); // Assert - SqlConnectionEncryptionInfo info = ex.EncryptionInfo; - Assert.Null(info.PresentedServerCertificateRawData); - Assert.Null(info.GetServerCertificate()); - Assert.True(info.IsEmpty); + AssertNoCertificateCaptured(ex.EncryptionInfo); + } + + /// + /// Within one asynchronous login, when the routed attempt fails in pre-login, before any + /// certificate is presented, the exception carries nothing from the routing server's + /// completed handshake: each attempt starts with a clean capture. + /// + [Fact] + public async Task OpenAsync_RoutedTerminalAttemptFailsBeforeTls_ExceptionCarriesNoCertificate() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartUnencryptedServer(); + using RoutingTdsServer router = StartRouter(_fixture.OtherHost, server.EndPoint.Port); + using SqlConnection connection = new( + BuildConnectionString(router.EndPoint.Port, trustServerCertificate: true)); + + // Act + SqlException ex = await Assert.ThrowsAsync(() => connection.OpenAsync()); + + // Assert + AssertNoCertificateCaptured(ex.EncryptionInfo); + } + + /// + /// A failed synchronous open on one connection does not leak its certificate into a later + /// synchronous open on a different connection: each connection publishes only its own + /// certificate. + /// + [Fact] + public void Open_FailureThenSuccessOnNewConnection_DoesNotCarryPreviousCertificate() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer otherServer = StartServer(_fixture.OtherHost, + expectTlsHandshakeFailure: true); + using TdsServer server = StartServer(_fixture.Localhost); + using TempCertFile pin = new(_fixture.Localhost); + using SqlConnection failing = new( + BuildConnectionString(otherServer.EndPoint.Port, serverCertificate: pin.Path)); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); + + // Act + SqlException ex = Assert.Throws(() => failing.Open()); + connection.Open(); + + // Assert + AssertEachConnectionPublishesOwnCertificate(ex, connection); } /// - /// A failed open on one connection does not leak its certificate into a later open on a - /// different connection: each connection publishes only its own certificate. + /// A failed asynchronous open on one connection does not leak its certificate into a later + /// asynchronous open on a different connection: each connection publishes only its own + /// certificate. /// - [Theory] - [InlineData(false)] - [InlineData(true)] - public async Task Open_FailureThenSuccessOnNewConnection_DoesNotCarryPreviousCertificate( - bool async) + [Fact] + public async Task OpenAsync_FailureThenSuccessOnNewConnection_DoesNotCarryPreviousCertificate() { // Arrange using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); @@ -367,17 +517,148 @@ public async Task Open_FailureThenSuccessOnNewConnection_DoesNotCarryPreviousCer BuildConnectionString(server.EndPoint.Port, serverCertificate: pin.Path)); // Act - SqlException ex = await Assert.ThrowsAsync( - () => OpenAsync(failing, async)); - await OpenAsync(connection, async); + SqlException ex = await Assert.ThrowsAsync(() => failing.OpenAsync()); + await connection.OpenAsync(); // Assert + AssertEachConnectionPublishesOwnCertificate(ex, connection); + } + + #endregion + + #region Scenario assertions + + /// + /// Asserts the TrustServerCertificate snapshot: certificate, mode, protocol and the client + /// SslStream's cipher suite are published, with no verdict or chain status. + /// + private void AssertTrustedCertificateSnapshot(SqlConnection connection) + { + SqlConnectionEncryptionInfo info = connection.EncryptionInfo; + Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); + Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); + AssertCertificate(_fixture.Localhost, info); + // The certificate was presented but SqlClient did not evaluate it. + Assert.Null(info.ValidationErrors); + Assert.Null(info.ChainStatus); + // The published cipher suite is the one the client SslStream negotiated. + Assert.NotNull(info.NegotiatedCipherSuiteId); + Assert.Equal(GetClientSslStreamCipherSuite(connection), info.NegotiatedCipherSuiteId); + } + + /// + /// Asserts the matching-pin snapshot: the certificate with no validation errors and no + /// chain status, because the chain is not consulted when a pin decides trust. + /// + private void AssertMatchingPinSnapshot(SqlConnectionEncryptionInfo info) + { + Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); + Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); + AssertCertificate(_fixture.Localhost, info); + Assert.Equal(SqlServerCertificateValidationErrors.None, info.ValidationErrors); + Assert.Null(info.ChainStatus); + } + + /// + /// Asserts the untrusted-certificate failure: the exception carries the certificate, + /// ChainError, a non-clean chain status and the observed negotiation, the connection stays + /// empty, and nothing leaks into the message. + /// + private void AssertUntrustedCertificateFailure(SqlException ex, SqlConnection connection) + { + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + AssertCertificate(_fixture.Localhost, info); + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, info.ValidationErrors); + Assert.NotNull(info.ChainStatus); + Assert.NotEqual(X509ChainStatusFlags.NoError, info.ChainStatus); + // Certificate validation failed after the protocol was agreed; the observed values + // are kept. + AssertObservedNegotiation(info); + Assert.True(connection.EncryptionInfo.IsEmpty); + AssertNoLeak(ex, info); + } + + /// + /// Asserts the host-name-mismatch failure: ChainError and HostNameMismatch, a chain status, + /// the observed negotiation, and no leak into the message. + /// + private void AssertHostNameMismatchFailure(SqlException ex) + { + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + AssertCertificate(_fixture.OtherHost, info); + Assert.Equal( + SqlServerCertificateValidationErrors.ChainError + | SqlServerCertificateValidationErrors.HostNameMismatch, + info.ValidationErrors); + Assert.NotNull(info.ChainStatus); + AssertObservedNegotiation(info); + AssertNoLeak(ex, info); + } + + /// + /// Asserts the HostNameInCertificate-override failure: the platform reported a name + /// mismatch, but the override resolves it, so only the untrusted chain remains in + /// SqlClient's effective verdict. + /// + private void AssertHostNameOverrideFailure(SqlException ex) + { + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, + ex.EncryptionInfo.ValidationErrors); + AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); + AssertObservedNegotiation(ex.EncryptionInfo); + } + + /// + /// Asserts a pin-mismatch failure: the presented certificate, PinnedCertificateMismatch, no + /// chain status, and the observed negotiation. + /// + private static void AssertPinnedMismatchFailure(SqlException ex, X509Certificate2 presented) + { + SqlConnectionEncryptionInfo info = ex.EncryptionInfo; + AssertCertificate(presented, info); + Assert.Equal(SqlServerCertificateValidationErrors.PinnedCertificateMismatch, + info.ValidationErrors); + Assert.Null(info.ChainStatus); + AssertObservedNegotiation(info); + } + + /// + /// Asserts that a routed open published only the terminal attempt's certificate, with no + /// verdict or chain status because TrustServerCertificate bypassed evaluation. + /// + private void AssertRoutedTerminalAttemptSnapshot(SqlConnectionEncryptionInfo info) + { + AssertCertificate(_fixture.Localhost, info); + Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); + Assert.Null(info.ValidationErrors); + Assert.Null(info.ChainStatus); + } + + /// + /// Asserts that a snapshot carries no certificate and is otherwise empty. + /// + private static void AssertNoCertificateCaptured(SqlConnectionEncryptionInfo info) + { + Assert.Null(info.PresentedServerCertificateRawData); + Assert.Null(info.GetServerCertificate()); + Assert.True(info.IsEmpty); + } + + /// + /// Asserts that the failed connection's exception carries its own certificate and the later + /// successful connection publishes only its own certificate with no validation errors. + /// + private void AssertEachConnectionPublishesOwnCertificate( + SqlException ex, SqlConnection connection) + { AssertCertificate(_fixture.OtherHost, ex.EncryptionInfo); AssertCertificate(_fixture.Localhost, connection.EncryptionInfo); Assert.Equal(SqlServerCertificateValidationErrors.None, connection.EncryptionInfo.ValidationErrors); } + #endregion + #region Helpers /// @@ -447,6 +728,20 @@ private static TdsServer StartServer(X509Certificate2 certificate, bool expectTl return server; } + /// + /// Starts a simulated server that omits encryption support from its pre-login response, + /// so a client demanding encryption fails before TLS starts. + /// + private static TdsServer StartUnencryptedServer() + { + TdsServer server = new(new TdsServerArguments + { + Encryption = TDSPreLoginTokenEncryptionType.None, + }); + server.Start(); + return server; + } + /// /// Starts a TLS 1.2 simulated routing server that requires encryption and, after login, /// routes every connection to the given local port. @@ -498,21 +793,6 @@ private static string BuildConnectionString( return builder.ConnectionString; } - /// - /// Opens the connection with when - /// is true, otherwise with . - /// - private static Task OpenAsync(SqlConnection connection, bool async) - { - if (async) - { - return connection.OpenAsync(); - } - - connection.Open(); - return Task.CompletedTask; - } - /// /// Asserts that the published certificate is exactly the expected certificate's DER, both /// as raw data and as a reconstructed certificate without a private key. From 44fe90b79b01eac2fbd76dedae4e74ca16b5b75c Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Tue, 10 Nov 2026 21:32:39 +0530 Subject: [PATCH 09/12] Align native SNI failure note with Managed SNI capture Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/design-notes/2353-connection-encryption-info.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index 01c840ca0b..71dbee54f7 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -293,8 +293,9 @@ non-`SqlException` failures, keep `Empty`. .NET (`net10.0`). - **Native SNI.** With the current SNI package, native SNI also rejects an untrusted server certificate during the handshake, so this slice reports the mode but no protocol for that - failure (the tests assert this for both SNI implementations). If a deferred validation - failure surfaces after a successful `EnableSsl`, the protocol recorded by `EnableSsl` is kept. + failure (the tests assert this for native SNI; Managed SNI also reports the protocol, as + described above). If a deferred validation failure surfaces after a successful `EnableSsl`, the + protocol recorded by `EnableSsl` is kept. These rules only touch mode and protocol; certificate fields are never affected. Once login completes the accumulator is released, so SSL errors on an open connection never alter a published snapshot. From 7076de8539b350a7ddc5768ee0aed55f3bb29812 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Wed, 11 Nov 2026 18:03:18 +0530 Subject: [PATCH 10/12] Adapt reconnect tests to Managed SNI certificate capture Slice B's reconnect tests asserted that certificate fields are null. Managed SNI now records the presented certificate under TrustServerCertificate, so use the bypass assertion. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../SimulatedServerTests/ConnectionEncryptionInfoTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs index 6abea4135a..dc4c899775 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs @@ -646,7 +646,7 @@ public void ExecuteNonQuery_ReconnectAfterServerDrop_PublishesNewSnapshot() Assert.Equal(ConnectionState.Open, connection.State); Assert.NotSame(held, connection.EncryptionInfo); AssertNegotiated(connection.EncryptionInfo, ServerEncryption.Required); - AssertCertificateFieldsNull(connection.EncryptionInfo); + AssertBypassedCertificateFields(connection.EncryptionInfo, ServerEncryption.Required); AssertNegotiated(held, ServerEncryption.Required); } @@ -673,7 +673,7 @@ public async Task ExecuteNonQueryAsync_ReconnectAfterServerDrop_PublishesNewSnap Assert.Equal(ConnectionState.Open, connection.State); Assert.NotSame(held, connection.EncryptionInfo); AssertNegotiated(connection.EncryptionInfo, ServerEncryption.Required); - AssertCertificateFieldsNull(connection.EncryptionInfo); + AssertBypassedCertificateFields(connection.EncryptionInfo, ServerEncryption.Required); AssertNegotiated(held, ServerEncryption.Required); } From a12b6ad8056bb8bd02810908876dfc1c365935cb Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Thu, 12 Nov 2026 13:14:31 +0530 Subject: [PATCH 11/12] Adapt Slice C tests to the Slice A review follow-up helpers Use the shared EncryptionInfoTestData.AssertEmpty helper and value-returning Assert.NotNull instead of ad-hoc IsEmpty checks and null-forgiving operators. Test-only; no product change. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../SniCommonServerCertificateCaptureTest.cs | 2 +- .../ConnectionEncryptionInfoTests.cs | 6 ++---- .../ManagedSniCertificateCaptureTests.cs | 13 ++++++------- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs index 71e4ef6815..9b429db4b3 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -706,7 +706,7 @@ public void EncryptionInfoCapture_RecordServerCertificate_PublishesInSnapshot() Assert.Null(snapshot.NegotiatedEncryptionMode); Assert.Null(snapshot.NegotiatedEncryptionProtocol); Assert.Equal(serverCert.RawData, - snapshot.PresentedServerCertificateRawData!.Value.ToArray()); + Assert.NotNull(snapshot.PresentedServerCertificateRawData).ToArray()); using (X509Certificate2? roundTripped = snapshot.GetServerCertificate()) { Assert.NotNull(roundTripped); diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs index dc4c899775..fee7de9b6f 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs @@ -1087,8 +1087,7 @@ private static void AssertUntrustedCertificateFailure(SqlException ex, SqlConnec if (LocalAppContextSwitches.UseManagedNetworking) { Assert.Equal(SslProtocols.Tls12, ex.EncryptionInfo.NegotiatedEncryptionProtocol); - Assert.NotNull(ex.EncryptionInfo.NegotiatedCipherSuiteId); - Assert.InRange(ex.EncryptionInfo.NegotiatedCipherSuiteId!.Value, 1, 0xFFFF); + Assert.InRange(Assert.NotNull(ex.EncryptionInfo.NegotiatedCipherSuiteId), 1, 0xFFFF); } else { @@ -1131,8 +1130,7 @@ private void AssertBypassedCertificateFields(SqlConnectionEncryptionInfo info, S } else if (LocalAppContextSwitches.UseManagedNetworking) { - Assert.NotNull(info.NegotiatedCipherSuiteId); - Assert.InRange(info.NegotiatedCipherSuiteId!.Value, 1, 0xFFFF); + Assert.InRange(Assert.NotNull(info.NegotiatedCipherSuiteId), 1, 0xFFFF); } } diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs index 37eae4c112..d8a3073d00 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -19,6 +19,8 @@ using Microsoft.SqlServer.TDS.Servers; using Xunit; +using static Microsoft.Data.SqlClient.UnitTests.Utilities.EncryptionInfoTestData; + namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests { /// @@ -574,7 +576,7 @@ private void AssertUntrustedCertificateFailure(SqlException ex, SqlConnection co // Certificate validation failed after the protocol was agreed; the observed values // are kept. AssertObservedNegotiation(info); - Assert.True(connection.EncryptionInfo.IsEmpty); + AssertEmpty(connection.EncryptionInfo); AssertNoLeak(ex, info); } @@ -639,9 +641,7 @@ private void AssertRoutedTerminalAttemptSnapshot(SqlConnectionEncryptionInfo inf /// private static void AssertNoCertificateCaptured(SqlConnectionEncryptionInfo info) { - Assert.Null(info.PresentedServerCertificateRawData); - Assert.Null(info.GetServerCertificate()); - Assert.True(info.IsEmpty); + AssertEmpty(info); } /// @@ -669,8 +669,7 @@ private static void AssertObservedNegotiation(SqlConnectionEncryptionInfo info) { Assert.Equal(SqlConnectionEncryptionMode.Full, info.NegotiatedEncryptionMode); Assert.Equal(SslProtocols.Tls12, info.NegotiatedEncryptionProtocol); - Assert.NotNull(info.NegotiatedCipherSuiteId); - Assert.InRange(info.NegotiatedCipherSuiteId!.Value, 1, 0xFFFF); + Assert.InRange(Assert.NotNull(info.NegotiatedCipherSuiteId), 1, 0xFFFF); } /// @@ -814,7 +813,7 @@ private static void AssertCertificate(X509Certificate2 expected, SqlConnectionEn /// private static void AssertNoLeak(SqlException ex, SqlConnectionEncryptionInfo info) { - byte[] der = info.PresentedServerCertificateRawData!.Value.ToArray(); + byte[] der = Assert.NotNull(info.PresentedServerCertificateRawData).ToArray(); string[] encodings = { Convert.ToHexString(der), From f771fb42716a581988767985c636c2627b7d32b0 Mon Sep 17 00:00:00 2001 From: Priyanka Tiwari Date: Tue, 17 Nov 2026 12:59:39 +0530 Subject: [PATCH 12/12] Adapt Slice C to the Slice B accumulator design Move C's certificate-field tests into EncryptionInfoAccumulatorTests using the accumulator's settable properties, drop the RecordServerCertificate-based tests, remove the inherited AssertCertificateFieldsNull use from the enlistment test (Managed SNI now records the presented certificate), and update the remaining EncryptionInfoCapture references in docs and comments. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../2353-connection-encryption-info.md | 11 +- .../Connection/ServerCertificateCapture.cs | 2 +- .../EncryptionInfoAccumulatorTests.cs | 85 +++++++++++- .../SniCommonServerCertificateCaptureTest.cs | 128 ------------------ .../ConnectionEncryptionInfoTests.cs | 1 - 5 files changed, 90 insertions(+), 137 deletions(-) diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index 71dbee54f7..7f1d325395 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -341,8 +341,9 @@ Native SNI does not yet report certificate details; those fields remain `null` t same two points as the protocol, on both the TCP and named-pipe handles (MARS passes through to the physical handle): -- **After the handshake completes,** `TdsParser.EnableSsl` records the value from the session - handle into the accumulator's `CipherSuite` property. This read is authoritative for a successful attempt. +- **After the handshake completes,** `TdsParser.EnableSsl` assigns the value from the session + handle to the accumulator's `CipherSuite` property. This read is authoritative for a + successful attempt. - **Inside the validation callback,** the value is stored with the certificate capture. `SslStream` processes the ServerHello, which selects the suite, before it raises the callback, so the value is real there. The tests confirm it matches the suite a trusted handshake with the @@ -351,9 +352,9 @@ the physical handle): Both reads are wrapped in `try`/`catch` so that capture never affects the handshake. A suite of `0` (`TLS_NULL_WITH_NULL_NULL`, nothing agreed yet) is treated as unavailable. Without TLS, the -properties are `null`. The value flows through the SNI handles, `ServerCertificateCapture` and -`EncryptionInfoCapture` as an `int`. `NegotiatedCipherSuiteId` returns it unchanged, and on .NET -`NegotiatedCipherSuite` casts the same value to `TlsCipherSuite`. +properties are `null`. The value flows through the SNI handles and `ServerCertificateCapture` as +an `int`; `TdsParser.EnableSsl` casts it to `TlsCipherSuite` on .NET when it assigns it to the +accumulator. `NegotiatedCipherSuiteId` returns the same IANA identifier. Managed SNI runs only on `net10.0`; on `net462` this capture is not compiled and `NegotiatedCipherSuiteId` stays `null` until native SNI support (Slice D). diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs index ecfd450d63..c5390b77e2 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs @@ -11,7 +11,7 @@ namespace Microsoft.Data.SqlClient.Connection { /// /// Immutable record of the server certificate details observed by the transport during one TLS - /// handshake. Produced by the transport layer and consumed by . + /// handshake. Produced by the transport layer and consumed by . /// /// /// Each value is when it is unavailable: no certificate was presented diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulatorTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulatorTests.cs index 59f036e039..47349433e0 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulatorTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/Connection/EncryptionInfoAccumulatorTests.cs @@ -2,7 +2,9 @@ // 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.Security.Authentication; +using System.Security.Cryptography.X509Certificates; using Microsoft.Data.SqlClient.Connection; using Xunit; using static Microsoft.Data.SqlClient.UnitTests.Utilities.EncryptionInfoTestData; @@ -18,6 +20,9 @@ public class EncryptionInfoAccumulatorTests // IANA identifier for TLS_AES_128_GCM_SHA256. private const int OtherCipherSuite = 0x1301; + // Stand-in DER bytes; the accumulator stores the certificate without parsing it. + private static readonly byte[] SampleCertificate = { 0x30, 0x82, 0x01, 0x0A, 0x5A, 0xC3, 0x7E, 0x11 }; + #region Protocol /// @@ -146,6 +151,75 @@ public void CipherSuite_SetAlone_HasValuesAndSnapshotNotEmpty() #endregion + #region Certificate + + /// + /// Certificate details are published in the snapshot alongside the negotiated values. + /// + [Fact] + public void ToSnapshot_CertificateFieldsSet_SurfacesCertificateFields() + { + // Arrange + EncryptionInfoAccumulator accumulator = new(); + accumulator.Mode = SqlConnectionEncryptionMode.Full; + accumulator.ServerCertificateRawData = SampleCertificate; + accumulator.ValidationErrors = SqlServerCertificateValidationErrors.ChainError; + accumulator.ChainStatus = X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.NotTimeValid; + + // Act + SqlConnectionEncryptionInfo snapshot = accumulator.ToSnapshot(); + + // Assert + Assert.Equal(SqlConnectionEncryptionMode.Full, snapshot.NegotiatedEncryptionMode); + Assert.Equal(SampleCertificate, Assert.NotNull(snapshot.PresentedServerCertificateRawData).ToArray()); + Assert.Equal(SqlServerCertificateValidationErrors.ChainError, snapshot.ValidationErrors); + Assert.Equal(X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.NotTimeValid, snapshot.ChainStatus); + } + + /// + /// Zero values (no validation errors, a clean chain) are available values, distinct from + /// unavailable ones. + /// + [Fact] + public void ToSnapshot_ZeroCertificateVerdict_ReportedAsAvailable() + { + // Arrange + EncryptionInfoAccumulator accumulator = new(); + accumulator.ValidationErrors = SqlServerCertificateValidationErrors.None; + accumulator.ChainStatus = X509ChainStatusFlags.NoError; + + // Act + SqlConnectionEncryptionInfo snapshot = accumulator.ToSnapshot(); + + // Assert + Assert.True(accumulator.HasValues); + Assert.False(snapshot.IsEmpty); + Assert.Equal(SqlServerCertificateValidationErrors.None, snapshot.ValidationErrors); + Assert.Equal(X509ChainStatusFlags.NoError, snapshot.ChainStatus); + Assert.Null(snapshot.PresentedServerCertificateRawData); + } + + /// + /// The snapshot's text never contains the certificate or any common encoding of it. + /// + [Fact] + public void ToSnapshot_CertificateSet_NotInSnapshotText() + { + // Arrange + EncryptionInfoAccumulator accumulator = new(); + accumulator.ServerCertificateRawData = SampleCertificate; + accumulator.ValidationErrors = SqlServerCertificateValidationErrors.ChainError; + + // Act + string text = accumulator.ToSnapshot().ToString() ?? string.Empty; + + // Assert + Assert.DoesNotContain(Convert.ToBase64String(SampleCertificate), text); + Assert.DoesNotContain(BitConverter.ToString(SampleCertificate).Replace("-", string.Empty), text, StringComparison.OrdinalIgnoreCase); + } + + #endregion + #region Reset /// @@ -159,6 +233,9 @@ public void Reset_ValuesSet_ClearsAllValues() accumulator.Mode = SqlConnectionEncryptionMode.Full; accumulator.Protocol = SslProtocols.Tls12; accumulator.CipherSuite = ToConstructorCipherSuite(SampleCipherSuite); + accumulator.ServerCertificateRawData = SampleCertificate; + accumulator.ValidationErrors = SqlServerCertificateValidationErrors.ChainError; + accumulator.ChainStatus = X509ChainStatusFlags.UntrustedRoot; // Act accumulator.Reset(); @@ -167,6 +244,9 @@ public void Reset_ValuesSet_ClearsAllValues() Assert.Null(accumulator.Mode); Assert.Null(accumulator.Protocol); Assert.Null(accumulator.CipherSuite); + Assert.Null(accumulator.ServerCertificateRawData); + Assert.Null(accumulator.ValidationErrors); + Assert.Null(accumulator.ChainStatus); Assert.False(accumulator.HasValues); Assert.Same(SqlConnectionEncryptionInfo.Empty, accumulator.ToSnapshot()); } @@ -193,10 +273,11 @@ public void ToSnapshot_NothingSet_ReturnsEmpty() } /// - /// The snapshot carries the mode, protocol and cipher suite, and no certificate fields. + /// Without certificate details, the snapshot carries the mode, protocol and cipher suite, and + /// reports the certificate fields as unavailable. /// [Fact] - public void ToSnapshot_AllSet_SurfacesValuesWithoutCertificateFields() + public void ToSnapshot_CertificateFieldsNotSet_ReturnsNullCertificateFields() { // Arrange EncryptionInfoAccumulator accumulator = new(); diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs index 9b429db4b3..9c5eef0d46 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -520,28 +520,6 @@ public void GetNegotiatedCipherSuite_NoStreamOrNoHandshake_Unavailable() Assert.Null(noHandshake); } - /// - /// A cipher suite carried by a certificate capture is adopted only when the attempt has - /// not already recorded one. - /// - [Fact] - public void RecordServerCertificate_CipherSuite_AdoptedOnlyWhenNotAlreadyRecorded() - { - // Arrange - EncryptionInfoCapture capture = new(); - EncryptionInfoCapture alreadyKnown = new(); - alreadyKnown.RecordCipherSuite(0x1301); - ServerCertificateCapture fromCallback = new(null, null, null, cipherSuite: 0xC030); - - // Act - capture.RecordServerCertificate(fromCallback); - alreadyKnown.RecordServerCertificate(fromCallback); - - // Assert - Assert.Equal(0xC030, capture.CipherSuite); - Assert.Equal(0x1301, alreadyKnown.CipherSuite); - } - /// /// When no certificate is presented, the certificate is unavailable and the verdict is /// kept. @@ -678,112 +656,6 @@ public void GetChainStatus_DoesNotBuildChain() Assert.Empty(unbuilt.ChainElements); } - #region EncryptionInfoCapture - - /// - /// A recorded certificate capture is published in the snapshot, round-trips through - /// , and is cleared by - /// . - /// - [Fact] - public void EncryptionInfoCapture_RecordServerCertificate_PublishesInSnapshot() - { - // Arrange - using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); - EncryptionInfoCapture capture = new(); - - // Act - capture.RecordServerCertificate(new ServerCertificateCapture( - SniCommon.GetRawCertificate(serverCert), - SqlServerCertificateValidationErrors.ChainError, - X509ChainStatusFlags.UntrustedRoot)); - SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); - - // Assert - Assert.True(capture.HasValues); - Assert.Equal(serverCert.RawData, capture.ServerCertificateRawData); - Assert.False(snapshot.IsEmpty); - Assert.Null(snapshot.NegotiatedEncryptionMode); - Assert.Null(snapshot.NegotiatedEncryptionProtocol); - Assert.Equal(serverCert.RawData, - Assert.NotNull(snapshot.PresentedServerCertificateRawData).ToArray()); - using (X509Certificate2? roundTripped = snapshot.GetServerCertificate()) - { - Assert.NotNull(roundTripped); - Assert.Equal(serverCert.RawData, roundTripped.RawData); - Assert.False(roundTripped.HasPrivateKey); - } - Assert.Equal(SqlServerCertificateValidationErrors.ChainError, snapshot.ValidationErrors); - Assert.Equal(X509ChainStatusFlags.UntrustedRoot, snapshot.ChainStatus); - - // Reset clears the attempt. - capture.Reset(); - Assert.False(capture.HasValues); - Assert.Same(SqlConnectionEncryptionInfo.Empty, capture.ToSnapshot()); - } - - /// - /// Zero values (no errors, a clean chain) are available values, distinct from null. - /// - [Fact] - public void EncryptionInfoCapture_ZeroValuesAreAvailable() - { - // Arrange - EncryptionInfoCapture capture = new(); - - // Act - capture.RecordServerCertificate(new ServerCertificateCapture(null, - SqlServerCertificateValidationErrors.None, X509ChainStatusFlags.NoError)); - SqlConnectionEncryptionInfo snapshot = capture.ToSnapshot(); - - // Assert - Assert.True(capture.HasValues); - Assert.Equal(SqlServerCertificateValidationErrors.None, snapshot.ValidationErrors); - Assert.Equal(X509ChainStatusFlags.NoError, snapshot.ChainStatus); - Assert.Null(snapshot.PresentedServerCertificateRawData); - Assert.Null(snapshot.GetServerCertificate()); - } - - /// - /// Recording a null capture leaves the certificate fields unavailable. - /// - [Fact] - public void EncryptionInfoCapture_NullCapture_LeavesCertificateFieldsUnavailable() - { - // Arrange - EncryptionInfoCapture capture = new(); - - // Act - capture.RecordServerCertificate(null); - - // Assert - Assert.False(capture.HasValues); - Assert.Same(SqlConnectionEncryptionInfo.Empty, capture.ToSnapshot()); - } - - /// - /// The snapshot's text never contains the certificate, any encoding of it, or its - /// thumbprint. - /// - [Fact] - public void EncryptionInfoCapture_CertificateNotInSnapshotText() - { - // Arrange - using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName); - EncryptionInfoCapture capture = new(); - capture.RecordServerCertificate(new ServerCertificateCapture(serverCert.RawData, - SqlServerCertificateValidationErrors.ChainError, X509ChainStatusFlags.UntrustedRoot)); - - // Act - string text = capture.ToSnapshot().ToString() ?? string.Empty; - - // Assert - AssertNoLeak(serverCert.RawData, text); - Assert.DoesNotContain(serverCert.Thumbprint, text, StringComparison.OrdinalIgnoreCase); - } - - #endregion - #region Helpers /// diff --git a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs index fee7de9b6f..9bb1fc9881 100644 --- a/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ConnectionEncryptionInfoTests.cs @@ -871,7 +871,6 @@ private static void AssertEnlistmentFailure( { Assert.Equal(expectedLogins, server.Login7Count); AssertNegotiated(ex.EncryptionInfo, ServerEncryption.Required); - AssertCertificateFieldsNull(ex.EncryptionInfo); AssertEmpty(connection.EncryptionInfo); Assert.NotEqual(ConnectionState.Open, connection.State);