diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-30 12:40:00 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-10-30 12:40:00 -0500 |
| commit | 8624a5387b6db17141fa6bb7601b1490c1f95c30 (patch) | |
| tree | b2264599945ff634f25286c485ee2848db7287e8 /src | |
| parent | 915ed6aa255636cfd339e9b53b4da202a3799f98 (diff) | |
| parent | dbe3a9e82036a0db8049f3b884342dc98cc98d58 (diff) | |
| download | slskd-8624a5387b6db17141fa6bb7601b1490c1f95c30.tar.gz | |
Merge branch 'master' into secret-gen
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/CommonExtensions.cs | 16 | ||||
| -rw-r--r-- | src/slskd/Network/API/Controllers/NetworkController.cs | 122 | ||||
| -rw-r--r-- | src/slskd/Network/API/Hubs/NetworkHub.cs | 89 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkClient.cs | 65 | ||||
| -rw-r--r-- | src/slskd/Network/NetworkService.cs | 8 |
5 files changed, 221 insertions, 79 deletions
diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 561162d4..9cf80a4a 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -95,6 +95,22 @@ namespace slskd } /// <summary> + /// Safely disposes this object without throwing if it is already exposed. + /// </summary> + /// <param name="obj">The object.</param> + public static void TryDispose(this IDisposable obj) + { + try + { + obj?.Dispose(); + } + catch (ObjectDisposedException) + { + // no-op; something else beat us to it + } + } + + /// <summary> /// Recursively retrieves all properties. /// </summary> /// <param name="type">The type from which to retrieve properties.</param> diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 624d7a2c..276cdcd0 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -39,36 +39,29 @@ namespace slskd.Network public class NetworkController : ControllerBase { public NetworkController( - INetworkService networkService, - IShareService shareService, - IShareRepositoryFactory shareRepositoryFactory) + INetworkService networkService) { Network = networkService; - Shares = shareService; - - ShareRepositoryFactory = shareRepositoryFactory; } - private IShareRepositoryFactory ShareRepositoryFactory { get; } - private IShareService Shares { get; } - private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext<NetworkController>(); + private INetworkService Network { get; } - [HttpPost("files/{agentName}/{token}")] + /// <summary> + /// Uploads a file. + /// </summary> + /// <param name="token">The unique identifier for the request.</param> + /// <returns></returns> + [HttpPost("files/{token}")] [RequestSizeLimit(10L * 1024L * 1024L * 1024L)] [RequestFormLimits(MultipartBodyLengthLimit = 10L * 1024L * 1024L * 1024L)] [DisableFormValueModelBinding] [Authorize] - public async Task<IActionResult> UploadFile(string agentName, string token) + public async Task<IActionResult> UploadFile(string token) { if (!Guid.TryParse(token, out var guid)) { - return BadRequest("Token is not a valid Guid"); - } - - if (!Network.RegisteredAgents.Any(a => a.Name == agentName)) - { - return Unauthorized(); + return BadRequest("Token is not in a valid format"); } if (!Request.HasFormContentType @@ -78,8 +71,7 @@ namespace slskd.Network return new UnsupportedMediaTypeResult(); } - Log.Information("Handling file upload for token {Token} from a caller claiming to be agent {Agent}", token, agentName); - + string agentName = default; string credential = default; Stream stream = default; string filename = default; @@ -90,10 +82,14 @@ namespace slskd.Network { var reader = new MultipartReader(HeaderUtilities.RemoveQuotes(mediaTypeHeader.Boundary).Value, Request.Body); - // the multipart response contains two sections; a credential, and the file + // the multipart response contains two sections; the name of the agent, the upload credential, and the file + var agentNameSection = await reader.ReadNextSectionAsync(); + using var sra = new StreamReader(agentNameSection.Body); + agentName = sra.ReadToEnd(); + var credentialSection = await reader.ReadNextSectionAsync(); - using var sr = new StreamReader(credentialSection.Body); - credential = sr.ReadToEnd(); + using var src = new StreamReader(credentialSection.Body); + credential = src.ReadToEnd(); var fileSection = await reader.ReadNextSectionAsync(); var contentDisposition = ContentDispositionHeaderValue.Parse(fileSection.ContentDisposition); @@ -106,10 +102,17 @@ namespace slskd.Network return BadRequest(); } - // agents must encrypt the Id they were given in the request with the secret they share with the controller, and provide - // the encrypted value as the credential with the request. the validation below verifies a bunch of things, including that - // the encrypted value matches the expected value. the goal here is to ensure that the caller is the same caller that - // received the request, and that the caller knows the shared secret. + if (!Network.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 + // provide the encrypted value as the credential with the request. the validation below verifies a bunch of + // things, including that the encrypted value matches the expected value. the goal here is to ensure that the + // caller is the same caller that received the request, and that the caller knows the shared secret. if (!Network.TryValidateFileStreamResponseCredential(token: guid, agentName, filename, credential)) { Log.Warning("Failed to authenticate file upload token {Token} from a caller claiming to be agent {Agent}", agentName); @@ -118,9 +121,8 @@ namespace slskd.Network Log.Information("File upload of {Filename} ({Token}) from agent {Agent} validated and authenticated. Forwarding file stream.", filename, token, agentName); - // pass the stream back to the network service, which will in turn pass it to the - // upload service, and use it to feed data into the remote upload. await this call, - // it will complete when the upload is complete, one way or the other. + // pass the stream back to the network service, which will in turn pass it to the upload service, and use it to + // feed data into the remote upload. await this call, it will complete when the upload is complete, one way or the other. await Network.HandleFileStreamResponse(agentName, id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); @@ -128,25 +130,39 @@ namespace slskd.Network } finally { - stream?.Dispose(); + stream?.TryDispose(); } } - [HttpPost("shares/{agentName}/{token}")] + /// <summary> + /// Uploads share information. + /// </summary> + /// <param name="token">The unique identifier for the request.</param> + /// <returns></returns> + [HttpPost("shares/{token}")] [Authorize] - public async Task<IActionResult> UploadShares(string agentName, string token) + public async Task<IActionResult> UploadShares(string token) { if (!Guid.TryParse(token, out var guid)) { return BadRequest("Token is not a valid Guid"); } - string credential; + if (!Request.HasFormContentType + || !MediaTypeHeaderValue.TryParse(Request.ContentType, out var mediaTypeHeader) + || string.IsNullOrEmpty(mediaTypeHeader.Boundary.Value)) + { + return new UnsupportedMediaTypeResult(); + } + + string agentName = default; + string credential = default; IEnumerable<Share> shares; IFormFile database; try { + agentName = Request.Form["name"].ToString(); credential = Request.Form["credential"].ToString(); shares = Request.Form["shares"].ToString().FromJson<IEnumerable<Share>>(); database = Request.Form.Files[0]; @@ -157,6 +173,11 @@ namespace slskd.Network return BadRequest(); } + if (!Network.RegisteredAgents.Any(a => a.Name == agentName)) + { + return Unauthorized(); + } + if (!Network.TryValidateShareUploadCredential(token: guid, agentName, credential)) { Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent}"); @@ -164,26 +185,41 @@ namespace slskd.Network } var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agentName}_{Path.GetRandomFileName()}.db"); + Stream outputStream = default; - Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp); + try + { + Log.Debug("Uploading share from {Agent} to {Filename}", agentName, temp); - using var outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); - using var inputStream = database.OpenReadStream(); + outputStream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write); + using var inputStream = database.OpenReadStream(); - await inputStream.CopyToAsync(outputStream); + await inputStream.CopyToAsync(outputStream); - Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); + await outputStream.FlushAsync(); + + Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); - try - { await Network.HandleShareUpload(agentName, id: guid, shares, temp); + + return Ok(); } catch (ShareValidationException ex) { return BadRequest(ex.Message); } - - return Ok(); + finally + { + try + { + outputStream?.TryDispose(); + System.IO.File.Delete(temp); + } + catch (Exception ex) + { + Log.Debug(ex, "Failed to remove temporary share upload file: {Message}", ex.Message); + } + } } } -} +}
\ No newline at end of file diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 0ee80f9a..cf29f15f 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -24,11 +24,33 @@ namespace slskd.Network using Microsoft.AspNetCore.SignalR; using Serilog; + /// <summary> + /// Methods for the <see cref="NetworkHub"/>. + /// </summary> public interface INetworkHub { + /// <summary> + /// Sends an authentication challenge token to the newly connected agent. + /// </summary> + /// <param name="token">The token.</param> + /// <returns>The operation context.</returns> Task Challenge(string token); - Task RequestFile(string filename, Guid id); + + /// <summary> + /// Requests information about the specified <paramref name="filename"/> from the agent. + /// </summary> + /// <param name="filename">The name of the file.</param> + /// <param name="id">The unique identifier for the request.</param> + /// <returns>The operation context.</returns> Task RequestFileInfo(string filename, Guid id); + + /// <summary> + /// Requests the specified <paramref name="filename"/> from the agent. + /// </summary> + /// <param name="filename">The name of the file.</param> + /// <param name="id">The unique identifier for the request.</param> + /// <returns>The operation context.</returns> + Task RequestFileUpload(string filename, Guid id); } /// <summary> @@ -37,15 +59,23 @@ namespace slskd.Network [Authorize] public class NetworkHub : Hub<INetworkHub> { + /// <summary> + /// Initializes a new instance of the <see cref="NetworkHub"/> class. + /// </summary> + /// <param name="networkService"></param> public NetworkHub( INetworkService networkService) { Network = networkService; } - private INetworkService Network { get; } private ILogger Log { get; } = Serilog.Log.ForContext<NetworkService>(); + private INetworkService Network { get; } + /// <summary> + /// Executed when a new connection is established. + /// </summary> + /// <returns></returns> public override async Task OnConnectedAsync() { var token = Network.GenerateAuthenticationChallengeToken(Context.ConnectionId); @@ -54,6 +84,11 @@ namespace slskd.Network await Clients.Caller.Challenge(token); } + /// <summary> + /// Executed when a connection is disconnected. + /// </summary> + /// <param name="exception">The Exception that caused the disconnect.</param> + /// <returns></returns> public override Task OnDisconnectedAsync(Exception exception) { if (Network.TryDeregisterAgent(Context.ConnectionId, out var record)) @@ -64,25 +99,34 @@ namespace slskd.Network return Task.CompletedTask; } - public bool Login(string agent, string challengeResponse) + /// <summary> + /// Executed by the agent after receipt of an authentication challenge token, shortly after the connection is established. + /// </summary> + /// <param name="agent">The agent's name.</param> + /// <param name="challengeResponse">The response to the challenge token.</param> + /// <exception cref="UnauthorizedAccessException">Thrown when the challenge response is invalid.</exception> + public void Login(string agent, string challengeResponse) { - if (Network.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) + if (!Network.TryValidateAuthenticationCredential(Context.ConnectionId, agent, challengeResponse)) { - var remoteIp = Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString(); - var record = new Agent { Name = agent, ConnectedAt = DateTime.UtcNow, IPAddress = remoteIp }; - - Log.Information("Agent connection {Id} ({IP}) authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); - Network.RegisterAgent(Context.ConnectionId, record); - return true; + Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); + Network.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! + throw new UnauthorizedAccessException(); } - Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); - Network.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! - return false; - // todo: throw UnauthorizedAccessException()? + var remoteIp = Context.Features.Get<IHttpConnectionFeature>().RemoteIpAddress.ToString(); + var record = new Agent { Name = agent, ConnectedAt = DateTime.UtcNow, IPAddress = remoteIp }; + + Log.Information("Agent connection {Id} ({IP}) authenticated as agent {Agent}", Context.ConnectionId, remoteIp, agent); + Network.RegisterAgent(Context.ConnectionId, record); } - public Guid GetShareUploadToken() + /// <summary> + /// Initiates the share upload workflow by generating and retrieving a request token. + /// </summary> + /// <returns>The generated token.</returns> + /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> + public Guid BeginShareUpload() { if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) { @@ -96,7 +140,13 @@ namespace slskd.Network throw new UnauthorizedAccessException(); } - public void NotifyUploadFailed(Guid id, Exception exception) + /// <summary> + /// Notifies the controller that the agent was unable to upload the file requested by a call to <see cref="INetworkHub.RequestFileUpload"/>. + /// </summary> + /// <param name="id">The unique identifier of the request.</param> + /// <param name="exception">The Exception that caused the failure.</param> + /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> + public void NotifyFileUploadFailed(Guid id, Exception exception) { if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) { @@ -107,6 +157,13 @@ namespace slskd.Network throw new UnauthorizedAccessException(); } + /// <summary> + /// Returns the response to a call to <see cref="INetworkHub.RequestFileInfo"/>. + /// </summary> + /// <param name="id">The unique identifier for the request.</param> + /// <param name="exists">A value indicating whether the requested file exists on the agent's filesystem.</param> + /// <param name="length">The length of the file, or 0 if the file does not exist.</param> + /// <exception cref="UnauthorizedAccessException">Thrown when the agent is not fully authenticated.</exception> public void ReturnFileInfo(Guid id, bool exists, long length) { if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 49f483fc..e0aec505 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -29,14 +29,37 @@ namespace slskd.Network using slskd.Cryptography; using slskd.Shares; + /// <summary> + /// Network client (agent). + /// </summary> public interface INetworkClient { + /// <summary> + /// Starts the client and connects to the controller. + /// </summary> + /// <param name="cancellationToken"></param> + /// <returns></returns> Task StartAsync(CancellationToken cancellationToken = default); + + /// <summary> + /// Stops the client and disconnects from the controller. + /// </summary> + /// <param name="cancellationToken"></param> + /// <returns></returns> Task StopAsync(CancellationToken cancellationToken = default); } + /// <summary> + /// Network client (agent). + /// </summary> public class NetworkClient : INetworkClient { + /// <summary> + /// Initializes a new instance of the <see cref="NetworkClient"/> class. + /// </summary> + /// <param name="shareService"></param> + /// <param name="optionsMonitor"></param> + /// <param name="httpClientFactory"></param> public NetworkClient( IShareService shareService, IOptionsMonitor<Options> optionsMonitor, @@ -63,6 +86,11 @@ namespace slskd.Network private ILogger Log { get; } = Serilog.Log.ForContext<NetworkClient>(); private TaskCompletionSource LoggedIn { get; set; } + /// <summary> + /// Starts the client and connects to the controller. + /// </summary> + /// <param name="cancellationToken"></param> + /// <returns></returns> public async Task StartAsync(CancellationToken cancellationToken = default) { if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum<OperationMode>() != OperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) @@ -106,6 +134,11 @@ namespace slskd.Network Log.Information("Shares uploaded. Ready to upload files."); } + /// <summary> + /// Stops the client and disconnects from the controller. + /// </summary> + /// <param name="cancellationToken"></param> + /// <returns></returns> public async Task StopAsync(CancellationToken cancellationToken = default) { StartRequested = false; @@ -129,14 +162,15 @@ namespace slskd.Network Log.Debug("Share backup successful"); Log.Debug("Requesting share upload token..."); - var token = await HubConnection.InvokeAsync<Guid>(nameof(NetworkHub.GetShareUploadToken)); + var token = await HubConnection.InvokeAsync<Guid>(nameof(NetworkHub.BeginShareUpload)); Log.Debug("Share upload token {Token}", token); var stream = new FileStream(temp, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/shares/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, { new StringContent(ComputeCredential(token)), "credential" }, { new StringContent(Shares.LocalHost.Shares.ToJson()), "shares" }, { new StreamContent(stream), "database", "shares" }, @@ -167,7 +201,7 @@ namespace slskd.Network private string ComputeCredential(Guid token) => ComputeCredential(token.ToString()); - private Task HandleFileRequest(string filename, Guid token) + private Task HandleFileUploadRequest(string filename, Guid token) { _ = Task.Run(async () => { @@ -186,9 +220,10 @@ namespace slskd.Network } using var stream = new FileStream(localFileInfo.FullName, FileMode.Open, FileAccess.Read); - using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{OptionsMonitor.CurrentValue.InstanceName}/{token}"); + using var request = new HttpRequestMessage(HttpMethod.Post, $"api/v0/network/files/{token}"); using var content = new MultipartFormDataContent { + { new StringContent(OptionsMonitor.CurrentValue.InstanceName), "name" }, { new StringContent(ComputeCredential(token)), "credential" }, { new StreamContent(stream), "file", filename }, }; @@ -212,7 +247,7 @@ namespace slskd.Network Log.Error(ex, "Failed to handle file request: {Message}", ex.Message); // report the failure to the controller. this avoids a failure due to timeout. - await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyUploadFailed), token); + await HubConnection.InvokeAsync(nameof(NetworkHub.NotifyFileUploadFailed), token); } }); @@ -240,27 +275,25 @@ namespace slskd.Network private async Task HandleAuthenticationChallenge(string challengeToken) { - Log.Debug("Network controller sent an authentication challenge"); - try { + Log.Debug("Network controller sent an authentication challenge"); + var options = OptionsMonitor.CurrentValue; var agent = options.InstanceName; var response = ComputeCredential(challengeToken); Log.Debug("Logging in..."); - var success = await HubConnection.InvokeAsync<bool>(nameof(NetworkHub.Login), agent, response); - - if (!success) - { - await HubConnection.StopAsync(); - Log.Error("Network controller authentication failed. Check configuration."); - } - + await HubConnection.InvokeAsync(nameof(NetworkHub.Login), agent, response); Log.Debug("Login succeeded."); LoggedIn?.TrySetResult(); } + catch (UnauthorizedAccessException) + { + await HubConnection.StopAsync(); + Log.Error("Network controller authentication failed. Check configuration."); + } catch (Exception ex) { Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); @@ -334,7 +367,7 @@ namespace slskd.Network HubConnection.Reconnecting += HubConnection_Reconnecting; HubConnection.Closed += HubConnection_Closed; - HubConnection.On<string, Guid>(nameof(INetworkHub.RequestFile), HandleFileRequest); + HubConnection.On<string, Guid>(nameof(INetworkHub.RequestFileUpload), HandleFileUploadRequest); HubConnection.On<string, Guid>(nameof(INetworkHub.RequestFileInfo), HandleFileInfoRequest); HubConnection.On<string>(nameof(INetworkHub.Challenge), HandleAuthenticationChallenge); diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs index 7dbd79cd..44628e1b 100644 --- a/src/slskd/Network/NetworkService.cs +++ b/src/slskd/Network/NetworkService.cs @@ -54,13 +54,12 @@ namespace slskd.Network /// <summary> /// Retrieves a new share upload token for the specified <paramref name="agentName"/>. /// </summary> - /// <remarks>The token is cached internally, and is only valid while it remains in the cache.</remarks> /// <remarks> /// <para>This is the first step in a multi-step workflow. The entire sequence is:</para> /// <list type="number"> /// <item> /// A remote agent makes a request to the SignalR hub to retrieve a share upload token, which in turn - /// calls <see cref="GenerateShareUploadToken"/>. The token is generated and cached. + /// calls <see cref="GenerateShareUploadToken"/>. The token is generated and cached, and is only valid while it is in the cache. /// </item> /// <item> /// The remote agent makes an HTTP POST request containing a multipart upload including a backup of its @@ -313,7 +312,8 @@ namespace slskd.Network { var token = Guid.NewGuid(); - MemoryCache.Set(GetShareTokenCacheKey(token), agentName, TimeSpan.FromMinutes(1)); + // allow a generous amount of time, in case it takes a while to upload the response + MemoryCache.Set(GetShareTokenCacheKey(token), agentName, TimeSpan.FromMinutes(5)); Log.Debug("Cached share upload token {Token} for agent {Agent}", token, agentName); return token; @@ -427,7 +427,7 @@ namespace slskd.Network var key = new WaitKey(nameof(GetFileStreamAsync), agentName, id); var wait = Waiter.Wait<Stream>(key, timeout, cancellationToken); - await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id); + await NetworkHub.Clients.Client(record.ConnectionId).RequestFileUpload(filename, id); Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, id); var task = await Task.WhenAny(wait, Task.Delay(timeout, cancellationToken)); |
