From 20959a9a193a2148ddb5296bd22c832d87425177 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 Jan 2023 19:23:46 -0600 Subject: validate CIDR prior to login --- src/slskd/Relay/API/Hubs/RelayHub.cs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index d0e9a962..43f49976 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // +using Microsoft.Extensions.Options; + namespace slskd.Relay { using System; @@ -24,6 +26,7 @@ namespace slskd.Relay using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; + using NetTools; using Serilog; /// @@ -74,17 +77,21 @@ namespace slskd.Relay /// Initializes a new instance of the class. /// /// + /// /// public RelayHub( IRelayService relayService, + IOptionsMonitor optionsMonitor, OptionsAtStartup optionsAtStartup) { Relay = relayService; + OptionsMonitor = optionsMonitor; OptionsAtStartup = optionsAtStartup; } private ILogger Log { get; } = Serilog.Log.ForContext(); private IRelayService Relay { get; } + private IOptionsMonitor OptionsMonitor { get; } private OptionsAtStartup OptionsAtStartup { get; } private RelayMode OperationMode => OptionsAtStartup.Relay.Mode.ToEnum(); private IPAddress RemoteIpAddress => Context.Features.Get().RemoteIpAddress; @@ -131,9 +138,25 @@ namespace slskd.Relay /// Thrown when the challenge response is invalid. public void Login(string agent, string challengeResponse) { + OptionsMonitor.CurrentValue.Relay.Agents.TryGetValue(agent, out var agentOptions); + + if (agentOptions == default) + { + Log.Warning("Unauthorized login attempt from unknown Agent {Agent} (connection {Id}) from {IP}", agent, Context.ConnectionId, RemoteIpAddress); + throw new UnauthorizedAccessException(); + } + + if (!agentOptions.Cidr.Split(',') + .Select(cidr => IPAddressRange.Parse(cidr)) + .Any(range => range.Contains(RemoteIpAddress))) + { + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}); remote IP address {IP} is not within the configured range {CIDR}", agent, Context.ConnectionId, RemoteIpAddress, agentOptions.Cidr); + throw new UnauthorizedAccessException(); + } + if (!Relay.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { - Log.Information("Agent connection {Id} from {IP} authentication failed", Context.ConnectionId, RemoteIpAddress); + Log.Warning("Unauthorized login attempt by Agent {Agent} (connection {Id}) from {IP}; authentication failed", agent, Context.ConnectionId, RemoteIpAddress); Relay.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! throw new UnauthorizedAccessException(); } -- cgit v1.2.3