aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Core
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-10-30 18:50:33 -0500
committerGitHub <noreply@github.com>2022-10-30 18:50:33 -0500
commitea845d19fd3bf1acca08f1062526d1cfe90716f9 (patch)
tree238f9ebc9215dddb0517b2311372ce25f17aff85 /src/slskd/Core
parent5c19d4fd6a7eb98d83a5f8c7e2c3092cb2b3b62a (diff)
parent093763beaea0f891410f83febea67b22005bd406 (diff)
downloadslskd-ea845d19fd3bf1acca08f1062526d1cfe90716f9.tar.gz
Merge pull request #717 from slskd/tls
Rework API authentication
Diffstat (limited to 'src/slskd/Core')
-rw-r--r--src/slskd/Core/API/Controllers/SessionController.cs41
-rw-r--r--src/slskd/Core/Options.cs26
-rw-r--r--src/slskd/Core/Security/SecurityService.cs100
3 files changed, 128 insertions, 39 deletions
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;
/// <summary>
@@ -39,18 +34,18 @@ namespace slskd.Core.API
public class SessionController : ControllerBase
{
public SessionController(
+ ISecurityService securityService,
IOptionsSnapshot<Options> optionsSnapshot,
- OptionsAtStartup optionsAtStartup,
- SymmetricSecurityKey jwtSigningKey)
+ OptionsAtStartup optionsAtStartup)
{
+ Security = securityService;
OptionsSnapshot = optionsSnapshot;
OptionsAtStartup = optionsAtStartup;
- JwtSigningKey = jwtSigningKey;
}
- private SymmetricSecurityKey JwtSigningKey { get; set; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; set; }
private OptionsAtStartup OptionsAtStartup { get; set; }
+ private ISecurityService Security { get; }
/// <summary>
/// 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<Claim>()
- {
- 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/Options.cs b/src/slskd/Core/Options.cs
index f4ca99e5..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;
@@ -296,7 +297,7 @@ namespace slskd
{
var results = new List<ValidationResult>();
- if (InstanceName == "local" && Network.OperationMode.ToEnum<OperationMode>() == OperationMode.Agent)
+ if (InstanceName == "local" && Network.Mode.ToEnum<OperationMode>() == OperationMode.Agent)
{
results.Add(new ValidationResult("Instance name must be something other than 'local' when operating in Network Agent mode"));
}
@@ -395,7 +396,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();
/// <summary>
/// Gets the controller configuration.
@@ -409,7 +410,7 @@ namespace slskd
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
- var mode = OperationMode.ToEnum<OperationMode>();
+ var mode = Mode.ToEnum<OperationMode>();
var results = new List<ValidationResult>();
var modeResults = new List<ValidationResult>();
@@ -461,10 +462,22 @@ namespace slskd
public bool IgnoreCertificateErrors { get; init; } = false;
/// <summary>
+ /// Gets the controller API key.
+ /// </summary>
+ [Argument(default, "controller-api-key")]
+ [EnvironmentVariable("CONTROLLER_API_KEY")]
+ [Description("controller api key")]
+ [StringLength(255, MinimumLength = 16)]
+ [NotNullOrWhiteSpace]
+ [Secret]
+ public string ApiKey { get; init; }
+
+ /// <summary>
/// Gets the controller secret.
/// </summary>
[Argument(default, "controller-secret")]
[EnvironmentVariable("CONTROLLER_SECRET")]
+ [Description("shared secret")]
[StringLength(255, MinimumLength = 16)]
[NotNullOrWhiteSpace]
[Secret]
@@ -1412,6 +1425,13 @@ namespace slskd
public string Key { get; init; }
/// <summary>
+ /// Gets the role for the key.
+ /// </summary>
+ [Description("user role for the key; readonly, readwrite, administrator")]
+ [Enum(typeof(Role))]
+ public string Role { get; init; } = slskd.Authentication.Role.ReadOnly.ToString();
+
+ /// <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")]
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 file="SecurityService.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
+{
+ 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<Options> optionsMonitor)
+ {
+ JwtSigningKey = jwtSigningKey;
+ OptionsAtStartup = optionsAtStartup;
+ OptionsMonitor = optionsMonitor;
+ }
+
+ private SymmetricSecurityKey JwtSigningKey { get; }
+ private OptionsAtStartup OptionsAtStartup { get; }
+ private IOptionsMonitor<Options> 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<Role>());
+ }
+
+ 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<Claim>()
+ {
+ 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;
+ }
+ }
+}