Skip to content

Commit

Permalink
Fix TLS hosts for implicit connections
Browse files Browse the repository at this point in the history
  • Loading branch information
mtmk committed Oct 16, 2023
1 parent 5899776 commit f6134b1
Showing 1 changed file with 17 additions and 11 deletions.
28 changes: 17 additions & 11 deletions src/NATS.Client.Core/NatsConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ private async ValueTask InitialConnectAsync()
{
// upgrade TcpConnection to SslConnection
var sslConnection = conn.UpgradeToSslStreamConnection(Opts.TlsOpts, _tlsCerts);
await sslConnection.AuthenticateAsClientAsync(uri).ConfigureAwait(false);
await sslConnection.AuthenticateAsClientAsync(FixTlsHost(uri)).ConfigureAwait(false);
_socket = sslConnection;
}
}
Expand Down Expand Up @@ -359,15 +359,7 @@ private async ValueTask SetupReaderWriterAsync(bool reconnect)
if (Opts.TlsOpts.TryTls(_currentConnectUri) && (WritableServerInfo!.TlsRequired || WritableServerInfo.TlsAvailable))
{
// do TLS upgrade
// if the current URI is not a seed URI and is not a DNS hostname, check the server cert against the
// last seed hostname if it was a DNS hostname
var targetUri = _currentConnectUri;
if (!_currentConnectUri.IsSeed
&& Uri.CheckHostName(targetUri.Host) != UriHostNameType.Dns
&& Uri.CheckHostName(_lastSeedConnectUri!.Host) == UriHostNameType.Dns)
{
targetUri = targetUri.CloneWith(_lastSeedConnectUri.Host);
}
var targetUri = FixTlsHost(_currentConnectUri);

_logger.LogDebug("Perform TLS Upgrade to " + targetUri);

Expand Down Expand Up @@ -495,7 +487,7 @@ private async void ReconnectLoop()
{
// upgrade TcpConnection to SslConnection
var sslConnection = conn.UpgradeToSslStreamConnection(Opts.TlsOpts, _tlsCerts);
await sslConnection.AuthenticateAsClientAsync(url).ConfigureAwait(false);
await sslConnection.AuthenticateAsClientAsync(FixTlsHost(url)).ConfigureAwait(false);
_socket = sslConnection;
}
}
Expand Down Expand Up @@ -542,6 +534,20 @@ private async void ReconnectLoop()
}
}

private NatsUri FixTlsHost(NatsUri uri)
{
// if the current URI is not a seed URI and is not a DNS hostname, check the server cert against the
// last seed hostname if it was a DNS hostname
if (!uri.IsSeed
&& Uri.CheckHostName(uri.Host) != UriHostNameType.Dns
&& Uri.CheckHostName(_lastSeedConnectUri!.Host) == UriHostNameType.Dns)
{
return uri.CloneWith(_lastSeedConnectUri.Host);
}

return uri;
}

private async Task WaitWithJitterAsync()
{
var jitter = Random.Shared.NextDouble() * Opts.ReconnectJitter.TotalMilliseconds;
Expand Down

0 comments on commit f6134b1

Please sign in to comment.