Skip to content

Unhandled native exception by SniNativeWrapper.SniOpenSyncEx / SNI_Spn::MakeSpn when opening a connection #3661

Open

Description

@ManuelRin

Describe the bug

Opening a (pooled) database connection "sometimes" throws a native exception in unmanaged code Microsoft.Data.SqlClient.SNI.dll function SNI_Spn::MakeSpn (according to debug symbols).
This does not happen every time but once in a while (maybe every 100th or 5000th call).

There is no managed exception and the application crashes, leaving an entry in the Windows Event Log like the following.

Log Name: Application
Source: Application Error
Event ID: 1000

Faulting application name: MyApplication.exe, version: 1.0.0.0, time stamp: 0x68760000
Faulting module name: ntdll.dll, version: 10.0.20348.3932, time stamp: 0xc75bbaae
Exception code: 0xc0000409
Fault offset: 0x000000000008ebff
Faulting process id: 0x1208
Faulting application start time: 0x01dc1b72db812087
Faulting application path: C:\SomePath\MyApplication.exe
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: cd9ba991-be98-4342-8c08-f46a6493ede5
Faulting package full name: 
Faulting package-relative application ID: 

A detailed exception cannot be seen. But with Windows Error Reporting (WER) configured to collect user-mode full dumps on such errors according to Collecting User-Mode Dumps on Microsoft Learn a full dump can be collected.

Full crash dump mixed mode debugging showed the following native exception (Windows x64, debug symbols loaded):

Unhandled exception at 0x00007FFAB886EBFF (ntdll.dll) in MyApplication.exe.14380.dmp: Indirect call guard check detected invalid control transfer.

Exception message:
Stack trace:

