// // 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; using static slskd.Authentication.ApiKeyAuthenticationHandler; /// /// API key authentication. /// public static class ApiKeyAuthentication { /// /// Gets the API key authentication scheme name. /// public static string AuthenticationScheme { get; } = "API Key"; } /// /// Handles API key authentication. /// public class ApiKeyAuthenticationHandler : AuthenticationHandler { /// /// Initializes a new instance of the class. /// /// The current slskd options snapshot. /// 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) { SlskdOptionsSnapshot = slskdOptionsSnapshot; } private IOptionsSnapshot SlskdOptionsSnapshot { get; } /// /// Authenticates via API key. /// /// A successful authentication result containing a ticket for the API key. protected override async Task 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); } /// /// 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; } } }