From 2d1b24164357af9f15ee0629979035d7c365e94a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 Jan 2023 19:22:48 -0600 Subject: add agent CIDR --- src/slskd/Core/Options.cs | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index bc6f14a6..063da9e6 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -513,15 +513,46 @@ namespace slskd /// /// Relay agent configuration options. /// - public class RelayAgentConfigurationOptions + public class RelayAgentConfigurationOptions : IValidatableObject { /// /// Gets the agent secret. /// + [Description("shared secret for this agent")] [StringLength(255, MinimumLength = 16)] [NotNullOrWhiteSpace] [Secret] public string Secret { get; init; } + + /// + /// Gets the comma separated list of CIDRs that are authorized to connect as this agent. + /// + [Description("optional; comma separated list of CIDRs that are authorized to connect as this agent")] + public string Cidr { get; init; } = "0.0.0.0/0,::/0"; + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + foreach (var cidr in Cidr.Split(',')) + { + try + { + _ = IPAddressRange.Parse(cidr); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}")); + } + } + + return results; + } } } @@ -1476,7 +1507,7 @@ namespace slskd /// /// Gets the comma separated list of CIDRs that are authorized to use the key. /// - [Description("An optional comma separated list of CIDRs that are authorized to use the key")] + [Description("optional; comma separated list of CIDRs that are authorized to use the key")] public string Cidr { get; init; } = "0.0.0.0/0,::/0"; /// -- cgit v1.2.3 From c74888b05169bc5c2e0233cf63300bceeaef30de Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 5 Jan 2023 19:23:11 -0600 Subject: check and validate credentials --- src/slskd/Relay/API/Controllers/RelayController.cs | 32 ++++++++++++++-------- 1 file changed, 21 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 7183283f..d4fb4810 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -82,6 +82,11 @@ namespace slskd.Relay return NoContent(); } + /// + /// Downloads a file. + /// + /// The unique identifier for the request. + /// [HttpGet("downloads/{token}")] [Authorize(Policy = AuthPolicy.ApiKeyOnly)] public IActionResult DownloadFile([FromRoute]string token) @@ -100,11 +105,16 @@ namespace slskd.Relay var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); var filename = Request.Headers["X-Relay-Filename"].FirstOrDefault(); - if (!Relay.RegisteredAgents.Any(a => a.Name == agentName)) + if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential)) { return Unauthorized(); } + if (string.IsNullOrEmpty(filename)) + { + return BadRequest(); + } + Log.Information("Handling file download for token {Token} from a caller claiming to be agent {Agent}", token, agentName); // note: the token remains valid after the validation attempt, unlike most other endpoints. @@ -155,6 +165,11 @@ namespace slskd.Relay var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); + if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential)) + { + return Unauthorized(); + } + Stream stream = default; string filename = default; @@ -179,11 +194,6 @@ namespace slskd.Relay return BadRequest(); } - if (!Relay.RegisteredAgents.Any(a => a.Name == agentName)) - { - return Unauthorized(); - } - Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); // agents must encrypt the Id they were given in the request with the secret they share with the controller, and @@ -240,6 +250,11 @@ namespace slskd.Relay var agentName = Request.Headers["X-Relay-Agent"].FirstOrDefault(); var credential = Request.Headers["X-Relay-Credential"].FirstOrDefault(); + if (!Relay.RegisteredAgents.Any(a => a.Name == agentName) || string.IsNullOrEmpty(credential)) + { + return Unauthorized(); + } + IEnumerable shares; IFormFile database; @@ -254,11 +269,6 @@ namespace slskd.Relay return BadRequest(); } - if (!Relay.RegisteredAgents.Any(a => a.Name == agentName)) - { - return Unauthorized(); - } - if (!Relay.TryValidateShareUploadCredential(token: guid, agentName, credential)) { Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent} using token {Token}", agentName, guid); -- cgit v1.2.3 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