// // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see https://www.gnu.org/licenses/. // using Microsoft.Extensions.Options; namespace slskd.Relay { using System; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.SignalR; using NetTools; using Serilog; /// /// Methods for the . /// public interface IRelayHub { /// /// Sends an authentication challenge token to the newly connected agent. /// /// The token. /// The operation context. Task Challenge(string token); /// /// Requests information about the specified from the agent. /// /// The name of the file. /// The unique identifier for the request. /// The operation context. Task RequestFileInfo(string filename, Guid id); /// /// Requests the specified from the agent. /// /// The name of the file. /// The starting offset for the transfer. /// The unique identifier for the request. /// The operation context. Task RequestFileUpload(string filename, long startOffset, Guid id); /// /// Notifies the agent that the download of the specified is complete and that the file is ready for downloading. /// /// The name of the newly downloaded file. /// The unique identifier for the request. /// The operation context. Task NotifyFileDownloadCompleted(string filename, Guid id); } /// /// The relay SignalR hub. /// [Authorize] public class RelayHub : Hub { /// /// 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; /// /// Executed when a new connection is established. /// /// public override async Task OnConnectedAsync() { if (!OptionsAtStartup.Relay.Enabled || !new[] { RelayMode.Controller, RelayMode.Debug }.Contains(OperationMode)) { Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, RemoteIpAddress); Context.Abort(); } var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); Log.Information("Agent connection {Id} from {IP} established. Sending authentication challenge {Token}...", Context.ConnectionId, RemoteIpAddress, token); await Clients.Caller.Challenge(token); } /// /// Executed when a connection is disconnected. /// /// The Exception that caused the disconnect. /// public override Task OnDisconnectedAsync(Exception exception) { if (Relay.TryDeregisterAgent(Context.ConnectionId, out var record)) { Log.Warning("Agent {Agent} (connection {Id}) from {IP} disconnected", record.Agent.Name, Context.ConnectionId, RemoteIpAddress); Relay.TryDeregisterAgent(record.Agent.Name, out _); } return Task.CompletedTask; } /// /// Executed by the agent after receipt of an authentication challenge token, shortly after the connection is established. /// /// The agent's name. /// The response to the challenge token. /// Thrown when the challenge response is invalid. public void Login(string agent, string challengeResponse) { bool TryGetAgentConfig(string agent, out Options.RelayOptions.RelayAgentConfigurationOptions options) { var allAgents = OptionsMonitor.CurrentValue.Relay.Agents; var found = allAgents.Values.SingleOrDefault(a => a.InstanceName == agent); if (found != default) { options = found; return true; } Log.Warning("Unable to locate Agent config for '{Agent}' (configured Agents: {Agents})", agent, string.Join(", ", allAgents.Values.Select(a => a.InstanceName))); options = null; return false; } if (!TryGetAgentConfig(agent, out var agentOptions)) { 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.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(); } var remoteIp = Context.Features.Get().RemoteIpAddress.ToString(); var record = new Agent { Name = agent, IPAddress = remoteIp }; Log.Information("Agent connection {Id} from {IP} authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); Relay.RegisterAgent(Context.ConnectionId, record); } /// /// Executed by the agent to initiate the share upload workflow by generating and retrieving a request token. /// /// The generated token. /// Thrown when the agent is not fully authenticated. public Guid BeginShareUpload() { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { // this can happen if the agent attempts to upload before logging in Log.Information("Agent connection {Id} from {IP} requested a share upload token, but is not registered.", Context.ConnectionId, RemoteIpAddress); throw new UnauthorizedAccessException(); } var token = Relay.GenerateShareUploadToken(record.Agent.Name); Log.Information("Agent {Agent} (connection {Id}) from {IP} requested share upload token {Token}", record.Agent.Name, record.ConnectionId, RemoteIpAddress, token); return token; } /// /// Executed by the agent to notify the controller that the agent was unable to upload the file requested by a call to . /// /// The unique identifier of the request. /// The Exception that caused the failure. /// Thrown when the agent is not fully authenticated. public void NotifyFileUploadFailed(Guid id, Exception exception) { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { Log.Warning("Agent connection {Id} from {IP} attempted to report a failed upload, but is not registered.", Context.ConnectionId, RemoteIpAddress); throw new UnauthorizedAccessException(); } Log.Warning("Agent {Agent} (connection {ConnectionId}) from {IP} reported upload failure for {Id}: {Message}", record.Agent, Context.ConnectionId, RemoteIpAddress, id, exception.Message); Relay.NotifyFileStreamException(id, exception); } /// /// Executed by the agent to return the response to a call to . /// /// The unique identifier for the request. /// A value indicating whether the requested file exists on the agent's filesystem. /// The length of the file, or 0 if the file does not exist. /// Thrown when the agent is not fully authenticated. public void ReturnFileInfo(Guid id, bool exists, long length) { if (!Relay.TryGetAgentRegistration(Context.ConnectionId, out var record)) { Log.Warning("Agent connection {Id} from {IP} attempted to return file information, but is not registered.", Context.ConnectionId, RemoteIpAddress); throw new UnauthorizedAccessException(); } Log.Information("Agent {Agent} (connection {ConnectionId}) from {IP} returned file info for {Id}; exists: {Exists}, length: {Length}", record.Agent.Name, Context.ConnectionId, RemoteIpAddress, id, exists, length); Relay.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); } } }