Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
1552fe9
Connection encryption info: Native SNI certificate capture (Slice D)
priyankatiwari08 Oct 13, 2026
ce37b05
Test: native deferred-validation failure keeps certificate fields aft…
priyankatiwari08 Oct 13, 2026
fc4a00b
Slice D: keep observed negotiation on native validation failure (G2/D15)
priyankatiwari08 Oct 15, 2026
b91c796
Design note: native deferred validation is always on; remove fixed na…
priyankatiwari08 Oct 19, 2026
b88da06
Capture the negotiated cipher suite from native SNI
priyankatiwari08 Oct 22, 2026
8133c1a
Slice D: import NativeSni namespace after main's TDS parser refactor …
priyankatiwari08 Oct 26, 2026
44ada10
Adapt Slice D tests and design note to NegotiatedCipherSuiteId
priyankatiwari08 Oct 28, 2026
56b913b
Capture the presented server certificate from native SNI instead of i…
priyankatiwari08 Oct 30, 2026
5dc63ac
Add live native SNI server certificate test
priyankatiwari08 Nov 10, 2026
c1448c0
Address Slice D review feedback
priyankatiwari08 Nov 10, 2026
9cf1e74
Adapt ConnectionEncryptionInfoTests to native certificate capture
priyankatiwari08 Nov 10, 2026
4a3d7d8
Design note: reconcile native SNI failure path with deferred validation
priyankatiwari08 Nov 10, 2026
7c400e8
Test: native cipher suite does not imply certificate export
priyankatiwari08 Nov 10, 2026
5749b23
Adapt Slice D tests to Slice A review follow-up conventions
priyankatiwari08 Nov 12, 2026
121d8c0
Adapt Slice D native SNI capture to EncryptionInfoAccumulator
priyankatiwari08 Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 75 additions & 10 deletions doc/design-notes/2353-connection-encryption-info.md
Original file line number Diff line number Diff line change
Expand Up @@ -291,11 +291,19 @@ non-`SqlException` failures, keep `Empty`.
selected at PRELOGIN together with that protocol. A protocol already determined for the attempt
takes precedence over the one reported with the certificate details. Managed SNI is used only on
.NET (`net10.0`).
- **Native SNI.** With the current SNI package, native SNI also rejects an untrusted server
certificate during the handshake, so this slice reports the mode but no protocol for that
failure (the tests assert this for native SNI; Managed SNI also reports the protocol, as
described above). If a deferred validation failure surfaces after a successful `EnableSsl`, the
protocol recorded by `EnableSsl` is kept.
- **Native SNI** reports the protocol through `dwProtocol` in the certificate capture, or
through the handshake wait, and the cipher suite through `dwCipherSuite`. Native deferred
validation is always on: Schannel agrees the protocol and cipher suite, `EnableSsl` reports
success, and an untrusted or mismatched certificate only surfaces as an SSL-provider SNI error
on the first post-handshake I/O (the LOGIN7 write). `TdsParser.EnableSsl` has already assigned
the observed protocol, cipher suite and certificate details to the accumulator, and nothing
erases them when the error is processed. With an `sni.dll` that provides the validation info
export, an untrusted-certificate failure therefore reports the mode selected for the attempt
(`Full`, or `Strict`), the server-selected protocol and the cipher suite, together with the
certificate details (the tests assert this when the export is present). Observing the
protocol does not mean the handshake completed. An older `sni.dll` without the export reports
only the mode, and the tests assert a `null` protocol and cipher suite in that case.

These rules only touch mode and protocol; certificate fields are never affected. Once login
completes the accumulator is released, so SSL errors on an open connection never alter a published
snapshot.
Expand Down Expand Up @@ -335,8 +343,65 @@ callback chain status, are recorded first so they survive the exception. The exc
unchanged. When no error was established before the check, the fields stay `null` rather than
reporting `None`.

Native SNI does not yet report certificate details; those fields remain `null` there.

### Native SNI certificate capture

Native SNI (Windows) records the same details through two `sni.dll` exports that return values
SNI saved during the client TLS handshake: `SNIGetCertValidationInfoWrapper` fills a structure
with the validation details, and `SNIGetServerCertificateWrapper` copies the presented leaf
certificate's DER encoding. SqlClient queries them after the handshake completes and again when
it fails (before the handle closes). Querying performs no validation or network work, never
changes `SNIGetLastError`, and never throws: any error leaves the fields `null` without changing
the connection outcome or the thrown exception.

`SNI_CERT_VALIDATION_INFO` is a 32-byte blittable structure of `DWORD` fields (version 1):
`cbSize` (0), `dwVersion` (4), `dwAvailable` (8), `dwValidationMode` (12), `dwProtocol` (16),
`dwValidationErrors` (20), `dwChainStatus` (24) and `dwCipherSuite` (28). SqlClient passes
`cbSize = 32`; SNI writes 32 bytes and sets `cbSize = 32` and `dwVersion = 1`. A field is used
only when its `dwAvailable` flag is set; structures with `cbSize < 32` or `dwVersion < 1` are
ignored, and trailing data from newer versions is ignored.

The certificate is read only when the `CERTIFICATE` flag (0x4) is set. SqlClient first queries
its size with an empty buffer, which returns `ERROR_INSUFFICIENT_BUFFER` (122) and the size, and
then copies it into a buffer of that size, which must return `ERROR_SUCCESS` with the same size.
A size of 0 or above 64 KiB (`ServerCertificateCapture.MaxRawCertificateSize`), any other return
code (such as `ERROR_NOT_FOUND`, 1168), or a size that changed between the calls leaves the
certificate `null`; the other fields are still reported.

| Field | Native source (`dwAvailable` flag) | Mapping |
| --- | --- | --- |
| `PresentedServerCertificateRawData` / `GetServerCertificate()` | `SNIGetServerCertificateWrapper` (`CERTIFICATE` 0x4) | DER bytes copied; 1 byte to 64 KiB |
| `ServerCertificateValidationErrors` | `dwValidationErrors` (`VALIDATION_ERRORS`) | Same bit values; unknown bits preserved |
| `ServerCertificateChainStatus` | `dwChainStatus` (`CHAIN_STATUS`) | Raw `CERT_TRUST_*` error status equals `X509ChainStatusFlags`; unknown bits preserved. `null` when `CHAIN_STATUS_LEAF_TIME_ONLY` (0x40) is also set: for a pinned certificate SNI checks only the leaf validity period and builds no chain, matching Managed SNI, which reports no chain status in pinned modes |
| `NegotiatedProtocol` | `dwProtocol` (`PROTOCOL`) | `SP_PROT_*` client bits mapped as for the handshake result; used only when the protocol was not already recorded (for example, after a failed handshake). SNI reads it from the Schannel connection info after the server hello, so it is the version the server selected, not the client's offered set |
| `NegotiatedCipherSuiteId` (and `NegotiatedCipherSuite` on .NET) | `dwCipherSuite` (`CIPHER_SUITE` 0x80) | Values of 0 or above 0xFFFF are ignored. `TdsParser.EnableSsl` reads it through `GetNegotiatedCipherSuite()` (which queries only the validation info, without copying the certificate) and, when that reported none, adopts it from the certificate capture. Exposed as `int?` `NegotiatedCipherSuiteId` on every target; on .NET, `NegotiatedCipherSuite` returns the same value as `TlsCipherSuite`, keeping identifiers with no named member |

The cipher suite is captured at the same points as the certificate and protocol: after a
successful handshake, after a deferred-validation failure, and best effort after an
`InitializeSecurityContext` failure. Native SNI resets all values at every handshake, and an
observed value is kept on failure like the protocol.

**Older `sni.dll`:** a missing export is detected once (`EntryPointNotFoundException`) and
cached. Without `SNIGetCertValidationInfoWrapper`, the certificate fields and the cipher suite
remain `null`, and the certificate isn't read. Without `SNIGetServerCertificateWrapper`, only
the certificate is `null`. Earlier preview libraries that used a larger structure reject
`cbSize = 32` with `ERROR_INVALID_PARAMETER`, so they report nothing.

**Deferred validation:** native SNI always defers server certificate validation until after
Schannel has the presented certificate. There is no opt-in or opt-out switch. Deferral
records the certificate, validation errors, and chain status in every validation mode, including
Schannel automatic validation (`Encrypt` without `HostNameInCertificate`), on both success
and failure. A certificate that fails the chain and doesn't match the host name reports
`HostNameMismatch | ChainError`, the same as Managed SNI. Deferral doesn't change whether a
certificate is accepted or rejected, or the resulting error codes. Fields are never derived
from HRESULTs or messages; a field whose availability flag isn't set stays `null`.

**SNI dependency:** this behavior requires a `sni.dll` built with the certificate capture
exports (`SNIGetCertValidationInfoWrapper` with the 32-byte structure and
`SNIGetServerCertificateWrapper`), deferred validation (SNI commit `b9d842c`), and the
host-name verdict fix (SNI commit `55d318d`). These are introduced by an upcoming native SNI
package (SNI PR 8573). Until it ships, or with any older `sni.dll`, Native SNI reports no
certificate details and the fields remain `null`, as described for older `sni.dll` versions
above.
**Cipher suite (Managed SNI).** Managed SNI reads `(int)SslStream.NegotiatedCipherSuite` at the
same two points as the protocol, on both the TCP and named-pipe handles (MARS passes through to
the physical handle):
Expand All @@ -355,8 +420,8 @@ Both reads are wrapped in `try`/`catch` so that capture never affects the handsh
properties are `null`. The value flows through the SNI handles and `ServerCertificateCapture` as
an `int`; `TdsParser.EnableSsl` casts it to `TlsCipherSuite` on .NET when it assigns it to the
accumulator. `NegotiatedCipherSuiteId` returns the same IANA identifier.
Managed SNI runs only on `net10.0`; on `net462` this capture is not compiled
and `NegotiatedCipherSuiteId` stays `null` until native SNI support (Slice D).
Managed SNI runs only on `net10.0`; on `net462` the cipher suite comes from native SNI (see
**Native SNI certificate capture**).

## 5. Scope

Expand All @@ -376,4 +441,4 @@ The feature is delivered as a stack of pull requests:
| **A** | Public API surface only. Both getters return an empty snapshot. |
| **B** | Capture the negotiated mode, TLS protocol and cipher suite, and attach the snapshot to `SqlException` when opening fails. |
| **C** | Capture certificate details (presented certificate, validation errors, and chain status) in Managed SNI, on both successful and failed attempts. |
| **D** | Native SNI interop for the certificate details and cipher suite. |
| **D** | Native SNI interop for the certificate details and cipher suite, degrading gracefully with older `sni.dll` versions. |
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ internal interface ISniNativeMethods

uint SniClose(IntPtr pConn);

uint SniGetCertValidationInfo(SNIHandle pConn, ref SniCertValidationInfo pInfo);

uint SniGetMaxComposedSpnLength();

uint SniGetInfoWrapper(SNIHandle pConn, QueryType queryType, out bool pbQueryInfo);
Expand All @@ -32,6 +34,8 @@ internal interface ISniNativeMethods

void SniGetLastError(out SniError pLastError);

unsafe uint SniGetServerCertificate(SNIHandle pConn, byte* pbCertificate, uint cbCertificate, out uint pcbCertificate);

uint SniGetPeerAddrStrWrapper(SNIHandle pConn, int bufferSize, StringBuilder addrBuffer, out uint addrLength);

uint SniInitialize(IntPtr pmo);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Runtime.InteropServices;

