Repository navigation
Connection encryption info – Slice C: Managed SNI certificate capture - #4835
priyankatiwari08 wants to merge 17 commits into
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% 70.38% +1.39%
==========================================
Files 314 316 +2
Lines 45857 70193 +24336
==========================================
+ Hits 31638 49407 +17769
- Misses 14219 20786 +6567
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
… 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>
- 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>
There was a problem hiding this comment.
🔵 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
left a comment
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
Why do we have this limit, and how did we choose it?
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
| /// 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"/> |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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
X509Cetrificate2instance to ourValidateServerCertificatecallback. - We can check for that type and use its
RawDataMemoryproperty to check the DER size and avoid callingGetRawCertData()entirely. - Accessing
RawDataMemorywill 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 ofRawDataMemory, and we can avoid that unnecessary allocation though.- Pass the
ReadOnlyMemory<byte>returned byRawDataMemorydirectly 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
RemoteCertificateValidationCallbackactually receives an oldX509Certificateinstance, we would have to fall back to callingGetRawCertData()and wrapping that in aReadOnlyMemory<byte>is zero-copy.



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: