diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-12-13 16:59:51 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-12-13 16:59:51 -0600 |
| commit | 1d27718843b0d62afa8a52847eadcbdbcbf44b98 (patch) | |
| tree | bc6d2bd7fd959d0740a68b5b35a3baf8f1de31c0 /src/slskd/Core | |
| parent | 6dbedb038a152a22dd9ee4b04a41a8b3ffde5d1f (diff) | |
| parent | 54584b8edd08f704427355d59323163086102207 (diff) | |
| download | slskd-1d27718843b0d62afa8a52847eadcbdbcbf44b98.tar.gz | |
Merge branch 'master' into copilot/add-sort-directories-files
Diffstat (limited to 'src/slskd/Core')
| -rw-r--r-- | src/slskd/Core/API/Controllers/SessionController.cs | 4 | ||||
| -rw-r--r-- | src/slskd/Core/Data/Databases.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 112 | ||||
| -rw-r--r-- | src/slskd/Core/Security/SecurityService.cs | 171 |
4 files changed, 222 insertions, 67 deletions
diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs index 861fd468..cfcb3f23 100644 --- a/src/slskd/Core/API/Controllers/SessionController.cs +++ b/src/slskd/Core/API/Controllers/SessionController.cs @@ -36,7 +36,7 @@ namespace slskd.Core.API public class SessionController : ControllerBase { public SessionController( - ISecurityService securityService, + SecurityService securityService, IOptionsSnapshot<Options> optionsSnapshot, OptionsAtStartup optionsAtStartup) { @@ -47,7 +47,7 @@ namespace slskd.Core.API private IOptionsSnapshot<Options> OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } - private ISecurityService Security { get; } + private SecurityService Security { get; } private ILogger Log { get; } = Serilog.Log.ForContext<SessionController>(); /// <summary> diff --git a/src/slskd/Core/Data/Databases.cs b/src/slskd/Core/Data/Databases.cs index f118ad2a..a5d51ea6 100644 --- a/src/slskd/Core/Data/Databases.cs +++ b/src/slskd/Core/Data/Databases.cs @@ -15,6 +15,8 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +namespace slskd; + /// <summary> /// A primitive type for Database names and a static value for each of them. And a list. /// </summary> diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 254adcab..20b53f6c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -115,7 +115,7 @@ namespace slskd /// <summary> /// Gets a value indicating whether to display a list of configuration environment variables. /// </summary> - [Argument('e', "envars")] + [Argument(default, "envars")] [Description("display environment variables")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -125,7 +125,7 @@ namespace slskd /// <summary> /// Gets a value indicating whether to generate an X509 certificate and password. /// </summary> - [Argument('g', "generate-cert")] + [Argument(default, "generate-cert")] [Description("generate X509 certificate and password for HTTPS")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -135,7 +135,7 @@ namespace slskd /// <summary> /// Gets a value indicating whether to generate a random secret. /// </summary> - [Argument('k', "generate-secret")] + [Argument(default, "generate-secret")] [Description("generate random secret of the specified length")] [Obsolete("Used only for documentation; see Program for actual implementation")] [JsonIgnore] @@ -1252,6 +1252,12 @@ namespace slskd return results; } + if (string.IsNullOrWhiteSpace(File)) + { + results.Add(new ValidationResult("The Enabled field is true, but no File has been specified.")); + return results; + } + // loading/validating the entire list will be costly on low spec systems // just make sure that we can detect a valid format and leave it at that // if there's a problem with any of the entries, the load will fail and @@ -1833,6 +1839,16 @@ namespace slskd public int Port { get; init; } = 5030; /// <summary> + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTP requests. + /// </summary> + [Argument(default, "http-ip-address")] + [EnvironmentVariable("HTTP_IP_ADDRESS")] + [Description("IP addresses on which to listen for HTTP requests")] + [IPAddress(allowCommaSeparatedValues: true)] + [RequiresRestart] + public string IpAddress { get; init; } + + /// <summary> /// Gets the HTTP listen unix domain socket (UDS) path. /// </summary> [Argument(default, "http-socket")] @@ -1887,7 +1903,7 @@ namespace slskd /// <summary> /// Authentication options. /// </summary> - public class WebAuthenticationOptions + public class WebAuthenticationOptions : IValidatableObject { /// <summary> /// Gets a value indicating whether authentication should be disabled. @@ -1925,11 +1941,89 @@ namespace slskd public JwtOptions Jwt { get; init; } = new JwtOptions(); /// <summary> + /// Gets the primary API key. Defaults to 'Administrator' role and CIDR '0.0.0.0/0,::/0'. + /// role and CIDR can be supplied by prefixing the key with 'role=[role];cidr=[cidrs];[key]'. + /// </summary> + [Argument('k', "api-key")] + [EnvironmentVariable("API_KEY")] + [Description("primary API key value")] + [Secret] + [RequiresRestart] + public string ApiKey { get; init; } + + /// <summary> /// Gets API keys. /// </summary> [Validate] public Dictionary<string, ApiKeyOptions> ApiKeys { get; init; } = new Dictionary<string, ApiKeyOptions>(); + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (string.IsNullOrWhiteSpace(ApiKey)) + { + return results; + } + + var tuples = ApiKey.Split(';'); + + // if only one tuple is supplied, it's just the key, no role or list of CIDRs + if (tuples.Length == 1) + { + var key = tuples.FirstOrDefault(); + + if (key?.Length < 16 || key?.Length > 255) + { + results.Add(new ValidationResult("API key must be between 16 and 255 characters")); + } + + return results; + } + + /* + if multiple tuples are supplied, verify that: + + * if a tuple starts with 'role=', it's defining a role and it must match one of the Role enum values + * if a tuple starts with 'cidr=', it's defining a list of CIDRs which need to be valid + * if a tuple doesn't start with a prefix, it's the API key itself and it must be between 16 and 255 characters + */ + foreach (var tuple in tuples) + { + if (tuple.StartsWith("role=", StringComparison.OrdinalIgnoreCase)) + { + var role = tuple.Split('=').LastOrDefault(); + + if (!Enum.TryParse(typeof(Role), value: role, ignoreCase: true, out _)) + { + results.Add(new ValidationResult($"API key role must be one of: {string.Join(", ", Enum.GetNames(typeof(Role)))}")); + } + } + else if (tuple.StartsWith("cidr=", StringComparison.OrdinalIgnoreCase)) + { + var cidrs = tuple.Split('=').LastOrDefault(); + + foreach (var cidr in cidrs.Split(',')) + { + try + { + _ = IPAddressRange.Parse(cidr); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"API key CIDR {cidr} is invalid: {ex.Message}")); + } + } + } + else if (tuple?.Length < 16 || tuple?.Length > 255) + { + results.Add(new ValidationResult("API key must be between 16 and 255 characters")); + } + } + + return results; + } + /// <summary> /// JWT options. /// </summary> @@ -2034,6 +2128,16 @@ namespace slskd public int Port { get; init; } = 5031; /// <summary> + /// Gets the comma separated list of IPv4 or IPv6 IP addresses on which to listen for HTTPS requests. + /// </summary> + [Argument(default, "https-ip-address")] + [EnvironmentVariable("HTTPS_IP_ADDRESS")] + [Description("IP addresses on which to listen for HTTPS requests")] + [IPAddress(allowCommaSeparatedValues: true)] + [RequiresRestart] + public string IpAddress { get; init; } + + /// <summary> /// Gets a value indicating whether HTTP requests should be redirected to HTTPS. /// </summary> [Argument('f', "force-https")] diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs index 6da88571..254b3081 100644 --- a/src/slskd/Core/Security/SecurityService.cs +++ b/src/slskd/Core/Security/SecurityService.cs @@ -17,84 +17,133 @@ 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 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<Options> 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<Options> optionsMonitor) + // parse the configured string into an instance of ApiKeyOptions and assign it to + // 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; + + if (!string.IsNullOrWhiteSpace(adminApiKeyString)) { - JwtSigningKey = jwtSigningKey; - OptionsAtStartup = optionsAtStartup; - OptionsMonitor = optionsMonitor; - } + if (!adminApiKeyString.Contains(';')) + { + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = adminApiKeyString, + }; + } - private SymmetricSecurityKey JwtSigningKey { get; } - private OptionsAtStartup OptionsAtStartup { get; } - private IOptionsMonitor<Options> OptionsMonitor { get; } + var tuples = adminApiKeyString.Split(';'); - public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) - { - var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys - .FirstOrDefault(k => k.Value.Key == key); + string key = null; + string role = null; + string cidr = null; - if (record.Key == null) + foreach (var tuple in tuples) { - throw new NotFoundException($"The provided API key does not match an existing key"); + 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 (!record.Value.Cidr.Split(',') - .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(callerIpAddress))) + if (!string.IsNullOrEmpty(key)) { - throw new OutOfRangeException("The remote IP address is not within the range specified for the key"); + PrimaryApiKey = new Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions + { + Key = key, + Role = string.IsNullOrWhiteSpace(role) ? Role.Administrator.ToString() : role, + Cidr = string.IsNullOrWhiteSpace(cidr) ? "0.0.0.0/0,::/0" : cidr, + }; } + } + } + + private SymmetricSecurityKey JwtSigningKey { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private IOptionsMonitor<Options> OptionsMonitor { get; } + 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(); - return (record.Key, record.Value.Role.ToEnum<Role>()); + if (PrimaryApiKey is not null) + { + keys = keys.Prepend(new KeyValuePair<string, Options.WebOptions.WebAuthenticationOptions.ApiKeyOptions>(nameof(PrimaryApiKey), PrimaryApiKey)); } - 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); + throw new NotFoundException($"Unknown API key beginning with: {key.Substring(0, 4)}"); + } - var claims = new List<Claim>() - { - 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))) + { + 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<Role>()); + } + + 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<Claim>() + { + 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; } } |
