Repository navigation
Connection encryption info – Slice D: Native SNI interop - #4836
priyankatiwari08 wants to merge 15 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 @@
## dev/automation/encryption-info-slice-c-managed-sni #4836 +/- ##
======================================================================================
- Coverage 72.01% 69.59% -2.42%
======================================================================================
Files 316 318 +2
Lines 71326 70135 -1191
======================================================================================
- Hits 51365 48813 -2552
- Misses 19961 21322 +1361
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
1965a79 to
f515c1e
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The tests incorrectly require a non-null certificate when Native SNI can report a cipher suite without one if SNIGetServerCertificateWrapper is unavailable, causing failures in a supported degradation case.
2 open issues
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
The native ABI and deferred certificate-validation contracts depend on unshipped SNI exports, leaving native/security-owner review and key TLS and architecture verification outstanding.
1 resolved since last review
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Unshipped SNI exports and deferred-validation ABI changes require coordinated native/security review and validation with a matching Windows native build, especially for x86, ARM64, and Strict/TLS 1.3 paths.
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
Native ABI and deferred certificate-validation behavior require native/security-owner verification with the matching feature-enabled 8.0.x SNI build, while x86/ARM64, Strict/TLS 1.3, and failure-path validation remain incomplete.
Review effort: Balanced
There was a problem hiding this comment.
🔵 Needs a closer look
The native ABI and deferred-validation changes require review against the unavailable matching SNI implementation, with x86/ARM64, Strict/TLS 1.3, and security validation still outstanding.
No open issues 🎉
1 resolved since last review
Review effort: Balanced
| Pooling = false, | ||
| }; | ||
|
|
||
| using SqlConnection connection = new(builder.ConnectionString); |
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 <223556219+Copilot@users.noreply.github.com>
…er ClearNegotiated Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…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 <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
…4810) SNIHandle moved to Microsoft.Data.SqlClient.NativeSni and TdsParserStateObjectNative to Microsoft.Data.SqlClient.Parser. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
…ts hash Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
- 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 <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
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 <223556219+Copilot@users.noreply.github.com>
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



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: queries and maps the values, and handles degradation. Native calls go through an internal seam (delegates) so tests can inject structs and certificate bytes.TdsParserStateObjectNative.GetServerCertificateCapture()andGetNegotiatedCipherSuite()overrides (the latter reads only the validation info, without copying the certificate).TdsParser.EnableSslassigns theEncryptionInfoAccumulatorproperties (ServerCertificateRawData,ValidationErrors,ChainStatus,Protocol ??=,CipherSuiteif unset) directly, afterEnableSsland again right afterWaitForSSLHandShakeToComplete, before its error check (covers async handshakes on success and failure). A protocol ofNonefrom the SSL wait no longer overwrites an observed protocol.SqlConnectionEncryptionInfoconstructor (byte[]? presentedServerCertificate) through Slice C'sServerCertificateCapture.Certificate read
When
dwAvailablehas0x4, SqlClient callsSNIGetServerCertificateWrappertwice:written == size.Any other result, an
EntryPointNotFoundException, or any exception gives anullcertificate; the other fields are still reported.Mapping
dwAvailableflag)SNIGetServerCertificateWrapper(CERTIFICATE0x4)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). Used only if no protocol was already recorded.NegotiatedCipherSuiteId(all targets) /NegotiatedCipherSuite(TlsCipherSuite?, .NET only)dwCipherSuite(CIPHER_SUITE0x80)GetNegotiatedCipherSuite(), else adopted from the capture when no suite was recorded for the attempt; kept on a deferred-validation failure. Cast toTlsCipherSuiteon .NET.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.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
SniNativeCertificateCaptureTestscover:Certificate= 0x4,CipherSuite= 0x80X509ChainStatusFlagsvalue, plus unknown bitsTryGetCipherSuite: available/unavailable/out-of-range, error codes, missing export cached for all queries, exceptions swallowed without disabling, no usable handle121d8c07d(stacked on Cf771fb427, after Paul's B review:EncryptionInfoCapturerenamed toEncryptionInfoAccumulator,Record*helpers removed, mode kept on TLS/certificate failure). Rebased from C1aed09457; conflicts: commit 1 (EncryptionInfoCapture.csdeleted upstream, D's logic re-expressed via accumulator properties), commit 11 (AssertUntrustedCertificateFailurenow expects modeFullalways;Tls12+ cipher only when managed or the native export is present), commit 12 (design note: took C's failure-path text, rewrote D's Native bullet). Range-diff: the other 11 commits=; new commit 15 adapts to the accumulator. Driver, ref, NotSupported, UnitTests and ManualTests build with 0 warnings. Focused filter with main's SNI 8.0.0-preview1.26309.4 (no exports): net10.0 1200/1200 (exit 0); net462 1178/1178, then the known teardown hang (exit 1). Export-present branches remain untestable until the feature-enabled SNI 8.0.x package ships. Earlier: heada09ba74c7(stacked on C1aed09457, on B99db5b52d, on main with the merged Slice A review follow-up Connection encryption info – Slice A review follow-up #50438d330f187). Rebasing from C7f962e900produced no conflicts. The range-diff shows all 14 D commits as=, and D's cumulative patch is identical toe529d5166when index and hunk-header lines are ignored. No product change was needed. The driver, ref, NotSupported and UnitTests build with 0 warnings. The focusedEncryptionInfo|SniNativeCertificateCapture|SimulatedServerTests|InternalsVisibleTo|SqlExceptionTest|SqlConnectionTestsfilter ran with main's SNI 8.0.0-preview1.26309.4 (x643AADEA37). On net10.0, 1206/1206 passed (exit 0). On net462, 1178/1178 passed, followed by the known teardown hang (exit 1). Earlier:e529d5166on C7f962e900adopted Connection encryption info – Slice A review follow-up #5043's test conventions with no product change (net10.0 1206/1206, net462 1178/1178). Earlier:6b86e9c9bon C8a0b3a36b(net10.0 1208/1208, before C's test consolidation). Earlier history: at030c293b4, the head was stacked on C928f40a85, B7149c8753, A1e1dc8628, maine16417f71. Product code is unchanged sincef515c1e9b.030c293b4changes only one simulated-server assertion: with Native SNI, the certificate is required only when the separateSNIGetServerCertificateWrapperexport is available, so a cipher suite no longer implies a certificate. D does not modifyDirectory.Packages.props. Focused filter with main's SNI 8.0.0-preview1.26309.4 (x643AADEA37): 513/513 on net10.0 and 509/509 on net462, both with exit 0. Build of the driver, ref and UnitTests: 0 warnings on both TFMs.8.0.0-preview1.26309.4(deployed x643AADEA37…, no exports): focused filter plusSimulatedServerTestsandConnectionPooltests passed 1666/1666 on net10.0. On net462, 1471/1471 passed, but the host then hit the known net462 teardown hang (blame namedTdsTokenBoundsTests.BatchResponse_PromoteTransaction_OversizedLength_ThrowsParsingError;TdsTokenBoundsTestspasses 12/12 when run alone).-p:SniVersion=7.1.0-preview3.26303.1(deployed x64FFC43EB7…725Eon both TFMs): focused filterEncryptionInfo|SniNativeCertificateCapture|InternalsVisibleTo|SqlExceptionTestpassed 513/513 on net10.0 and 509/509 on net462, both with exit 0. On Native SNI with these exports, an untrusted-certificate failure reportsFull,Tls12and a cipher suite; with an oldersni.dllonly the mode (Full/Strict, recorded at PRELOGIN) is reported and protocol/cipher are null. net462 runs used a clean Windows PowerShellPSModulePath.NativeSniEncryptionInfoTests(Open and OpenAsync, Native SNI, self-signed certificate,TrustServerCertificate=false) assert thatSqlException.EncryptionInfocarries the presented DER,ChainErrorandUntrustedRoot. With an sni.dll lacking the exports they assertnullinstead. Both ran and passed on net10.0 and net462.NativeSniServerCertificateTest(Open and OpenAsync, Native SNI,Encrypt=Mandatory,TrustServerCertificate=true) asserts thatGetServerCertificate()returns non-null DER with no private key, and that each call returns a distinct instance. If the loaded sni.dll lacks the export, it asserts null instead. Result against local SQL Server 2022: 2/2 on net10.0, 2/2 on net462. A temporary strict run that required the export also passed 2/2 on each TFM.localhost:1433(the default instance is stopped and was left stopped), so the run used named instanceMSSQLSERVER_02attcp:localhost,50904. No server config was changed.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 with identical D content)