From 012e433ef67ea9eb35a112cfeb5523e2ffc289e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 27 Oct 2022 16:57:22 -0500 Subject: add ShareValidationException --- .../Common/Exceptions/ShareValidationException.cs | 72 ++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/slskd/Common/Exceptions/ShareValidationException.cs (limited to 'src') diff --git a/src/slskd/Common/Exceptions/ShareValidationException.cs b/src/slskd/Common/Exceptions/ShareValidationException.cs new file mode 100644 index 00000000..97a3e126 --- /dev/null +++ b/src/slskd/Common/Exceptions/ShareValidationException.cs @@ -0,0 +1,72 @@ +// +// 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/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents an error that occurs when multiple share scans are attempted concurrently. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class ShareValidationException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public ShareValidationException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ShareValidationException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public ShareValidationException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected ShareValidationException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file -- cgit v1.2.3 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 --- .../Network/API/Controllers/NetworkController.cs | 18 ++-- src/slskd/Network/API/Hubs/NetworkHub.cs | 17 +++- src/slskd/Network/NetworkService.cs | 106 ++++++++++++++++++--- src/slskd/Transfers/Uploads/UploadService.cs | 6 +- 4 files changed, 118 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 4cd6437a..624d7a2c 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -121,7 +121,7 @@ namespace slskd.Network // 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(id: guid, stream); + await Network.HandleFileStreamResponse(agentName, id: guid, stream); Log.Information("File upload of {Filename} ({Token}) from agent {Agent} complete", filename, token, agentName); return Ok(); @@ -174,18 +174,14 @@ namespace slskd.Network Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp); - var repository = ShareRepositoryFactory.CreateFromFile(temp); - - if (!repository.TryValidate(out var problems)) + try { - return BadRequest("Invalid database: " + string.Join(", ", problems)); + await Network.HandleShareUpload(agentName, id: guid, shares, temp); + } + catch (ShareValidationException ex) + { + return BadRequest(ex.Message); } - - var destinationRepository = ShareRepositoryFactory.CreateFromHost(agentName); - - destinationRepository.RestoreFrom(repository); - - Shares.AddOrUpdateHost(new Host(agentName, shares)); return Ok(); } diff --git a/src/slskd/Network/API/Hubs/NetworkHub.cs b/src/slskd/Network/API/Hubs/NetworkHub.cs index 298dd9ec..0ee80f9a 100644 --- a/src/slskd/Network/API/Hubs/NetworkHub.cs +++ b/src/slskd/Network/API/Hubs/NetworkHub.cs @@ -79,6 +79,7 @@ namespace slskd.Network Log.Information("Agent connection {Id} authentication failed", Context.ConnectionId); Network.TryDeregisterAgent(Context.ConnectionId, out var _); // just in case! return false; + // todo: throw UnauthorizedAccessException()? } public Guid GetShareUploadToken() @@ -97,12 +98,24 @@ namespace slskd.Network public void NotifyUploadFailed(Guid id, Exception exception) { - Network.NotifyFileStreamException(id, exception); + if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) + { + Network.NotifyFileStreamException(id, exception); + } + + Log.Warning("Agent connection {Id} attempted to report a failed upload, but is not registered.", Context.ConnectionId); + throw new UnauthorizedAccessException(); } public void ReturnFileInfo(Guid id, bool exists, long length) { - Network.HandleFileInfoResponse(id, (exists, length)); + if (Network.TryGetAgentRegistration(Context.ConnectionId, out var record)) + { + Network.HandleFileInfoResponse(record.Agent.Name, id, (exists, length)); + } + + Log.Warning("Agent connection {Id} attempted to return file information, but is not registered.", Context.ConnectionId); + throw new UnauthorizedAccessException(); } } } \ No newline at end of file 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) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 3dd80292..8cc6ee45 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -273,7 +273,7 @@ namespace slskd.Transfers.Uploads options: topts, cancellationToken: cts.Token); - Network.TryCloseFileStream(id); + Network.TryCloseFileStream(host, id); transfer = transfer.WithSoulseekTransfer(completedTransfer); } @@ -294,7 +294,7 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); - Network.TryCloseFileStream(id, ex); + Network.TryCloseFileStream(host, id, ex); throw; } @@ -309,7 +309,7 @@ namespace slskd.Transfers.Uploads // todo: broadcast SynchronizedUpdate(transfer, cancellable: false); - Network.TryCloseFileStream(id, ex); + Network.TryCloseFileStream(host, id, ex); throw; } finally -- cgit v1.2.3 From 845937dede800928f380285dad47a4c48f0ea731 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 Oct 2022 09:11:02 -0500 Subject: redact dictionaries --- src/slskd/Common/Redactor.cs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/Redactor.cs b/src/slskd/Common/Redactor.cs index b2069b12..e819a6a8 100644 --- a/src/slskd/Common/Redactor.cs +++ b/src/slskd/Common/Redactor.cs @@ -59,7 +59,14 @@ namespace slskd } else { - if (value.GetType().IsAssignableTo(typeof(IEnumerable))) + if (value.IsDictionary()) + { + foreach (string key in ((IDictionary)value).Keys) + { + Redact(((IDictionary)value)[key]); + } + } + else if (value.GetType().IsAssignableTo(typeof(IEnumerable))) { foreach (var element in (IEnumerable)value) { -- cgit v1.2.3 From 192db033cb76f129e9c71a1d82e0e71a291ad001 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 Oct 2022 09:11:39 -0500 Subject: allow PBKDF2 keys to have variable length --- src/slskd/Common/Cryptography/Pbkdf2.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Cryptography/Pbkdf2.cs b/src/slskd/Common/Cryptography/Pbkdf2.cs index 3c3246d6..eea5c966 100644 --- a/src/slskd/Common/Cryptography/Pbkdf2.cs +++ b/src/slskd/Common/Cryptography/Pbkdf2.cs @@ -29,15 +29,16 @@ namespace slskd.Cryptography /// Gets a 256 bit (32 byte) key derived from the specified using PBKDF2/RFC 2898. /// /// The password from which to derive the key. + /// The desired length of the key, in bytes. /// The derived key. - public static byte[] GetKey(string password) + public static byte[] GetKey(string password, int length = 32) { byte[] salt = new byte[16]; int iterations = 1000; using var rng = RandomNumberGenerator.Create(); rng.GetBytes(salt); - return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32); + return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, length); } } } -- cgit v1.2.3 From 923627328c8e40a97f0d66be7c7d5dbaba949e6e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 Oct 2022 09:36:37 -0500 Subject: add UrlAttribute --- src/slskd/Common/Validation/UrlAttribute.cs | 38 +++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/slskd/Common/Validation/UrlAttribute.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/UrlAttribute.cs b/src/slskd/Common/Validation/UrlAttribute.cs new file mode 100644 index 00000000..9c980c9b --- /dev/null +++ b/src/slskd/Common/Validation/UrlAttribute.cs @@ -0,0 +1,38 @@ +// +// 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/. +// + +namespace slskd.Common.Validation +{ + using System; + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the value is a valid URL. + /// + public class UrlAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (!Uri.TryCreate((string)value, default(UriCreationOptions), out _)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must contain a valid URL"); + } + + return ValidationResult.Success; + } + } +} -- cgit v1.2.3 From 2fd9253cedb5cbb871783f30921232e500aa6459 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 Oct 2022 17:48:30 -0500 Subject: add variable length key gen --- src/slskd/Common/Cryptography/Pbkdf2.cs | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Cryptography/Pbkdf2.cs b/src/slskd/Common/Cryptography/Pbkdf2.cs index eea5c966..15b4a7ed 100644 --- a/src/slskd/Common/Cryptography/Pbkdf2.cs +++ b/src/slskd/Common/Cryptography/Pbkdf2.cs @@ -18,6 +18,7 @@ namespace slskd.Cryptography { using System.Security.Cryptography; + using System.Text; using Microsoft.AspNetCore.Cryptography.KeyDerivation; /// @@ -29,16 +30,29 @@ namespace slskd.Cryptography /// Gets a 256 bit (32 byte) key derived from the specified using PBKDF2/RFC 2898. /// /// The password from which to derive the key. - /// The desired length of the key, in bytes. /// The derived key. - public static byte[] GetKey(string password, int length = 32) + public static byte[] GetKey(string password) { byte[] salt = new byte[16]; int iterations = 1000; using var rng = RandomNumberGenerator.Create(); rng.GetBytes(salt); - return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, length); + return KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, iterations, 32); + } + + /// + /// Gets a variable key derived from the specified and using PBKDF2/RFC 2898. + /// + /// The password from which to derive the key. + /// The value with which to salt the key. + /// The desired length of the key, in bytes. + /// The derived key. + public static byte[] GetKey(string password, string salt, int length) + { + int iterations = 1000; + + return KeyDerivation.Pbkdf2(password, Encoding.UTF8.GetBytes(salt), KeyDerivationPrf.HMACSHA256, iterations, length); } } } -- cgit v1.2.3 From 319239c034ae240f092f0c70ea177ed361f4bbbf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 Oct 2022 17:48:53 -0500 Subject: relax key length requirements, mark address as url --- src/slskd/Core/Options.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index b75f9356..6b0d2aa1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -429,6 +429,7 @@ namespace slskd /// [Argument(default, "controller-address")] [EnvironmentVariable("CONTROLLER_ADDRESS")] + [Url] public string Address { get; init; } /// @@ -436,7 +437,7 @@ namespace slskd /// [Argument(default, "controller-secret")] [EnvironmentVariable("CONTROLLER_SECRET")] - [StringLength(48, MinimumLength = 48)] + [StringLength(255, MinimumLength = 16)] [Secret] public string Secret { get; init; } } @@ -449,7 +450,7 @@ namespace slskd /// /// Gets the agent secret. /// - [StringLength(48, MinimumLength = 48)] + [StringLength(255, MinimumLength = 16)] [Secret] public string Secret { get; init; } } -- cgit v1.2.3 From 97e592c3b477edf74931d1e5ce3f9dde5ac6d214 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 28 Oct 2022 17:52:01 -0500 Subject: validate url, relax secret length --- src/slskd/Core/Options.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6b0d2aa1..af46f23c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -391,6 +391,7 @@ namespace slskd /// /// Gets the controller configuration. /// + [Validate] public NetworkControllerConfigurationOptions Controller { get; init; } = new NetworkControllerConfigurationOptions(); /// -- 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') 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