From 6cbd758a276446f34802b0b81b6dd925ef0c5f26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 Oct 2022 19:07:14 -0500 Subject: use agent in cache keys, handle uploads in service --- src/slskd/Network/NetworkService.cs | 106 +++++++++++++++++++++++++++++++----- 1 file changed, 93 insertions(+), 13 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 100d9448..5de2ecb3 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -21,6 +21,7 @@ namespace slskd.Network { using System; using System.Collections.Concurrent; + using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; @@ -30,6 +31,7 @@ namespace slskd.Network using Microsoft.Extensions.Caching.Memory; using Serilog; using slskd.Cryptography; + using slskd.Shares; /// /// Handles network (controller/agent) interactions. @@ -58,6 +60,19 @@ namespace slskd.Network /// Retrieves a new share upload token for the specified . /// /// The token is cached internally, and is only valid while it remains in the cache. + /// + /// This is the first step in a multi-step workflow. The entire sequence is: + /// + /// + /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn + /// calls . The token is generated and cached. + /// + /// + /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its + /// shared database and a serialized list of locally configured shares, and the controller invokes . + /// + /// + /// /// The name of the agent. /// The generated token. Guid GenerateShareUploadToken(string agentName); @@ -132,18 +147,30 @@ namespace slskd.Network /// /// Handles the client response for a request. /// + /// The name of the agent. /// The ID of the request. /// The client response to the request. - void HandleFileInfoResponse(Guid id, (bool Exists, long Length) response); + void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response); /// /// Handles the client response for a request, returning when the corresponding file /// upload is complete. /// + /// The name of the agent. /// The ID of the request. /// The client response to the request. /// The operation context. - Task HandleFileStreamResponse(Guid id, Stream response); + Task HandleFileStreamResponse(string agentName, Guid id, Stream response); + + /// + /// Handles incoming share uploads. + /// + /// The name of the agent. + /// The ID obtained by the caller prior to uploading. + /// The list of shares provided. + /// The filename of the temporary file containing the upload. + /// The operation context. + Task HandleShareUpload(string agentName, Guid id, IEnumerable shares, string filename); /// /// Notifies the caller of of a failure to obtain a file stream from the requested agent. @@ -162,9 +189,10 @@ namespace slskd.Network /// /// Safely attempts to close a stream obtained with . /// + /// The name of the agent. /// The unique ID for the stream. /// If the transfer associated with the stream failed, the exception that caused the failure. - void TryCloseFileStream(Guid id, Exception exception = null); + void TryCloseFileStream(string agentName, Guid id, Exception exception = null); /// /// Attempts to remove the registration for the specified . @@ -218,9 +246,13 @@ namespace slskd.Network { public NetworkService( IWaiter waiter, + IShareService shareService, + IShareRepositoryFactory shareRepositoryFactory, IOptionsMonitor optionsMonitor, IHubContext networkHub) { + Shares = shareService; + ShareRepositoryFactory = shareRepositoryFactory; Waiter = waiter; NetworkHub = networkHub; @@ -243,6 +275,8 @@ namespace slskd.Network private IOptionsMonitor OptionsMonitor { get; } private ConcurrentDictionary> PendingFileInquiryDictionary { get; } = new(); private ConcurrentDictionary RegisteredAgentDictionary { get; } = new(); + private IShareRepositoryFactory ShareRepositoryFactory { get; } + private IShareService Shares { get; } private IWaiter Waiter { get; } private ConcurrentDictionary WaitIdDictionary { get; } = new(); @@ -266,6 +300,23 @@ namespace slskd.Network /// Retrieves a new share upload token for the specified . /// /// The token is cached internally, and is only valid while it remains in the cache. + /// + /// This is the first step in a multi-step workflow. The entire sequence is: + /// + /// + /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn + /// calls . The token is generated and cached. + /// + /// + /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its + /// shared database and a serialized list of locally configured shares. + /// + /// + /// The HTTP controller saves the database backup to a temporary file, validates it, and then adds (or updates) + /// a share host for the agent. + /// + /// + /// /// The name of the agent. /// The generated token. public Guid GenerateShareUploadToken(string agentName) @@ -309,7 +360,7 @@ namespace slskd.Network // prepare a wait for the response. we don't cache the token along with the agent here, as all data is exchanged over // an authenticated SignalR connection var id = Guid.NewGuid(); - var key = new WaitKey(nameof(GetFileInfoAsync), id); + var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); var wait = Waiter.Wait<(bool Exists, long Length)>(key, timeout); try @@ -383,7 +434,7 @@ namespace slskd.Network // create a wait for the agent response. this wait will be completed in the response handler, ultimately called from // the API controller when the agent makes an HTTP request to return the file - var key = new WaitKey(nameof(GetFileStreamAsync), id); + var key = new WaitKey(nameof(GetFileStreamAsync), agentName, id); var wait = Waiter.Wait(key, timeout, cancellationToken); await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id); @@ -407,15 +458,16 @@ namespace slskd.Network /// /// Handles the client response for a request. /// + /// The name of the agent. /// The ID of the request. /// The client response to the request. - public void HandleFileInfoResponse(Guid id, (bool Exists, long Length) response) + public void HandleFileInfoResponse(string agentName, Guid id, (bool Exists, long Length) response) { - var key = new WaitKey(nameof(GetFileInfoAsync), id); + var key = new WaitKey(nameof(GetFileInfoAsync), agentName, id); if (!Waiter.IsWaitingFor(key)) { - var msg = $"A file info response matching Id {id} was not expected"; + var msg = $"A file info response from Agent {agentName} matching Id {id} was not expected"; Log.Warning(msg); throw new NotFoundException(msg); } @@ -430,12 +482,13 @@ namespace slskd.Network /// /// Assumes has previously been used to ensure the Id and agent match. /// + /// The name of the agent. /// The ID of the request. /// The client response to the request. /// The operation context. - public async Task HandleFileStreamResponse(Guid id, Stream response) + public async Task HandleFileStreamResponse(string agentName, Guid id, Stream response) { - var streamKey = new WaitKey(nameof(GetFileStreamAsync), id); + var streamKey = new WaitKey(nameof(GetFileStreamAsync), agentName, id); if (!Waiter.IsWaitingFor(streamKey)) { @@ -447,7 +500,7 @@ namespace slskd.Network // create a wait (but do not await it) for the completion of the upload to the remote client. we need to await this to // keep execution in the body of the API controller that provided the stream, in order to keep the stream open for the // duration of the remote transfer. omit the id from the key, the caller doesn't know it. - var completionKey = new WaitKey(nameof(HandleFileStreamResponse), id); + var completionKey = new WaitKey(nameof(HandleFileStreamResponse), agentName, id); var completion = Waiter.WaitIndefinitely(completionKey); // complete the wait that's waiting for the stream, so we can send the stream back to the caller of GetFileStream this @@ -459,6 +512,32 @@ namespace slskd.Network await completion; } + /// + /// Handles incoming share uploads. + /// + /// The name of the agent. + /// The ID obtained by the caller prior to uploading. + /// The list of shares provided. + /// The filename of the temporary file containing the upload. + /// The operation context. + public Task HandleShareUpload(string agentName, Guid id, IEnumerable shares, string filename) + { + var repository = ShareRepositoryFactory.CreateFromFile(filename); + + if (!repository.TryValidate(out var problems)) + { + throw new ShareValidationException("Invalid database: " + string.Join(", ", problems)); + } + + var destinationRepository = ShareRepositoryFactory.CreateFromHost(agentName); + + destinationRepository.RestoreFrom(repository); + + Shares.AddOrUpdateHost(new Host(agentName, shares)); + + return Task.CompletedTask; + } + /// /// Notifies the caller of of a failure to obtain a file stream from the requested agent. /// @@ -481,11 +560,12 @@ namespace slskd.Network /// /// Safely attempts to close a stream obtained with . /// + /// The name of the agent. /// The unique ID for the stream. /// If the transfer associated with the stream failed, the exception that caused the failure. - public void TryCloseFileStream(Guid id, Exception exception = default) + public void TryCloseFileStream(string agentName, Guid id, Exception exception = default) { - var key = new WaitKey(nameof(HandleFileStreamResponse), id); + var key = new WaitKey(nameof(HandleFileStreamResponse), agentName, id); if (exception != default) { -- cgit v1.2.3 From f953b2eb0764fbd256ddacad36c4a59c05097b05 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 Oct 2022 17:52:53 -0500 Subject: compute AES key from password --- src/slskd/Network/NetworkClient.cs | 13 ++++++------- src/slskd/Network/NetworkService.cs | 8 ++++---- 2 files changed, 10 insertions(+), 11 deletions(-) (limited to 'src/slskd/Network/NetworkService.cs') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 5d8ab100..1ffd2b1f 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -155,16 +155,18 @@ namespace slskd.Network Log.Information("Upload shares succeeded"); } - private string ComputeCredential(Guid token) + private string ComputeCredential(string token) { var options = OptionsMonitor.CurrentValue; - var key = options.Network.Controller.Secret.FromBase62(); - var tokenBytes = token.ToString().FromBase62(); + var key = Pbkdf2.GetKey(options.Network.Controller.Secret, options.InstanceName, 48); + var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token); return Aes.Encrypt(tokenBytes, key).ToBase62(); } + private string ComputeCredential(Guid token) => ComputeCredential(token.ToString()); + private Task HandleFileRequest(string filename, Guid token) { _ = Task.Run(async () => @@ -245,10 +247,7 @@ namespace slskd.Network 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(); + var response = ComputeCredential(challengeToken); Log.Debug("Logging in..."); var success = await HubConnection.InvokeAsync(nameof(NetworkHub.Login), agent, response); diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 5de2ecb3..6515d94d 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -628,8 +628,8 @@ namespace slskd.Network return false; } - var key = agentOptions.Secret.FromBase62(); - var tokenBytes = ((string)challengeToken).FromBase62(); + var key = Pbkdf2.GetKey(password: agentOptions.Secret, salt: agentName, length: 48); + var tokenBytes = System.Text.Encoding.UTF8.GetBytes((string)challengeToken); var expectedResponse = Aes.Encrypt(tokenBytes, key).ToBase62(); return expectedResponse == credential; @@ -694,8 +694,8 @@ namespace slskd.Network return false; } - var key = agentOptions.Secret.FromBase62(); - var tokenBytes = token.ToString().FromBase62(); + var key = Pbkdf2.GetKey(password: agentOptions.Secret, salt: agentName, length: 48); + var tokenBytes = System.Text.Encoding.UTF8.GetBytes(token); var expectedCredential = Aes.Encrypt(tokenBytes, key).ToBase62(); if (expectedCredential != credential) -- cgit v1.2.3