Skip to content

Commit c8b5604

Browse files
github-actions[bot]apoorvdeshmukhCopilotpriyankatiwari08
authored
[6.1.8 Cherry-pick] Honor HostNameInCertificate in managed SNI certificate validation (#4909)
* Honor HostNameInCertificate in managed SNI certificate validation (#4905) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 18415205-5120-4f0e-9815-f2325898516c * Fix certificate validation test compatibility in 6.1 backport Use the .NET 8 certificate import fallback and branch-compatible nullable annotations. Register the manual hostname test in set 1 and construct connections using the release-branch API. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: d02b81a2-8d04-492b-8fc8-66d4dbb020f5 --------- Co-authored-by: Apoorv Deshmukh <apdeshmukh@microsoft.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Priyanka Tiwari <prtiwar@microsoft.com> Copilot-Session: 18415205-5120-4f0e-9815-f2325898516c Copilot-Session: d02b81a2-8d04-492b-8fc8-66d4dbb020f5
1 parent fc240c7 commit c8b5604

5 files changed

Lines changed: 356 additions & 22 deletions

File tree

‎doc/snippets/Microsoft.Data.SqlClient/SqlConnectionStringBuilder.xml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -732,6 +732,10 @@ This property corresponds to the "FailoverPartnerSPN" and "Failover Partner SPN"
732732
<![CDATA[
733733
This property corresponds to the "HostNameInCertificate" and "Host Name in Certificate" keys within the connection string.
734734
735+
When certificate hostname validation is performed, an explicitly supplied value is the only
736+
expected hostname. It replaces the hostname from `Data Source` for that validation without
737+
changing the connection destination.
738+
735739
> [!NOTE]
736740
> This property only applies when using `Encrypt` in <xref:Microsoft.Data.SqlClient.SqlConnectionEncryptOption.Mandatory%2A> or <xref:Microsoft.Data.SqlClient.SqlConnectionEncryptOption.Strict%2A> mode, otherwise it is ignored.
737741

‎src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,9 @@ internal class SniCommon
4343
internal const int LocalDBBadRuntime = 57;
4444

4545
/// <summary>
46-
/// We either validate that the provided 'validationCert' matches the 'serverCert', or we validate that the server name in the 'serverCert' matches 'targetServerName'.
47-
/// Certificate validation and chain trust validations are done by SSLStream class [System.Net.Security.SecureChannel.VerifyRemoteCertificate method]
48-
/// This method is called as a result of callback for SSL Stream Certificate validation.
46+
/// Validates an exact certificate pin or the expected certificate hostname.
47+
/// An explicit hostname replaces the target server name for hostname validation.
48+
/// Certificate-chain policy errors are supplied by the SslStream validation callback.
4949
/// </summary>
5050
/// <remarks>
5151
/// When <paramref name="validationCertFileName"/> is supplied, the presented server
@@ -72,15 +72,17 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ
7272
{
7373
using (TrySNIEventScope.Create(nameof(SniCommon)))
7474
{
75-
// When a pin is configured, require it to match even if the platform trusts the cert.
76-
if (string.IsNullOrEmpty(validationCertFileName) && policyErrors == SslPolicyErrors.None)
75+
bool hasHostNameInCertificate = !string.IsNullOrEmpty(hostNameInCertificate);
76+
if (!hasHostNameInCertificate
77+
&& string.IsNullOrEmpty(validationCertFileName)
78+
&& policyErrors == SslPolicyErrors.None)
7779
{
78-
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, targetServerName {1}, SSL Server certificate has no policy errors and no ServerCertificate was supplied; skipping certificate comparison.", args0: connectionId, args1: targetServerName);
80+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, targetServerName {1}, SSL Server certificate has no policy errors and no HostNameInCertificate or ServerCertificate was supplied; skipping certificate comparison.", args0: connectionId, args1: targetServerName);
7981
return true;
8082
}
8183

8284
string serverNameToValidate;
83-
if (!string.IsNullOrEmpty(hostNameInCertificate))
85+
if (hasHostNameInCertificate)
8486
{
8587
serverNameToValidate = hostNameInCertificate;
8688
}
@@ -116,15 +118,16 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ
116118
}
117119
}
118120

119-
// If we get to this point then there is a ssl policy flag.
120121
StringBuilder messageBuilder = new();
121-
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
122+
if (serverCert is null ||
123+
policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
122124
{
123125
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SSL Server certificate not validated as PolicyErrors set to RemoteCertificateNotAvailable.", args0: connectionId, args1: targetServerName);
124126
messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNotAvailable);
125127
}
126128

127-
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
129+
if (serverCert is not null &&
130+
policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
128131
{
129132
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {0}, SslPolicyError {1}, SSL Policy certificate chain has errors.", args0: connectionId, args1: targetServerName, args2: policyErrors);
130133

@@ -148,7 +151,9 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ
148151
messageBuilder.AppendLine();
149152
}
150153

151-
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
154+
if (serverCert is not null &&
155+
(hasHostNameInCertificate ||
156+
policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch)))
152157
{
153158
X509Certificate2 cert2 = serverCert as X509Certificate2;
154159
if (!cert2.MatchesHostname(serverNameToValidate))

‎src/Microsoft.Data.SqlClient/tests/ManualTests/Microsoft.Data.SqlClient.ManualTesting.Tests.csproj‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@
8181
<Compile Include="SQL\AsyncTest\BeginExecReaderAsyncTest.cs" />
8282
<Compile Include="SQL\AsyncTest\XmlReaderAsyncTest.cs" />
8383
<Compile Include="SQL\AsyncTest\AsyncCancelledConnectionsTest.cs" />
84+
<Compile Include="SQL\ConnectionTestWithSSLCert\HostNameInCertificateTest.cs" />
8485
</ItemGroup>
8586
<ItemGroup Condition="'$(TestSet)' == '' OR '$(TestSet)' == '2'">
8687
<Compile Include="SQL\AdapterTest\AdapterTest.cs" />
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
#if NET
6+
7+
using System;
8+
using System.Data;
9+
using System.Security.Authentication;
10+
using System.Threading.Tasks;
11+
using Xunit;
12+
13+
namespace Microsoft.Data.SqlClient.ManualTesting.Tests
14+
{
15+
/// <summary>
16+
/// Verifies managed SNI certificate-name selection against a configured trusted SQL Server.
17+
/// </summary>
18+
[Trait("Set", "1")]
19+
public class HostNameInCertificateTest
20+
{
21+
/// <summary>
22+
/// Requires managed SNI and a TCP configuration that validates its default server name.
23+
/// No certificate installation or server reconfiguration is performed by these tests.
24+
/// </summary>
25+
/// <returns>Whether the configured server can exercise hostname validation.</returns>
26+
public static bool IsCertificateValidationConfigured()
27+
{
28+
if (!DataTestUtility.IsTCPConnStringSetup() || !DataTestUtility.IsUsingManagedSNI())
29+
{
30+
return false;
31+
}
32+
33+
SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionString);
34+
return builder.Encrypt != SqlConnectionEncryptOption.Optional
35+
&& !builder.TrustServerCertificate
36+
&& string.IsNullOrEmpty(builder.HostNameInCertificate)
37+
&& string.IsNullOrEmpty(builder.ServerCertificate);
38+
}
39+
40+
/// <summary>
41+
/// Both connection entry points enforce an explicitly configured certificate name.
42+
/// </summary>
43+
[ConditionalTheory(nameof(IsCertificateValidationConfigured))]
44+
[InlineData(false)]
45+
[InlineData(true)]
46+
public async Task Open_WithHostNameInCertificate_UsesConfiguredName(bool async)
47+
{
48+
SqlConnectionStringBuilder builder = new(DataTestUtility.TCPConnectionString)
49+
{
50+
Pooling = false,
51+
ConnectRetryCount = 0
52+
};
53+
using (SqlConnection connection = new(builder.ConnectionString))
54+
{
55+
if (async)
56+
{
57+
await connection.OpenAsync();
58+
}
59+
else
60+
{
61+
connection.Open();
62+
}
63+
Assert.Equal(ConnectionState.Open, connection.State);
64+
}
65+
66+
builder.HostNameInCertificate = $"sqlclient-{Guid.NewGuid():N}.invalid";
67+
using SqlConnection mismatched = new(builder.ConnectionString);
68+
SqlException exception = async
69+
? await Assert.ThrowsAsync<SqlException>(() => mismatched.OpenAsync())
70+
: Assert.Throws<SqlException>(() => mismatched.Open());
71+
72+
AuthenticationException inner =
73+
Assert.IsType<AuthenticationException>(exception.InnerException);
74+
Assert.Contains("Certificate name mismatch.", inner.Message);
75+
Assert.Equal(ConnectionState.Closed, mismatched.State);
76+
}
77+
}
78+
}
79+
80+
#endif

0 commit comments

Comments
 (0)