Skip to content

Commit 8acf068

Browse files
Fix | Perform ServerCertificate pin validation to verify with server provided cert (#4445)
* Server Certificate validation changes * Address comments * Address review feedback: reorder pin check after policy checks - Perform ServerCertificate pin validation after chain/name policy error handling, making the additive semantics explicit in control flow. - Extract ValidateCertificatePin/LoadValidationCertificate helpers so the loaded pin certificate lives in a narrow 'using' scope (no try/finally). - Guard against a null server certificate in the pin path. - Clarify method docs on the policyErrors relationship and reword the no-pin fast-path trace message. - Replace ambiguous 'platform trust' wording in docs with chain-and-name validation, and note that pinning does not itself confer trust. - Add TempCertFile disposable test helper and a null-server-cert regression test for the policyErrors == None case. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Revert to minimal design: pin always consulted, fail closed on load error Restores the original semantic where an exact ServerCertificate match satisfies certificate validation. The only behavior changes remain: - The policyErrors == None fast path now also requires that no ServerCertificate was supplied, so a configured certificate is always compared against the one presented by the server. - A ServerCertificate that cannot be loaded/parsed now fails the connection instead of being silently ignored. Also keeps the non-design fixes: the loaded certificate is disposed via a narrow using scope, and a null server certificate throws AuthenticationException instead of NullReferenceException. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * Address review: dedicated string, RemoteCertificateNotAvailable guard, safe Dispose - Add SQL_ServerCertificateNotAvailable so the failure names the option in play rather than reusing the generic policy-error text. - A matching ServerCertificate no longer satisfies validation when RemoteCertificateNotAvailable is reported. The flag and a null serverCert are expected to agree, but both are now checked so the contradictory combination cannot be accepted via comparison. Documented the relationship on the method. - Guard TempCertFile.Dispose so a cleanup failure cannot mask a real assertion failure. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 51af56e commit 8acf068

6 files changed

Lines changed: 411 additions & 57 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1015,7 +1015,7 @@ The following table lists the valid names for keyword values within the <xref:Mi
10151015
|Failover Partner|N/A|The name of the failover partner server where database mirroring is configured.<br /><br /> If the value of this key is "", then **Initial Catalog** must be present, and its value must not be "".<br /><br /> The server name can be 128 characters or less.<br /><br /> If you specify a failover partner but the failover partner server is not configured for database mirroring and the primary server (specified with the Server keyword) is not available, then the connection will fail.<br /><br /> If you specify a failover partner and the primary server is not configured for database mirroring, the connection to the primary server (specified with the Server keyword) will succeed if the primary server is available.|
10161016
|Failover Partner SPN<br /><br /> -or-<br /><br /> FailoverPartnerSPN|N/A|The SPN for the failover partner. The default value is an empty string, which causes SqlClient to use the default, driver-generated SPN.<br /><br /> (Only available in v5.0+)|
10171017
|Host Name In Certificate<br /><br /> -or-<br /><br />HostNameInCertificate|N/A|The host name to use when validating the server certificate. When not specified, the server name from the Data Source is used for certificate validation.<br /><br /> (Only available in v5.0+)|
1018-
|Server Certificate<br /><br /> -or-<br /><br />ServerCertificate|N/A|The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match.<br /><br /> (Only available in v5.1+)|
1018+
|Server Certificate<br /><br /> -or-<br /><br />ServerCertificate|N/A|The path to a certificate file to match against the SQL Server TLS/SSL certificate. The accepted certificate formats are PEM, DER, and CER. If specified, the SQL Server certificate is checked by verifying if the ServerCertificate provided is an exact match.<br /><br />When specified, this comparison is always performed, including when the certificate already passes the usual chain-and-name validation. If the presented certificate does not match, or the file cannot be loaded or parsed, the TLS handshake fails; a configured `ServerCertificate` is never silently ignored.<br /><br />Certificate validation itself can be disabled by `TrustServerCertificate=true` (except with `Encrypt=strict`, where validation is always performed). When validation is disabled, `ServerCertificate` is not consulted.<br /><br /> (Only available in v5.1+)|
10191019
|Initial Catalog<br /><br /> -or-<br /><br /> Database|N/A|The name of the database.<br /><br /> The database name can be 128 characters or less.|
10201020
|Integrated Security<br /><br /> -or-<br /><br /> Trusted_Connection|'false'|When `false`, User ID and Password are specified in the connection. When `true`, the current Windows account credentials are used for authentication.<br /><br /> Recognized values are `true`, `false`, `yes`, `no`, and `sspi` (strongly recommended), which is equivalent to `true`.<br /><br /> If User ID and Password are specified and Integrated Security is set to true, the User ID and Password will be ignored and Integrated Security will be used.<br /><br /> <xref:Microsoft.Data.SqlClient.SqlCredential> is a more secure way to specify credentials for a connection that uses SQL Server Authentication (`Integrated Security=false`).|
10211021
|IP Address Preference<br /><br /> -or-<br /><br /> IPAddressPreference|IPv4First|The IP address family preference when establishing TCP connections. If `Transparent Network IP Resolution` (in .NET Framework) or `Multi Subnet Failover` is set to true, this setting has no effect. Supported values include:<br /><br /> `IPAddressPreference=IPv4First`<br /><br />`IPAddressPreference=IPv6First`<br /><br />`IPAddressPreference=UsePlatformDefault`|

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

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1332,6 +1332,13 @@ Database = AdventureWorks
13321332
<![CDATA[
13331333
This property corresponds to the "Server Certificate" and "ServerCertificate" keys within the connection string.
13341334
1335+
> [!NOTE]
1336+
> When `ServerCertificate` is specified, the certificate presented by the server is always compared against the certificate loaded from this path, including when the presented certificate already passes chain-and-name validation. An exact match satisfies certificate validation.
1337+
>
1338+
> If the presented certificate does not match, or the file cannot be loaded or parsed, the TLS handshake fails; a configured `ServerCertificate` is never silently ignored.
1339+
>
1340+
> Certificate validation itself can be disabled by `TrustServerCertificate=true` (except with `Encrypt=strict`, where validation is always performed). When validation is disabled, `ServerCertificate` is not consulted.
1341+
13351342
]]>
13361343
</format>
13371344
</remarks>

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

Lines changed: 95 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,20 @@ internal class SniCommon
4848
/// Certificate validation and chain trust validations are done by SSLStream class [System.Net.Security.SecureChannel.VerifyRemoteCertificate method]
4949
/// This method is called as a result of callback for SSL Stream Certificate validation.
5050
/// </summary>
51+
/// <remarks>
52+
/// When <paramref name="validationCertFileName"/> is supplied, the presented server
53+
/// certificate is always compared against it, even when <paramref name="policyErrors"/> is
54+
/// <see cref="SslPolicyErrors.None"/>. An exact match satisfies certificate validation. A
55+
/// configured certificate that cannot be loaded or parsed, or that does not match, fails
56+
/// the connection; it is never silently ignored.
57+
/// <para>
58+
/// The one condition a match does not satisfy is a missing server certificate. SslStream
59+
/// reports that as <see cref="SslPolicyErrors.RemoteCertificateNotAvailable"/> and passes a
60+
/// null <paramref name="serverCert"/>; the two are expected to agree, but both are checked
61+
/// so that neither an absent certificate nor the contradictory combination can be accepted
62+
/// on the basis of a comparison.
63+
/// </para>
64+
/// </remarks>
5165
/// <param name="connectionId">Connection ID/GUID for tracing</param>
5266
/// <param name="targetServerName">Server that client is expecting to connect to</param>
5367
/// <param name="hostNameInCertificate">Optional hostname to use for server certificate validation</param>
@@ -59,14 +73,14 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ
5973
{
6074
using (SqlClientSNIEventScope.Create(nameof(SniCommon)))
6175
{
62-
if (policyErrors == SslPolicyErrors.None)
76+
// When a pin is configured, require it to match even if the platform trusts the cert.
77+
if (string.IsNullOrEmpty(validationCertFileName) && policyErrors == SslPolicyErrors.None)
6378
{
64-
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, targetServerName {1}, SSL Server certificate not validated as PolicyErrors set to None.", args0: connectionId, args1: targetServerName);
79+
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);
6580
return true;
6681
}
6782

6883
string serverNameToValidate;
69-
X509Certificate validationCertificate = null;
7084
if (!string.IsNullOrEmpty(hostNameInCertificate))
7185
{
7286
serverNameToValidate = hostNameInCertificate;
@@ -78,89 +92,114 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ
7892

7993
if (!string.IsNullOrEmpty(validationCertFileName))
8094
{
81-
try
95+
// There is no trustworthy certificate to compare against when the server
96+
// presented none. SslStream reports that as RemoteCertificateNotAvailable, and
97+
// serverCert is null in that case; both are checked because a matching
98+
// ServerCertificate must never satisfy validation when the presented
99+
// certificate is absent or cannot be relied upon.
100+
if (serverCert is null || policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
82101
{
83-
#if NET9_0_OR_GREATER
84-
validationCertificate = X509CertificateLoader.LoadCertificateFromFile(validationCertFileName);
85-
#else
86-
validationCertificate = new X509Certificate(validationCertFileName);
87-
#endif
88-
}
89-
catch (Exception e)
90-
{
91-
// if this fails, then fall back to the HostNameInCertificate or TargetServer validation.
92-
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Exception occurred loading specified ServerCertificate: {1}, treating it as if ServerCertificate has not been specified.", args0: connectionId, args1: e.Message);
102+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, ServerCertificate was specified but the server presented no certificate. Certificate validation failed.", args0: connectionId);
103+
throw ADP.SSLCertificateAuthenticationException(Strings.SQL_ServerCertificateNotAvailable);
93104
}
94-
}
95105

96-
if (validationCertificate != null)
97-
{
106+
using X509Certificate validationCertificate = LoadValidationCertificate(connectionId, validationCertFileName);
107+
98108
if (serverCert.GetRawCertData().AsSpan().SequenceEqual(validationCertificate.GetRawCertData().AsSpan()))
99109
{
100110
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, ServerCertificate matches the certificate provided by the server. Certificate validation passed.", args0: connectionId);
101111
return true;
102112
}
103113
else
104114
{
105-
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, ServerCertificate doesn't match the certificate provided by the server. Certificate validation failed.", args0: connectionId);
115+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, ServerCertificate doesn't match the certificate provided by the server. Certificate validation failed.", args0: connectionId);
106116
throw ADP.SSLCertificateAuthenticationException(Strings.SQL_RemoteCertificateDoesNotMatchServerCertificate);
107117
}
108118
}
109-
else
119+
120+
// If we get to this point then there is a ssl policy flag.
121+
StringBuilder messageBuilder = new();
122+
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
110123
{
111-
// If we get to this point then there is a ssl policy flag.
112-
StringBuilder messageBuilder = new();
113-
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
114-
{
115-
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);
116-
messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNotAvailable);
117-
}
124+
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);
125+
messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNotAvailable);
126+
}
118127

