diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-03 07:55:21 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-10-03 07:55:21 -0500 |
| commit | 454c0d5cfd230d27077557c954169ef22e7ffcea (patch) | |
| tree | f58ec0dd82b235c3123926488ff6aefa4d61dd3a /src | |
| parent | 78f7309c6db71581a91189526abf2ef7ad0897ac (diff) | |
| parent | 6028ae895cf9832a3ecce4cabdbd73bd98940b73 (diff) | |
| download | slskd-454c0d5cfd230d27077557c954169ef22e7ffcea.tar.gz | |
Merge pull request #674 from slskd/api-keys
Add the ability to authenticate API calls with an API key
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 150 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 61 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 22 | ||||
| -rw-r--r-- | src/slskd/slskd.csproj | 1 |
4 files changed, 233 insertions, 1 deletions
diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs new file mode 100644 index 00000000..d11e00fb --- /dev/null +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -0,0 +1,150 @@ +// <copyright file="ApiKeyAuthentication.cs" company="slskd Team"> +// 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/. +// </copyright> + +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; + using static slskd.Authentication.ApiKeyAuthenticationHandler; + + /// <summary> + /// API key authentication. + /// </summary> + public static class ApiKeyAuthentication + { + /// <summary> + /// Gets the API key authentication scheme name. + /// </summary> + public static string AuthenticationScheme { get; } = "API Key"; + } + + /// <summary> + /// Handles API key authentication. + /// </summary> + public class ApiKeyAuthenticationHandler : AuthenticationHandler<ApiKeyAuthenticationOptions> + { + /// <summary> + /// Initializes a new instance of the <see cref="ApiKeyAuthenticationHandler"/> class. + /// </summary> + /// <param name="slskdOptionsSnapshot">The current slskd options snapshot.</param> + /// <param name="apiKeyOptionsMonitor">An options monitor.</param> + /// <param name="logger">A logger factory.</param> + /// <param name="urlEncoder">A url encoder.</param> + /// <param name="systemClock">A system clock interface.</param> + public ApiKeyAuthenticationHandler( + IOptionsSnapshot<Options> slskdOptionsSnapshot, + IOptionsMonitor<ApiKeyAuthenticationOptions> apiKeyOptionsMonitor, + ILoggerFactory logger, + UrlEncoder urlEncoder, + ISystemClock systemClock) + : base(apiKeyOptionsMonitor, logger, urlEncoder, systemClock) + { + SlskdOptionsSnapshot = slskdOptionsSnapshot; + } + + private IOptionsSnapshot<Options> SlskdOptionsSnapshot { get; } + + /// <summary> + /// Authenticates via API key. + /// </summary> + /// <returns>A successful authentication result containing a ticket for the API key.</returns> + protected override async Task<AuthenticateResult> HandleAuthenticateAsync() + { + await Task.Yield(); + + 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")) + { + // 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 + { + return AuthenticateResult.NoResult(); + } + + var matchingRecord = slskdOptions.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[] { apiKeyOptions.Role.ToString() }); + var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), ApiKeyAuthentication.AuthenticationScheme); + + return AuthenticateResult.Success(ticket); + } + + /// <summary> + /// API key authentication options. + /// </summary> + public class ApiKeyAuthenticationOptions : AuthenticationSchemeOptions + { + /// <summary> + /// Initializes a new instance of the <see cref="ApiKeyAuthenticationOptions"/> class. + /// </summary> + public ApiKeyAuthenticationOptions() + { + } + + /// <summary> + /// Gets or sets the route prefix used to identify SignalR authentication attempts. + /// </summary> + public string SignalRRoutePrefix { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to support SignalR authentication. + /// </summary> + public bool EnableSignalRSupport { get; set; } + + /// <summary> + /// Gets or sets the role for authenticated tickets. + /// </summary> + public Role Role { get; set; } = Role.Administrator; + } + } +} 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; @@ -127,6 +128,16 @@ namespace slskd public bool GenerateCertificate { get; init; } = false; /// <summary> + /// Gets a value indicating whether to generate a random API key. + /// </summary> + [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; + + /// <summary> /// Gets a value indicating whether the application should run in debug mode. /// </summary> [Argument('d', "debug")] @@ -1215,6 +1226,12 @@ namespace slskd public JwtOptions Jwt { get; init; } = new JwtOptions(); /// <summary> + /// Gets API keys. + /// </summary> + [Validate] + public Dictionary<string, ApiKeyOptions> ApiKeys { get; init; } = new Dictionary<string, ApiKeyOptions>(); + + /// <summary> /// JWT options. /// </summary> public class JwtOptions @@ -1240,6 +1257,50 @@ namespace slskd [RequiresRestart] public int Ttl { get; init; } = 604800000; } + + /// <summary> + /// API key options. + /// </summary> + public class ApiKeyOptions : IValidatableObject + { + /// <summary> + /// Gets the API key value. + /// </summary> + [Description("API key value")] + [StringLength(255, MinimumLength = 16)] + [Secret] + public string Key { get; init; } + + /// <summary> + /// Gets the comma separated list of CIDRs that are authorized to use the key. + /// </summary> + [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"; + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + 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; + } + } } /// <summary> diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 8dbf39ff..fd80d649 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; @@ -69,6 +70,7 @@ namespace slskd using Soulseek; using Utility.CommandLine; using Utility.EnvironmentVariables; + using static slskd.Authentication.ApiKeyAuthenticationHandler; using IOFile = System.IO.File; /// <summary> @@ -207,6 +209,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 +268,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; @@ -600,6 +611,14 @@ namespace slskd }, }; }); + + services.AddAuthentication(ApiKeyAuthentication.AuthenticationScheme) + .AddScheme<ApiKeyAuthenticationOptions, ApiKeyAuthenticationHandler>(ApiKeyAuthentication.AuthenticationScheme, options => + { + options.EnableSignalRSupport = true; + options.SignalRRoutePrefix = "/hub"; + options.Role = Role.Administrator; + }); } else { @@ -805,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) @@ -945,8 +965,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) 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 @@ <ItemGroup> <PackageReference Include="FluentFTP" Version="39.0.1" /> + <PackageReference Include="IPAddressRange" Version="4.2.0" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.7" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.0.0" /> <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="6.0.0"> |