namespace Interop.Windows.Sni
{
/// <summary>
/// Managed mirror of the native <c>SNI_CERT_VALIDATION_INFO</c> structure filled by
/// <c>SNIGetCertValidationInfoWrapper</c>. Version 1 is 32 bytes of sequential, blittable
/// <c>DWORD</c> fields.
/// </summary>
/// <remarks>
/// A field is meaningful only when its corresponding <see cref="SniCertInfoAvailability"/> flag is
/// set in <see cref="dwAvailable"/>. The presented certificate itself is not part of this
/// structure; when <see cref="SniCertInfoAvailability.Certificate"/> is set it is read with
/// <c>SNIGetServerCertificateWrapper</c>. Earlier preview SNI libraries used a larger structure
/// and reject a <see cref="cbSize"/> of 32 with <c>ERROR_INVALID_PARAMETER</c>, so no data is
/// read from them.
/// </remarks>
[StructLayout(LayoutKind.Sequential)]
internal struct SniCertValidationInfo
{
/// <summary>Size, in bytes, of the structure requested by this client.</summary>
internal const int Size = 32;
Comment thread
priyankatiwari08 marked this conversation as resolved.
Resolved

/// <summary>Minimum structure version understood by this client.</summary>
internal const uint CurrentVersion = 1;

/// <summary>In: size of the caller's buffer (at least <see cref="Size"/>). Out: number of bytes written.</summary>
public uint cbSize;

/// <summary>Out: structure version.</summary>
public uint dwVersion;

/// <summary>Out: <see cref="SniCertInfoAvailability"/> flags.</summary>
public uint dwAvailable;

/// <summary>Out: <see cref="SniCertValidationMode"/> value.</summary>
public uint dwValidationMode;

/// <summary>Out: negotiated <c>SP_PROT_*</c> protocol bits.</summary>
public uint dwProtocol;

/// <summary>Out: effective validation error bits; identical to <c>SqlServerCertificateValidationErrors</c>.</summary>
public uint dwValidationErrors;

/// <summary>Out: raw <c>CERT_TRUST_STATUS.dwErrorStatus</c>; identical to <c>X509ChainStatusFlags</c>.</summary>
public uint dwChainStatus;

/// <summary>Out: IANA identifier of the negotiated TLS cipher suite.</summary>
public uint dwCipherSuite;

/// <summary>
/// Creates an instance ready to be passed to native code, with <see cref="cbSize"/> set.
/// </summary>
internal static SniCertValidationInfo Create() => new SniCertValidationInfo { cbSize = Size };
}

/// <summary>
/// Availability flags reported in <see cref="SniCertValidationInfo.dwAvailable"/>.
/// </summary>
[Flags]
internal enum SniCertInfoAvailability : uint
{
None = 0x0,
AttemptStarted = 0x1,
Protocol = 0x2,
Certificate = 0x4,
ValidationErrors = 0x8,
ChainStatus = 0x10,
HandshakeCompleted = 0x20,

/// <summary>
/// <see cref="SniCertValidationInfo.dwChainStatus"/> reflects only a leaf validity-period check
/// for a pinned certificate; no chain was built, so the chain status is not reported.
/// </summary>
ChainStatusLeafTimeOnly = 0x40,
CipherSuite = 0x80,
}

/// <summary>
/// Validation mode reported in <see cref="SniCertValidationInfo.dwValidationMode"/>.
/// </summary>
internal enum SniCertValidationMode : uint
{
Unknown = 0,
NotValidated = 1,
SchannelAutomatic = 2,
ChainPolicy = 3,
PinnedCertificate = 4,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public uint SniCheckConnection(SNIHandle pConn) =>
public uint SniClose(IntPtr pConn) =>
SNICloseWrapper(pConn);

public uint SniGetCertValidationInfo(SNIHandle pConn, ref SniCertValidationInfo pInfo) =>
SNIGetCertValidationInfoWrapper(pConn, ref pInfo);

public uint SniGetMaxComposedSpnLength() =>
GetSniMaxComposedSpnLength();

Expand All @@ -48,6 +51,9 @@ public uint SniGetInfoWrapper(SNIHandle pConn, QueryType queryType, out ushort p
public void SniGetLastError(out SniError pLastError) =>
SNIGetLastError(out pLastError);

public unsafe uint SniGetServerCertificate(SNIHandle pConn, byte* pbCertificate, uint cbCertificate, out uint pcbCertificate) =>
SNIGetServerCertificateWrapper(pConn, pbCertificate, cbCertificate, out pcbCertificate);

public uint SniGetPeerAddrStrWrapper(
SNIHandle pConn,
int bufferSize,
Expand Down Expand Up @@ -195,6 +201,18 @@ private static extern uint SNIGetInfoWrapper(
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void SNIGetLastError(out SniError pErrorStruct);

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIGetCertValidationInfoWrapper(
[In] SNIHandle pConn,
ref SniCertValidationInfo pInfo);

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe uint SNIGetServerCertificateWrapper(
[In] SNIHandle pConn,
byte* pbCertificate,
uint cbCertificate,
out uint pcbCertificate);

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern uint SNIGetPeerAddrStrWrapper(
[In] SNIHandle pConn,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public uint SniCheckConnection(SNIHandle pConn) =>
public uint SniClose(IntPtr pConn) =>
SNICloseWrapper(pConn);

public uint SniGetCertValidationInfo(SNIHandle pConn, ref SniCertValidationInfo pInfo) =>
SNIGetCertValidationInfoWrapper(pConn, ref pInfo);

public uint SniGetMaxComposedSpnLength() =>
GetSniMaxComposedSpnLength();

Expand All @@ -48,6 +51,9 @@ public uint SniGetInfoWrapper(SNIHandle pConn, QueryType queryType, out ushort p
public void SniGetLastError(out SniError pLastError) =>
SNIGetLastError(out pLastError);

public unsafe uint SniGetServerCertificate(SNIHandle pConn, byte* pbCertificate, uint cbCertificate, out uint pcbCertificate) =>
SNIGetServerCertificateWrapper(pConn, pbCertificate, cbCertificate, out pcbCertificate);

public uint SniGetPeerAddrStrWrapper(
SNIHandle pConn,
int bufferSize,
Expand Down Expand Up @@ -195,6 +201,18 @@ private static extern uint SNIGetInfoWrapper(
[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern void SNIGetLastError(out SniError pErrorStruct);

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern uint SNIGetCertValidationInfoWrapper(
[In] SNIHandle pConn,
ref SniCertValidationInfo pInfo);

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe uint SNIGetServerCertificateWrapper(
[In] SNIHandle pConn,
byte* pbCertificate,
uint cbCertificate,
out uint pcbCertificate);

[DllImport(DllName, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern uint SNIGetPeerAddrStrWrapper(
[In] SNIHandle pConn,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ public uint SniCheckConnection(SNIHandle pConn) =>
public uint SniClose(IntPtr pConn) =>
throw ADP.SNIPlatformNotSupported(_architecture);

public uint SniGetCertValidationInfo(SNIHandle pConn, ref SniCertValidationInfo pInfo) =>
throw ADP.SNIPlatformNotSupported(_architecture);

public uint SniGetMaxComposedSpnLength() =>
throw ADP.SNIPlatformNotSupported(_architecture);

Expand All @@ -52,6 +55,9 @@ public uint SniGetInfoWrapper(SNIHandle pConn, QueryType queryType, out ushort p
public void SniGetLastError(out SniError pLastError) =>
throw ADP.SNIPlatformNotSupported(_architecture);

public unsafe uint SniGetServerCertificate(SNIHandle pConn, byte* pbCertificate, uint cbCertificate, out uint pcbCertificate) =>
throw ADP.SNIPlatformNotSupported(_architecture);

public uint SniGetPeerAddrStrWrapper(
SNIHandle pConn,
int bufferSize,
Expand Down
Loading
Loading