Skip to content

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

Open
priyankatiwari08 wants to merge 17 commits into
mainfrom
dev/automation/encryption-info-slice-c-managed-sni
Open

priyankatiwari08 wants to merge 17 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 87.63441% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 70.38%. Comparing base (17bef7b) to head (f58216f).
⚠️ Report is 24 commits behind head on main.

Files with missing lines Patch % Lines
...t/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs 7.14% 13 Missing ⚠️
...oft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs 96.34% 3 Missing ⚠️
...t/src/Microsoft/Data/SqlClient/Parser/TdsParser.cs 78.57% 3 Missing ⚠️
...oft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs 0.00% 1 Missing ⚠️
.../SqlClient/ManagedSni/SniMarsConnection.netcore.cs 0.00% 1 Missing ⚠️
...Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs 0.00% 1 Missing ⚠️
...soft/Data/SqlClient/Parser/TdsParserStateObject.cs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4835      +/-   ##
==========================================
+ Coverage   68.99%   70.38%   +1.39%     
==========================================
  Files         314      316       +2     
  Lines       45857    70193   +24336     
==========================================
+ Hits        31638    49407   +17769     
- Misses      14219    20786    +6567     
Flag Coverage Δ
CI-SqlClient ?
sqlclient-pr 70.38% <87.63%> (?)

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
priyankatiwari08 and others added 7 commits November 18, 2026 10:04
… SNI)

Managed SNI now captures a copy of the presented leaf certificate's DER
encoding (GetRawCertData) instead of its SHA-256 hash, and passes it to the
snapshot so SqlConnectionEncryptionInfo.GetServerCertificate() can return it.
Certificates over 64 KiB are not captured, and the first certificate
presented in an attempt is kept. Capture still happens in the validation
callback's finally block, so it is present on TrustServerCertificate bypass
and on validation failure.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
- Reset the attempt's encryption info capture when Connect retries after an
  instance-resolution failure, so only the retried attempt's values publish.
- Document that an observed protocol is kept after a failure.
- Compare capture outcomes against an independent restatement of the
  validation rules instead of the legacy overload.
- Add routed single-login tests proving only the terminal attempt's certificate
  is published, including a terminal attempt that fails before TLS.
- Add XML summaries and Arrange/Act/Assert structure to the capture tests.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Replace the bool-async theories with separate Open_ and OpenAsync_ tests that call each API directly, sharing setup and scenario assertion helpers.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Slice B's reconnect tests asserted that certificate fields are null. Managed SNI now records the presented certificate under TrustServerCertificate, so use the bypass assertion.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Use the shared EncryptionInfoTestData.AssertEmpty helper and value-returning Assert.NotNull instead of ad-hoc IsEmpty checks and null-forgiving operators. Test-only; no product change.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Move C's certificate-field tests into EncryptionInfoAccumulatorTests using the
accumulator's settable properties, drop the RecordServerCertificate-based tests,
remove the inherited AssertCertificateFieldsNull use from the enlistment test
(Managed SNI now records the presented certificate), and update the remaining
EncryptionInfoCapture references in docs and comments.

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

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

Platform-dependent TLS callback behavior requires human runtime validation on Linux, named pipes over TLS, and real MARS sessions to establish observation-only behavior.

No open issues 🎉

Review effort: Balanced

- Rename ServerCertificateCapture to ServerCertificate, with matching handle,
  state-object, factory, file and test names.
- Document MaxRawCertificateSize as 64 KiB (65,536 bytes) and sort properties.
- Document SNI handle overrides with inheritdoc; make SniMarsConnection
  pass-throughs internal and document them.
- Use a volatile field for the captured certificate on TCP and NP handles.
- Use a using declaration in SniNpHandle.ValidateServerCertificate.
- Replace the accumulator property-subset theory with the existing
  per-property 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

Platform-dependent TLS callback behavior still requires human validation against real SQL Server, managed named pipes, and actual MARS sessions beyond the supplied simulated TCP/Strict tests.

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.

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

/// 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;

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.

Why do we have this limit, and how did we choose it?

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

/// did not evaluate the certificate (<see cref="ValidationErrors"/>), the original chain was
/// not consulted or reported no usable status (<see cref="ChainStatus"/>), or the transport
/// did not report a protocol or cipher suite.
/// Values are recorded as the transport observed them. <see cref="EncryptionInfoAccumulator"/>

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.

This class has no idea how/why it's values are set, so it shouldn't discuss this at all. This entire remarks block can be removed.

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.

This whole class may disappear, so this comment may be moot.

#endif

/// <summary>
/// Gets the DER encoding of the presented leaf certificate, or <see langword="null"/> if no

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.

This comment also makes assumptions about how/why the DER bytes are set. Let's just say:

Gets the DER encoding of the presented leaf certificate, or null if none was provided.


if (derBytes is not null
&& (derBytes.Length == 0 || derBytes.Length > TlsHandshakeInfo.MaxDerBytesSize))
&& !EncryptionInfoAccumulator.IsReportableServerCertificateSize(derBytes.Length))

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.

Ahhh now I see how this is all related. Sorry for not identifying this earlier!

What if EnableSsl received the current Accumulator instance? Then the call chain would look like this:

Parser obtains the current per-attempt accumulator
    -> passes it into EnableSsl
        -> certificate callback validates as today
        -> callback's finally records into accumulator:
             protocol, cipher suite, certificate memory,
             validation errors, chain status
    -> EnableSsl returns
Parser processes success/failure

What this buys us:

  • Eliminate _tlsHandshakeInfo from TCP and named-pipe handles.
  • Potentially eliminate the entire intermediate record type.
  • Remove its accessors through the state object and MARS layers.
  • Apply the accumulator’s certificate-size policy before the callback returns.
  • Pass RawDataMemory directly into the accumulator; use GetRawCertData() only for a legacy certificate.
  • Preserve failure diagnostics by recording in the callback’s finally, before the handshake failure is processed.

This will involve changing when we register our ValidateServerCertificate callback with SslStream:

  • Stop registering the fixed callback in the stream constructor.
  • Inside SNI’s handshake method, configure SslClientAuthenticationOptions.RemoteCertificateValidationCallback with a closure over a nullable, handshake-local accumulator reference.
  • Have that callback validate normally and record observations in finally.
  • Clear the captured accumulator reference in the handshake method’s finally.

Note the other optimization suggested above:

  • .NET 10 currently passes an X509Cetrificate2 instance to our ValidateServerCertificate callback.
  • We can check for that type and use its RawDataMemory property to check the DER size and avoid calling GetRawCertData() entirely.
  • Accessing RawDataMemory will materialize the DER bytes - we cannot avoid that allocation - there is no way to ask for the size of the cert without allocating the DER bytes unfortunately.
  • GetRawCertData() makes a copy of RawDataMemory, and we can avoid that unnecessary allocation though.
  • Pass the ReadOnlyMemory<byte> returned by RawDataMemory directly to the accumulator, and it can perform the max size check itself. It would take a defensive copy of the bytes if they are within the limit.
  • If our RemoteCertificateValidationCallback actually receives an old X509Certificate instance, we would have to fall back to calling GetRawCertData() and wrapping that in a ReadOnlyMemory<byte> is zero-copy.

This branch has not been deployed

No deployments
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: Waiting for customer

Development

Successfully merging this pull request may close these issues.

Feature | Expose connection encryption information to clients

5 participants