From 8892dfa4eaffcc1cbc3b1f74127911fe056188d9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:11:01 -0600 Subject: auth with admin api key --- src/slskd/Core/Security/SecurityService.cs | 56 ++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) (limited to 'src/slskd/Core/Security/SecurityService.cs') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 6da88571..871e6e95 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -45,16 +45,68 @@ namespace slskd JwtSigningKey = jwtSigningKey; OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; + + var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; + + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + { + if (!adminApiKeyString.Contains(';')) + { + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = adminApiKeyString, + }; + } + + var tuples = adminApiKeyString.Split(';'); + + string key = null; + string role = null; + string cidr = null; + + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) + { + role = tuple.Split('=').LastOrDefault(); + } + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) + { + cidr = tuple.Split('=').LastOrDefault(); + } + else + { + key = tuple; + } + } + + if (!string.IsNullOrEmpty(key)) + { + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = role, + Cidr = cidr, + }; + } + } } private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) { - var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys - .FirstOrDefault(k => k.Value.Key == key); + var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); + + if (AdministrativeApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + } + + var record = keys.FirstOrDefault(k => k.Value.Key == key); if (record.Key == null) { -- cgit v1.2.3 From c6f912f4df7cba8abc947f4ed57a23ed0e58d995 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 12 Dec 2025 19:13:15 -0600 Subject: todos --- src/slskd/Core/Options.cs | 1 + src/slskd/Core/Security/SecurityService.cs | 5 +++++ 2 files changed, 6 insertions(+) (limited to 'src/slskd/Core/Security/SecurityService.cs') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index fc367578..ced7c96f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1957,6 +1957,7 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { + // TODO: test me! var results = new List(); if (string.IsNullOrWhiteSpace(ApiKey)) diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 871e6e95..c5531a35 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -46,6 +46,10 @@ namespace slskd OptionsAtStartup = optionsAtStartup; OptionsMonitor = optionsMonitor; + // parse the configured string into an instance of ApiKeyOptions and assign it to + // AdministrativeApiKey, if a string is provided. + // this is kind of expensive in terms of allocations, so do it once at instantiation + // and mark the option with [RequiresRestart] var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; if (!string.IsNullOrWhiteSpace(adminApiKeyString)) @@ -101,6 +105,7 @@ namespace slskd { var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); + // TODO: test me! if (AdministrativeApiKey is not null) { keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); -- cgit v1.2.3 From 1c2983723e4c683f101bb9988844a2812aab749d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 13:02:35 -0600 Subject: add logger, use file scoped namespace --- src/slskd/Core/Security/SecurityService.cs | 218 ++++++++++++++--------------- 1 file changed, 107 insertions(+), 111 deletions(-) (limited to 'src/slskd/Core/Security/SecurityService.cs') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index c5531a35..9a87449e 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -17,141 +17,137 @@ using Microsoft.Extensions.Options; -namespace slskd +namespace slskd; + +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Linq; +using System.Net; +using System.Security.Claims; +using Microsoft.IdentityModel.Tokens; +using NetTools; +using Serilog; +using slskd.Authentication; + +public class SecurityService { - using System; - using System.Collections.Generic; - using System.IdentityModel.Tokens.Jwt; - using System.Linq; - using System.Net; - using System.Security.Claims; - using Microsoft.IdentityModel.Tokens; - using NetTools; - using slskd.Authentication; - - public interface ISecurityService + public SecurityService( + SymmetricSecurityKey jwtSigningKey, + OptionsAtStartup optionsAtStartup, + IOptionsMonitor optionsMonitor) { - JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null); - (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress); - } + JwtSigningKey = jwtSigningKey; + OptionsAtStartup = optionsAtStartup; + OptionsMonitor = optionsMonitor; - public class SecurityService : ISecurityService - { - public SecurityService( - SymmetricSecurityKey jwtSigningKey, - OptionsAtStartup optionsAtStartup, - IOptionsMonitor optionsMonitor) - { - JwtSigningKey = jwtSigningKey; - OptionsAtStartup = optionsAtStartup; - OptionsMonitor = optionsMonitor; + // parse the configured string into an instance of ApiKeyOptions and assign it to + // AdministrativeApiKey, if a string is provided. + // this is kind of expensive in terms of allocations, so do it once at instantiation + // and mark the option with [RequiresRestart] + var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; - // parse the configured string into an instance of ApiKeyOptions and assign it to - // AdministrativeApiKey, if a string is provided. - // this is kind of expensive in terms of allocations, so do it once at instantiation - // and mark the option with [RequiresRestart] - var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; - - if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) + { + if (!adminApiKeyString.Contains(';')) { - if (!adminApiKeyString.Contains(';')) + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions - { - Key = adminApiKeyString, - }; - } + Key = adminApiKeyString, + }; + } - var tuples = adminApiKeyString.Split(';'); + var tuples = adminApiKeyString.Split(';'); - string key = null; - string role = null; - string cidr = null; + string key = null; + string role = null; + string cidr = null; - foreach (var tuple in tuples) + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) { - if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) - { - role = tuple.Split('=').LastOrDefault(); - } - else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) - { - cidr = tuple.Split('=').LastOrDefault(); - } - else - { - key = tuple; - } + role = tuple.Split('=').LastOrDefault(); } - - if (!string.IsNullOrEmpty(key)) + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions - { - Key = key, - Role = role, - Cidr = cidr, - }; + cidr = tuple.Split('=').LastOrDefault(); + } + else + { + key = tuple; } } - } - private SymmetricSecurityKey JwtSigningKey { get; } - private OptionsAtStartup OptionsAtStartup { get; } - private IOptionsMonitor OptionsMonitor { get; } - private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; - - public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) - { - var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - - // TODO: test me! - if (AdministrativeApiKey is not null) + if (!string.IsNullOrEmpty(key)) { - keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = role, + Cidr = cidr, + }; } + } + } - var record = keys.FirstOrDefault(k => k.Value.Key == key); - - if (record.Key == null) - { - throw new NotFoundException($"The provided API key does not match an existing key"); - } + private ILogger Log { get; } = Serilog.Log.ForContext(); + private SymmetricSecurityKey JwtSigningKey { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private IOptionsMonitor OptionsMonitor { get; } + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; - if (!record.Value.Cidr.Split(',') - .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(callerIpAddress))) - { - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); - } + public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) + { + var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - return (record.Key, record.Value.Role.ToEnum()); + if (AdministrativeApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); } - public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null) + var record = keys.FirstOrDefault(k => k.Value.Key == key); + + if (record.Key == null) { - var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl); + Log.Warning("Unauthorized access attempt: unknown API key beginning with {FirstFourCharacters}", key.Substring(0, 4)); + throw new NotFoundException($"The provided API key does not match an existing key"); + } - var claims = new List() - { - new Claim(ClaimTypes.Name, username), - new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), - new Claim(ClaimTypes.Role, role.ToString()), - new Claim("name", username), - new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), - }; - - var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); - - var token = new JwtSecurityToken( - issuer: Program.AppName, - claims: claims, - notBefore: issuedUtc, - expires: expiresUtc, - signingCredentials: credentials); - - return token; + if (!record.Value.Cidr.Split(',') + .Select(cidr => IPAddressRange.Parse(cidr)) + .Any(range => range.Contains(callerIpAddress))) + { + Log.Warning("Unauthorized access attempt: IP Address {IP} not included in CIDR(s) for API key {Name}: {CIDR}", callerIpAddress, record.Key, record.Value.Cidr); + throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); } + + return (record.Key, record.Value.Role.ToEnum()); + } + + public JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null) + { + var issuedUtc = DateTime.UtcNow; + var expiresUtc = DateTime.UtcNow.AddMilliseconds(ttl ?? OptionsAtStartup.Web.Authentication.Jwt.Ttl); + + var claims = new List() + { + new Claim(ClaimTypes.Name, username), + new Claim(ClaimTypes.NameIdentifier, Guid.NewGuid().ToString()), + new Claim(ClaimTypes.Role, role.ToString()), + new Claim("name", username), + new Claim("iat", ((DateTimeOffset)issuedUtc).ToUnixTimeSeconds().ToString()), + }; + + var credentials = new SigningCredentials(JwtSigningKey, SecurityAlgorithms.HmacSha256); + + var token = new JwtSecurityToken( + issuer: Program.AppName, + claims: claims, + notBefore: issuedUtc, + expires: expiresUtc, + signingCredentials: credentials); + + return token; } } -- cgit v1.2.3 From 942eeb1eeb535dbaa99e3701ffea39cadcabc4db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:19:13 -0600 Subject: remove serilog --- src/slskd/Core/Security/SecurityService.cs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'src/slskd/Core/Security/SecurityService.cs') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 9a87449e..8b3afa44 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -27,7 +27,6 @@ using System.Net; using System.Security.Claims; using Microsoft.IdentityModel.Tokens; using NetTools; -using Serilog; using slskd.Authentication; public class SecurityService @@ -91,7 +90,6 @@ public class SecurityService } } - private ILogger Log { get; } = Serilog.Log.ForContext(); private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } @@ -110,16 +108,14 @@ public class SecurityService if (record.Key == null) { - Log.Warning("Unauthorized access attempt: unknown API key beginning with {FirstFourCharacters}", key.Substring(0, 4)); - throw new NotFoundException($"The provided API key does not match an existing key"); + throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}"); } if (!record.Value.Cidr.Split(',') .Select(cidr => IPAddressRange.Parse(cidr)) .Any(range => range.Contains(callerIpAddress))) { - Log.Warning("Unauthorized access attempt: IP Address {IP} not included in CIDR(s) for API key {Name}: {CIDR}", callerIpAddress, record.Key, record.Value.Cidr); - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); + throw new OutOfRangeException($"IP Address {callerIpAddress} not included in CIDR(s) for API key {record.Key}: {record.Value.Cidr}"); } return (record.Key, record.Value.Role.ToEnum()); -- cgit v1.2.3 From fc1aecbe54b0077d0fde20f9f8e6350312344692 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 14:36:09 -0600 Subject: tweak logging --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 2 +- src/slskd/Core/Security/SecurityService.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Core/Security/SecurityService.cs') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index fb209478..e2733442 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -88,7 +88,7 @@ namespace slskd.Authentication } catch (Exception ex) { - Log.Warning(ex, "Unauthorized: {Message}", ex.Message); + Log.Warning("Unauthorized request from IP address {IP}: {Message}", Request.HttpContext.Connection.RemoteIpAddress, ex.Message); return AuthenticateResult.Fail(ex); } } diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 8b3afa44..e98dd5eb 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -115,7 +115,7 @@ public class SecurityService .Select(cidr => IPAddressRange.Parse(cidr)) .Any(range => range.Contains(callerIpAddress))) { - throw new OutOfRangeException($"IP Address {callerIpAddress} not included in CIDR(s) for API key {record.Key}: {record.Value.Cidr}"); + throw new OutOfRangeException($"IP address {callerIpAddress} not included in CIDR range(s) for API key {record.Key}; allowed: {record.Value.Cidr}"); } return (record.Key, record.Value.Role.ToEnum()); -- cgit v1.2.3 From 0b06e03e7091b486b99c74d71609fe1caa9e1093 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 13 Dec 2025 16:00:33 -0600 Subject: default to administrator and all CIDRs --- src/slskd/Core/Security/SecurityService.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src/slskd/Core/Security/SecurityService.cs') diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index e98dd5eb..254b3081 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -41,7 +41,7 @@ public class SecurityService OptionsMonitor = optionsMonitor; // parse the configured string into an instance of ApiKeyOptions and assign it to - // AdministrativeApiKey, if a string is provided. + // PrimaryApiKey, if a string is provided. // this is kind of expensive in terms of allocations, so do it once at instantiation // and mark the option with [RequiresRestart] var adminApiKeyString = OptionsMonitor.CurrentValue.Web.Authentication.ApiKey; @@ -50,7 +50,7 @@ public class SecurityService { if (!adminApiKeyString.Contains(';')) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { Key = adminApiKeyString, }; @@ -80,11 +80,11 @@ public class SecurityService if (!string.IsNullOrEmpty(key)) { - AdministrativeApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions { Key = key, - Role = role, - Cidr = cidr, + Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role, + Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr, }; } } @@ -93,15 +93,15 @@ public class SecurityService private SymmetricSecurityKey JwtSigningKey { get; } private OptionsAtStartup OptionsAtStartup { get; } private IOptionsMonitor OptionsMonitor { get; } - private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions AdministrativeApiKey { get; } = null; + private Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions PrimaryApiKey { get; } = null; public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) { var keys = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys.AsEnumerable(); - if (AdministrativeApiKey is not null) + if (PrimaryApiKey is not null) { - keys = keys.Prepend(new KeyValuePair(nameof(AdministrativeApiKey), AdministrativeApiKey)); + keys = keys.Prepend(new KeyValuePair(nameof(PrimaryApiKey), PrimaryApiKey)); } var record = keys.FirstOrDefault(k => k.Value.Key == key); -- cgit v1.2.3