ntdll.dll!LdrpICallHandler()
ntdll.dll!RtlpExecuteHandlerForException()
ntdll.dll!RtlDispatchException()
ntdll.dll!KiUserExceptionDispatch()
ntdll.dll!LdrpDispatchUserCallTarget()
Microsoft.Data.SqlClient.SNI.dll!SNI_Spn::MakeSpn(unsigned short *,unsigned short *,unsigned short,unsigned short *,unsigned long)
Microsoft.Data.SqlClient.SNI.dll!Connect(class ConnectParameter *,struct SNI_CLIENT_CONSUMER_INFO *,class ProtElem *,class SNI_Conn * *,int)
Microsoft.Data.SqlClient.SNI.dll!SNIOpenSyncEx()
Microsoft.Data.SqlClient.SNI.dll!SNIOpenSyncExWrapper()
[Managed to Native Transition]
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SniNativeWrapper.SniOpenSyncEx(Interop.Windows.Sni.ConsumerInfo consumerInfo, string connString, ref nint pConn, ref string spn, byte[] instanceName, bool fOverrideCache, bool fSync, int timeout, bool fParallel, Microsoft.Data.SqlClient.SqlConnectionIPAddressPreference ipPreference, Microsoft.Data.SqlClient.SQLDNSInfo cachedDnsInfo, string hostNameInCertificate)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SNIHandle.SNIHandle(Interop.Windows.Sni.ConsumerInfo myInfo, string serverName, ref string spn, int timeout, out byte[] instanceName, bool flushCache, bool fSync, bool fParallel, Microsoft.Data.SqlClient.SqlConnectionIPAddressPreference ipPreference, Microsoft.Data.SqlClient.SQLDNSInfo cachedDNSInfo, string hostNameInCertificate)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.TdsParserStateObjectNative.CreatePhysicalSNIHandle(string serverName, Microsoft.Data.ProviderBase.TimeoutTimer timeout, out byte[] instanceName, out Microsoft.Data.SqlClient.ManagedSni.ResolvedServerSpn resolvedSpn, bool flushCache, bool async, bool fParallel, Microsoft.Data.SqlClient.SqlConnectionIPAddressPreference ipPreference, string cachedFQDN, ref Microsoft.Data.SqlClient.SQLDNSInfo pendingDNSInfo, string serverSPN, bool isIntegratedSecurity, bool tlsFirst, string hostNameInCertificate, string serverCertificateFilename)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.TdsParser.Connect(Microsoft.Data.SqlClient.ServerInfo serverInfo, Microsoft.Data.SqlClient.SqlInternalConnectionTds connHandler, Microsoft.Data.ProviderBase.TimeoutTimer timeout, Microsoft.Data.SqlClient.SqlConnectionString connectionOptions, bool withFailover)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(Microsoft.Data.SqlClient.ServerInfo serverInfo, string newPassword, System.Security.SecureString newSecurePassword, Microsoft.Data.ProviderBase.TimeoutTimer timeout, bool withFailover)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(Microsoft.Data.SqlClient.ServerInfo serverInfo, string newPassword, System.Security.SecureString newSecurePassword, bool redirectedUserInstance, Microsoft.Data.SqlClient.SqlConnectionString connectionOptions, Microsoft.Data.SqlClient.SqlCredential credential, Microsoft.Data.ProviderBase.TimeoutTimer timeout)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(Microsoft.Data.ProviderBase.TimeoutTimer timeout, Microsoft.Data.SqlClient.SqlConnectionString connectionOptions, Microsoft.Data.SqlClient.SqlCredential credential, string newPassword, System.Security.SecureString newSecurePassword, bool redirectedUserInstance)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SqlInternalConnectionTds.SqlInternalConnectionTds(Microsoft.Data.SqlClient.ConnectionPool.DbConnectionPoolIdentity identity, Microsoft.Data.SqlClient.SqlConnectionString connectionOptions, Microsoft.Data.SqlClient.SqlCredential credential, object providerInfo, string newPassword, System.Security.SecureString newSecurePassword, bool redirectedUserInstance, Microsoft.Data.SqlClient.SqlConnectionString userConnectionOptions, Microsoft.Data.SqlClient.SessionData reconnectSessionData, bool applyTransientFaultHandling, string accessToken, Microsoft.Data.SqlClient.ConnectionPool.IDbConnectionPool pool, System.Func<Microsoft.Data.SqlClient.SqlAuthenticationParameters, System.Threading.CancellationToken, System.Threading.Tasks.Task<Microsoft.Data.SqlClient.SqlAuthenticationToken>> accessTokenCallback)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(Microsoft.Data.Common.ConnectionString.DbConnectionOptions options, Microsoft.Data.SqlClient.ConnectionPool.DbConnectionPoolKey poolKey, Microsoft.Data.SqlClient.ConnectionPool.DbConnectionPoolGroupProviderInfo poolGroupProviderInfo, Microsoft.Data.SqlClient.ConnectionPool.IDbConnectionPool pool, System.Data.Common.DbConnection owningConnection, Microsoft.Data.Common.ConnectionString.DbConnectionOptions userOptions)
Microsoft.Data.SqlClient.dll!Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(Microsoft.Data.SqlClient.ConnectionPool.IDbConnectionPool pool, System.Data.Common.DbConnection owningObject, Microsoft.Data.Common.ConnectionString.DbConnectionOptions options, Microsoft.Data.SqlClient.ConnectionPool.DbConnectionPoolKey poolKey, Microsoft.Data.Common.ConnectionString.DbConnectionOptions userOptions)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.CreateObject(System.Data.Common.DbConnection owningObject, Microsoft.Data.Common.ConnectionString.DbConnectionOptions userOptions, Microsoft.Data.ProviderBase.DbConnectionInternal oldConnection)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.UserCreateRequest(System.Data.Common.DbConnection owningObject, Microsoft.Data.Common.ConnectionString.DbConnectionOptions userOptions, Microsoft.Data.ProviderBase.DbConnectionInternal oldConnection)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.TryGetConnection(System.Data.Common.DbConnection owningObject, uint waitForMultipleObjectsTimeout, bool allowCreate, bool onlyOneCheckConnection, Microsoft.Data.Common.ConnectionString.DbConnectionOptions userOptions, out Microsoft.Data.ProviderBase.DbConnectionInternal connection)
Microsoft.Data.SqlClient.dll!Microsoft.Data.SqlClient.ConnectionPool.WaitHandleDbConnectionPool.WaitForPendingOpen()
[Native to Managed Transition]
kernel32.dll!00007ffab7584cb0()
ntdll.dll!00007ffab885edcb()

To reproduce

Prerequisites (may or may not have influence):

  • Have a DNS Alias for the database

  • Have a SQL Server Always On availability group

  • Have setup Kerberos authentication enforced

  • Have setup SPNs for the alias associated with the gMSAs (Group Managed Service Accounts) running the cluster nodes: MSSQLSvc/myDbServerDnsAlias.example.com:1433 and MSSQLSvc/myDbServerDnsAlias:1433 (note that the casing may be different form the casing of the server alias used in the connection string)

  • Compile and publish the application as Release build with .NET R2R Ready-to-Run compilation

  • Setup WER (Windows Error Reporting) to collect user-mode full dumps on such errors according to Collecting User-Mode Dumps on Microsoft Learn

Use the below simple code to connect.
This typically works, but throws the native exception once in a while.

using Microsoft.Data.SqlClient;

string connectionString = new SqlConnectionStringBuilder
    {
        DataSource = "MyDbServerDnsAlias", // no FQDN
        InitialCatalog = "MyDatabase",
        IntegratedSecurity = true,
        MultipleActiveResultSets = true,
        ApplicationName = AppDomain.CurrentDomain.FriendlyName,
        ConnectTimeout = 5,
    }.ConnectionString;

await using var sqlConnection = new SqlConnection(connectionString);
await sqlConnection.OpenAsync();
Console.WriteLine("SUCCESS.");

Expected behavior

In any case, no unmanaged exception from SNI should bubble up through managed code.
In case of incorrect usage, the input should be validated and managed exceptions should be thrown.
In case of a native exception state, this should be handled orderly.
Exceptions should not happen randomly / sometimes.

Further technical details

Microsoft.Data.SqlClient version: 6.1.1
Microsoft.Data.SqlClient.SNI.runtime version: 6.0.2
.NET target: .NET 8
SQL Server version: SQL Server 2016 (13.0.6465.1)
Operating system: Windows Server 2022 (server and client)

Additional context
DLL versions:

  • Microsoft.Data.SqlClient.dll: 6.11.25226.3
  • Microsoft.Data.SqlClient.SNI.dll: 6.2.0.0
  • ntdll.dll: 10.0.20348.3932 (WinBuild.160101.0800)

