Skip to content

Connection encryption info – Slice C: Managed SNI certificate capture - #4835

Merged
priyankatiwari08 merged 20 commits into
mainfrom
dev/automation/encryption-info-slice-c-managed-sni
Nov 20, 2026
Merged

priyankatiwari08 merged 20 commits into
mainfrom
dev/automation/encryption-info-slice-c-managed-sni

Conversation

@priyankatiwari08

@priyankatiwari08 priyankatiwari08 commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #4831 — review only the commits on top of the Slice B branch (dev/automation/encryption-info-slice-b-mode-protocol).

Description

Slice C of the connection encryption info feature. Managed SNI now captures the server certificate details from RemoteCertificateValidationCallback during the TLS handshake. It flows them through TdsParserStateObject into Slice B's per-attempt EncryptionInfoAccumulator, so both snapshots include them:

  • SqlConnection.EncryptionInfo on success
  • SqlException.EncryptionInfo on failure

Native SNI does not return certificate data yet; that is Slice D.

Scope and guarantees

  • Observation only. Capture reuses the callback's inputs and SqlClient's existing verdict. It performs no extra validation or network work, and it does not rebuild the chain.
  • No behavior change. Trust decisions, exception messages and tracing text are unchanged. Certificate data and flags never appear in Message, ToString() or EventSource output.
  • No public API change. Slice C fills the snapshot constructor added in Slice A (Connection encryption info – Slice A: public API surface #4830).
  • Per attempt. Values reset at the start of every TLS handshake or login attempt. The callback writes them to a volatile field in its finally block, and they are read after AuthenticateAsClient returns inside EnableSsl.

Capture points

Field Source null when
GetServerCertificate() / internal PresentedServerCertificateRawData Copy of the presented leaf certificate's DER (GetRawCertData()), taken in the callback's finally and stored in the handle's TlsHandshakeInfo record (each callback replaces it; latest wins). Captured even under TrustServerCertificate bypass and on validation failure. No certificate was presented, its encoding couldn't be read (CryptographicException), or its DER exceeds 64 KiB (TlsHandshakeInfo.MaxDerBytesSize).
ServerCertificateValidationErrors SqlClient's effective verdict: ServerCertificateMissing (null certificate or RemoteCertificateNotAvailable), ChainError, HostNameMismatch (after HostNameInCertificate), PinnedCertificateMismatch. None when validation passed. Validation bypassed (TrustServerCertificate), or the ServerCertificate file couldn't be read.
ServerCertificateChainStatus OR of the original callback X509Chain.ChainStatus flags (no rebuild). NoError when the chain was clean. Bypass; ServerCertificate pin mode (chain not consulted, even on match); no certificate; null chain; or RemoteCertificateChainErrors with no flags.
NegotiatedEncryptionProtocol (Managed contribution) SslStream.SslProtocol, read inside the callback into the TlsHandshakeInfo record and assigned by EnableSsl directly. The record is the single source of truth; the completed-handshake protocol is used only when there is no record (native SNI). No TLS, or the value is None.
NegotiatedCipherSuiteId (Managed contribution) SslStream.NegotiatedCipherSuite, read inside the callback into the record as TlsCipherSuite? (no casts on .NET) and assigned by EnableSsl directly. No post-handshake read. TCP and named pipes; MARS passes through. No TLS, or the value is 0 (TLS_NULL_WITH_NULL_NULL).
NegotiatedEncryptionMode Slice B: recorded at PRELOGIN selection (or before the TLS-first handshake for Strict) and kept on TLS/certificate failure. No mode selected yet.

The protocol and cipher suite contributions are .NET only, because Managed SNI isn't compiled for .NET Framework.

Notable behavior

  • Validation failure on Managed SNI. The exception snapshot reports mode Full, the observed protocol (for example Tls12) and cipher suite, together with the certificate, ServerCertificateValidationErrors and ServerCertificateChainStatus. EnableSsl assigns the handshake record before reporting the failure. Native SNI still reports none of them.
  • Named pipes. Managed SNI validates named pipes against the target ., and X509Certificate2.MatchesHostname(".") throws ArgumentException, as it already does on main. ValidateSslServerCertificate records the errors it already knows (for example ChainError and the chain status) before the host name check, so the capture survives the throw. The exception is not caught or changed. If no error is known before the check, the fields stay null rather than reporting None.
  • Certificate instead of hash. Following the Threat Model Review, the earlier SHA-256 hash was replaced by the certificate itself. The internal names are TlsHandshakeInfo.DerBytes and EncryptionInfoAccumulator.ServerCertificateDerBytes.

Documentation

doc/design-notes/2353-connection-encryption-info.md gains a "Managed SNI certificate capture" section. Its failure-path notes now distinguish Managed SNI (mode, protocol and certificate reported) from native SNI (none reported).

Issues

Part of #2353. Stacked on #4831 (Slice B), which is stacked on #4830 (Slice A).

Testing

Automated tests

  • SniCommonTlsHandshakeInfoTest (unit, .NET):
    • Table-driven verdicts: null certificate, each SslPolicyErrors combination, HostNameInCertificate override and mismatch, pin match, mismatch, missing and unreadable.
    • Outcome and message match the legacy overload, using an independent message baseline.
    • Every X509ChainStatusFlags value, and the full set, is preserved. An unbuilt chain is not rebuilt.
    • Captured bytes equal the DER of a CertificateRequest self-signed certificate and are a copy. A certificate over 64 KiB is not captured. GetServerCertificate().RawData round-trips.
    • null (unavailable) and zero values stay distinct. Nothing leaks into Message or ToString().
    • CreateTlsHandshakeInfo runs inside a real loopback TLS handshake callback: DER, protocol and cipher suite recorded; size cap; bypass (verdict unavailable); no certificate.
    • ValidateSslServerCertificate_NamedPipeDotTarget_CapturesKnownErrorsAndKeepsException. Without the fix it fails with Expected ChainError, Actual null.
  • ManagedSniCertificateCaptureTests (simulated TDS server over TLS, Managed SNI forced on Windows). Each scenario has separate Open and OpenAsync tests:
    • TrustServerCertificate bypass (certificate only), and a matching pin.
    • Untrusted self-signed (ChainError, chain flags, certificate), host name mismatch, HostNameInCertificate override and mismatch, and pin mismatch. Failure cases also assert mode Full and protocol Tls12.
    • Per-attempt isolation, including failure then success. This was mutation-checked against removing the per-attempt Reset().
    • The cipher suite equals SslStream.NegotiatedCipherSuite on success. On failure it equals the suite a trusted handshake with the same server negotiates.
  • ConnectionEncryptionInfoTests (Slice B tests, adapted): TrustServerCertificate bypass and reconnect on Managed SNI report the certificate. An untrusted failure on Managed SNI reports mode, protocol and cipher suite.

Results on head 597acee2c

Base: main, which includes the merged #4831 (0a46e011d). Filter: ManagedSni|SniCommon|SimulatedServerTests|SqlException|SqlConnection|EncryptionInfo.

Target Result
net10.0 1210/1210 passed
net462 (clean PSModulePath, --blame-hang-timeout 10m) 1007/1007 passed. The run reports only the known post-run testhost teardown hang.
Driver, ref, notsupported, UnitTests and ManualTests builds 0 warnings, 0 errors

Changes from the previous head (7ba56fe41), addressing Paul's review:

  • Renamed the internal ServerCertificate record to TlsHandshakeInfo (DerBytes, MaxDerBytesSize, TlsCipherSuite? CipherSuite on .NET), with GetTlsHandshakeInfo() and SniCommon.CreateTlsHandshakeInfo. Renamed the accumulator's ServerCertificateRawData to ServerCertificateDerBytes.
  • The record is the single source of truth for protocol and cipher suite: removed NegotiatedCipherSuite from the SNI handles, GetNegotiatedCipherSuite() and the post-handshake cipher read; EnableSsl assigns the record's values directly.
  • Each callback replaces the record (latest wins). CreateTlsHandshakeInfo takes an SslStream, and only CryptographicException is caught (around GetRawCertData()).
  • Folded helpers into CreateTlsHandshakeInfo and GetChainStatus; nullable enabled for the new code; plain if instead of clever conditionals; one argument per line.
  • Replaced synthetic SslStream tests with in-callback loopback handshake tests. Test counts changed accordingly.

Manual tests still needed

  • Real SQL Server with trusted, untrusted and host-name-mismatch certificates, on Managed SNI (Windows and Linux).
  • Named pipes over TLS.
  • TDS 8 / Encrypt=Strict against a real server. The simulated server covers it in the automated tests.
  • MARS over TLS.

Guidelines

Please review the contribution guidelines before submitting a pull request:

Copilot AI balanced review requested due to automatic review settings October 13, 2026 03:41

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

TLS transport changes still lack effective same-attempt isolation coverage and require the listed real-server validation.

4 open findings
What changed in this PR

Adds Slice C of connection encryption diagnostics, capturing Managed SNI server certificate details for successful and failed connections.

Changes:

  • Captures certificate hashes, validation verdicts, and chain status.
  • Propagates captured data through TDS and MARS layers.
  • Adds unit coverage and design documentation.
File Description
ManagedSniCertificateCaptureTests.cs Adds simulated TLS integration tests.
ConnectionEncryptionInfoTests.cs Updates managed-SNI hash expectations.
SniCommonServerCertificateCaptureTest.cs Tests validation and capture logic.
TdsParserStateObjectManaged.netcore.cs Exposes managed transport capture.
TdsParserStateObject.cs Defines the transport capture hook.
TdsParser.cs Records capture after TLS negotiation.
SniTcpHandle.netcore.cs Captures TCP TLS certificate details.
SniNpHandle.netcore.cs Captures Named Pipes TLS certificate details.
SniMarsHandle.netcore.cs Forwards capture through MARS handles.
SniMarsConnection.netcore.cs Exposes the physical MARS capture.
SniHandle.netcore.cs Adds the capture property contract.
SniCommon.netcore.cs Produces validation verdicts, hashes, and chain flags.
ServerCertificateCapture.cs Defines the immutable transport capture.
EncryptionInfoCapture.cs Publishes certificate fields in snapshots.
2353-connection-encryption-info.md Documents Managed SNI capture semantics.

🧠 Review effort: Balanced


💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@codecov

codecov Bot commented Oct 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.64804% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 72.86%. Comparing base (17bef7b) to head (be7e2f0).
⚠️ Report is 27 commits behind head on main.

Files with missing lines Patch % Lines
...oft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs 96.10% 3 Missing ⚠️
.../SqlClient/ManagedSni/SniMarsConnection.netcore.cs 0.00% 1 Missing ⚠️
...Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs 0.00% 1 Missing ⚠️
...t/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs 94.11% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4835      +/-   ##
==========================================
+ Coverage   68.99%   72.86%   +3.87%     
==========================================
  Files         314      315       +1     
  Lines       45857    71434   +25577     
==========================================
+ Hits        31638    52053   +20415     
- Misses      14219    19381    +5162     
Flag Coverage Δ
CI-SqlClient ?
sqlclient-pr 72.86% <96.64%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copilot AI balanced review requested due to automatic review settings October 13, 2026 09:20
@priyankatiwari08
priyankatiwari08 force-pushed the dev/automation/encryption-info-slice-c-managed-sni branch from 7d60501 to 549fd10 Compare October 13, 2026 09:20

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Four unresolved review findings leave regression and attempt-isolation coverage incomplete.

4 open findings

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 15, 2026 09:28
@priyankatiwari08
priyankatiwari08 force-pushed the dev/automation/encryption-info-slice-c-managed-sni branch from 549fd10 to 502f3f3 Compare October 15, 2026 09:28

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Security-sensitive TLS changes still need the documented cross-platform real-server, Strict encryption, Named Pipes, and MARS validation.

4 open findings

🧠 Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings October 19, 2026 09:33

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Retry isolation needs correction, and real-server, Strict, Named Pipes, and MARS TLS validation remains pending.

5 open issues

Review effort: Balanced

@priyankatiwari08 priyankatiwari08 added this to the 8.0.0-preview1 milestone Oct 19, 2026
@priyankatiwari08 priyankatiwari08 changed the title [Draft] Connection encryption info – Slice C: Managed SNI certificate capture [DO NOT MERGE] [Draft] Connection encryption info – Slice C: Managed SNI certificate capture Oct 19, 2026
@mdaigle mdaigle linked an issue Oct 20, 2026 that may be closed by this pull request
Copilot AI balanced review requested due to automatic review settings October 22, 2026 08:31
@priyankatiwari08
priyankatiwari08 force-pushed the dev/automation/encryption-info-slice-c-managed-sni branch from e4e6869 to e9fbf4b Compare October 22, 2026 08:31

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human validation remains necessary for real-server certificate scenarios on Windows/Linux, named-pipe TLS, Strict/TDS 8, and MARS.

5 open issues

Review effort: Balanced

@priyankatiwari08
priyankatiwari08 force-pushed the dev/automation/encryption-info-slice-c-managed-sni branch from e9fbf4b to 78f101e Compare October 26, 2026 17:45

@paulmedynski paulmedynski left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will look at the tests once the codebase feedback has been addressed.

benrr101
benrr101 previously approved these changes Nov 18, 2026

@benrr101 benrr101 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for addressing my comments

- Rename ServerCertificate to TlsHandshakeInfo (DerBytes, MaxDerBytesSize,
  TlsCipherSuite? CipherSuite on .NET); GetTlsHandshakeInfo() on state objects.
- Remove NegotiatedCipherSuite from SNI handles and GetNegotiatedCipherSuite;
  EnableSsl assigns all record values directly, without precedence logic.
- Fold helpers into CreateTlsHandshakeInfo(SslStream, ...) and GetChainStatus;
  only CryptographicException is caught; latest callback record wins.
- Rename accumulator ServerCertificateRawData to ServerCertificateDerBytes.
- Enable nullable for new code, simplify conditionals, update design note.
- Replace synthetic tests with in-callback loopback handshake tests.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

TLS callback capture affects multiple transports and failed handshakes, but simulator coverage does not establish behavior on real SQL Server across Windows/Linux, named-pipe TLS, Strict/TDS 8, and MARS.

No open issues 🎉

Review effort: Balanced

benrr101
benrr101 previously approved these changes Nov 18, 2026
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed to weigh an unpublished, low-severity documentation mismatch between certificate-diagnostics member names and the actual public API.

No open issues 🎉

Review effort: Balanced

benrr101
benrr101 previously approved these changes Nov 18, 2026

@paulmedynski paulmedynski left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the cleanup based on my previous round of feedback - this is much simpler now and easy to understand, with no data inconsistencies.

I will have a look at the tests shortly.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

The TLS callback changes affect transport and diagnostic paths that still require human validation against real SQL Server on Windows/Linux, including named pipes, Strict/TDS 8, and MARS.

No open issues 🎉

Review effort: Balanced

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

TLS callback capture affects every Managed SNI handshake, but real-server validation across Windows/Linux, named pipes, Strict/TDS 8, and MARS remains outstanding, and current-head CI is still running.

No open issues 🎉

Review effort: Balanced

benrr101
benrr101 previously approved these changes Nov 19, 2026
priyankatiwari08 and others added 2 commits November 20, 2026 20:47
Pass the per-attempt EncryptionInfoAccumulator into EnableSsl and
register a per-handshake certificate validation callback through
SslClientAuthenticationOptions. The callback captures a local reference
that is cleared in finally, so the handle keeps no handshake state and a
late callback cannot write to the attempt.

SniCommon.RecordTlsHandshake writes the certificate, chain status,
cipher suite, protocol and validation errors straight to the
accumulator, which owns normalization and the 64 KiB cap. This removes
TlsHandshakeInfo and the copy step in TdsParser.EnableSsl.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e
Read the presented certificate through X509Certificate2.RawDataMemory
and add EncryptionInfoAccumulator.SetServerCertificateDerBytes, which
copies the span only when it is within the 64 KiB cap. An oversized
certificate is now never copied, rather than copied and then dropped.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

TLS callback changes affect both TCP and named pipes, but current-head CI and real-server validation of Windows/Linux certificate failures, named-pipe TLS, Strict/TDS 8, and MARS remain outstanding.

No open issues 🎉

Review effort: Balanced

@paulmedynski paulmedynski left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes look great! One suggestion to avoid copying the DER bytes when creating an encryption info snapshot from the accumulator.

ServerCertificateDerBytes is now ReadOnlyMemory<byte>? and its setter
applies the size cap and stores the accumulator's own copy, replacing
SetServerCertificateDerBytes. SqlConnectionEncryptionInfo retains that
never-mutated copy instead of cloning it, so ToSnapshot copies nothing.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

TLS callback changes span both managed transports, but real SQL Server validation across Windows/Linux, named-pipe TLS, Strict/TDS 8, and MARS remains pending, with current-head build/test checks still running.

No open issues 🎉

Review effort: Balanced

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Hotfix 8.0.0 PRs that must be backported to release/8.0

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Feature | Expose connection encryption information to clients

5 participants