From f585c9c63c7d97a751a0f8d4658696053c3d0262 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 13:31:54 -0500 Subject: add api key --- src/slskd/Application.cs | 2 +- src/slskd/Core/Options.cs | 18 +++++++++++++++--- src/slskd/Network/NetworkClient.cs | 20 +++++++++++++++++--- 3 files changed, 33 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index b38a97af..35da10f6 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -396,7 +396,7 @@ namespace slskd { Log.Warning($"Not connecting to the Soulseek server; username and/or password invalid. Specify valid credentials and manually connect, or update config and restart."); } - else if (OptionsAtStartup.Network.OperationMode.ToEnum() == OperationMode.Agent && !OptionsAtStartup.Flags.DualNetworkMode) + else if (OptionsAtStartup.Network.Mode.ToEnum() == OperationMode.Agent && !OptionsAtStartup.Flags.DualNetworkMode) { Log.Information("Running in Agent mode; not connecting to the Soulseek server."); await NetworkClient.StartAsync(cancellationToken); diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f4ca99e5..765ba6e9 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -296,7 +296,7 @@ namespace slskd { var results = new List(); - if (InstanceName == "local" && Network.OperationMode.ToEnum() == OperationMode.Agent) + if (InstanceName == "local" && Network.Mode.ToEnum() == OperationMode.Agent) { results.Add(new ValidationResult("Instance name must be something other than 'local' when operating in Network Agent mode")); } @@ -395,7 +395,7 @@ namespace slskd [Description("network operation mode; controller, agent")] [RequiresRestart] [Enum(typeof(OperationMode))] - public string OperationMode { get; init; } = slskd.Network.OperationMode.Controller.ToString().ToLowerInvariant(); + public string Mode { get; init; } = slskd.Network.OperationMode.Controller.ToString().ToLowerInvariant(); /// /// Gets the controller configuration. @@ -409,7 +409,7 @@ namespace slskd public IEnumerable Validate(ValidationContext validationContext) { - var mode = OperationMode.ToEnum(); + var mode = Mode.ToEnum(); var results = new List(); var modeResults = new List(); @@ -460,11 +460,23 @@ namespace slskd [Description("ignore controller certificate errors")] public bool IgnoreCertificateErrors { get; init; } = false; + /// + /// Gets the controller API key. + /// + [Argument(default, "controller-api-key")] + [EnvironmentVariable("CONTROLLER_API_KEY")] + [Description("controller api key")] + [StringLength(255, MinimumLength = 16)] + [NotNullOrWhiteSpace] + [Secret] + public string ApiKey { get; init; } + /// /// Gets the controller secret. /// [Argument(default, "controller-secret")] [EnvironmentVariable("CONTROLLER_SECRET")] + [Description("shared secret")] [StringLength(255, MinimumLength = 16)] [NotNullOrWhiteSpace] [Secret] diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index e0aec505..4ef86e27 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -93,7 +93,7 @@ namespace slskd.Network /// public async Task StartAsync(CancellationToken cancellationToken = default) { - if (OptionsMonitor.CurrentValue.Network.OperationMode.ToEnum() != OperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) + if (OptionsMonitor.CurrentValue.Network.Mode.ToEnum() != OperationMode.Agent && !OptionsMonitor.CurrentValue.Flags.DualNetworkMode) { throw new InvalidOperationException($"Network client can only be started when operation mode is {OperationMode.Agent}"); } @@ -328,7 +328,7 @@ namespace slskd.Network private void Configure(Options options) { - if (options.Network.OperationMode.ToEnum() != OperationMode.Agent && !options.Flags.DualNetworkMode) + if (options.Network.Mode.ToEnum() != OperationMode.Agent && !options.Flags.DualNetworkMode) { return; } @@ -352,7 +352,21 @@ namespace slskd.Network StartCancellationTokenSource?.Cancel(); HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Network.Controller.Address}/hub/agents") + .WithUrl($"{options.Network.Controller.Address}/hub/agents", builder => + { + builder.AccessTokenProvider = () => Task.FromResult(options.Network.Controller.ApiKey); + // options.HttpMessageHandlerFactory = (message) => + // { + // if (message is HttpClientHandler clientHandler) + // { + // // always verify the SSL certificate + // clientHandler.ServerCertificateCustomValidationCallback += + // (sender, certificate, chain, sslPolicyErrors) => true; + // } + + // return message; + // }; + }) .WithAutomaticReconnect(new[] { TimeSpan.FromSeconds(0), -- cgit v1.2.3 From db830fba26dbef2720a786c88ec30fc1df4fc714 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 15:16:26 -0500 Subject: add OutOfRangeException --- src/slskd/Common/Exceptions/OutOfRangeException.cs | 72 ++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/slskd/Common/Exceptions/OutOfRangeException.cs (limited to 'src') diff --git a/src/slskd/Common/Exceptions/OutOfRangeException.cs b/src/slskd/Common/Exceptions/OutOfRangeException.cs new file mode 100644 index 00000000..7de8cc7b --- /dev/null +++ b/src/slskd/Common/Exceptions/OutOfRangeException.cs @@ -0,0 +1,72 @@ +// +// 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/. +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// + /// Represents errors that originate when a value falls out of an expected range. + /// + [ExcludeFromCodeCoverage] + [Serializable] + public class OutOfRangeException : SlskdException + { + /// + /// Initializes a new instance of the class. + /// + public OutOfRangeException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public OutOfRangeException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public OutOfRangeException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// + /// Initializes a new instance of the class with serialized data. + /// + /// The SerializationInfo that holds the serialized object data about the exception being thrown. + /// The StreamingContext that contains contextual information about the source or destination. + protected OutOfRangeException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +} \ No newline at end of file -- cgit v1.2.3 From 8d1ae7b3357cc7d10b86940d98b22d072bbdbe8c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 15:18:31 -0500 Subject: add Role to API key options --- config/slskd.example.yml | 1 + src/slskd/Core/Options.cs | 8 ++++++++ 2 files changed, 9 insertions(+) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 5939fb58..10c59288 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -97,6 +97,7 @@ # api_keys: # my_api_key: # key: +# role: readonly # readonly, readwrite, administrator # cidr: 0.0.0.0/0,::/0 # logger: # loki: ~ diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 765ba6e9..a1591923 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -29,6 +29,7 @@ namespace slskd using System.Text.RegularExpressions; using FluentFTP; using NetTools; + using slskd.Authentication; using slskd.Configuration; using slskd.Cryptography; using slskd.Network; @@ -1423,6 +1424,13 @@ namespace slskd [Secret] public string Key { get; init; } + /// + /// Gets the role for the key. + /// + [Description("user role for the key; readonly, readwrite, administrator")] + [Enum(typeof(Role))] + public string Role { get; init; } = slskd.Authentication.Role.ReadOnly.ToString(); + /// /// Gets the comma separated list of CIDRs that are authorized to use the key. /// -- cgit v1.2.3 From c6b23c8d082a9ead282a622940ffd904865677bf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 15:25:06 -0500 Subject: add security service, move security stuff --- .../Common/Authentication/ApiKeyAuthentication.cs | 75 +++------------- src/slskd/Common/Authentication/Role.cs | 2 +- .../Core/API/Controllers/SessionController.cs | 41 ++------- src/slskd/Core/Security/SecurityService.cs | 100 +++++++++++++++++++++ 4 files changed, 120 insertions(+), 98 deletions(-) create mode 100644 src/slskd/Core/Security/SecurityService.cs (limited to 'src') diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 9225b5a8..a41a9d59 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -20,13 +20,11 @@ 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; /// /// API key authentication. @@ -47,23 +45,23 @@ namespace slskd.Authentication /// /// Initializes a new instance of the class. /// - /// The current slskd options snapshot. /// An options monitor. + /// The security service. /// A logger factory. /// A url encoder. /// A system clock interface. public ApiKeyAuthenticationHandler( - IOptionsSnapshot slskdOptionsSnapshot, IOptionsMonitor apiKeyOptionsMonitor, + ISecurityService securityService, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock) : base(apiKeyOptionsMonitor, logger, urlEncoder, systemClock) { - SlskdOptionsSnapshot = slskdOptionsSnapshot; + Security = securityService; } - private IOptionsSnapshot SlskdOptionsSnapshot { get; } + private ISecurityService Security { get; } /// /// Authenticates via API key. @@ -73,49 +71,25 @@ namespace slskd.Authentication { 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 + if (!Request.Headers.TryGetValue("X-API-Key", out var headerKeyValue)) { return AuthenticateResult.NoResult(); } - var matchingRecord = slskdOptions.Web.Authentication.ApiKeys - .FirstOrDefault(kvp => kvp.Value.Key == key); - - if (matchingRecord.Key == null) + try { - return AuthenticateResult.Fail(new Exception("The provided API key does not match an existing key")); - } + var key = Security.AuthenticateWithApiKey(headerKeyValue, Request.HttpContext.Connection.RemoteIpAddress); - var ip = Request.HttpContext.Connection.RemoteIpAddress; + var identity = new GenericIdentity(key.Name); + var principal = new GenericPrincipal(identity, new[] { key.Role.ToString() }); + var ticket = new AuthenticationTicket(principal, new AuthenticationProperties(), ApiKeyAuthentication.AuthenticationScheme); - if (!matchingRecord.Value.Cidr.Split(',') - .Select(cidr => IPAddressRange.Parse(cidr)) - .Any(range => range.Contains(ip))) + return AuthenticateResult.Success(ticket); + } + catch (Exception ex) { - return AuthenticateResult.Fail(new Exception("The remote IP address is not within the range specified for the key")); + return AuthenticateResult.Fail(ex); } - - 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); } } @@ -124,26 +98,5 @@ namespace slskd.Authentication /// 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/Common/Authentication/Role.cs b/src/slskd/Common/Authentication/Role.cs index c6c64a7c..2f88283c 100644 --- a/src/slskd/Common/Authentication/Role.cs +++ b/src/slskd/Common/Authentication/Role.cs @@ -20,7 +20,7 @@ namespace slskd.Authentication public enum Role { ReadOnly = 0, - User = 1, + ReadWrite = 1, Administrator = 2, } } diff --git a/src/slskd/Core/API/Controllers/SessionController.cs b/src/slskd/Core/API/Controllers/SessionController.cs index 65a43e72..2aa26c27 100644 --- a/src/slskd/Core/API/Controllers/SessionController.cs +++ b/src/slskd/Core/API/Controllers/SessionController.cs @@ -19,13 +19,8 @@ using Microsoft.Extensions.Options; namespace slskd.Core.API { - using System; - using System.Collections.Generic; - using System.IdentityModel.Tokens.Jwt; - using System.Security.Claims; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; - using Microsoft.IdentityModel.Tokens; using slskd.Authentication; /// @@ -39,18 +34,18 @@ namespace slskd.Core.API public class SessionController : ControllerBase { public SessionController( + ISecurityService securityService, IOptionsSnapshot optionsSnapshot, - OptionsAtStartup optionsAtStartup, - SymmetricSecurityKey jwtSigningKey) + OptionsAtStartup optionsAtStartup) { + Security = securityService; OptionsSnapshot = optionsSnapshot; OptionsAtStartup = optionsAtStartup; - JwtSigningKey = jwtSigningKey; } - private SymmetricSecurityKey JwtSigningKey { get; set; } private IOptionsSnapshot OptionsSnapshot { get; set; } private OptionsAtStartup OptionsAtStartup { get; set; } + private ISecurityService Security { get; } /// /// Checks whether the provided authentication is valid. @@ -113,36 +108,10 @@ namespace slskd.Core.API // only admin login for now if (OptionsSnapshot.Value.Web.Authentication.Username == login.Username && OptionsSnapshot.Value.Web.Authentication.Password == login.Password) { - return Ok(new TokenResponse(GetJwtSecurityToken(login.Username, Role.Administrator))); + return Ok(new TokenResponse(Security.GenerateJwt(login.Username, Role.Administrator))); } return Unauthorized(); } - - private JwtSecurityToken GetJwtSecurityToken(string username, Role role) - { - var issuedUtc = DateTime.UtcNow; - var expiresUtc = DateTime.UtcNow.AddMilliseconds(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; - } } } \ No newline at end of file diff --git a/src/slskd/Core/Security/SecurityService.cs b/src/slskd/Core/Security/SecurityService.cs new file mode 100644 index 00000000..6da88571 --- /dev/null +++ b/src/slskd/Core/Security/SecurityService.cs @@ -0,0 +1,100 @@ +// +// 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 +{ + 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 + { + JwtSecurityToken GenerateJwt(string username, Role role, int? ttl = null); + (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress); + } + + public class SecurityService : ISecurityService + { + public SecurityService( + SymmetricSecurityKey jwtSigningKey, + OptionsAtStartup optionsAtStartup, + IOptionsMonitor optionsMonitor) + { + JwtSigningKey = jwtSigningKey; + OptionsAtStartup = optionsAtStartup; + OptionsMonitor = optionsMonitor; + } + + private SymmetricSecurityKey JwtSigningKey { get; } + private OptionsAtStartup OptionsAtStartup { get; } + private IOptionsMonitor OptionsMonitor { get; } + + public (string Name, Role Role) AuthenticateWithApiKey(string key, IPAddress callerIpAddress) + { + var record = OptionsMonitor.CurrentValue.Web.Authentication.ApiKeys + .FirstOrDefault(k => k.Value.Key == key); + + if (record.Key == null) + { + throw new NotFoundException($"The provided API key does not match an existing key"); + } + + 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"); + } + + 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 70d99495146fed87fad93aae593acf0ee686f9b9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 17:34:46 -0500 Subject: add policies to network endpoints --- src/slskd/Network/API/Controllers/NetworkController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/API/Controllers/NetworkController.cs b/src/slskd/Network/API/Controllers/NetworkController.cs index 276cdcd0..d5e53563 100644 --- a/src/slskd/Network/API/Controllers/NetworkController.cs +++ b/src/slskd/Network/API/Controllers/NetworkController.cs @@ -56,7 +56,7 @@ namespace slskd.Network [RequestSizeLimit(10L * 1024L * 1024L * 1024L)] [RequestFormLimits(MultipartBodyLengthLimit = 10L * 1024L * 1024L * 1024L)] [DisableFormValueModelBinding] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task UploadFile(string token) { if (!Guid.TryParse(token, out var guid)) @@ -140,7 +140,7 @@ namespace slskd.Network /// The unique identifier for the request. /// [HttpPost("shares/{token}")] - [Authorize] + [Authorize(Policy = AuthPolicy.Any)] public async Task UploadShares(string token) { if (!Guid.TryParse(token, out var guid)) -- cgit v1.2.3 From dda92d4efc1c4b6d83a5a2a2a1fe637f6d83f58f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 17:39:39 -0500 Subject: fix signalR api key support --- src/slskd/Common/CommonExtensions.cs | 9 +++++++++ src/slskd/Program.cs | 38 ++++++++++++++++++++++++------------ 2 files changed, 35 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 9cf80a4a..29383fcb 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -20,6 +20,7 @@ namespace slskd using System; using System.Collections; using System.Collections.Generic; + using System.IdentityModel.Tokens.Jwt; using System.IO; using System.Linq; using System.Numerics; @@ -177,6 +178,14 @@ namespace slskd return str.Substring(0, pos) + replacement + str.Substring(pos + phrase.Length); } + /// + /// Serializes the JWT. + /// + /// The JWT. + /// The serialized string. + public static string Serialize(this JwtSecurityToken jwt) + => new JwtSecurityTokenHandler().WriteToken(jwt); + /// /// Formats byte to nearest size (KB, MB, etc.) /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index ea0b382f..eefbe8c6 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -584,11 +584,12 @@ namespace slskd using var runtimeMetrics = DotNetRuntimeStatsBuilder.Default().StartCollecting(); services.AddDataProtection() - .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, ".DataProtection-Keys"))); + .PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(DataDirectory, "misc", ".DataProtection-Keys"))); var jwtSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(OptionsAtStartup.Web.Authentication.Jwt.Key)); services.AddSingleton(jwtSigningKey); + services.AddSingleton(); if (!OptionsAtStartup.Web.Authentication.Disabled) { @@ -596,6 +597,7 @@ namespace slskd { options.AddPolicy(AuthPolicy.JwtOnly, policy => { + policy.RequireRole(Role.Administrator.ToString()); policy.AuthenticationSchemes.Add(JwtBearerDefaults.AuthenticationScheme); policy.RequireAuthenticatedUser(); }); @@ -628,24 +630,36 @@ namespace slskd { OnMessageReceived = context => { - // 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 - if (context.HttpContext.Request.Path.StartsWithSegments("/hub")) + // signalr authentication is stupid + if (context.Request.Path.StartsWithSegments("/hub")) { - context.Token = context.Request.Query["access_token"]; + // some clients (like the one used for agents) provide the token in a header + // in this case it'll be an API key, presented as a bearer token + if (context.Request.Headers.ContainsKey("Authorization")) + { + var key = context.Request.Headers["Authorization"].ToString().Split(' ')?[1]; + + // derive the key name and role from the key value + var service = services.BuildServiceProvider().GetRequiredService(); + var (name, role) = service.AuthenticateWithApiKey(key, callerIpAddress: context.HttpContext.Connection.RemoteIpAddress); + + // create a new, short lived jwt for the key name and role + context.Token = service.GenerateJwt(name, role, ttl: 1000).Serialize(); + } + else if (context.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 + context.Token = context.Request.Query["access_token"]; + } } return Task.CompletedTask; }, }; }) - .AddScheme(ApiKeyAuthentication.AuthenticationScheme, options => - { - options.EnableSignalRSupport = true; - options.SignalRRoutePrefix = "/hub"; - options.Role = Role.Administrator; - }); + .AddScheme(ApiKeyAuthentication.AuthenticationScheme, (_) => { }); } else { -- cgit v1.2.3 From 8fdf5d8ec920d4ac6f9460a0491cd91c4532e43a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 17:40:35 -0500 Subject: use API key for network calls --- src/slskd/Network/NetworkClient.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 4ef86e27..6ad3928c 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -176,6 +176,7 @@ namespace slskd.Network { new StreamContent(stream), "database", "shares" }, }; + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Network.Controller.ApiKey); request.Content = content; Log.Information("Beginning upload of shares"); @@ -228,6 +229,7 @@ namespace slskd.Network { new StreamContent(stream), "file", filename }, }; + request.Headers.Add("X-API-Key", OptionsMonitor.CurrentValue.Network.Controller.ApiKey); request.Content = content; Log.Information("Beginning upload of file {Filename} with ID {Id}", filename, token); -- cgit v1.2.3 From f0cd9675a9e6857fbbdc8381b057730c7038d4e2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 18:29:29 -0500 Subject: ignore signalr ssl errors --- src/slskd/Network/NetworkClient.cs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 6ad3928c..704531ac 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -357,17 +357,15 @@ namespace slskd.Network .WithUrl($"{options.Network.Controller.Address}/hub/agents", builder => { builder.AccessTokenProvider = () => Task.FromResult(options.Network.Controller.ApiKey); - // options.HttpMessageHandlerFactory = (message) => - // { - // if (message is HttpClientHandler clientHandler) - // { - // // always verify the SSL certificate - // clientHandler.ServerCertificateCustomValidationCallback += - // (sender, certificate, chain, sslPolicyErrors) => true; - // } - - // return message; - // }; + builder.HttpMessageHandlerFactory = (message) => + { + if (message is HttpClientHandler clientHandler && options.Network.Controller.IgnoreCertificateErrors) + { + clientHandler.ServerCertificateCustomValidationCallback += (_, _, _, _) => true; + } + + return message; + }; }) .WithAutomaticReconnect(new[] { -- cgit v1.2.3 From 093763beaea0f891410f83febea67b22005bd406 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 30 Oct 2022 18:37:07 -0500 Subject: optionally ignore cert errors in http requests --- src/slskd/Network/NetworkClient.cs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Network/NetworkClient.cs b/src/slskd/Network/NetworkClient.cs index 704531ac..30aced62 100644 --- a/src/slskd/Network/NetworkClient.cs +++ b/src/slskd/Network/NetworkClient.cs @@ -322,9 +322,24 @@ namespace slskd.Network private HttpClient CreateHttpClient() { - var client = new HttpClient(); + var options = OptionsMonitor.CurrentValue.Network.Controller; + HttpClient client; + + if (options.IgnoreCertificateErrors) + { + client = new HttpClient(new HttpClientHandler() + { + ClientCertificateOptions = ClientCertificateOption.Manual, + ServerCertificateCustomValidationCallback = (_, _, _, _) => true, + }); + } + else + { + client = new HttpClient(); + } + client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue); - client.BaseAddress = new(OptionsMonitor.CurrentValue.Network.Controller.Address); + client.BaseAddress = new(options.Address); return client; } -- cgit v1.2.3