aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jpdillingham@gmail.com>2022-10-22 12:17:17 -0500
committerJP Dillingham <jpdillingham@gmail.com>2022-10-22 12:17:17 -0500
commit4196d2224a4024a26b9bfbf946197360aeab707b (patch)
tree4e24a571e3eb2dc5e71850dc06d5f06c3b0e6e69 /src
parent1d927e49a93ad24ba6dbc91f30f185212775ff30 (diff)
downloadslskd-4196d2224a4024a26b9bfbf946197360aeab707b.tar.gz
validate credentials for rest calls
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Network/API/Controllers/NetworkController.cs61
-rw-r--r--src/slskd/Network/NetworkService.cs101
2 files changed, 122 insertions, 40 deletions
diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs
index d2170d45..656178f0 100644
--- a/src/slskd/Network/API/Controllers/NetworkController.cs
+++ b/src/slskd/Network/API/Controllers/NetworkController.cs
@@ -52,13 +52,33 @@ namespace slskd.Network
private INetworkService Network { get; }
private ILogger Log { get; } = Serilog.Log.ForContext<NetworkController>();
- [HttpPost("files/{id}")]
+ [HttpPost("files/{agentName}/{token}")]
[Authorize]
- public async Task<IActionResult> UploadFile(string id)
+ public async Task<IActionResult> UploadFile(string agentName, string token)
{
- if (!Guid.TryParse(id, out var guid))
+ if (!Guid.TryParse(token, out var guid))
{
- return BadRequest("Id is not a valid Guid");
+ return BadRequest("Token is not a valid Guid");
+ }
+
+ string credential;
+ IFormFile file;
+
+ try
+ {
+ credential = Request.Form["credential"].ToString();
+ file = Request.Form.Files[0];
+ }
+ catch (Exception ex)
+ {
+ Log.Warning("Failed to handle file upload from agent {Agent}: {Message}", agentName, ex.Message);
+ return BadRequest();
+ }
+
+ if (!Network.TryValidateFileUploadCredential(token: guid, agentName, credential))
+ {
+ Log.Warning("Failed to authenticate file upload from caller claiming to be agent {Agent}", agentName);
+ return Unauthorized();
}
// get the record for the waiting file
@@ -88,44 +108,47 @@ namespace slskd.Network
}
}
- [HttpPost("shares/{id}")]
+ [HttpPost("shares/{agentName}/{token}")]
[Authorize]
- public async Task<IActionResult> UploadShares(string id)
+ public async Task<IActionResult> UploadShares(string agentName, string token)
{
- if (!Guid.TryParse(id, out var guid))
- {
- return BadRequest("Id is not a valid Guid");
- }
-
- if (!Network.TryValidateShareUploadToken(guid, out var agent))
+ if (!Guid.TryParse(token, out var guid))
{
- return Unauthorized();
+ return BadRequest("Token is not a valid Guid");
}
+ string credential;
IEnumerable<Share> shares;
IFormFile database;
try
{
+ credential = Request.Form["credential"].ToString();
shares = Request.Form["shares"].ToString().FromJson<IEnumerable<Share>>();
database = Request.Form.Files[0];
}
catch (Exception ex)
{
- Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agent, ex.Message);
+ Log.Warning("Failed to handle share upload from agent {Agent}: {Message}", agentName, ex.Message);
return BadRequest();
}
- var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agent}_{Path.GetRandomFileName()}.db");
+ if (!Network.TryValidateShareUploadCredential(token: guid, agentName, credential))
+ {
+ Log.Warning("Failed to authenticate share upload from caller claiming to be agent {Agent}");
+ return Unauthorized();
+ }
+
+ var temp = Path.Combine(Path.GetTempPath(), $"slskd_share_{agentName}_{Path.GetRandomFileName()}.db");
- Log.Debug("Uploading share from {Agent} to {Filename}", agent, temp);
+ 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();
await inputStream.CopyToAsync(outputStream);
- Log.Debug("Upload of share from {Agent} to {Filename} complete", agent, temp);
+ Log.Debug("Upload of share from {Agent} to {Filename} complete", agentName, temp);
var repository = ShareRepositoryFactory.CreateFromFile(temp);
@@ -134,11 +157,11 @@ namespace slskd.Network
return BadRequest("Invalid database: " + string.Join(", ", problems));
}
- var destinationRepository = ShareRepositoryFactory.CreateFromHost(agent);
+ var destinationRepository = ShareRepositoryFactory.CreateFromHost(agentName);
destinationRepository.RestoreFrom(repository);
- Shares.AddOrUpdateHost(new Host(agent, shares));
+ Shares.AddOrUpdateHost(new Host(agentName, shares));
return Ok();
}
diff --git a/src/slskd/Network/NetworkService.cs b/src/slskd/Network/NetworkService.cs
index 8f25da5d..738ea7a5 100644
--- a/src/slskd/Network/NetworkService.cs
+++ b/src/slskd/Network/NetworkService.cs
@@ -117,12 +117,22 @@ namespace slskd.Network
bool TryValidateAuthenticationChallengeResponse(string connectionId, string agentName, string challengeResponse);
/// <summary>
- /// Attempts to retrieve the specified share upload <paramref name="token"/>.
+ /// Attempts to validate the share upload response credential associated with the specified <paramref name="token"/>.
/// </summary>
/// <param name="token">The token.</param>
- /// <param name="agentName">The name of the agent associated with the token.</param>
- /// <returns>A value indicating whether the specified token exists.</returns>
- bool TryValidateShareUploadToken(Guid token, out string agentName);
+ /// <param name="agentName">The name of the responding agent.</param>
+ /// <param name="credential">The response credential.</param>
+ /// <returns>A value indicating whether the credential is valid.</returns>
+ bool TryValidateShareUploadCredential(Guid token, string agentName, string credential);
+
+ /// <summary>
+ /// Attempts to validate the file upload response credential associated with the specified <paramref name="token"/>.
+ /// </summary>
+ /// <param name="token">The token.</param>
+ /// <param name="agentName">The name of the responding agent.</param>
+ /// <param name="credential">The response credential.</param>
+ /// <returns>A value indicating whether the credential is valid.</returns>
+ bool TryValidateFileUploadCredential(Guid token, string agentName, string credential);
}
public class NetworkService : INetworkService
@@ -250,7 +260,17 @@ namespace slskd.Network
/// <returns>The operation context, including a stream containing the requested file, and an upload TaskCompletionSource.</returns>
public async Task<(Stream Stream, TaskCompletionSource Completion)> GetFile(string agentName, string filename, int timeout = 3000)
{
- var id = Guid.NewGuid();
+ if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record))
+ {
+ throw new NotFoundException($"Agent {agentName} is not registered");
+ }
+
+ var token = Guid.NewGuid();
+ var key = new WaitKey(nameof(GetFile), agentName, token);
+ var wait = Waiter.Wait(key, timeout);
+
+ MemoryCache.Set(GetFileTokenCacheKey(token), agentName, TimeSpan.FromMinutes(1));
+ Log.Debug("Cached file upload token {Token} for agent {Agent}", token, agentName);
// create a TCS for the upload stream. this is awaited below and completed in the API controller when the agent POSTs
// the file
@@ -261,17 +281,12 @@ namespace slskd.Network
// complete in order to keep the stream open for the duration
var completion = new TaskCompletionSource();
- if (!RegisteredAgentDictionary.TryGetValue(agentName, out var record))
- {
- throw new NotFoundException($"Agent {agentName} is not registered");
- }
-
- PendingFileUploadDictionary.TryAdd(id, (upload, completion));
+ PendingFileUploadDictionary.TryAdd(token, (upload, completion));
try
{
- await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, id);
- Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, id);
+ await NetworkHub.Clients.Client(record.ConnectionId).RequestFile(filename, token);
+ Log.Information("Requested file {Filename} from Agent {Agent} with ID {Id}. Waiting for incoming connection.", filename, agentName, token);
var task = await Task.WhenAny(upload.Task, Task.Delay(timeout));
@@ -287,10 +302,24 @@ namespace slskd.Network
}
finally
{
- PendingFileUploadDictionary.TryRemove(id, out _);
+ PendingFileUploadDictionary.TryRemove(token, out _);
}
}
+ public void HandleGetFileResponse(string agentName, Guid id, Stream response)
+ {
+ var key = new WaitKey(nameof(GetFile), agentName, id);
+
+ if (!Waiter.ContainsKey(key))
+ {
+ Log.Warning("Agent {Agent} responded to a file request with Id {Id}, but a response was not expected", agentName, id);
+ return;
+ }
+
+ Waiter.Complete(key, response);
+ Log.Information("Agent {Agent} responded to a file request with Id {Id}", agentName, id);
+ }
+
/// <summary>
/// Registers the specified <paramref name="agent"/> name with the specified <paramref name="connectionId"/>.
/// </summary>
@@ -359,23 +388,53 @@ namespace slskd.Network
}
/// <summary>
- /// Attempts to retrieve the specified share upload <paramref name="token"/>.
+ /// Attempts to validate the share upload response credential associated with the specified <paramref name="token"/>.
/// </summary>
/// <param name="token">The token.</param>
- /// <param name="agentName">The name of the agent associated with the token.</param>
- /// <returns>A value indicating whether the specified token exists.</returns>
- public bool TryValidateShareUploadToken(Guid token, out string agentName)
+ /// <param name="agentName">The name of the responding agent.</param>
+ /// <param name="credential">The response credential.</param>
+ /// <returns>A value indicating whether the credential is valid.</returns>
+ public bool TryValidateShareUploadCredential(Guid token, string agentName, string credential)
{
- if (MemoryCache.TryGetValue(GetShareTokenCacheKey(token), out agentName))
+ return TryValidateCredential(token.ToString(), agentName, credential, GetFileTokenCacheKey(token));
+ }
+
+ /// <summary>
+ /// Attempts to validate the file upload response credential associated with the specified <paramref name="token"/>.
+ /// </summary>
+ /// <param name="token">The token.</param>
+ /// <param name="agentName">The name of the responding agent.</param>
+ /// <param name="credential">The response credential.</param>
+ /// <returns>A value indicating whether the credential is valid.</returns>
+ public bool TryValidateFileUploadCredential(Guid token, string agentName, string credential)
+ {
+ return TryValidateCredential(token.ToString(), agentName, credential, GetShareTokenCacheKey(token));
+ }
+
+ private bool TryValidateCredential(string token, string agentName, string credential, string cacheKey)
+ {
+ bool valid = false;
+
+ if (OptionsMonitor.CurrentValue.Network.Agents.TryGetValue(agentName, out var agentOptions)
+ && RegisteredAgentDictionary.TryGetValue(agentName, out _)
+ && MemoryCache.TryGetValue(cacheKey, out var cachedAgentName)
+ && (string)cachedAgentName == agentName)
{
- return true;
+ var key = agentOptions.Secret.FromBase62();
+ var tokenBytes = token.ToString().FromBase62();
+ var expectedCredential = Aes.Encrypt(tokenBytes, key).ToBase62();
+
+ valid = expectedCredential == credential;
}
- return false;
+ // tokens can be used exactly once, pass or fail
+ MemoryCache.Remove(cacheKey);
+ return valid;
}
private string GetAuthTokenCacheKey(string connectionId) => $"{connectionId}.auth";
private string GetShareTokenCacheKey(Guid token) => $"{token}.share";
+ private string GetFileTokenCacheKey(Guid token) => $"{token}.file";
}
} \ No newline at end of file