Repository navigation
Connection encryption info – Slice D: Native SNI interop - #4836
priyankatiwari08 wants to merge 19 commits into
Conversation
There was a problem hiding this comment.
🟡 Changes recommended
Failed handshakes can expose an attempted protocol as negotiated, and the new tests omit required XML summaries.
2 open findings
What changed in this PR
Adds Native SNI certificate and TLS diagnostics to connection encryption snapshots, with graceful fallback for older native libraries.
Changes:
- Adds native certificate-validation interop and mapping.
- Captures certificate details after native TLS handshakes.
- Adds documentation and extensive unit coverage.
| File | Description |
|---|---|
doc/design-notes/2353-connection-encryption-info.md |
Documents Native SNI capture. |
Connection/EncryptionInfoCapture.cs |
Records transport-reported protocol. |
Connection/ServerCertificateCapture.cs |
Carries optional TLS protocol. |
SniNativeCertificateCapture.cs |
Queries and maps native details. |
TdsParser.cs |
Captures details after handshake waits. |
TdsParserStateObjectNative.cs |
Exposes native certificate capture. |
ISniNativeMethods.cs |
Extends the native interface. |
SniCertValidationInfo.cs |
Defines the native interop structure. |
SniNativeMethodsArm64.netfx.cs |
Adds ARM64 declarations. |
SniNativeMethodsNotSupported.netfx.cs |
Adds unsupported-platform stubs. |
SniNativeMethodsX64.netfx.cs |
Adds x64 declarations. |
SniNativeMethodsX86.netfx.cs |
Adds x86 declarations. |
SniNativeMethods.netcore.cs |
Adds modern .NET declarations. |
SniNativeWrapper.cs |
Wraps exports and protocol mapping. |
SniNativeCertificateCaptureTests.cs |
Tests mapping and degradation behavior. |
🧠 Review effort: Balanced
💡 Configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
5c61fc2 to
5e5fd50
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #4836 +/- ##
==========================================
+ Coverage 68.99% 72.89% +3.90%
==========================================
Files 314 316 +2
Lines 45857 71576 +25719
==========================================
+ Hits 31638 52174 +20536
- Misses 14219 19402 +5183
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:
|
5e5fd50 to
f1a8e10
Compare
db0de4e to
0d5e476
Compare
There was a problem hiding this comment.
🔵 Needs a closer look
Directly constructing SqlConnection bypasses the shared factory’s access-token handling for supported credential-free Azure SQL configurations, causing both theory cases to fail authentication before reaching certificate assertions.
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
The test bypasses the connection factory’s access-token injection, causing both cases to fail at login for supported credential-free Azure SQL configurations before reaching the certificate assertions.
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
The test directly constructs SqlConnection, bypassing managed-identity token assignment and causing both theory cases to fail authentication before certificate assertions for credential-free Azure SQL configurations accepted by its guard.
Review effort: Balanced
Query the new sni.dll exports SNIGetCertValidationInfoWrapper and SNIGetServerCertificateHashWrapper after the TLS handshake (success or failure, before handle close) and populate the per-attempt capture: hash (HASH flag), validation errors (VALIDATION_ERRORS), chain status (CHAIN_STATUS, unknown bits preserved), and protocol fallback (PROTOCOL) when not already recorded. Missing exports in older sni.dll are detected once and cached; fields stay null. Capture never throws or alters connection outcome. No SNI package bump: the native exports are not shipped yet (SNI PR 8573). Part of #2353 Co-authored-by: Copilot App <[email protected]>
…er ClearNegotiated Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
…tive gaps Native SNI now defers certificate validation unconditionally (SNI b9d842c) and reports HostNameMismatch|ChainError (SNI 55d318d), so the SchannelAutomatic and single-error gaps no longer apply. Older sni.dll still leaves fields null. Add a mapping test for the full deferred-validation verdict. Co-authored-by: Copilot App <[email protected]>
Request version 2 of SNI_CERT_VALIDATION_INFO (cbSize = 68) and map dwCipherSuite into the capture when dwVersion >= 2, cbSize >= 68 and the CIPHER_SUITE (0x80) availability flag is set. Version 1 responses from older sni.dll builds and missing exports leave the cipher suite null. Co-authored-by: Copilot App <[email protected]>
…4810) SNIHandle moved to Microsoft.Data.SqlClient.NativeSni and TdsParserStateObjectNative to Microsoft.Data.SqlClient.Parser. Co-authored-by: Copilot App <[email protected]>
Use the CLS-compliant NegotiatedCipherSuiteId in native capture tests and keep the .NET-only TlsCipherSuite enum assertion. Update the native SNI mapping row. Co-authored-by: Copilot App <[email protected]>
…ts hash Co-authored-by: Copilot App <[email protected]>
The native SNI package on main (8.0.0-preview1.26309.4) does not yet provide SNIGetServerCertificateWrapper/SNIGetCertValidationInfoWrapper, so the test checks for the export and expects a null certificate without it. Part of #2353 Co-authored-by: Copilot App <[email protected]>
- Leave native chain status null for leaf-time-only (pinned) results, matching Managed SNI. - Document that the native protocol is the server-selected version. - Add Native SNI simulator tests for untrusted certificates on Open and OpenAsync. - Use spy assertions instead of a throwing certificate query, and add test summaries. Co-authored-by: Copilot App <[email protected]>
Native SNI with the validation info export reports the protocol, cipher suite and mode on an untrusted-certificate failure, and the presented certificate when TrustServerCertificate=true; an older sni.dll reports none of them. Part of #2353 Co-authored-by: Copilot App <[email protected]>
With an sni.dll that provides the validation info export, native SNI reports mode Full, the server-selected protocol and the cipher suite on an untrusted-certificate failure; an older sni.dll reports none of them. Observing the protocol does not imply a completed handshake. Part of #2353 Co-authored-by: Copilot App <[email protected]>
The cipher suite comes from SNIGetCertValidationInfoWrapper while the presented certificate comes from the separate SNIGetServerCertificateWrapper export, so require the certificate only when that export is available. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Assign accumulator properties directly from the native capture, add the GetNegotiatedCipherSuite override backed by SNIGetCertValidationInfoWrapper, and keep an observed protocol when the SSL wait reports none. Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Native SNI now produces C's TlsHandshakeInfo record through the GetTlsHandshakeInfo override; the record is the single source of the protocol, cipher suite and certificate details. Remove the separate cipher-suite path and the swallowed exceptions (only missing-export EntryPointNotFoundException is cached), map cipher suites to TlsCipherSuite? on .NET, fall back to the handshake protocol when the record reports none, and drop the NativeSniServerCertificateTest manual test. Co-authored-by: Copilot App <[email protected]>
Adopt the Slice C accumulator pattern for native SNI: the native handle writes the certificate, validation errors, chain status, protocol and cipher suite straight into the attempt's EncryptionInfoAccumulator when EnableSsl fails and after WaitForSSLHandShakeToComplete, replacing the intermediate TlsHandshakeInfo record and GetTlsHandshakeInfo. The certificate is read into a pooled buffer and copied by the accumulator. A null handle is rejected before native code. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e
There was a problem hiding this comment.
🟡 Changes recommended
The null-handle test incorrectly assumes a process-wide flag is false, causing order-dependent failures; it should capture the initial value and assert that the calls leave it unchanged.
2 open issues
1 resolved since last review
Review effort: Balanced
paulmedynski
left a comment
There was a problem hiding this comment.
I'll look at the tests after we address my code feedback.
| /// <summary> | ||
| /// Copies the DER encoding of the server certificate presented during the most recent client | ||
| /// TLS handshake on <paramref name="pConn"/> into <paramref name="certificate"/>. Pass an empty | ||
| /// buffer to query the size, which is returned in <paramref name="certificateSize"/>. |
There was a problem hiding this comment.
If SqlClient asks for the size, and then never asks for the cert, does that leave a cert allocated on the SNI side, and if yes, for how long, and how large can it be?
There was a problem hiding this comment.
Yes, native SNI keeps a copy. During the handshake, SNI_Conn::m_CertCapture stores a heap copy of the leaf certificate DER, whether or not SqlClient ever asks for it.
- It is capped at 64 KB (
SNI_CERT_MAX_CAPTURED_SIZE). A larger certificate is not captured and reported as unavailable; the connection is unaffected. - It is replaced on a re-handshake and freed on reset or when the
SNI_Connis released. - The size query does not allocate.
So the worst case is one leaf certificate (at most 64 KB) per open native connection, for that connection's lifetime.
Auto-replied by the GitHub Copilot app
…ive capture - SNI_CERT_VALIDATION_INFO is a fixed 24-byte layout with no cbSize/dwVersion header. - SniNativeWrapper detects a missing export once per process and returns ERROR_PROC_NOT_FOUND. - Each native state object owns its SniNativeCertificateCapture; Default and flags removed. - Single certificate size check in Record; Apply is private; docs and flow comments added. - EncryptionInfoAccumulator parameters are nullable-annotated; tests and design note updated. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 5b0df491-21cd-4da0-b776-7cd9a8af085e
There was a problem hiding this comment.
🟡 Changes recommended
The native interop layout omits required header fields, causing queries to fail against the supported native build and leaving certificate, validation, and cipher diagnostics unavailable.
1 open issue
2 resolved since last review
Review effort: Balanced
| internal struct SniCertValidationInfo | ||
| { | ||
| /// <summary>Out: <see cref="SniCertInfoAvailability"/> flags.</summary> | ||
| public uint dwAvailable; |



Summary
Native SNI (Windows) now populates the per-attempt connection encryption info with the full presented server certificate (raw DER), validation errors, chain status, and (as a fallback) the server-selected TLS protocol observed by Schannel, which can be present even when the handshake did not complete, and the negotiated cipher suite. The values come from two new
sni.dllexports. This brings Native SNI to parity with Managed SNI (Slice C).Following the Threat Model Review outcome, the SHA-256 hash of the certificate is no longer captured or exposed; the driver exposes the presented certificate instead.
Part of #2353
Native dependency
SNIGetCertValidationInfoWrapperandSNIGetServerCertificateWrapperare added by native SNI PR 8573 (Microsoft.Data.SqlClient.sni), which hasn't shipped yet. The behavior also relies on SNI deferred validation (commitb9d842c) and the host-name verdict fix (commit55d318d) on ADOdev/automation/encryption-info-cert-exports.SniVersion. Main moved to8.0.0-preview1.26309.4(Update SNI dependencies to 8.0.0-preview1.26309.4 #5011), and D keeps main's version rather than downgrading it. That package does not contain these exports, so with the default build Native SNI reports no certificate details (graceful degradation). The exports are in7.1.0-preview3.26303.1(Microsoft.Data.SqlClient.SNIand.SNI.runtime; SNI pipeline 2312, run 187399, native commitd77d9e15e; signed DLL SHA-256: x64FFC43EB7…725E, x862941FD98…5937, arm644E89C37D…A9B0). An8.0.xSNI build containing native PR 8573 is needed before this PR can deliver native certificate details by default.7.1.0-preview3.26303.1.7.1.0-preview3.26303.1(run 187399, commitd77d9e15e), used locally with-p:SniVersion=7.1.0-preview3.26303.1. Superseded private test builds are not supported; if one is loaded, it rejects the 32-byte request with 87 and every field staysnull.Changes
SniCertValidationInfo: blittable 32-byte v1 struct (cbSize,dwVersion,dwAvailable,dwValidationMode,dwProtocol,dwValidationErrors,dwChainStatus,dwCipherSuite), plus the availability flag and validation mode enums. The certificate flag is0x4. SqlClient sendscbSize = 32.Cdecl) forSNIGetCertValidationInfoWrapperandSNIGetServerCertificateWrapper(pConn, pb, cb, pcb)for net10.0 and for the net462 x64/x86/ARM64 dlls. The NotSupported stub throws.SniNativeWrapper:SniGetServerCertificate; protocol mapping inToSslProtocols, shared by the handshake and capture paths.SniNativeCertificateCapture(#nullable enable):Record(handle, accumulator)queries the exports and writes directly into the attempt'sEncryptionInfoAccumulator(Slice C's accumulator pattern; no intermediate record and no state on the handle). A usable report replaces all five values (certificate, validation errors, chain status, protocol, cipher suite), withnullfor any value whose availability flag isn't set; an error code, missing export or malformed struct leaves the accumulator unchanged. The certificate is read into anArrayPoolbuffer and copied by the accumulator. A null handle is rejected before reaching native code. Native calls go through an internal delegate seam so tests can inject structs and certificate bytes.TdsParserStateObjectNativerecords inEnableSslwhen adding the SSL provider fails, and inWaitForSSLHandShakeToCompleteafter the wait (success or failure), so async native handshakes are covered.WaitForSSLHandShakeToCompletegains anEncryptionInfoAccumulatorparameter; Managed SNI ignores it because its validation callback already recorded the handshake. When nothing reported a protocol,TdsParser.EnableSslrecords the protocol from the completed handshake (existing fallback).Certificate read
When
dwAvailablehas0x4, SqlClient callsSNIGetServerCertificateWrappertwice:written == size.Any other result, or an
EntryPointNotFoundException(cached), gives anullcertificate; the other fields are still reported. Other exceptions propagate.Mapping
dwAvailableflag)SNIGetServerCertificateWrapper(CERTIFICATE0x4)ServerCertificateDerBytes(1..MaxServerCertificateDerBytesSize= 64 KiB)ServerCertificateValidationErrorsdwValidationErrors(VALIDATION_ERRORS0x8)ServerCertificateChainStatusdwChainStatus(CHAIN_STATUS0x10)CERT_TRUST_*value read asX509ChainStatusFlags; unknown bits preservedNegotiatedProtocoldwProtocol(PROTOCOL0x2)SP_PROT_*client bits mapped like the handshake result (TLS 1.3 is 0x3000 on net462). When unavailable, the handshake wait's protocol is used after a successful handshake.NegotiatedCipherSuiteId(all targets) /NegotiatedCipherSuite(TlsCipherSuite?, .NET only)dwCipherSuite(CIPHER_SUITE0x80)null. Mapped byMapCipherSuitetoTlsCipherSuite?on .NET (no int cast) andint?on netfx; the record is the only source; kept on a deferred-validation failure.The struct is ignored when
cbSize < 32ordwVersion < 1. Newer versions are accepted and their trailing data is ignored. Any field whose flag isn't set staysnull.Degradation behavior
EntryPointNotFoundExceptionis cached once per export. A missing validation-info export leaves all fieldsnull; a missing certificate export leaves only the certificatenull. There is no hash fallback.null.null.catch (Exception)blocks).Native deferred validation (always on)
Native SNI always defers server certificate validation until Schannel has the presented certificate; there is no opt-in or opt-out switch (decision by Paul Medynski; going to security review). With the matching SNI build, the certificate, validation errors and chain status are reported in every validation mode, including SchannelAutomatic failures, and a wrong
HostNameInCertificatewith an untrusted chain reportsHostNameMismatch | ChainError, the same as Managed SNI. Accept/reject results and error codes are unchanged. Fields are never derived from HRESULTs or error messages.Open questions
dwProtocolfrom the Schannel connection info after the server hello, so it is the version the server selected, not the client's offered set. This PR records it when no protocol was already recorded (G2/D15: observed mode/protocol kept on validation failure).CHAIN_STATUS_LEAF_TIME_ONLY(0x40). Set only for pinned-certificate expiry, where SNI checks the leaf validity period and builds no chain. Chain status is reported asnullin that case, matching Managed SNI in pinned modes.dwValidationMode. Read but not used in the mapping.Test results
0bab0c633, rebased onto main (after Slice C merged asce73774d1). The last commit replaces theTlsHandshakeInforecord with direct accumulator writes.SniNativeCertificateCapture|EncryptionInfoAccumulator|ServerCertificateCapturefilter with main's SNI 8.0.0-preview1.26309.4 (no exports): net10.0 412/412, net462 413/413.SniNativeCertificateCaptureTestscover: 32-byte struct layout; all 256 availability-flag combinations; certificate size limits (0, 1, 64 KiB, 64 KiB + 1), size query then read, read failures and short reads; missing exports (cached, no fallback); every validation-error bit and chain flag plus unknown bits; protocol mapping including TLS 1.3; cipher suite range; malformed and newer struct versions; return codes 87, 122, 1168 and others; propagating exceptions; null handle with the real binding; null accumulator; a later report replacing earlier values (including withnull); and an unusable report leaving earlier values unchanged.NativeSniEncryptionInfoTests(simulated server, Open and OpenAsync, Native SNI, untrusted self-signed certificate) assert the presented DER,ChainErrorandUntrustedRootwhen the exports exist, andnullotherwise.ConnectionEncryptionInfoTestsfixture fails to create its certificate (Cannot find drive 'Cert'in the PowerShell host); this is environmental and unrelated to this change.7.1.0-preview3.26303.1.Further manual tests
Run on Native SNI for net462 and net10.0, on x64, x86 and ARM64, with both sync and async Open:
None/NoError, protocol and cipher suite populatedChainErrorplus the correct chain flags onSqlException.EncryptionInfoHostNameInCertificate:HostNameMismatch(HostNameMismatch | ChainErrorwith an untrusted chain)ServerCertificatepin mismatch:PinnedCertificateMismatch, withChainStatusnullTrustServerCertificate=true: certificate present, validation fields nullChainErrorand chain status reportedChecklist
7.1.0-preview3.26303.1via-p:SniVersion, live Open/OpenAsync on an earlier head)