Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 57 additions & 6 deletions doc/design-notes/2353-connection-encryption-info.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Net.Security;
#endif
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

#nullable enable

Expand All @@ -31,6 +32,12 @@ namespace Microsoft.Data.SqlClient.Connection
/// </remarks>
internal sealed class EncryptionInfoAccumulator
{
/// <summary>
/// Gets or sets the combined chain status flags for the current attempt, or
/// <see langword="null"/> if the chain was not consulted or is unavailable.
/// </summary>
public X509ChainStatusFlags? ChainStatus { get; set; }

#if NET
/// <summary>
/// Gets or sets the TLS cipher suite negotiated for the current attempt, or
Expand Down Expand Up @@ -62,7 +69,13 @@ public int? CipherSuite
/// <summary>
/// Gets a value indicating whether any value has been recorded for the current attempt.
/// </summary>
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;

/// <summary>
/// Gets or sets the final negotiated encryption mode for the current attempt, or
Expand All @@ -86,6 +99,18 @@ public SslProtocols? Protocol
set => field = value == SslProtocols.None ? null : value;
}

/// <summary>
/// Gets or sets the DER encoding of the presented server certificate for the current attempt,
/// or <see langword="null"/> if the transport did not capture a presented certificate.
/// </summary>
public byte[]? ServerCertificateRawData { get; set; }

/// <summary>
/// Gets or sets SqlClient's effective certificate validation verdict for the current attempt,
/// or <see langword="null"/> if SqlClient did not evaluate the certificate.
/// </summary>
public SqlServerCertificateValidationErrors? ValidationErrors { get; set; }

/// <summary>
/// Clears all accumulated values. Called at the start of each physical login attempt.
/// </summary>
Expand All @@ -94,23 +119,27 @@ public void Reset()
Mode = null;
Protocol = null;
CipherSuite = null;
ServerCertificateRawData = null;
ValidationErrors = null;
ChainStatus = null;
}

/// <summary>
/// Creates an immutable snapshot of the accumulated values. Returns
/// <see cref="SqlConnectionEncryptionInfo.Empty"/> when nothing was recorded.
/// </summary>
/// <remarks>
/// Certificate fields are never inferred here; they remain unavailable.
/// Certificate fields are never inferred here; they are published only as recorded by the
/// transport.
/// </remarks>
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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// Immutable record of the server certificate details observed by the transport during one TLS
/// handshake. Produced by the transport layer and consumed by <see cref="EncryptionInfoAccumulator"/>.
/// </summary>
/// <remarks>
/// Each value is <see langword="null"/> when it is unavailable: no certificate was presented
/// or it was larger than <see cref="MaxRawCertificateSize"/> (<see cref="RawCertificate"/>),
/// SqlClient did not evaluate the certificate (<see cref="ValidationErrors"/>), or the original
/// chain was not consulted or reported no usable status (<see cref="ChainStatus"/>).
/// </remarks>
internal sealed class ServerCertificateCapture
{
/// <summary>
/// The largest DER-encoded certificate, in bytes, that is captured. A larger certificate is
/// not captured; the connection is unaffected.
/// </summary>
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;
}

/// <summary>
/// Gets the DER encoding of the presented leaf certificate, or <see langword="null"/> if no
/// certificate was presented or it was larger than <see cref="MaxRawCertificateSize"/>.
/// The array is owned by this capture and must not be modified.
/// </summary>
public byte[]? RawCertificate { get; }
Comment thread
benrr101 marked this conversation as resolved.
Resolved

/// <summary>
/// Gets SqlClient's effective validation verdict, or <see langword="null"/> if SqlClient did
/// not evaluate the certificate.
/// </summary>
public SqlServerCertificateValidationErrors? ValidationErrors { get; }

/// <summary>
/// Gets the combined status flags of the chain supplied to the certificate validation
/// callback, or <see langword="null"/> if the chain was not consulted or is unavailable.
/// </summary>
public X509ChainStatusFlags? ChainStatus { get; }

/// <summary>
/// Gets the TLS protocol the transport reported for this handshake, or <see langword="null"/>
/// 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).
/// </summary>
public SslProtocols? Protocol { get; }

/// <summary>
/// Gets the IANA identifier of the cipher suite the transport reported for this handshake,
/// or <see langword="null"/> 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).
/// </summary>
public int? CipherSuite { get; }
}
}
Loading
Loading