diff --git a/NATS.Client/Conn.cs b/NATS.Client/Conn.cs index c3bcd388c..f90cc972a 100644 --- a/NATS.Client/Conn.cs +++ b/NATS.Client/Conn.cs @@ -439,6 +439,7 @@ internal void open(Srv s, int timeoutMillis) task.ContinueWith(t => GC.KeepAlive(t.Exception), TaskContinuationOptions.OnlyOnFaulted); if (!task.Wait(TimeSpan.FromMilliseconds(timeoutMillis))) { + close(client); client = null; throw new NATSConnectionException("timeout"); } @@ -467,7 +468,7 @@ private static bool remoteCertificateValidation( return false; } - internal void closeClient(TcpClient c) + internal static void close(TcpClient c) { if (c != null) { @@ -500,7 +501,10 @@ internal void makeTLS(Options options) } catch (Exception ex) { - closeClient(client); + sslStream.Dispose(); + sslStream = null; + + close(client); throw new NATSConnectionException("TLS Authentication error", ex); } } @@ -540,7 +544,7 @@ internal void teardown() s.Dispose(); if (c != null) - closeClient(c); + close(c); } catch (Exception) { } } @@ -601,7 +605,7 @@ void Dispose(bool disposing) if (stream != null) stream.Dispose(); if (client != null) - closeClient(client); + close(client); disposedValue = true; } diff --git a/NATSUnitTests/UnitTestTLS.cs b/NATSUnitTests/UnitTestTLS.cs index d34166bf9..fbc736c5d 100644 --- a/NATSUnitTests/UnitTestTLS.cs +++ b/NATSUnitTests/UnitTestTLS.cs @@ -155,6 +155,33 @@ public void TestTlsFailWithCert() } } + // Test verfier to fail on the server cert. + // + private bool verifyCertAlwaysFail(object sender, + X509Certificate certificate, X509Chain chain, + SslPolicyErrors sslPolicyErrors) + { + return false; + } + + [Fact] + public void TestTlsFailWithInvalidServerCert() + { + using (NATSServer srv = util.CreateServerWithConfig("tls_1222_verify.conf")) + { + Options opts = util.DefaultTestOptions; + opts.Secure = true; + opts.Url = "nats://localhost:1222"; + opts.TLSRemoteCertificationValidationCallback = verifyCertAlwaysFail; + + // this will fail, because it's not complete - missing the private + // key. + opts.AddCertificate(UnitTestUtilities.GetFullCertificatePath("client-cert.pem")); + + Assert.ThrowsAny(() => new ConnectionFactory().CreateConnection(opts)); + } + } + [Fact] public void TestTlsFailWithBadAuth() {