diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-08 18:16:34 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2022-10-08 18:16:34 -0500 |
| commit | 9af9f9119f32734414fa725a9d742448e937732b (patch) | |
| tree | 54df23cdefe69b4c85fd32156bbc97e0e6ce8c3c /src | |
| parent | 5203788c41d652d17f67c3c45658b289a6acf380 (diff) | |
| download | slskd-9af9f9119f32734414fa725a9d742448e937732b.tar.gz | |
implement auth and registration
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Agents/API/Hubs/AgentHub.cs | 49 | ||||
| -rw-r--r-- | src/slskd/Agents/AgentService.cs | 184 |
2 files changed, 195 insertions, 38 deletions
diff --git a/src/slskd/Agents/API/Hubs/AgentHub.cs b/src/slskd/Agents/API/Hubs/AgentHub.cs index 99df6bf8..20ccdad0 100644 --- a/src/slskd/Agents/API/Hubs/AgentHub.cs +++ b/src/slskd/Agents/API/Hubs/AgentHub.cs @@ -15,19 +15,20 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> -using Microsoft.Extensions.Options; - namespace slskd.Agents { using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.SignalR; - using slskd; + using Serilog; public static class AgentHubMethods { public static readonly string RequestFile = "REQUEST_FILE"; + public static readonly string AuthenticationChallenge = "AUTHENTICATION_CHALLENGE"; + public static readonly string AuthenticationChallengeAccepted = "AUTHENTICATION_CHALLENGE_ACCEPTED"; + public static readonly string AuthenticationChallengeRejected = "AUTHENTICATION_CHALLENGE_REJECTED"; } /// <summary> @@ -49,24 +50,42 @@ namespace slskd.Agents public class AgentHub : Hub { public AgentHub( - IStateMonitor<State> stateMonitor, - IOptionsMonitor<Options> optionsMonitor) + IAgentService agentService) { - StateMonitor = stateMonitor; - OptionsMonitor = optionsMonitor; + Agents = agentService; } - private IStateMonitor<State> StateMonitor { get; } - private IOptionsMonitor<Options> OptionsMonitor { get; } + private IAgentService Agents { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<AgentService>(); public override async Task OnConnectedAsync() { - // upon connection we need to do a little handshaking to establish - // that this is a registered agent, and which agent it is. whoever is calling - // has an api key or jwt, but users might disable auth, so literally anyone could - // connect. they should at least say who they are, and we'd allow or disallow - // todo: how to authenticate? - // todo: how to identify? + Log.Information("Agent connection {Id} established. Sending authentication challenge...", Context.ConnectionId); + await Clients.Caller.SendAsync(AgentHubMethods.AuthenticationChallenge, Agents.GenerateAuthenticationChallengeToken(Context.ConnectionId)); + } + + public override Task OnDisconnectedAsync(Exception exception) + { + if (Agents.TryRemoveAgentRegistration(Context.ConnectionId, out var agent)) + { + Log.Warning("Agent {Agent} (connection {Id}) disconnected", agent, Context.ConnectionId); + } + + return Task.CompletedTask; + } + + public bool Login(string agent, string challengeResponse) + { + if (Agents.TryValidateAuthenticationChallengeResponse(Context.ConnectionId, agent, challengeResponse)) + { + Log.Information("Agent connection {Id} authenticated as agent {Agent}", Context.ConnectionId, agent); + Agents.RegisterAgent(agent, Context.ConnectionId); + return true; + } + + Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); + Agents.TryRemoveAgentRegistration(Context.ConnectionId, out var _); // just in case! + return false; } } }
\ No newline at end of file diff --git a/src/slskd/Agents/AgentService.cs b/src/slskd/Agents/AgentService.cs index 5b17d996..5749c8c8 100644 --- a/src/slskd/Agents/AgentService.cs +++ b/src/slskd/Agents/AgentService.cs @@ -21,20 +21,29 @@ namespace slskd.Agents { using System; using System.Collections.Concurrent; + using System.Collections.ObjectModel; using System.IO; + using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR.Client; + using Microsoft.Extensions.Caching.Memory; using Serilog; + using slskd.Cryptography; public interface IAgentService { /// <summary> /// Gets the collection of pending Agent uploads. /// </summary> - ConcurrentDictionary<Guid, (TaskCompletionSource<Stream> Upload, TaskCompletionSource Completion)> PendingUploads { get; } + ReadOnlyDictionary<Guid, (TaskCompletionSource<Stream> Upload, TaskCompletionSource Completion)> PendingUploads { get; } + + /// <summary> + /// Gets the collection of registered Agents. + /// </summary> + ReadOnlyDictionary<string, string> RegisteredAgents { get; } /// <summary> /// Retrieves an upload of the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. @@ -44,6 +53,36 @@ namespace slskd.Agents /// <param name="timeout">An optional timeout value.</param> /// <returns>The operation context, including a stream containing the requested file, and an upload TaskCompletionSource.</returns> Task<(Stream Stream, TaskCompletionSource Completion)> GetUpload(string agent, string filename, int timeout = 3000); + + /// <summary> + /// Registers the specified <paramref name="agent"/> name with the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <param name="agent">The name of the agent.</param> + void RegisterAgent(string connectionId, string agent); + + /// <summary> + /// Attempts to remove the registration for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <returns>A value indicating whether a registration was removed.</returns> + bool TryRemoveAgentRegistration(string connectionId, out string agent); + + /// <summary> + /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <returns>The generated token.</returns> + string GenerateAuthenticationChallengeToken(string connectionId); + + /// <summary> + /// Validates an authentication challenge response. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <param name="agent">The agent name.</param> + /// <param name="challengeResponse">The challenge response provided by the agent.</param> + /// <returns>A value indicating whether the response is valid.</returns> + bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse); } public class AgentService : IAgentService @@ -62,19 +101,88 @@ namespace slskd.Agents Configure(OptionsMonitor.CurrentValue); } + /// <summary> + /// Gets the collection of pending Agent uploads. + /// </summary> + public ReadOnlyDictionary<Guid, (TaskCompletionSource<Stream> Upload, TaskCompletionSource Completion)> PendingUploads => new(PendingUploadDictionary); + + /// <summary> + /// Gets the collection of registered Agents. + /// </summary> + public ReadOnlyDictionary<string, string> RegisteredAgents => new(RegisteredAgentDictionary); + + private ConcurrentDictionary<Guid, (TaskCompletionSource<Stream> Upload, TaskCompletionSource Completion)> PendingUploadDictionary { get; } = new(); + private ConcurrentDictionary<string, string> RegisteredAgentDictionary { get; } = new(); + private MemoryCache MemoryCache { get; } = new MemoryCache(new MemoryCacheOptions()); private IOptionsMonitor<Options> OptionsMonitor { get; } private IHttpClientFactory HttpClientFactory { get; } private HttpClient HttpClient { get; set; } private HubConnection HubConnection { get; set; } private IHubContext<AgentHub> AgentHub { get; set; } private string LastOptionsHash { get; set; } - private SemaphoreSlim SyncRoot { get; } = new SemaphoreSlim(1, 1); + private SemaphoreSlim ConfigurationSyncRoot { get; } = new SemaphoreSlim(1, 1); private ILogger Log { get; } = Serilog.Log.ForContext<AgentService>(); /// <summary> - /// Gets the collection of pending Agent uploads. + /// Registers the specified <paramref name="agent"/> name with the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <param name="agent">The name of the agent.</param> + public void RegisterAgent(string connectionId, string agent) + => RegisteredAgentDictionary.TryAdd(connectionId, agent); + + /// <summary> + /// Attempts to remove the registration for the specified <paramref name="connectionId"/>. + /// </summary> + /// <param name="connectionId">The ID of the connection.</param> + /// <param name="agent">The name of the agent, if a registration was removed.</param> + /// <returns>A value indicating whether a registration was removed.</returns> + public bool TryRemoveAgentRegistration(string connectionId, out string agent) + => RegisteredAgentDictionary.TryRemove(connectionId, out agent); + + /// <summary> + /// Generates a random authentication challenge token for the specified <paramref name="connectionId"/>. /// </summary> - public ConcurrentDictionary<Guid, (TaskCompletionSource<Stream> Upload, TaskCompletionSource Completion)> PendingUploads { get; } = new(); + /// <param name="connectionId">The ID of the agent connection.</param> + /// <returns>The generated token.</returns> + public string GenerateAuthenticationChallengeToken(string connectionId) + { + var token = Cryptography.Random.GetBytes(16).ToBase62(); + + // this token is only valid for this connection id for a short time + // this is important to prevent replay-type attacks. + MemoryCache.Set(connectionId, token, TimeSpan.FromMinutes(1)); + Log.Debug("Cached token {Token} for ID {Id}", token, connectionId); + return token; + } + + /// <summary> + /// Validates an authentication challenge response. + /// </summary> + /// <param name="connectionId">The ID of the agent connection.</param> + /// <param name="agent">The agent name.</param> + /// <param name="challengeResponse">The challenge response provided by the agent.</param> + /// <returns>A value indicating whether the response is valid.</returns> + public bool TryValidateAuthenticationChallengeResponse(string connectionId, string agent, string challengeResponse) + { + if (!MemoryCache.TryGetValue(connectionId, out var challengeToken)) + { + Log.Debug("Auth challenge for {Id} failed: no challenge token cached for ID", connectionId); + return false; + } + + if (!OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agent, out var agentOptions)) + { + Log.Debug("Auth challenge for {Id} failed: no configuration for agent '{Agent}'", connectionId, agent); + return false; + } + + var key = agentOptions.Secret.FromBase62(); + var tokenBytes = ((string)challengeToken).FromBase62(); + var expectedResponse = Aes.Encrypt(tokenBytes, key).ToBase62(); + + return expectedResponse == challengeResponse; + } /// <summary> /// Retrieves an upload of the specified <paramref name="filename"/> from the specified <paramref name="agent"/>. @@ -97,7 +205,7 @@ namespace slskd.Agents // keep the stream open for the duration var completion = new TaskCompletionSource(); - PendingUploads.TryAdd(id, (upload, completion)); + PendingUploadDictionary.TryAdd(id, (upload, completion)); await AgentHub.RequestFileAsync(agent, filename, id); Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agent, id); @@ -146,13 +254,42 @@ namespace slskd.Agents } catch (Exception ex) { - Console.WriteLine(ex); + Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); + } + } + + private async Task HandleAuthenticationChallenge(string challengeToken) + { + Log.Information("Controller sent an authentication challenge"); + + try + { + var options = OptionsMonitor.CurrentValue; + + var agent = options.InstanceName; + var key = options.Network.Controller.Secret.FromBase62(); + var tokenBytes = challengeToken.FromBase62(); + + var response = Aes.Encrypt(tokenBytes, key).ToBase62(); + + Log.Information("Logging in..."); + var success = await HubConnection.InvokeAsync<bool>("Login", agent, response); + + if (!success) + { + await HubConnection.StopAsync(); + Log.Error("Controller authentication failed. Check configuration."); + } + } + catch (Exception ex) + { + Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); } } private void Configure(Options options) { - SyncRoot.Wait(); + ConfigurationSyncRoot.Wait(); try { @@ -170,31 +307,32 @@ namespace slskd.Agents HttpClient = HttpClientFactory.CreateClient(); HttpClient.BaseAddress = new(options.Network.Controller.Address); - Console.WriteLine("-------------------------- building hub ------------------------"); HubConnection = new HubConnectionBuilder() .WithUrl($"{options.Network.Controller.Address}/hub/agents") - .WithAutomaticReconnect() + .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30) }) .Build(); - HubConnection.On<Guid, string>(AgentHubMethods.RequestFile, HandleFileRequest); HubConnection.Reconnected += HubConnection_Reconnected; HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; + HubConnection.On<Guid, string>(AgentHubMethods.RequestFile, HandleFileRequest); + HubConnection.On<string>(AgentHubMethods.AuthenticationChallenge, HandleAuthenticationChallenge); + _ = Task.Run(async () => { - try - { - await Task.Delay(1000); - Console.WriteLine("------------------- connecting hub -------------------"); - await HubConnection.StartAsync(); - Log.Information("Controller connection established"); - Console.WriteLine("---------------------------- hub connected ----------------------"); - } - catch (Exception ex) - { - Console.WriteLine(ex); - } + // it takes a bit for the application to become responsive to network calls + await Task.Delay(3000); + + // retry indefinitely + await Retry.Do( + task: () => HubConnection.StartAsync(), + isRetryable: (attempts, ex) => true, + onFailure: (attempts, ex) => Log.Warning("Failed attempt #{Attempts} to connect to controller: {Message}", attempts, ex.Message), + maxAttempts: int.MaxValue, + maxDelayInMilliseconds: 30000); + + Log.Information("Controller connection established"); }); //} @@ -202,7 +340,7 @@ namespace slskd.Agents } finally { - SyncRoot.Release(); + ConfigurationSyncRoot.Release(); } } |