119-
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
120-
{
121-
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);
122-
123-
// get the chain status from the certificate
124-
X509Certificate2 cert2 = serverCert as X509Certificate2;
125-
X509Chain chain = new();
126-
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
127-
StringBuilder chainStatusInformation = new();
128-
bool chainIsValid = chain.Build(cert2);
129-
Debug.Assert(!chainIsValid, "RemoteCertificateChainError flag is detected, but certificate chain is valid.");
130-
if (!chainIsValid)
131-
{
132-
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
133-
{
134-
chainStatusInformation.Append($"{chainStatus.StatusInformation}, [Status: {chainStatus.Status}]");
135-
chainStatusInformation.AppendLine();
136-
}
137-
}
138-
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SslPolicyError {2}, SSL Policy certificate chain has errors. ChainStatus {3}", args0: connectionId, args1: targetServerName, args2: policyErrors, args3: chainStatusInformation);
139-
messageBuilder.AppendFormat(Strings.SQL_RemoteCertificateChainErrors, chainStatusInformation);
140-
messageBuilder.AppendLine();
141-
}
128+
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors))
129+
{
130+
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);
142131

143-
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
132+
// get the chain status from the certificate
133+
X509Certificate2 cert2 = serverCert as X509Certificate2;
134+
X509Chain chain = new();
135+
chain.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
136+
StringBuilder chainStatusInformation = new();
137+
bool chainIsValid = chain.Build(cert2);
138+
Debug.Assert(!chainIsValid, "RemoteCertificateChainError flag is detected, but certificate chain is valid.");
139+
if (!chainIsValid)
144140
{
145-
X509Certificate2 cert2 = serverCert as X509Certificate2;
146-
if (!cert2.MatchesHostname(serverNameToValidate))
141+
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
147142
{
148-
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, serverNameToValidate {1}, Target Server name or HNIC does not match the Subject/SAN in Certificate.", args0: connectionId, args1: serverNameToValidate);
149-
messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNameMismatch);
143+
chainStatusInformation.Append($"{chainStatus.StatusInformation}, [Status: {chainStatus.Status}]");
144+
chainStatusInformation.AppendLine();
150145
}
151146
}
147+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SslPolicyError {2}, SSL Policy certificate chain has errors. ChainStatus {3}", args0: connectionId, args1: targetServerName, args2: policyErrors, args3: chainStatusInformation);
148+
messageBuilder.AppendFormat(Strings.SQL_RemoteCertificateChainErrors, chainStatusInformation);
149+
messageBuilder.AppendLine();
150+
}
152151

