aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Core
diff options
context:
space:
mode:
Diffstat (limited to 'src/slskd/Core')
-rw-r--r--src/slskd/Core/API/Controllers/OptionsController.cs3
-rw-r--r--src/slskd/Core/API/Controllers/ServerController.cs1
-rw-r--r--src/slskd/Core/API/Controllers/SessionController.cs27
-rw-r--r--src/slskd/Core/API/Hubs/LogsHub.cs2
-rw-r--r--src/slskd/Core/Blacklist.cs13
-rw-r--r--src/slskd/Core/Data/Migrator.cs2
-rw-r--r--src/slskd/Core/Options.cs14
-rw-r--r--src/slskd/Core/Security/SecurityService.cs7
8 files changed, 56 insertions, 13 deletions
diff --git a/src/slskd/Core/API/Controllers/OptionsController.cs b/src/slskd/Core/API/Controllers/OptionsController.cs
index e20017a8..e8769ca9 100644
--- a/src/slskd/Core/API/Controllers/OptionsController.cs
+++ b/src/slskd/Core/API/Controllers/OptionsController.cs
@@ -53,7 +53,6 @@ namespace slskd.Core.API
[ApiController]
[Produces("application/json")]
[Consumes("application/json")]
- [Authorize(Roles = AuthRole.AdministratorOnly)]
public class OptionsController : ControllerBase
{
public OptionsController(
@@ -76,7 +75,7 @@ namespace slskd.Core.API
/// </summary>
/// <returns></returns>
[HttpGet]
- [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)]
+ [Authorize(Policy = AuthPolicy.Any)]
[ProducesResponseType(typeof(Options), 200)]
public IActionResult Current()
{
diff --git a/src/slskd/Core/API/Controllers/ServerController.cs b/src/slskd/Core/API/Controllers/ServerController.cs
index 70adb858..41c1f1b1 100644
--- a/src/slskd/Core/API/Controllers/ServerController.cs
+++ b/src/slskd/Core/API/Controllers/ServerController.cs
@@ -48,7 +48,6 @@ namespace slskd.Core.API
[ApiController]
[Produces("application/json")]
[Consumes("application/json")]
- [Authorize(Roles = AuthRole.AdministratorOnly)]
public class ServerController : ControllerBase
{
public ServerController(
diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs
index b26dfe6e..1115f46c 100644
--- a/src/slskd/Core/API/Controllers/SessionController.cs
+++ b/src/slskd/Core/API/Controllers/SessionController.cs
@@ -34,8 +34,11 @@ using Microsoft.Extensions.Options;
namespace slskd.Core.API
{
+ using System.Security.Cryptography;
+ using System.Text;
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
+ using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using slskd.Authentication;
@@ -115,13 +118,15 @@ namespace slskd.Core.API
{
if (OptionsAtStartup.Headless)
{
- Log.Warning("Login from {User} rejected; web UI is DISABLED when running in headless mode", login.Username);
+ // if running headless, reject all login attempts and provide no feedback about inputs; there is nothing
+ // a caller can do to change the outcome, so a 400 is misleading
+ Log.Warning("Login from {User} rejected; web UI is DISABLED when running in headless mode", login?.Username ?? "<unspecified>");
return Forbid();
}
if (login == default)
{
- return BadRequest();
+ return BadRequest("No credentials provided");
}
if (string.IsNullOrWhiteSpace(login.Username) || string.IsNullOrWhiteSpace(login.Password))
@@ -129,8 +134,24 @@ namespace slskd.Core.API
return BadRequest("Username and/or Password missing or invalid");
}
+ Options.WebOptions.WebAuthenticationOptions options = OptionsSnapshot.Value.Web.Authentication;
+
+ if (string.IsNullOrEmpty(options.Username) || string.IsNullOrEmpty(options.Password))
+ {
+ // validation within the Options class should prevent this, but confirm in case of regression
+ Log.Error("Authentication is misconfigured; when enabled, username and password must be at least one character. Login is disabled.");
+ return StatusCode(StatusCodes.Status500InternalServerError, "Login disabled, check application logs for details");
+ }
+
+ // compare in constant time to avoid timing attacks
+ static bool ParanoidEquals(string left, string right)
+ => CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(left), Encoding.UTF8.GetBytes(right));
+
// only admin login for now
- if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password)
+ var usernameMatches = ParanoidEquals(options.Username, login.Username);
+ var passwordMatches = ParanoidEquals(options.Password, login.Password);
+
+ if (usernameMatches & passwordMatches)
{
return Ok(new TokenResponse(Security.GenerateJwt(login.Username, Role.Administrator)));
}
diff --git a/src/slskd/Core/API/Hubs/LogsHub.cs b/src/slskd/Core/API/Hubs/LogsHub.cs
index bec12d6a..0697f5ef 100644
--- a/src/slskd/Core/API/Hubs/LogsHub.cs
+++ b/src/slskd/Core/API/Hubs/LogsHub.cs
@@ -62,7 +62,7 @@ namespace slskd.Core.API
/// <summary>
/// The logs SignalR hub.
/// </summary>
- [Authorize(Policy = AuthPolicy.Any)]
+ [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.AdministratorOnly)]
public class LogsHub : Hub
{
public override async Task OnConnectedAsync()
diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs
index 517b5e4b..6f25b93c 100644
--- a/src/slskd/Core/Blacklist.cs
+++ b/src/slskd/Core/Blacklist.cs
@@ -39,6 +39,7 @@ using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
+using System.Net.Sockets;
using System.Threading.Tasks;
using NetTools;
using Serilog;
@@ -315,6 +316,18 @@ public class Blacklist
/// <returns>A value indicating whether the specified IP is contained within the blacklist.</returns>
public virtual bool Contains(IPAddress ip)
{
+ // looks like '::ffff:1.2.3.4'; convert it back to IPv4 so the lookup below works
+ if (ip.IsIPv4MappedToIPv6)
+ {
+ ip = ip.MapToIPv4();
+ }
+
+ // only IPv4 ranges are supported
+ if (ip.AddressFamily != AddressFamily.InterNetwork)
+ {
+ return false;
+ }
+
// grab the first octet
int first = ip.GetAddressBytes()[0];
diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs
index d53d7c8c..332077a9 100644
--- a/src/slskd/Core/Data/Migrator.cs
+++ b/src/slskd/Core/Data/Migrator.cs
@@ -133,7 +133,7 @@ public class Migrator
*/
Log.Warning("{Count} outstanding database migration(s) to apply. This operation must be completed before the application can start.", migrationsToApply.Count());
- var migrationId = DateTime.UtcNow.ToString("MMddyy_hhmmss");
+ var migrationId = DateTime.UtcNow.ToString("MMddyy_HHmmss");
Log.Warning("--> The ID for this migration is {MigrationId}. Use it to locate pre-migration database backups, should manual cleanup be needed. <--", migrationId);
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 05eaed57..1f6ceac2 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -1453,6 +1453,7 @@ namespace slskd
[EnvironmentVariable("LOKI")]
[Description("optional; url to a Grafana Loki instance to which to log")]
[RequiresRestart]
+ [Secret]
public string Loki { get; init; } = null;
/// <summary>
@@ -2185,9 +2186,12 @@ namespace slskd
{
var role = tuple.Split('=').LastOrDefault();
- if (!Enum.TryParse(typeof(Role), value: role, ignoreCase: true, out _))
+ var roleResult = new EnumAttribute(typeof(Role), ignoreCase: true)
+ .GetValidationResult(role, new ValidationContext(this) { MemberName = nameof(ApiKey), DisplayName = "API key role" });
+
+ if (roleResult != ValidationResult.Success)
{
- results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}"));
+ results.Add(new ValidationResult(roleResult.ErrorMessage));
}
}
else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase))
@@ -2242,7 +2246,7 @@ namespace slskd
[Argument(default, "jwt-ttl")]
[EnvironmentVariable("JWT_TTL")]
[Description("TTL for JWTs")]
- [Range(3600, int.MaxValue)]
+ [Range(3600000, int.MaxValue)]
[RequiresRestart]
public int Ttl { get; init; } = 604800000;
}
@@ -2572,6 +2576,7 @@ namespace slskd
/// Gets the fully qualified URL for the webhook.
/// </summary>
[NotNullOrWhiteSpace]
+ [Secret]
public string Url { get; init; }
/// <summary>
@@ -2608,6 +2613,7 @@ namespace slskd
/// <summary>
/// Gets the header's value.
/// </summary>
+ [Secret]
public string Value { get; init; }
}
@@ -2648,6 +2654,7 @@ namespace slskd
/// <summary>
/// Gets the shell command to run.
/// </summary>
+ [Secret]
public string Command { get; init; }
/// <summary>
@@ -2661,6 +2668,7 @@ namespace slskd
/// <remarks>
/// Mutually exclusive with <see cref="Arglist"/>.
/// </remarks>
+ [Secret]
public string Args { get; init; }
/// <summary>
diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs
index 790f5806..26ed49d2 100644
--- a/src/slskd/Core/Security/SecurityService.cs
+++ b/src/slskd/Core/Security/SecurityService.cs
@@ -40,6 +40,8 @@ using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net;
using System.Security.Claims;
+using System.Security.Cryptography;
+using System.Text;
using Microsoft.IdentityModel.Tokens;
using NetTools;
using Serilog;
@@ -121,11 +123,12 @@ public class SecurityService
keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(nameof(PrimaryApiKey), PrimaryApiKey));
}
- var record = keys.FirstOrDefault(k => k.Value.Key == key);
+ var keyBytes = Encoding.UTF8.GetBytes(key ?? string.Empty);
+ var record = keys.FirstOrDefault(k => k.Value.Key is not null && CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(k.Value.Key), keyBytes));
if (record.Key == null)
{
- throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}");
+ throw new NotFoundException("Unknown API key");
}
// looks like '::ffff:127.0.0.1'; not compatible with CIDR.Contains(), so convert it back to IPv4