Repository navigation
Connection encryption info – Slice C: Managed SNI certificate capture - #4835
Conversation
There was a problem hiding this comment.
🔵 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 Report❌ Patch coverage is 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
7d60501 to
549fd10
Compare
549fd10 to
502f3f3
Compare
e4e6869 to
e9fbf4b
Compare
e9fbf4b to
78f101e
Compare
paulmedynski
left a comment
There was a problem hiding this comment.
I will look at the tests once the codebase feedback has been addressed.
benrr101
left a comment
There was a problem hiding this comment.
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>
There was a problem hiding this comment.
🔵 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
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
paulmedynski
left a comment
There was a problem hiding this comment.
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
There was a problem hiding this comment.
🔵 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
There was a problem hiding this comment.
🔵 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
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
There was a problem hiding this comment.
🔵 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
left a comment
There was a problem hiding this comment.
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
There was a problem hiding this comment.
🔵 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



Description
Slice C of the connection encryption info feature. Managed SNI now captures the server certificate details from
RemoteCertificateValidationCallbackduring the TLS handshake. It flows them throughTdsParserStateObjectinto Slice B's per-attemptEncryptionInfoAccumulator, so both snapshots include them:SqlConnection.EncryptionInfoon successSqlException.EncryptionInfoon failureNative SNI does not return certificate data yet; that is Slice D.
Scope and guarantees
Message,ToString()or EventSource output.finallyblock, and they are read afterAuthenticateAsClientreturns insideEnableSsl.Capture points
nullwhenGetServerCertificate()/ internalPresentedServerCertificateRawDataGetRawCertData()), taken in the callback'sfinallyand stored in the handle'sTlsHandshakeInforecord (each callback replaces it; latest wins). Captured even underTrustServerCertificatebypass and on validation failure.CryptographicException), or its DER exceeds 64 KiB (TlsHandshakeInfo.MaxDerBytesSize).ServerCertificateValidationErrorsServerCertificateMissing(null certificate orRemoteCertificateNotAvailable),ChainError,HostNameMismatch(afterHostNameInCertificate),PinnedCertificateMismatch.Nonewhen validation passed.TrustServerCertificate), or theServerCertificatefile couldn't be read.ServerCertificateChainStatusX509Chain.ChainStatusflags (no rebuild).NoErrorwhen the chain was clean.ServerCertificatepin mode (chain not consulted, even on match); no certificate; null chain; orRemoteCertificateChainErrorswith no flags.NegotiatedEncryptionProtocol(Managed contribution)SslStream.SslProtocol, read inside the callback into theTlsHandshakeInforecord and assigned byEnableSsldirectly. The record is the single source of truth; the completed-handshake protocol is used only when there is no record (native SNI).None.NegotiatedCipherSuiteId(Managed contribution)SslStream.NegotiatedCipherSuite, read inside the callback into the record asTlsCipherSuite?(no casts on .NET) and assigned byEnableSsldirectly. No post-handshake read. TCP and named pipes; MARS passes through.0(TLS_NULL_WITH_NULL_NULL).NegotiatedEncryptionModeThe protocol and cipher suite contributions are .NET only, because Managed SNI isn't compiled for .NET Framework.
Notable behavior
Full, the observed protocol (for exampleTls12) and cipher suite, together with the certificate,ServerCertificateValidationErrorsandServerCertificateChainStatus.EnableSslassigns the handshake record before reporting the failure. Native SNI still reports none of them.., andX509Certificate2.MatchesHostname(".")throwsArgumentException, as it already does on main.ValidateSslServerCertificaterecords the errors it already knows (for exampleChainErrorand 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 staynullrather than reportingNone.TlsHandshakeInfo.DerBytesandEncryptionInfoAccumulator.ServerCertificateDerBytes.Documentation
doc/design-notes/2353-connection-encryption-info.mdgains 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):SslPolicyErrorscombination,HostNameInCertificateoverride and mismatch, pin match, mismatch, missing and unreadable.X509ChainStatusFlagsvalue, and the full set, is preserved. An unbuilt chain is not rebuilt.CertificateRequestself-signed certificate and are a copy. A certificate over 64 KiB is not captured.GetServerCertificate().RawDataround-trips.null(unavailable) and zero values stay distinct. Nothing leaks intoMessageorToString().CreateTlsHandshakeInforuns 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 ExpectedChainError, Actualnull.ManagedSniCertificateCaptureTests(simulated TDS server over TLS, Managed SNI forced on Windows). Each scenario has separateOpenandOpenAsynctests:TrustServerCertificatebypass (certificate only), and a matching pin.ChainError, chain flags, certificate), host name mismatch,HostNameInCertificateoverride and mismatch, and pin mismatch. Failure cases also assert modeFulland protocolTls12.Reset().SslStream.NegotiatedCipherSuiteon success. On failure it equals the suite a trusted handshake with the same server negotiates.ConnectionEncryptionInfoTests(Slice B tests, adapted):TrustServerCertificatebypass and reconnect on Managed SNI report the certificate. An untrusted failure on Managed SNI reports mode, protocol and cipher suite.Results on head
597acee2cBase: main, which includes the merged #4831 (
0a46e011d). Filter:ManagedSni|SniCommon|SimulatedServerTests|SqlException|SqlConnection|EncryptionInfo.PSModulePath,--blame-hang-timeout 10m)Changes from the previous head (
7ba56fe41), addressing Paul's review:ServerCertificaterecord toTlsHandshakeInfo(DerBytes,MaxDerBytesSize,TlsCipherSuite? CipherSuiteon .NET), withGetTlsHandshakeInfo()andSniCommon.CreateTlsHandshakeInfo. Renamed the accumulator'sServerCertificateRawDatatoServerCertificateDerBytes.NegotiatedCipherSuitefrom the SNI handles,GetNegotiatedCipherSuite()and the post-handshake cipher read;EnableSslassigns the record's values directly.CreateTlsHandshakeInfotakes anSslStream, and onlyCryptographicExceptionis caught (aroundGetRawCertData()).CreateTlsHandshakeInfoandGetChainStatus; nullable enabled for the new code; plainifinstead of clever conditionals; one argument per line.SslStreamtests with in-callback loopback handshake tests. Test counts changed accordingly.Manual tests still needed
Encrypt=Strictagainst a real server. The simulated server covers it in the automated tests.Guidelines
Please review the contribution guidelines before submitting a pull request: