Compare commits

...
Author SHA1 Message Date
Suhas Holla Karkada Chandrashekar 7be55ce922 Fix default TLS certificate validation (BREAKING CHANGE) (#2254)
Fix default TLS certificate validation
2026-07-03 17:56:41 +02:00
2 changed files with 30 additions and 9 deletions
+27 -1
View File
@@ -3,7 +3,10 @@
// See the LICENSE file in the project root for more information.
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using MQTTnet.Implementations;
namespace MQTTnet.Tests;
@@ -12,6 +15,21 @@ namespace MQTTnet.Tests;
[TestClass]
public class MqttTcpChannel_Tests
{
[TestMethod]
public void Certificate_Validation_Uses_Default_Handler_When_No_Custom_Handler()
{
var options = new MqttClientOptionsBuilder().WithTcpServer("localhost")
.WithTlsOptions(o => o.WithAllowUntrustedCertificates().WithIgnoreCertificateRevocationErrors())
.Build();
var tcpChannel = new MqttTcpChannel(options);
using var chain = new X509Chain();
var isValid = InvokeCertificateValidationCallback(tcpChannel, chain, SslPolicyErrors.RemoteCertificateChainErrors);
Assert.IsTrue(isValid);
}
[TestMethod]
public async Task Dispose_Channel_While_Used()
{
@@ -77,4 +95,12 @@ public class MqttTcpChannel_Tests
ct.Cancel(false);
}
}
}
static bool InvokeCertificateValidationCallback(MqttTcpChannel tcpChannel, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
var method = typeof(MqttTcpChannel).GetMethod("InternalUserCertificateValidationCallback", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(method);
return (bool)method.Invoke(tcpChannel, [null, null, chain, sslPolicyErrors]);
}
}
@@ -362,23 +362,18 @@ public sealed class MqttTcpChannel : IMqttChannel
bool InternalUserCertificateValidationCallback(object sender, X509Certificate x509Certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
var eventArgs = new MqttClientCertificateValidationEventArgs(x509Certificate, chain, sslPolicyErrors, _tcpOptions);
var certificateValidationHandler = _tcpOptions?.TlsOptions?.CertificateValidationHandler;
if (certificateValidationHandler != null)
{
var eventArgs = new MqttClientCertificateValidationEventArgs(x509Certificate, chain, sslPolicyErrors, _tcpOptions);
return certificateValidationHandler(eventArgs);
}
if (_tcpOptions?.TlsOptions?.IgnoreCertificateChainErrors ?? false)
{
sslPolicyErrors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
}
return sslPolicyErrors == SslPolicyErrors.None;
return MqttClientDefaultCertificateValidationHandler.Handle(eventArgs);
}
X509CertificateCollection LoadCertificates()
{
return _tcpOptions.TlsOptions.ClientCertificatesProvider?.GetCertificates();
}
}
}