153-
if (messageBuilder.Length > 0)
152+
if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch))
153+
{
154+
X509Certificate2 cert2 = serverCert as X509Certificate2;
155+
if (!cert2.MatchesHostname(serverNameToValidate))
154156
{
155-
throw ADP.SSLCertificateAuthenticationException(messageBuilder.ToString());
157+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, serverNameToValidate {1}, Target Server name or HNIC does not match the Subject/SAN in Certificate.", args0: connectionId, args1: serverNameToValidate);
158+
messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNameMismatch);
156159
}
157160
}
158161

162+
if (messageBuilder.Length > 0)
163+
{
164+
throw ADP.SSLCertificateAuthenticationException(messageBuilder.ToString());
165+
}
166+
159167
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, certificate with subject: {1}, validated successfully.", args0: connectionId, args1: serverCert.Subject);
160168
return true;
161169
}
162170
}
163171

172+
/// <summary>
173+
/// Loads the certificate specified by the <c>ServerCertificate</c> option, failing closed
174+
/// when it cannot be loaded or parsed.
175+
/// </summary>
176+
/// <param name="connectionId">Connection ID/GUID for tracing</param>
177+
/// <param name="validationCertFileName">Path to the X.509 certificate file</param>
178+
/// <exception cref="System.Security.Authentication.AuthenticationException">
179+
/// Thrown when the file cannot be loaded or parsed.
180+
/// </exception>
181+
private static X509Certificate LoadValidationCertificate(Guid connectionId, string validationCertFileName)
182+
{
183+
try
184+
{
185+
#if NET9_0_OR_GREATER
186+
return X509CertificateLoader.LoadCertificateFromFile(validationCertFileName);
187+
#else
188+
return new X509Certificate(validationCertFileName);
189+
#endif
190+
}
191+
catch (Exception e)
192+
{
193+
// Fail closed: the caller explicitly asked us to compare against a specific
194+
// certificate, so if we cannot load / parse it we must not fall back to validating
195+
// by host name alone. The exception details are traced separately; the user-facing
196+
// message identifies the configured file path so operators can locate the
197+
// misconfiguration.
198+
SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, Exception occurred loading specified ServerCertificate '{1}': {2}. Failing certificate validation.", args0: connectionId, args1: validationCertFileName, args2: e.Message);
199+
throw ADP.SSLCertificateAuthenticationException(StringsHelper.GetString(Strings.SQL_ServerCertificateFileLoadFailed, validationCertFileName));
200+
}
201+
}
202+
164203
internal static IPAddress[] GetDnsIpAddresses(string serverName, TimeoutTimer timeout)
165204
{
166205
IPAddress[] ipAddresses = GetDnsIpAddresses(serverName);

0 commit comments

Comments
 (0)