diff --git a/doc/design-notes/2353-connection-encryption-info.md b/doc/design-notes/2353-connection-encryption-info.md index 3495cafa87..7f1d325395 100644 --- a/doc/design-notes/2353-connection-encryption-info.md +++ b/doc/design-notes/2353-connection-encryption-info.md @@ -283,14 +283,19 @@ 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 - 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. @@ -307,6 +312,52 @@ 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 | +| --- | --- | --- | +| `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. | + +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. + +**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` 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 + 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 +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). + ## 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..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 @@ -6,6 +6,7 @@ using System.Net.Security; #endif using System.Security.Authentication; +using System.Security.Cryptography.X509Certificates; #nullable enable @@ -31,6 +32,12 @@ namespace Microsoft.Data.SqlClient.Connection /// internal sealed class EncryptionInfoAccumulator { + /// + /// 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 +69,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 || + ServerCertificateRawData 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 +99,18 @@ 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. + /// + 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; + ServerCertificateRawData = 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: ServerCertificateRawData, + 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..c5390b77e2 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/Connection/ServerCertificateCapture.cs @@ -0,0 +1,78 @@ +// 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 + /// 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[]? rawCertificate, + SqlServerCertificateValidationErrors? validationErrors, + X509ChainStatusFlags? chainStatus, + SslProtocols? protocol = null, + int? cipherSuite = null) + { + RawCertificate = rawCertificate; + ValidationErrors = validationErrors; + ChainStatus = chainStatus; + Protocol = protocol; + CipherSuite = cipherSuite; + } + + /// + /// 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[]? RawCertificate { 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; } + + /// + /// 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 bf72a91bc2..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 @@ -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,57 @@ 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. 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 + /// 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 +139,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 +149,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 +158,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 @@ -157,14 +209,26 @@ 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)) { 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 +239,155 @@ 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 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, ServerCertificateCapture previous = null) + { + byte[] rawCertificate = previous?.RawCertificate ?? GetRawCertificate(serverCert); + + return new ServerCertificateCapture( + 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 + /// 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; + } + } + + /// + /// 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 +479,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..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 @@ -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,19 @@ 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 + /// 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..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,10 @@ 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 6adb803ddf..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,10 @@ internal sealed class SniMarsHandle : SniHandle public override SslProtocols ProtocolVersion => _connection.ProtocolVersion; + public override int? NegotiatedCipherSuite => _connection.NegotiatedCipherSuite; + + 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..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 @@ -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(); @@ -140,6 +142,8 @@ public override SslProtocols ProtocolVersion } } + public override int? NegotiatedCipherSuite => SniCommon.GetNegotiatedCipherSuite(_sslStream); + public override uint CheckConnection() { using (SqlClientSNIEventScope.Create(nameof(SniNpHandle))) @@ -334,6 +338,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 +390,32 @@ 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 (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))); + } + } } + /// + 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..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 @@ -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(); @@ -115,6 +117,8 @@ public override SslProtocols ProtocolVersion } } + public override int? NegotiatedCipherSuite => SniCommon.GetNegotiatedCipherSuite(_sslStream); + /// /// Constructor /// @@ -757,6 +761,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 +821,29 @@ 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 (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))); + } } + /// + 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..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 @@ -955,6 +955,31 @@ 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.ServerCertificateRawData = certificateCapture.RawCertificate; + accumulator.ValidationErrors = certificateCapture.ValidationErrors; + accumulator.ChainStatus = certificateCapture.ChainStatus; + + // 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) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); @@ -996,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 59949d28a1..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 @@ -563,6 +563,19 @@ 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; + + /// + /// 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 d0a1a9a093..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 @@ -388,6 +388,10 @@ 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/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 new file mode 100644 index 0000000000..9c5eef0d46 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/Microsoft/Data/SqlClient/ManagedSni/SniCommonServerCertificateCaptureTest.cs @@ -0,0 +1,873 @@ +// 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 System.Text; +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 DER + /// encoding of the presented certificate. + /// + 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. + None, + /// A chain that was evaluated and found clean. + Clean, + /// 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, + } + + /// + /// 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() + { + 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"; + + 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( + SslPolicyErrors policyErrors, + ChainKind chainKind, + PinKind pinKind, + string? hostNameInCertificate, + string targetServerName, + bool nullCert, + bool expectSuccess, + SqlServerCertificateValidationErrors expectedErrors, + bool expectChainFromCallback) + { + // Arrange + 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; + + // Act + Exception? exception = Validate(targetServerName, hostNameInCertificate, + nullCert ? null : serverCert, pinPath, policyErrors, chain, + out ServerCertificateVerdict verdict); + + // Assert + 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); + } + } + + /// + /// 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)!; + + X509ChainStatusFlags expected = X509ChainStatusFlags.NoError; + foreach (X509ChainStatus status in chain.ChainStatus) + { + expected |= status.Status; + } + Assert.NotEqual(X509ChainStatusFlags.NoError, expected); + + // 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)!; + + // 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); + 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"); + + // 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 be the one that + /// MatchesHostname itself throws. + /// + [Theory] + [InlineData(SslPolicyErrors.RemoteCertificateChainErrors + | SslPolicyErrors.RemoteCertificateNameMismatch, true)] + [InlineData(SslPolicyErrors.RemoteCertificateNameMismatch, false)] + 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)!; + + // The exception that the host name check itself throws, independent of SqlClient. + ArgumentException expected = Assert.ThrowsAny( + () => serverCert.MatchesHostname(NamedPipeTarget)); + + // Act + Exception? capturing = Validate(NamedPipeTarget, null, serverCert, null, policyErrors, + chain, out ServerCertificateVerdict verdict); + + // Assert + // The pre-existing exception is neither caught nor changed. + Assert.NotNull(capturing); + Assert.Equal(expected.GetType(), capturing!.GetType()); + Assert.Equal(expected.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. 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))] + public void ValidateSslServerCertificate_CaptureDoesNotChangeOutcomeOrMessage( + SslPolicyErrors policyErrors, + ChainKind chainKind, + PinKind pinKind, + string? hostNameInCertificate, + string targetServerName, + bool nullCert, + bool expectSuccess, + SqlServerCertificateValidationErrors expectedErrors, + bool expectChainFromCallback) + { + _ = expectedErrors; + _ = expectChainFromCallback; + + // Arrange + 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; + string? expectedMessage = ExpectedMessage(targetServerName, hostNameInCertificate, cert, + pinKind, policyErrors); + + // 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) + { + Assert.Null(capturing); + } + else + { + Assert.IsType(capturing); + Assert.Equal(expectedMessage, capturing!.Message); + } + + if (capturing is not null && cert is not null) + { + ServerCertificateCapture capture = SniCommon.CreateServerCertificateCapture(cert, verdict); + AssertNoLeak(capture.RawCertificate!, capturing.Message); + AssertNoLeak(capture.RawCertificate!, capturing.ToString()); + } + } + + /// + /// 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); + + // 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); + 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); + } + + /// + /// 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() + { + // Arrange + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, + ServerCertificateCapture.MaxRawCertificateSize); + Assert.True(serverCert.RawData.Length > ServerCertificateCapture.MaxRawCertificateSize); + ServerCertificateVerdict verdict = new( + 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() + { + // Arrange + using X509Certificate2 serverCert = CreateSelfSignedCertificate(ServerName, + ServerCertificateCapture.MaxRawCertificateSize / 2); + Assert.InRange(serverCert.RawData.Length, 1, + ServerCertificateCapture.MaxRawCertificateSize); + + // Act + byte[]? rawCertificate = 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, verdict, sender: null, previous: previous); + ServerCertificateCapture afterEmpty = SniCommon.CreateServerCertificateCapture( + second, default, previous: empty); + + // Assert + Assert.Equal(first.RawData, next.RawCertificate); + Assert.Equal(SqlServerCertificateValidationErrors.HostNameMismatch, next.ValidationErrors); + 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); + + // 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); + + // 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() + { + // Arrange + using SslStream sslStream = new(new MemoryStream()); + + // Act + int? noStream = SniCommon.GetNegotiatedCipherSuite(null!); + int? noHandshake = SniCommon.GetNegotiatedCipherSuite(sslStream); + + // Assert + Assert.Null(noStream); + Assert.Null(noHandshake); + } + + /// + /// When no certificate is presented, the certificate is unavailable and the verdict is + /// kept. + /// + [Fact] + public void CreateServerCertificateCapture_NoCertificate_CertificateUnavailable() + { + // 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.Null(capture.ChainStatus); + } + + /// + /// Every value other than + /// . + /// + public static TheoryData AllChainStatusFlags() + { + TheoryData data = new(); + foreach (X509ChainStatusFlags flag in Enum.GetValues()) + { + if (flag != X509ChainStatusFlags.NoError) + { + 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 } }; + + // 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()) + { + statuses.Add(new X509ChainStatus { Status = flag }); + all |= flag; + } + + // 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() + { + // 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() + { + // 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. + /// + [Fact] + public void GetChainStatus_DoesNotBuildChain() + { + // Arrange + using X509Chain unbuilt = new(); + + // Act + X509ChainStatusFlags? status = + SniCommon.GetChainStatus(unbuilt, SslPolicyErrors.RemoteCertificateChainErrors); + + // Assert + Assert.Null(status); + Assert.Empty(unbuilt.ChainElements); + } + + #region Helpers + + /// + /// Runs the capturing validation overload and returns the exception it throws, if any. + /// + 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; + } + } + + /// + /// 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) + { + 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; + } + + /// + /// 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.ToBase64String(certificate), text, StringComparison.Ordinal); + 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) + { + 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)); + } + + /// + /// 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"); + 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 + { + 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..9bb1fc9881 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)] @@ -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); } @@ -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); @@ -1058,14 +1057,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 +1074,63 @@ 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.InRange(Assert.NotNull(ex.EncryptionInfo.NegotiatedCipherSuiteId), 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.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 new file mode 100644 index 0000000000..d8a3073d00 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/tests/UnitTests/SimulatedServerTests/ManagedSniCertificateCaptureTests.cs @@ -0,0 +1,871 @@ +// 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.Net.Security; +using System.Reflection; +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; + +using static Microsoft.Data.SqlClient.UnitTests.Utilities.EncryptionInfoTestData; + +namespace Microsoft.Data.SqlClient.UnitTests.SimulatedServerTests +{ + /// + /// Provides untrusted self-signed server certificates for the managed SNI certificate capture tests. + /// + 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()); + } + + /// 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, 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; + + /// Receives the shared server certificates. + public ManagedSniCertificateCaptureTests(ManagedSniCaptureCertificateFixture fixture) + { + _fixture = fixture; + } + #region Successful opens + + /// + /// 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. + /// + [Fact] + public void Open_TrustServerCertificate_PublishesCertificateWithoutVerdict() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost); + using SqlConnection connection = new( + BuildConnectionString(server.EndPoint.Port, trustServerCertificate: true)); + + // Act + connection.Open(); + + // Assert + 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); + } + + /// + /// 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. + /// + [Fact] + public void Open_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 + connection.Open(); + + // Assert + 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 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. + /// + [Fact] + public void Open_UntrustedCertificate_ExceptionCarriesChainErrorAndCertificate() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); + + // Act + SqlException ex = Assert.Throws(() => connection.Open()); + + // Assert + 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)); + trusted.Open(); + Assert.Equal( + GetClientSslStreamCipherSuite(trusted), ex.EncryptionInfo.NegotiatedCipherSuiteId); + } + + /// + /// 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. + /// + [Fact] + public async Task OpenAsync_UntrustedCertificate_ExceptionCarriesChainErrorAndCertificate() + { + // Arrange + using LocalAppContextSwitchesHelper? switches = ForceManagedSni(); + using TdsServer server = StartServer(_fixture.Localhost, expectTlsHandshakeFailure: true); + using SqlConnection connection = new(BuildConnectionString(server.EndPoint.Port)); + + // Act + SqlException ex = await Assert.ThrowsAsync(() => connection.OpenAsync()); + + // Assert + 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( + 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); + } + + /// + /// On a synchronous open, a HostNameInCertificate matching the certificate removes + /// HostNameMismatch from the effective verdict, leaving only ChainError. + /// + [Fact] + public void Open_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 = Assert.Throws(() => connection.Open()); + + // Assert + 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 a + /// synchronous open with PinnedCertificateMismatch and no chain status. + /// + [Fact] + public void Open_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 = Assert.Throws(() => connection.Open()); + + // Assert + 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 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. + /// + [Fact] + public void Open_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 + connection.Open(); + + // Assert + 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 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. + /// + [Fact] + public void Open_RoutedTerminalAttemptFails_ExceptionCarriesOnlyTerminalAttempt() + { + // 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 = Assert.Throws(() => connection.Open()); + + // Assert + AssertPinnedMismatchFailure(ex, _fixture.Localhost); + } + + /// + /// 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. + /// + [Fact] + public async Task OpenAsync_RoutedTerminalAttemptFails_ExceptionCarriesOnlyTerminalAttempt() + { + // 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(() => 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 = Assert.Throws(() => connection.Open()); + + // Assert + 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 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. + /// + [Fact] + public async Task OpenAsync_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 = 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); + AssertEmpty(connection.EncryptionInfo); + 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) + { + AssertEmpty(info); + } + + /// + /// 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 + + /// + /// 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.InRange(Assert.NotNull(info.NegotiatedCipherSuiteId), 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; + } + + /// + /// 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)) + { + // Managed SNI is the only implementation off Windows. + return null; + } + + LocalAppContextSwitchesHelper switches = new(); + switches.UseManagedNetworking = true; + return switches; + } + + /// + /// 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; + } + + /// + /// 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. + /// + /// 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, + 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; + } + + /// + /// 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); + 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); + } + + /// + /// 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 = Assert.NotNull(info.PresentedServerCertificateRawData).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); + Assert.DoesNotContain(encoding, ex.ToString(), StringComparison.OrdinalIgnoreCase); + } + } + + /// + /// 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"); + 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 + { + File.Delete(Path); + } + catch (IOException) + { + } + catch (UnauthorizedAccessException) + { + } + } + } + + #endregion + } +} + +#endif