From 30b2b42ccc9a51be4aee4c74b9184f5da1509932 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Oct 2022 15:24:50 -0500 Subject: add options for api keys --- src/slskd/Core/Options.cs | 61 +++++++++++++++++++++++++++++++++++++++++++++++ src/slskd/slskd.csproj | 1 + 2 files changed, 62 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 44cc4c71..4c146d32 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -28,6 +28,7 @@ namespace slskd using System.Text.Json.Serialization; using System.Text.RegularExpressions; using FluentFTP; + using NetTools; using slskd.Configuration; using slskd.Validation; using Soulseek.Diagnostics; @@ -126,6 +127,16 @@ namespace slskd [YamlIgnore] public bool GenerateCertificate { get; init; } = false; + /// + /// Gets a value indicating whether to generate a random API key. + /// + [Argument('k', "generate-api-key")] + [Description("generate random API key for HTTP/S")] + [Obsolete("USed only for documentation; see Program for actual implementation")] + [JsonIgnore] + [YamlIgnore] + public bool GenerateApiKey { get; init; } = false; + /// /// Gets a value indicating whether the application should run in debug mode. /// @@ -1214,6 +1225,12 @@ namespace slskd [RequiresRestart] public JwtOptions Jwt { get; init; } = new JwtOptions(); + /// + /// Gets API keys. + /// + [Validate] + public Dictionary ApiKeys { get; init; } = new Dictionary(); + /// /// JWT options. /// @@ -1240,6 +1257,50 @@ namespace slskd [RequiresRestart] public int Ttl { get; init; } = 604800000; } + + /// + /// API key options. + /// + public class ApiKeyOptions : IValidatableObject + { + /// + /// Gets the API key value. + /// + [Description("API key value")] + [StringLength(255, MinimumLength = 16)] + [Secret] + public string Key { get; init; } + + /// + /// Gets the comma separated list of CIDRs that are authorized to use the key. + /// + [Description("An optional comma separated list of CIDRs that are authorized to use the key")] + public string Cidr { get; init; } = "0.0.0.0/0,::/0"; + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + foreach (var cidr in Cidr.Split(',')) + { + try + { + _ = IPAddressRange.Parse(cidr); + } + catch (Exception ex) + { + results.Add(new ValidationResult($"CIDR {cidr} is invalid: {ex.Message}")); + } + } + + return results; + } + } } /// diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index f35a6485..1f0973b1 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -43,6 +43,7 @@ + -- cgit v1.2.3 From c0a6cf3f2e5e49314d93749194ebf5ca37796b9a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Oct 2022 15:25:03 -0500 Subject: add a command to generate api keys --- src/slskd/Program.cs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 8dbf39ff..2d41ee93 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -207,6 +207,9 @@ namespace slskd [Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")] private static bool GenerateCertificate { get; set; } + [Argument('k', "generate-api-key", "generate a random API key")] + private static bool GenerateApiKey { get; set; } + [Argument('n', "no-logo", "suppress logo on startup")] private static bool NoLogo { get; set; } @@ -263,6 +266,12 @@ namespace slskd return; } + if (GenerateApiKey) + { + Log.Information($"API Key: {Cryptography.Random.GetBytes(32).ToBase62String()}"); + return; + } + // the application isn't being run in command mode. derive the application directory value // and defaults that are dependent upon it AppDirectory ??= DefaultAppDirectory; @@ -945,8 +954,8 @@ namespace slskd var cert = X509.Generate(subject: AppName, password, X509KeyStorageFlags.Exportable); IOFile.WriteAllBytes(filename, cert.Export(X509ContentType.Pkcs12, password)); - Log.Information($"Password: {password}"); Log.Information($"Certificate exported to {filename}"); + Log.Information($"Password: {password}"); } private static void PrintCommandLineArguments(Type targetType) -- cgit v1.2.3 From a83c3829556c2c38b2367433953c7c731beaae95 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Oct 2022 17:21:34 -0500 Subject: add handler --- .../Common/Authentication/ApiKeyAuthentication.cs | 106 +++++++++++++++++++++ src/slskd/Program.cs | 4 + 2 files changed, 110 insertions(+) create mode 100644 src/slskd/Common/Authentication/ApiKeyAuthentication.cs (limited to 'src') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs new file mode 100644 index 00000000..835f3b23 --- /dev/null +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -0,0 +1,106 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as published +// by the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see https://www.gnu.org/licenses/. +// + +using Microsoft.Extensions.Options; + +namespace slskd.Authentication +{ + using System; + using System.Linq; + using System.Security.Principal; + using System.Text.Encodings.Web; + using System.Threading.Tasks; + using Microsoft.AspNetCore.Authentication; + using Microsoft.Extensions.Logging; + using NetTools; + + /// + /// Passthrough authentication. + /// + public static class ApiKeyAuthentication + { + /// + /// Gets the Passthrough authentication scheme name. + /// + public static string AuthenticationScheme { get; } = "API Key"; + } + + /// + /// Handles passthrough authentication. + /// + public class ApiKeyAuthenticationHandler : AuthenticationHandler + { + /// + /// Initializes a new instance of the class. + /// + /// Slskd options monitor. + /// An options monitor. + /// A logger factory. + /// A url encoder. + /// A system clock interface. + public ApiKeyAuthenticationHandler( + IOptionsSnapshot slskdOptionsSnapshot, + IOptionsMonitor apiKeyOptionsMonitor, + ILoggerFactory logger, + UrlEncoder urlEncoder, + ISystemClock systemClock) + : base(apiKeyOptionsMonitor, logger, urlEncoder, systemClock) + { + Console.WriteLine("init"); + SlskdOptionsSnapshot = slskdOptionsSnapshot; + } + + private IOptionsSnapshot SlskdOptionsSnapshot { get; } + + /// + /// Authenticates using the configured and . + /// + /// A successful authentication result containing a default ticket. + protected override async Task HandleAuthenticateAsync() + { + await Task.Yield(); + + if (!Request.Headers.TryGetValue("X-API-Key", out var key)) + { + return AuthenticateResult.NoResult(); + } + + var matchingRecord = SlskdOptionsSnapshot.Value.Web.Authentication.ApiKeys + .FirstOrDefault(kvp => kvp.Value.Key == key); + + if (matchingRecord.Key == null) + { + return AuthenticateResult.Fail(new Exception("The provided API key does not match an existing key")); + } + + var ip = Request.HttpContext.Connection.RemoteIpAddress; + + if (!matchingRecord.Value.Cidr.Split(',') + .Select(cidr => IPAddressRange.Parse(cidr)) + .Any(range => range.Contains(ip))) + { + return AuthenticateResult.Fail(new Exception("The remote IP address is not within the range specified for the key")); + } + + var identity = new GenericIdentity(matchingRecord.Key); + var principal = new GenericPrincipal(identity, new[] { Role.Administrator.ToString() }); + var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), ApiKeyAuthentication.AuthenticationScheme); + + return AuthenticateResult.Success(ticket); + } + } +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 2d41ee93..4d9f6830 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -32,6 +32,7 @@ namespace slskd using System.Text.Json.Serialization; using System.Threading; using System.Threading.Tasks; + using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; @@ -609,6 +610,9 @@ namespace slskd }, }; }); + + services.AddAuthentication(ApiKeyAuthentication.AuthenticationScheme) + .AddScheme(ApiKeyAuthentication.AuthenticationScheme, configureOptions: null); } else { -- cgit v1.2.3 From ccc753b045c1869e4e5146122a2603c44db05945 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 2 Oct 2022 17:37:51 -0500 Subject: add signalr support --- .../Common/Authentication/ApiKeyAuthentication.cs | 61 ++++++++++++++++++---- src/slskd/Program.cs | 8 ++- 2 files changed, 58 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 835f3b23..08cfa3b6 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -27,22 +27,23 @@ namespace slskd.Authentication using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Logging; using NetTools; + using static slskd.Authentication.ApiKeyAuthenticationHandler; /// - /// Passthrough authentication. + /// API key authentication. /// public static class ApiKeyAuthentication { /// - /// Gets the Passthrough authentication scheme name. + /// Gets the API key authentication scheme name. /// public static string AuthenticationScheme { get; } = "API Key"; } /// - /// Handles passthrough authentication. + /// Handles API key authentication. /// - public class ApiKeyAuthenticationHandler : AuthenticationHandler + public class ApiKeyAuthenticationHandler : AuthenticationHandler { /// /// Initializes a new instance of the class. @@ -54,32 +55,44 @@ namespace slskd.Authentication /// A system clock interface. public ApiKeyAuthenticationHandler( IOptionsSnapshot slskdOptionsSnapshot, - IOptionsMonitor apiKeyOptionsMonitor, + IOptionsMonitor apiKeyOptionsMonitor, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock) : base(apiKeyOptionsMonitor, logger, urlEncoder, systemClock) { - Console.WriteLine("init"); SlskdOptionsSnapshot = slskdOptionsSnapshot; } private IOptionsSnapshot SlskdOptionsSnapshot { get; } /// - /// Authenticates using the configured and . + /// Authenticates via API key. /// /// A successful authentication result containing a default ticket. protected override async Task HandleAuthenticateAsync() { await Task.Yield(); - if (!Request.Headers.TryGetValue("X-API-Key", out var key)) + var slskdOptions = SlskdOptionsSnapshot.Value; + var apiKeyOptions = OptionsMonitor.CurrentValue; + + string key = default; + + if (Request.Headers.TryGetValue("X-API-Key", out var headerKeyValue)) + { + key = headerKeyValue; + } + else if (apiKeyOptions.EnableSignalRSupport && Request.Path.StartsWithSegments(apiKeyOptions.SignalRRoutePrefix) && Request.Query.ContainsKey("access_token")) + { + key = Request.Query["access_token"]; + } + else { return AuthenticateResult.NoResult(); } - var matchingRecord = SlskdOptionsSnapshot.Value.Web.Authentication.ApiKeys + var matchingRecord = slskdOptions.Web.Authentication.ApiKeys .FirstOrDefault(kvp => kvp.Value.Key == key); if (matchingRecord.Key == null) @@ -97,10 +110,38 @@ namespace slskd.Authentication } var identity = new GenericIdentity(matchingRecord.Key); - var principal = new GenericPrincipal(identity, new[] { Role.Administrator.ToString() }); + var principal = new GenericPrincipal(identity, new[] { apiKeyOptions.Role.ToString() }); var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), ApiKeyAuthentication.AuthenticationScheme); return AuthenticateResult.Success(ticket); } + + /// + /// API key authentication options. + /// + public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions + { + /// + /// Initializes a new instance of the class. + /// + public ApiKeyAuthenticationOptions() + { + } + + /// + /// Gets or sets the route prefix used to identify SignalR authentication attempts. + /// + public string SignalRRoutePrefix { get; set; } + + /// + /// Gets or sets a value indicating whether to support SignalR authentication. + /// + public bool EnableSignalRSupport { get; set; } + + /// + /// Gets or sets the role for authenticated tickets. + /// + public Role Role { get; set; } = Role.Administrator; + } } } diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 4d9f6830..7b727308 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -70,6 +70,7 @@ namespace slskd using Soulseek; using Utility.CommandLine; using Utility.EnvironmentVariables; + using static slskd.Authentication.ApiKeyAuthenticationHandler; using IOFile = System.IO.File; /// @@ -612,7 +613,12 @@ namespace slskd }); services.AddAuthentication(ApiKeyAuthentication.AuthenticationScheme) - .AddScheme(ApiKeyAuthentication.AuthenticationScheme, configureOptions: null); + .AddScheme(ApiKeyAuthentication.AuthenticationScheme, options => + { + options.EnableSignalRSupport = true; + options.SignalRRoutePrefix = "/hub"; + options.Role = Role.Administrator; + }); } else { -- cgit v1.2.3 From 6f75ffa2ebf07999bd90396ad8ee3b09146d7321 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 3 Oct 2022 07:35:23 -0500 Subject: remove log noise from the API auth handler --- src/slskd/Program.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 7b727308..fd80d649 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -824,6 +824,7 @@ namespace slskd .MinimumLevel.Override("Microsoft", LogEventLevel.Error) .MinimumLevel.Override("System.Net.Http.HttpClient", OptionsAtStartup.Debug ? LogEventLevel.Warning : LogEventLevel.Fatal) .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) + .MinimumLevel.Override("slskd.Authentication.ApiKeyAuthenticationHandler", LogEventLevel.Warning) .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) -- cgit v1.2.3 From 56567464a5955ce6be66769ddec4acea90ac36b5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 3 Oct 2022 07:35:27 -0500 Subject: docs --- docs/config.md | 10 ++++++++++ src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 3 +++ 2 files changed, 13 insertions(+) (limited to 'src') diff --git a/docs/config.md b/docs/config.md index 5ad80033..a4c1c8ee 100644 --- a/docs/config.md +++ b/docs/config.md @@ -558,6 +558,12 @@ By default, a random JWT secret key is generated at each start. It is convenient The JWT TTL option determines how long issued JWTs are valid, defaulting to 7 days. +API keys can be configured to allow for secure communication without requiring the caller to obtain a JWT by signing in with a username and password. Each key must be given a name and a key with a length between 16 and 255 characters (inclusive). Callers may then supply one of the configured keys in the `X-API-Key` header when making web requests. Remember that API keys are secrets, so keep them safe. + +An optional comma separated list of [CIDRs](https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) can be defined for each key, which will restrict usage of the key to callers with a remote IP address that falls within one of the defined CIDRs. The default CIDR list for each key is `0.0.0.0/0,::0`, which applies to any IP address (IPv4 or IPv6). + +A common use case for CIDR filtering might be to restrict API access to clients within your home network. Assuming your network uses the common `192.168.1.x` addressing, you could specify a `cidr` of `192.168.1.0/24`, which would apply to any IP between `192.168.1.1` and `192.168.1.254`, inclusive. + | Command-Line | Environment Variable | Description | | ---------------- | -------------------- | --------------------------------------------------- | | `-X\|--no-auth` | `NO_AUTH` | Determines whether authentication is to be disabled | @@ -576,6 +582,10 @@ web: jwt: key: ~ ttl: 604800000 + api_keys: + my_api_key: + key: + cidr: 0.0.0.0/0,::/0 ``` # Filters diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 08cfa3b6..8baae3f9 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -85,6 +85,9 @@ namespace slskd.Authentication } else if (apiKeyOptions.EnableSignalRSupport && Request.Path.StartsWithSegments(apiKeyOptions.SignalRRoutePrefix) && Request.Query.ContainsKey("access_token")) { + // assign the request token from the access_token query parameter + // but only if the destination is a SignalR hub + // https://docs.microsoft.com/en-us/aspnet/core/signalr/authn-and-authz?view=aspnetcore-5.0 key = Request.Query["access_token"]; } else -- cgit v1.2.3 From a4c644eb2b47b7474f1bd66d3fc942f5ef622d68 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 3 Oct 2022 07:40:57 -0500 Subject: more docs --- src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 8baae3f9..d11e00fb 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -48,7 +48,7 @@ namespace slskd.Authentication /// /// Initializes a new instance of the class. /// - /// Slskd options monitor. + /// The current slskd options snapshot. /// An options monitor. /// A logger factory. /// A url encoder. @@ -69,7 +69,7 @@ namespace slskd.Authentication /// /// Authenticates via API key. /// - /// A successful authentication result containing a default ticket. + /// A successful authentication result containing a ticket for the API key. protected override async Task HandleAuthenticateAsync() { await Task.Yield(); -- cgit v1.2.3