diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-10-25 16:23:07 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-10-25 16:23:07 -0500 |
| commit | 2b827344d11e7490b323defa898264cadbdb6089 (patch) | |
| tree | 57fedb94861bb4116a8aed9cc7fecb5e87aa06ff /src | |
| parent | a4cce04d38544ad6d4c1506b9facb32407a79509 (diff) | |
| parent | be81b3b85b21d502feaf4918a0da92f445f7c2ab (diff) | |
| download | slskd-2b827344d11e7490b323defa898264cadbdb6089.tar.gz | |
Merge pull request #1911 from slskd/auth
Refine access levels on a number of endpoints, number of small tweaks and adjustments
Diffstat (limited to 'src')
21 files changed, 181 insertions, 76 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 diff --git a/src/slskd/Events/API/EventsController.cs b/src/slskd/Events/API/EventsController.cs index e031498c..5381f513 100644 --- a/src/slskd/Events/API/EventsController.cs +++ b/src/slskd/Events/API/EventsController.cs @@ -123,7 +123,7 @@ public class EventsController : ControllerBase /// <response code="500">An unexpected error is encountered.</response> /// <response code="201">The request completed successfully.</response> [HttpPost("{type}", Name = nameof(RaiseEvent))] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(401)] [ProducesResponseType(403)] @@ -131,7 +131,7 @@ public class EventsController : ControllerBase [ProducesResponseType(typeof(Event), 201)] public IActionResult RaiseEvent([FromRoute] string type, [FromBody] string disambiguator) { - if (!Enum.TryParse<EventType>(type, ignoreCase: true, out var eventType)) + if (!Enum.TryParse<EventType>(type, ignoreCase: true, out var eventType) || !Enum.IsDefined(eventType)) { var names = Enum.GetNames(typeof(EventType)) .Where(n => n != EventType.Any.ToString() && n != EventType.None.ToString()); diff --git a/src/slskd/Files/API/FilesController.cs b/src/slskd/Files/API/FilesController.cs index 5f30f325..8954c1ac 100644 --- a/src/slskd/Files/API/FilesController.cs +++ b/src/slskd/Files/API/FilesController.cs @@ -34,9 +34,9 @@ using Microsoft.Extensions.Options; namespace slskd.Files.API { + using System; using System.ComponentModel.DataAnnotations; using System.IO; - using System.Security; using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; @@ -95,7 +95,7 @@ namespace slskd.Files.API [ProducesResponseType(401)] [ProducesResponseType(403)] [ProducesResponseType(404)] - public Task<IActionResult> GetDownloadSubdirectoryContentsAsync([FromRoute] string base64SubdirectoryName, [FromQuery] bool recursive = false) + public Task<IActionResult> GetDownloadSubdirectoryContentsAsync([FromRoute, UrlEncoded] string base64SubdirectoryName, [FromQuery] bool recursive = false) => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName, recursive); /// <summary> @@ -108,9 +108,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("downloads/directories/{base64SubdirectoryName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteDownloadSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + public Task<IActionResult> DeleteDownloadSubdirectoryAsync([FromRoute, UrlEncoded] string base64SubdirectoryName) => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64SubdirectoryName); /// <summary> @@ -123,9 +123,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("downloads/files/{base64FileName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteDownloadFileAsync([FromRoute] string base64FileName) + public Task<IActionResult> DeleteDownloadFileAsync([FromRoute, UrlEncoded] string base64FileName) => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Downloads, base64FileName); /// <summary> @@ -154,7 +154,7 @@ namespace slskd.Files.API [HttpGet("incomplete/directories/{base64SubdirectoryName}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(FilesystemDirectory), 200)] - public Task<IActionResult> GetIncompleteSubdirectoryContentsAsync([FromRoute, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) + public Task<IActionResult> GetIncompleteSubdirectoryContentsAsync([FromRoute, UrlEncoded, Required] string base64SubdirectoryName, [FromQuery] bool recursive = false) => ListDirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName, recursive); /// <summary> @@ -167,9 +167,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("incomplete/directories/{base64SubdirectoryName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteIncompleteSubdirectoryAsync([FromRoute] string base64SubdirectoryName) + public Task<IActionResult> DeleteIncompleteSubdirectoryAsync([FromRoute, UrlEncoded] string base64SubdirectoryName) => DeleteSubdirectoryAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64SubdirectoryName); /// <summary> @@ -182,9 +182,9 @@ namespace slskd.Files.API /// <response code="403">Access to the specified subdirectory was denied.</response> /// <response code="404">The specified subdirectory does not exist.</response> [HttpDelete("incomplete/files/{base64FileName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] - public Task<IActionResult> DeleteIncompleteFileAsync([FromRoute] string base64FileName) + public Task<IActionResult> DeleteIncompleteFileAsync([FromRoute, UrlEncoded] string base64FileName) => DeleteFileAsync(rootDirectory: OptionsSnapshot.Value.Directories.Incomplete, base64FileName); private async Task<IActionResult> ListDirectoryAsync(string rootDirectory, string base64SubdirectoryName = null, bool recursive = false) @@ -192,7 +192,13 @@ namespace slskd.Files.API var requestedDir = (base64SubdirectoryName ?? string.Empty) .FromBase64() .Replace('\\', Path.DirectorySeparatorChar) - .Replace('/', Path.DirectorySeparatorChar); + .Replace('/', Path.DirectorySeparatorChar) + .TrimStart(Path.DirectorySeparatorChar); + + if (!FileSafety.IsPathRelative(requestedDir)) + { + return BadRequest("Path must be relative"); + } requestedDir = Path.GetFullPath(Path.Combine(rootDirectory, requestedDir)); @@ -210,11 +216,16 @@ namespace slskd.Files.API return Ok(response); } - catch (SecurityException) + catch (UnauthorizedException) { Log.Warning("Directory listing of '{Directory}' forbidden", requestedDir); return Forbid(); } + catch (ArgumentException ex) + { + Log.Warning("Bad request: {Message}", ex.Message); + return BadRequest(ex.Message); + } catch (NotFoundException) { Log.Debug("Directory '{Directory}' not found", requestedDir); @@ -235,6 +246,11 @@ namespace slskd.Files.API .Replace('/', Path.DirectorySeparatorChar) .TrimStart(Path.DirectorySeparatorChar); + if (!FileSafety.IsPathRelative(requestedDir)) + { + return BadRequest("Path must be relative"); + } + requestedDir = Path.GetFullPath(Path.Combine(rootDirectory, requestedDir)); Log.Information("Deleting directory '{Directory}'", requestedDir); @@ -247,11 +263,16 @@ namespace slskd.Files.API success => NoContent(), failure => throw failure); } - catch (SecurityException) + catch (UnauthorizedException) { Log.Warning("Directory deletion of '{Directory}' forbidden", requestedDir); return Forbid(); } + catch (ArgumentException ex) + { + Log.Warning("Bad request: {Message}", ex.Message); + return BadRequest(ex.Message); + } catch (NotFoundException) { Log.Information("Directory '{Directory}' not found", requestedDir); @@ -272,6 +293,11 @@ namespace slskd.Files.API .Replace('/', Path.DirectorySeparatorChar) .TrimStart(Path.DirectorySeparatorChar); + if (!FileSafety.IsPathRelative(requestedFilename)) + { + return BadRequest("Path must be relative"); + } + requestedFilename = Path.GetFullPath(Path.Combine(rootDirectory, requestedFilename)); Log.Information("Deleting file '{File}'", requestedFilename); @@ -284,11 +310,16 @@ namespace slskd.Files.API success => NoContent(), failure => throw failure); } - catch (SecurityException) + catch (UnauthorizedException) { Log.Warning("File deletion of '{File}' forbidden", requestedFilename); return Forbid(); } + catch (ArgumentException ex) + { + Log.Warning("Bad request: {Message}", ex.Message); + return BadRequest(ex.Message); + } catch (NotFoundException) { Log.Information("File '{File}' not found", requestedFilename); diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index 7ed0a92c..a1c6038f 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -87,7 +87,7 @@ namespace slskd.Messaging.API /// A conversation with the specified username, or a message matching the specified id could not be found. /// </response> [HttpPut("{username}/{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(200)] [ProducesResponseType(404)] public async Task<IActionResult> Acknowledge([FromRoute, UrlEncoded] string username, [FromRoute] int id) @@ -97,7 +97,7 @@ namespace slskd.Messaging.API return Forbid(); } - var message = Messages.Conversations.FindMessageAsync(username, id); + var message = await Messages.Conversations.FindMessageAsync(username, id); if (message == default) { @@ -117,7 +117,7 @@ namespace slskd.Messaging.API /// <response code="200">The request completed successfully.</response> /// <response code="404">A conversation with the specified username could not be found.</response> [HttpPut("{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(200)] [ProducesResponseType(404)] public async Task<IActionResult> AcknowledgeAll([FromRoute, UrlEncoded] string username) @@ -127,7 +127,7 @@ namespace slskd.Messaging.API return Forbid(); } - var conversation = Messages.Conversations.FindAsync(username); + var conversation = await Messages.Conversations.FindAsync(username); if (conversation == default) { @@ -146,7 +146,7 @@ namespace slskd.Messaging.API /// <response code="204">The request completed successfully.</response> /// <response code="404">A conversation with the specified username could not be found.</response> [HttpDelete("{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(404)] [ProducesResponseType(204)] public async Task<IActionResult> Close([FromRoute, UrlEncoded] string username) @@ -156,7 +156,7 @@ namespace slskd.Messaging.API return Forbid(); } - var conversation = Messages.Conversations.FindAsync(username, includeInactive: false); + var conversation = await Messages.Conversations.FindAsync(username, includeInactive: false); if (conversation == default) { @@ -259,7 +259,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="400">The specified message is null or empty.</response> [HttpPost("{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(400)] public async Task<IActionResult> Send([FromRoute, UrlEncoded] string username, [FromBody] string message) diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs index 3b2fe568..57d3b742 100644 --- a/src/slskd/Messaging/API/Controllers/RoomsController.cs +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -127,7 +127,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="404">The specified roomName could not be found.</response> [HttpPost("joined/{roomName}/messages")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task<IActionResult> SendMessage([FromRoute, UrlEncoded] string roomName, [FromBody] string message) @@ -155,7 +155,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="404">The specified roomName could not be found.</response> [HttpPost("joined/{roomName}/ticker")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task<IActionResult> SetTicker([FromRoute, UrlEncoded] string roomName, [FromBody] string message) @@ -183,7 +183,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="404">The specified roomName could not be found.</response> [HttpPost("joined/{roomName}/members")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(404)] public async Task<IActionResult> AddRoomMember([FromRoute, UrlEncoded] string roomName, [FromBody] string username) @@ -298,7 +298,7 @@ namespace slskd.Messaging.API /// <response code="201">The request completed successfully.</response> /// <response code="304">The room has already been joined.</response> [HttpPost("joined")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Room), 201)] [ProducesResponseType(304)] public async Task<IActionResult> JoinRoom([FromBody] string roomName) @@ -339,7 +339,7 @@ namespace slskd.Messaging.API /// <response code="204">The request completed successfully.</response> /// <response code="404">The room has not been joined.</response> [HttpDelete("joined/{roomName}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task<IActionResult> LeaveRoom([FromRoute, UrlEncoded] string roomName) diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index e236886b..372dc998 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -454,7 +454,17 @@ namespace slskd if (OptionsAtStartup.Debug) { - Log.Information($"Configuration:\n{Configuration.GetDebugView()}"); + // redact values for any key matching the name of a property marked [Secret]. keys from YAML may be + // snake or kebab case, so normalize before comparing. this over-redacts, which is fine here + var secretNames = typeof(Options).Assembly.GetTypes() + .Where(t => t == typeof(Options) || (t.FullName?.StartsWith($"{typeof(Options).FullName}+") ?? false)) + .SelectMany(t => t.GetProperties()) + .Where(p => p.GetCustomAttributes(typeof(SecretAttribute), inherit: false).Length > 0) + .Select(p => p.Name.ToLowerInvariant()) + .ToHashSet(); + + Log.Information($"Configuration:\n{Configuration.GetDebugView(context => + secretNames.Contains(context.Key.Replace("_", string.Empty).Replace("-", string.Empty).ToLowerInvariant()) ? "*****" : context.Value)}"); } if (!OptionsAtStartup.TryValidate(out var result)) @@ -465,7 +475,7 @@ namespace slskd } catch (Exception ex) { - Log.Information($"Invalid configuration: {(!OptionsAtStartup.Debug ? ex : ex.Message)}"); + Log.Information($"Invalid configuration: {(OptionsAtStartup.Debug ? ex : ex.Message)}"); return; } diff --git a/src/slskd/Relay/API/Hubs/RelayHub.cs b/src/slskd/Relay/API/Hubs/RelayHub.cs index 8430164c..e839cd1a 100644 --- a/src/slskd/Relay/API/Hubs/RelayHub.cs +++ b/src/slskd/Relay/API/Hubs/RelayHub.cs @@ -85,7 +85,7 @@ namespace slskd.Relay /// <summary> /// The relay SignalR hub. /// </summary> - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public class RelayHub : Hub<IRelayHub> { /// <summary> @@ -120,6 +120,7 @@ namespace slskd.Relay { Log.Debug("Agent connection {Id} from {IP} aborted; Relay is not enabled, or is not in Controller mode", Context.ConnectionId, GetRemoteIPAddress()); Context.Abort(); + return; } var token = Relay.GenerateAuthenticationChallengeToken(Context.ConnectionId); diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index fef16573..cbcde3c4 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -148,7 +148,15 @@ namespace slskd.Relay // the controller will send an authentication challenge immediately after connection // wait for the auth handler to log in before proceeding with the initial share upload - await LoggedInTaskCompletionSource.Task; + try + { + await LoggedInTaskCompletionSource.Task; + } + catch (Exception) + { + await StopAsync(cancellationToken); + throw; + } Log.Information("Uploading shares..."); @@ -366,6 +374,7 @@ namespace slskd.Relay catch (Exception ex) { Log.Error(ex, "Failed to handle authentication challenge: {Message}", ex.Message); + LoggedInTaskCompletionSource.TrySetException(ex); } } @@ -375,6 +384,7 @@ namespace slskd.Relay { Log.Warning("Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0); + return; } Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); @@ -399,7 +409,8 @@ namespace slskd.Relay if (FileSafety.ContainsTraversalSegments(filename)) { Log.Warning("Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); - await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); + await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token, "Requested filename contains unsafe path segments"); + return; } _ = Task.Run(async () => diff --git a/src/slskd/Search/API/Controllers/SearchesController.cs b/src/slskd/Search/API/Controllers/SearchesController.cs index 99214410..a573c1e0 100644 --- a/src/slskd/Search/API/Controllers/SearchesController.cs +++ b/src/slskd/Search/API/Controllers/SearchesController.cs @@ -78,7 +78,7 @@ namespace slskd.Search.API /// <response code="400">The specified <paramref name="request"/> was malformed.</response> /// <response code="500">The search terminated abnormally.</response> [HttpPost("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] public async Task<IActionResult> Post([FromBody] SearchRequest request) { if (Program.IsRelayAgent) @@ -207,7 +207,7 @@ namespace slskd.Search.API /// <response code="304">The search was not in progress.</response> /// <returns></returns> [HttpPut("{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(200)] [ProducesResponseType(304)] public async Task<IActionResult> Cancel([FromRoute] Guid id) @@ -236,7 +236,7 @@ namespace slskd.Search.API /// <response code="404">A search with the specified id could not be found.</response> /// <returns></returns> [HttpDelete("{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public async Task<IActionResult> Delete([FromRoute] Guid id) diff --git a/src/slskd/Shares/API/Controllers/SharesController.cs b/src/slskd/Shares/API/Controllers/SharesController.cs index 76ec4643..64d703bd 100644 --- a/src/slskd/Shares/API/Controllers/SharesController.cs +++ b/src/slskd/Shares/API/Controllers/SharesController.cs @@ -148,7 +148,7 @@ namespace slskd.Shares.API /// <response code="409">A share scan is already in progress.</response> [HttpPut] [Route("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(409)] public IActionResult RescanSharesAsync() @@ -173,7 +173,7 @@ namespace slskd.Shares.API /// <response code="409">A share scan was not in progress.</response> [HttpDelete] [Route("")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public IActionResult CancelShareScan() diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index 6d84308a..75d3064e 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -157,8 +157,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT COUNT(*) FROM directories WHERE name LIKE @prefix || '%'", conn); - cmd.Parameters.AddWithValue("prefix", parentDirectory); + cmd = new SqliteCommand("SELECT COUNT(*) FROM directories WHERE name LIKE @prefix || '%' ESCAPE '^'", conn); + cmd.Parameters.AddWithValue("prefix", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_")); } var reader = cmd.ExecuteReader(); @@ -190,8 +190,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT COUNT(*) FROM files WHERE maskedFilename LIKE @prefix || '%'", conn); - cmd.Parameters.AddWithValue("prefix", parentDirectory); + cmd = new SqliteCommand("SELECT COUNT(*) FROM files WHERE maskedFilename LIKE @prefix || '%' ESCAPE '^'", conn); + cmd.Parameters.AddWithValue("prefix", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_")); } var reader = cmd.ExecuteReader(); @@ -414,8 +414,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT name from directories WHERE name LIKE @prefix || '%' ORDER BY name ASC;", conn); - cmd.Parameters.AddWithValue("prefix", parentDirectory); + cmd = new SqliteCommand("SELECT name from directories WHERE name LIKE @prefix || '%' ESCAPE '^' ORDER BY name ASC;", conn); + cmd.Parameters.AddWithValue("prefix", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_")); } var reader = cmd.ExecuteReader(); @@ -454,8 +454,8 @@ namespace slskd.Shares } else { - cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ORDER BY maskedFilename ASC;", conn); - cmd.Parameters.AddWithValue("match", parentDirectory + '%'); + cmd = new SqliteCommand("SELECT maskedFilename, code, size, extension, attributeJson FROM files WHERE maskedFilename LIKE @match ESCAPE '^' ORDER BY maskedFilename ASC;", conn); + cmd.Parameters.AddWithValue("match", parentDirectory.Replace("^", "^^").Replace("%", "^%").Replace("_", "^_") + '%'); } var reader = cmd.ExecuteReader(); @@ -591,7 +591,7 @@ namespace slskd.Shares var sql = $"SELECT files.maskedFilename, files.code, files.size, files.extension, files.attributeJson FROM filenames " + "INNER JOIN files ON filenames.maskedFilename = files.maskedFilename " + - $"WHERE filenames MATCH '({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}' " + + "WHERE filenames MATCH @match " + $"ORDER BY filenames.maskedFilename ASC {(limit.HasValue ? $"LIMIT {limit.Value}" : string.Empty)};"; var results = new List<Soulseek.File>(); @@ -600,6 +600,7 @@ namespace slskd.Shares { using var conn = GetConnection(); using var cmd = new SqliteCommand(sql, conn); + cmd.Parameters.AddWithValue("match", $"({match}) {(query.Exclusions.Any() ? $"NOT ({exclusions})" : string.Empty)}"); using var reader = cmd.ExecuteReader(); while (reader.Read()) @@ -753,6 +754,7 @@ namespace slskd.Shares { if (disposing) { + KeepaliveTimer.Dispose(); KeepaliveConnection.Dispose(); } diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 3dd2f124..b3453530 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -89,7 +89,7 @@ namespace slskd.Transfers.API /// <response code="204">The download was cancelled successfully.</response> /// <response code="404">The specified download was not found.</response> [HttpDelete("downloads/{username}/{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public IActionResult CancelDownloadAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) @@ -127,7 +127,7 @@ namespace slskd.Transfers.API /// <returns></returns> /// <response code="204">The downloads were removed successfully.</response> [HttpDelete("downloads/all/completed")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] public IActionResult ClearCompletedDownloads() { @@ -158,7 +158,7 @@ namespace slskd.Transfers.API /// <response code="204">The upload was cancelled successfully.</response> /// <response code="404">The specified upload was not found.</response> [HttpDelete("uploads/{username}/{id}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] [ProducesResponseType(404)] public IActionResult CancelUpload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) @@ -196,7 +196,7 @@ namespace slskd.Transfers.API /// <returns></returns> /// <response code="204">The uploads were removed successfully.</response> [HttpDelete("uploads/all/completed")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(204)] public IActionResult ClearCompletedUploads() { @@ -228,7 +228,7 @@ namespace slskd.Transfers.API /// <response code="500">An unexpected error was encountered.</response> [Obsolete("Will be phased out in future versions; use batches")] [HttpPost("downloads/{username}")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] @@ -302,7 +302,7 @@ namespace slskd.Transfers.API /// <response code="429">Request throttled.</response> /// <response code="500">An unexpected error was encountered.</response> [HttpPost("downloads/batches")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status200OK)] [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status201Created)] [ProducesResponseType(typeof(EnqueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)] @@ -582,7 +582,7 @@ namespace slskd.Transfers.API /// <response code="200">The request completed successfully.</response> /// <response code="404">The specified download was not found.</response> [HttpGet("downloads/{username}/{id}/position")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 8029b5e0..41d2db6a 100644 --- a/src/slskd/Users/API/Controllers/UsersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -42,7 +42,6 @@ namespace slskd.Users.API using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Serilog; - using Soulseek; /// <summary> @@ -83,7 +82,7 @@ namespace slskd.Users.API /// <returns></returns> /// <response code="200">The request completed successfully.</response> [HttpGet("{username}/endpoint")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(IPEndPoint), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Endpoint([FromRoute, UrlEncoded, Required] string username) @@ -115,7 +114,7 @@ namespace slskd.Users.API /// <param name="username">The username of the user.</param> /// <returns></returns> [HttpGet("{username}/browse")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Browse([FromRoute, UrlEncoded, Required] string username) @@ -179,7 +178,7 @@ namespace slskd.Users.API /// <param name="request">The directory contents request.</param> /// <returns></returns> [HttpPost("{username}/directory")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Directory([FromRoute, UrlEncoded, Required] string username, [FromBody, Required] DirectoryContentsRequest request) @@ -219,7 +218,7 @@ namespace slskd.Users.API /// <param name="username">The username of the user.</param> /// <returns></returns> [HttpGet("{username}/info")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Info), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Info([FromRoute, UrlEncoded, Required] string username) @@ -251,7 +250,7 @@ namespace slskd.Users.API /// <param name="username">The username of the user.</param> /// <returns></returns> [HttpGet("{username}/status")] - [Authorize(Policy = AuthPolicy.Any)] + [Authorize(Policy = AuthPolicy.Any, Roles = AuthRole.ReadWriteOrAdministrator)] [ProducesResponseType(typeof(Status), 200)] [ProducesResponseType(404)] public async Task<IActionResult> Status([FromRoute, UrlEncoded, Required] string username) diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 3ce827c8..51b47d5b 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -325,7 +325,15 @@ namespace slskd.Users { ArgumentNullException.ThrowIfNull(username); - if (BlacklistDecisionCache.TryGetValue<bool>(username, out var cached)) + // looks like '::ffff:1.2.3.4'; convert it back to IPv4 so CIDR checks work + if (ipAddress is not null && ipAddress.IsIPv4MappedToIPv6) + { + ipAddress = ipAddress.MapToIPv4(); + } + + var cacheKey = ipAddress is null ? username : $"{username}@{ipAddress}"; + + if (BlacklistDecisionCache.TryGetValue<bool>(cacheKey, out var cached)) { return cached; } @@ -343,7 +351,7 @@ namespace slskd.Users var blacklisted = IsBlacklistedInternal(username, ipAddress); BlacklistDecisionCache.Set( - key: username, + key: cacheKey, value: blacklisted, options: new MemoryCacheEntryOptions { |