Activity

  1. self-assigned this
    on Oct 7, 2025
  2. moved this from To triage to Backlog in SqlClient Boardon Oct 28, 2025
  3. removed their assignment
    on Oct 28, 2025
  4. moved this from Backlog to Needs Response in SqlClient Boardon Nov 21, 2025
  5. apoorvdeshmukh commented on Dec 16, 2025

    @apoorvdeshmukh
    Contributor

    @ManuelRin Can you enable event tracing and share the driver logs?

  6. ManuelRin commented on Dec 18, 2025

    @ManuelRin
    Author

    Hi @apoorvdeshmukh, thanks for reaching out and addressing that issue.

    I'll need to check whether and which tracing information I will be able to share from a information security perspective as sensitive information might be included. I might be able to extract some relevant pieces of the trace.

    @apoorvdeshmukh, could you let me know which specific keywords and event IDs you're looking for?

    Also note that it might take a couple of days to gather the information due to the upcoming holiday season.

  7. ManuelRin commented on Feb 11, 2026

    @ManuelRin
    Author

    Hi @apoorvdeshmukh

    We've collected event trace information in a reproduction (now against SQL server 2022, but that doesn't matter) using xperf and analyzed via PerfView. As there is sensitive information included in the trace files I'm not able to submit the full trace.

    We are able to provide specific sections of the trace in case that's helpful.
    As asked above, please let me know which information would be of value and useful for you.

    My analysis so far didn't show any surprising information (as far as I can tell). I can attach some PerfView screenshots here.

    The process (which then fails in calling MakeSpn) seems to make two calls. The first one succeeds, the second one fails and makes the process fail. You can see in the last screenshot that there is no RET trace entry for MakeSpn.

    MakeSpn calls by the failing process:
    Image

    Trace for the thread where MakeSpn succeeds (1st call):
    Image

    Trace for the thread which stops calling MakeSpn which doesn’t return (2nd call):
    Image

    Please let us know which further information you need (from the traces) and whether there is an approx. timeline for this to be fixed.

    Thanks and best,
    Manuel

  8. mdaigle commented on Apr 1, 2026

    @mdaigle
    Contributor

    Hi @ManuelRin are you still facing this issue? we made a fix to spn generation here that may be related: #3946

  9. moved this from Needs Response to Waiting for customer in SqlClient Boardon Apr 1, 2026
  10. ManuelRin commented on Apr 29, 2026

    @ManuelRin
    Author

    Hello @mdaigle, thanks for reaching out!

    Thanks for your suggestion. This week we could upgraded to latest Microsoft.Data.SqlClient 7.0.1 package on .NET 8.

    We'll monitor whether we still observe this issue or whether it seems fixed by your mentioned issue.
    I'll get back here in a couple of weeks to report whether this has been resolved for us or whether the issue is still present.

    Best, Manuel

  11. ManuelRin commented on Jun 29, 2026

    @ManuelRin
    Author

    Hello @mdaigle

    Unfortunately we were able to observe that the same issue still exists with SqlClient version 7.0.1.
    Apparently this means that this bug in the native component is not resolved yet.

    Best, Manuel

  12. self-assigned this
    on Jul 16, 2026
  13. moved this from Waiting for customer to Investigating in SqlClient Boardon Jul 16, 2026
  14. priyankatiwari08 commented on Sep 17, 2026

    @priyankatiwari08
    Contributor

    /triage

  15. github-actions commented on Sep 17, 2026

    @github-actions

    🔍 Triage Summary (on-demand re-triage)

    Check Result
    Issue type Bug
    Environment All required environment details provided for investigation
    Area Area\Native SNI
    Duplicates None found with matching SNI_Spn::MakeSpn crash signature
    Regression Not indicated as a regression from a specific version — confirmed still reproducing on latest 7.0.1, after PR #3946 (related SPN generation fix) was tried and did not resolve it

    Analysis

    This is a native, unhandled access-violation-class crash (Indirect call guard check detected invalid control transfer) inside Microsoft.Data.SqlClient.SNI.dll's SNI_Spn::MakeSpn, triggered intermittently (roughly 1 in 100–5000 connection opens) during pooled connection creation with Kerberos/SPN + DNS alias + Always On availability group topology on Windows with R2R-compiled apps. The crash bypasses managed exception handling entirely and crashes the process, so it is high severity (P1) — reliability/availability impact, though low frequency. The author already tried the SPN-generation fix in #3946 (SqlClient 7.0.1) and confirmed the crash still occurs, indicating the root cause is a distinct native-layer bug in SNI_Spn::MakeSpn (possibly a buffer/race condition under concurrent SPN generation calls, given traces show two concurrent MakeSpn calls where the second one hangs/faults). Native SNI (Microsoft.Data.SqlClient.SNI/SNI.dll) is the affected component, not the managed ManagedSni implementation.

    Next Steps

    • Recommend assigning this issue to the Copilot coding agent to investigate the native SNI_Spn::MakeSpn implementation (in the native SNI source, not the managed ManagedSni layer) for thread-safety issues around concurrent SPN resolution/caching during pooled connection opens — the PerfView trace evidence showing two concurrent MakeSpn calls where the second never returns strongly suggests a race condition or reentrancy bug (e.g., non-thread-safe caching, buffer reuse, or CFG/indirect-call-guard incompatible function pointer usage) rather than an input validation gap.
    • Since [6.1] Avoid unintended SPN generation for non-integrated authentication on native SNI path #3946 addressed related but insufficient SPN generation issues, compare the fix scope in [6.1] Avoid unintended SPN generation for non-integrated authentication on native SNI path #3946 against the actual fault location (MakeSpn) to confirm whether the code path hit here was in scope of that PR at all.
    • Consider requesting a minimal native reproduction harness or asking the reporter whether the crash is reproducible under sustained concurrent connection-pool churn, to narrow down the race condition trigger.
    • As a stopgap, evaluate whether UseManagedSNIOnWindows/managed SNI avoids this crash entirely for affected users while the native fix is investigated, and mention this as a possible workaround to the reporter.

    Note: This triage summary is auto-generated by an AI agent. The analysis and suggestions above have not been verified by a human maintainer. Please treat as preliminary guidance only.

    Generated by SqlClient Issue Auto-Triage for #3661 · copilot · auto · 50.8 AIC · ⌖ 13.2 AIC · ⊞ 11.9K · ◷

  16. moved this from Investigating to Backlog in SqlClient Boardon Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions