diff options
| author | JP Dillingham <jp@dillingham.me> | 2022-10-30 18:50:33 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2022-10-30 18:50:33 -0500 |
| commit | ea845d19fd3bf1acca08f1062526d1cfe90716f9 (patch) | |
| tree | 238f9ebc9215dddb0517b2311372ce25f17aff85 /src/slskd/Common | |
| parent | 5c19d4fd6a7eb98d83a5f8c7e2c3092cb2b3b62a (diff) | |
| parent | 093763beaea0f891410f83febea67b22005bd406 (diff) | |
| download | slskd-ea845d19fd3bf1acca08f1062526d1cfe90716f9.tar.gz | |
Merge pull request #717 from slskd/tls
Rework API authentication
Diffstat (limited to 'src/slskd/Common')
| -rw-r--r-- | src/slskd/Common/Authentication/ApiKeyAuthentication.cs | 75 | ||||
| -rw-r--r-- | src/slskd/Common/Authentication/Role.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Common/CommonExtensions.cs | 9 | ||||
| -rw-r--r-- | src/slskd/Common/Exceptions/OutOfRangeException.cs | 72 |
4 files changed, 96 insertions, 62 deletions
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; /// <summary> /// API key authentication. @@ -47,23 +45,23 @@ namespace slskd.Authentication /// <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="securityService">The security service.</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, + ISecurityService securityService, ILoggerFactory logger, UrlEncoder urlEncoder, ISystemClock systemClock) : base(apiKeyOptionsMonitor, logger, urlEncoder, systemClock) { - SlskdOptionsSnapshot = slskdOptionsSnapshot; + Security = securityService; } - private IOptionsSnapshot<Options> SlskdOptionsSnapshot { get; } + private ISecurityService Security { get; } /// <summary> /// 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 /// </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/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/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; @@ -178,6 +179,14 @@ namespace slskd } /// <summary> + /// Serializes the JWT. + /// </summary> + /// <param name="jwt">The JWT.</param> + /// <returns>The serialized string.</returns> + public static string Serialize(this JwtSecurityToken jwt) + => new JwtSecurityTokenHandler().WriteToken(jwt); + + /// <summary> /// Formats byte to nearest size (KB, MB, etc.) /// </summary> /// <param name="value">The value to format.</param> 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 file="OutOfRangeException.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> + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Runtime.Serialization; + + /// <summary> + /// Represents errors that originate when a value falls out of an expected range. + /// </summary> + [ExcludeFromCodeCoverage] + [Serializable] + public class OutOfRangeException : SlskdException + { + /// <summary> + /// Initializes a new instance of the <see cref="OutOfRangeException"/> class. + /// </summary> + public OutOfRangeException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="OutOfRangeException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public OutOfRangeException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="OutOfRangeException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public OutOfRangeException(string message, Exception innerException) + : base(message, innerException) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="OutOfRangeException"/> class with serialized data. + /// </summary> + /// <param name="info">The SerializationInfo that holds the serialized object data about the exception being thrown.</param> + /// <param name="context">The StreamingContext that contains contextual information about the source or destination.</param> + protected OutOfRangeException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + } +}
\ No newline at end of file |
