aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Application.cs11
-rw-r--r--src/slskd/Core/Options.cs13
-rw-r--r--src/slskd/Messaging/API/Controllers/ConversationsController.cs10
-rw-r--r--src/slskd/Transfers/API/Controllers/TransfersController.cs18
-rw-r--r--src/slskd/Users/API/Controllers/UsersController.cs25
-rw-r--r--src/slskd/Users/IUserService.cs3
-rw-r--r--src/slskd/Users/Types/User.cs3
-rw-r--r--src/slskd/Users/UserService.cs134
8 files changed, 192 insertions, 25 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs
index 86dd9dd1..e36a5539 100644
--- a/src/slskd/Application.cs
+++ b/src/slskd/Application.cs
@@ -94,6 +94,7 @@ namespace slskd
/// <summary>
/// The name of the blacklisted user group.
/// </summary>
+ [Obsolete("use IsBlacklisted instead")]
public const string BlacklistedGroup = "blacklisted";
private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down";
@@ -1380,6 +1381,12 @@ namespace slskd
private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename)
{
+ if (Users.IsBlacklisted(username, endpoint.Address))
+ {
+ Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
+ return Task.FromResult<int?>(null);
+ }
+
try
{
var place = Transfers.Uploads.Queue.EstimatePosition(username, filename);
@@ -1651,7 +1658,9 @@ namespace slskd
var sw = new Stopwatch();
sw.Start();
- if (Users.IsBlacklisted(username))
+ // opportunistically try and avoid performing the search if we have a cached blacklisted value, otherwise
+ // hold off on computing it and filling the cache until we have the user's IP
+ if (Users.IsBlacklisted(username, bypassCache: false))
{
return null;
}
diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs
index 7b38143e..fcc65c3b 100644
--- a/src/slskd/Core/Options.cs
+++ b/src/slskd/Core/Options.cs
@@ -1150,6 +1150,11 @@ namespace slskd
public string[] Members { get; init; } = Array.Empty<string>();
/// <summary>
+ /// Gets the list of regular expression patterns matched against usernames.
+ /// </summary>
+ public string[] Patterns { get; init; } = Array.Empty<string>();
+
+ /// <summary>
/// Gets the list of group CIDRs.
/// </summary>
public string[] Cidrs { get; init; } = Array.Empty<string>();
@@ -1163,6 +1168,14 @@ namespace slskd
{
var results = new List<ValidationResult>();
+ foreach (var pattern in Patterns ?? Array.Empty<string>())
+ {
+ if (!pattern.IsValidRegex())
+ {
+ results.Add(new ValidationResult($"Pattern '{pattern}' is not a valid regular expression"));
+ }
+ }
+
foreach (var cidr in Cidrs ?? Array.Empty<string>())
{
try
diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs
index c60d0c2f..7ed0a92c 100644
--- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs
+++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs
@@ -40,6 +40,7 @@ namespace slskd.Messaging.API
using Asp.Versioning;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
+ using slskd.Users;
/// <summary>
/// Conversations.
@@ -56,19 +57,23 @@ namespace slskd.Messaging.API
/// </summary>
/// <param name="applicationStateMonitor"></param>
/// <param name="messagingService"></param>
+ /// <param name="userService"></param>
/// <param name="optionsSnapshot"></param>
public ConversationsController(
IStateMonitor<State> applicationStateMonitor,
IMessagingService messagingService,
+ IUserService userService,
IOptionsSnapshot<Options> optionsSnapshot)
{
ApplicationStateMonitor = applicationStateMonitor;
Messages = messagingService;
+ Users = userService;
OptionsSnapshot = optionsSnapshot;
}
private IStateMonitor<State> ApplicationStateMonitor { get; }
private IMessagingService Messages { get; }
+ private IUserService Users { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
/// <summary>
@@ -264,6 +269,11 @@ namespace slskd.Messaging.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return StatusCode(200);
+ }
+
if (string.IsNullOrEmpty(message))
{
return BadRequest();
diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs
index 2ffd50d4..494ee722 100644
--- a/src/slskd/Transfers/API/Controllers/TransfersController.cs
+++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs
@@ -44,6 +44,8 @@ namespace slskd.Transfers.API
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Serilog;
+ using slskd.Users;
+ using Soulseek;
/// <summary>
/// Transfers.
@@ -58,17 +60,21 @@ namespace slskd.Transfers.API
/// Initializes a new instance of the <see cref="TransfersController"/> class.
/// </summary>
/// <param name="optionsSnapshot"></param>
+ /// <param name="userService"></param>
/// <param name="transferService"></param>
public TransfersController(
ITransferService transferService,
+ IUserService userService,
IOptionsSnapshot<Options> optionsSnapshot)
{
Transfers = transferService;
+ Users = userService;
OptionsSnapshot = optionsSnapshot;
}
private static SemaphoreSlim DownloadRequestLimiter { get; } = new SemaphoreSlim(2, 2);
private ITransferService Transfers { get; }
+ private IUserService Users { get; }
private IOptionsSnapshot<Options> OptionsSnapshot { get; }
private ILogger Log { get; set; } = Serilog.Log.ForContext<TransfersController>();
@@ -253,6 +259,13 @@ namespace slskd.Transfers.API
try
{
+ var endpoint = await Users.GetIPEndPointAsync(username);
+
+ if (Users.IsBlacklisted(username, endpoint.Address))
+ {
+ throw new UserOfflineException($"User {username} appears to be offline");
+ }
+
var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(username, requests.Select(r => (r.Filename, r.Size)));
return StatusCode(201, new { Enqueued = enqueued, Failed = failed });
@@ -382,6 +395,11 @@ namespace slskd.Transfers.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
if (!Guid.TryParse(id, out var guid))
{
return BadRequest();
diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs
index 2a6f535f..8029b5e0 100644
--- a/src/slskd/Users/API/Controllers/UsersController.cs
+++ b/src/slskd/Users/API/Controllers/UsersController.cs
@@ -93,6 +93,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var endpoint = await Users.GetIPEndPointAsync(username);
@@ -120,6 +125,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var result = await Client.BrowseAsync(username);
@@ -184,6 +194,11 @@ namespace slskd.Users.API
return BadRequest();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var result = await Client.GetDirectoryContentsAsync(username, request.Directory);
@@ -214,6 +229,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var response = await Users.GetInfoAsync(username);
@@ -241,6 +261,11 @@ namespace slskd.Users.API
return Forbid();
}
+ if (Users.IsBlacklisted(username))
+ {
+ return NotFound();
+ }
+
try
{
var response = await Users.GetStatusAsync(username);
diff --git a/src/slskd/Users/IUserService.cs b/src/slskd/Users/IUserService.cs
index f2cfa5f1..28bb6459 100644
--- a/src/slskd/Users/IUserService.cs
+++ b/src/slskd/Users/IUserService.cs
@@ -144,8 +144,9 @@ namespace slskd.Users
/// </summary>
/// <param name="username">The username to check.</param>
/// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <param name="bypassCache">A value indicating whether to compute blacklisted status on a cache miss.</param>
/// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
- bool IsBlacklisted(string username, IPAddress ipAddress = null);
+ bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true);
/// <summary>
/// Retrieves a value indicating whether the specified peer is privileged.
diff --git a/src/slskd/Users/Types/User.cs b/src/slskd/Users/Types/User.cs
index 7297d747..473bedfb 100644
--- a/src/slskd/Users/Types/User.cs
+++ b/src/slskd/Users/Types/User.cs
@@ -42,6 +42,9 @@ namespace slskd.Users
/// <summary>
/// Gets the user's configured group.
/// </summary>
+ /// <remarks>
+ /// This is the group under which the username appears in config, *not* the group derived at runtime.
+ /// </remarks>
public string Group { get; init; }
/// <summary>
diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs
index d8b24f4d..3ce827c8 100644
--- a/src/slskd/Users/UserService.cs
+++ b/src/slskd/Users/UserService.cs
@@ -34,11 +34,15 @@ using Microsoft.Extensions.Options;
namespace slskd.Users
{
+ using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
+ using System.Text.RegularExpressions;
using System.Threading.Tasks;
+ using Microsoft.Extensions.Caching.Memory;
+ using Microsoft.Extensions.Internal;
using NetTools;
using Serilog;
using Soulseek;
@@ -85,15 +89,20 @@ namespace slskd.Users
/// </summary>
/// <param name="soulseekClient"></param>
/// <param name="optionsMonitor"></param>
+ /// <param name="systemClock"></param>
public UserService(
ISoulseekClient soulseekClient,
- IOptionsMonitor<Options> optionsMonitor)
+ IOptionsMonitor<Options> optionsMonitor,
+ ISystemClock systemClock = null)
{
Client = soulseekClient;
OptionsMonitor = optionsMonitor;
OptionsMonitor.OnChange(options => Configure(options));
+ InjectedClock = systemClock ?? new SystemClock();
+ BlacklistDecisionCache = new MemoryCache(new MemoryCacheOptions { Clock = InjectedClock, ExpirationScanFrequency = TimeSpan.FromMinutes(1), SizeLimit = 1000 });
+
// updates may be sent unsolicited from the server, so update when we get them. binding these events will cause
// multiple redundant round trips when initially watching a user or when explicitly requesting via
// GetStatus/GetStatistics. this is wasteful, but there's no functional side effect.
@@ -137,6 +146,9 @@ namespace slskd.Users
private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>();
private IOptionsMonitor<Options> OptionsMonitor { get; }
private Blacklist Blacklist { get; } = new Blacklist();
+ private IReadOnlyCollection<Regex> CompiledBlacklistPatterns { get; set; } = [];
+ private ISystemClock InjectedClock { get; }
+ private MemoryCache BlacklistDecisionCache { get; }
/// <summary>
/// Gets or sets the internal cache of User data.
@@ -162,31 +174,45 @@ namespace slskd.Users
private ConcurrentDictionary<string, bool> WatchedUsernamesDictionary { get; set; } = new ConcurrentDictionary<string, bool>();
/// <summary>
- /// Gets the name of the group for the specified <paramref name="username"/>.
+ /// Gets the name of the group for the specified <paramref name="username"/> from cached data.
/// </summary>
- /// <remarks>The group name is fetched from cached data, and lookups should always be fast.</remarks>
+ /// <remarks>
+ /// <para>
+ /// Excludes the 'blacklisted' group for performance; use <see cref="IsBlacklisted"/> to guard network operations instead.
+ /// </para>
+ /// <para>
+ /// This is an extremely hot path, and the value returned may be approximated or incorrect in the case of a
+ /// cache miss in order to provide low latency values.
+ /// </para>
+ /// </remarks>
/// <param name="username">The username of the peer.</param>
/// <returns>The group for the specified username.</returns>
public string GetGroup(string username)
{
- // note: this is an extremely hot path; keep the work done to an absolute minimum.
+ // users end up in this dictionary for a few reasons, including but maybe not limited to:
+ // * they show up in the user defined group list somewhere
+ // * the server told us they have privileges when we logged in
+ // * we 'watched' them
+ // * we fetched statistics or status for them
+ // if we handle any of their data they'll probably wind up here. if they show up in the config,
+ // their Group property will be set. otherwise we must resolve their group dynamically.
if (UserDictionary.TryGetValue(username ?? string.Empty, out var user))
{
- if (IsBlacklisted(user.Username))
- {
- return Application.BlacklistedGroup;
- }
-
+ // privileged users trump everything, and we resolve their group accordingly regardless of all other factors
if (user.Status?.IsPrivileged ?? false)
{
return Application.PrivilegedGroup;
}
+ // if the user isn't privileged and the user has put their username in any user defined group, that's
+ // their group. they aren't subjected to leecher checks.
if (user.Group != null)
{
return user.Group;
}
+ // check to see if they are a leecher. they may be in the dictionary because we checked their stats.
+ // if we don't have their stats we don't have enough info to make the call, group is inconclusive so fall through
var thresholds = OptionsMonitor.CurrentValue.Transfers.Groups.Leechers.Thresholds;
if (user.Statistics?.FileCount < thresholds.Files || user.Statistics?.DirectoryCount < thresholds.Directories)
@@ -286,33 +312,79 @@ namespace slskd.Users
/// <summary>
/// Gets a value indicating whether the specified <paramref name="username"/> and/or <paramref name="ipAddress"/> are blacklisted.
/// </summary>
+ /// <remarks>
+ /// This method may be taxing if the user has defined a blacklist file or large number of patterns. Call it to 'guard'
+ /// actions at the network level (with the exception of search results where latency is sensitive), but don't
+ /// use it to check once the user is 'in' the system (e.g. don't call this in the upload governor or queue logic).
+ /// </remarks>
/// <param name="username">The username to check.</param>
/// <param name="ipAddress">The IPAddress to check, if available.</param>
+ /// <param name="bypassCache">A value indicating whether to compute blacklisted status on a cache miss.</param>
/// <returns>A value indicating whether the specified user and/or IP are blacklisted.</returns>
- public bool IsBlacklisted(string username, IPAddress ipAddress = null)
+ public bool IsBlacklisted(string username, IPAddress ipAddress = null, bool bypassCache = true)
{
- var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted;
+ ArgumentNullException.ThrowIfNull(username);
- if (blacklist.Members.Contains(username))
+ if (BlacklistDecisionCache.TryGetValue<bool>(username, out var cached))
{
- return true;
+ return cached;
}
- // check the user-curated list of blacklisted CIDRs that exists along with the list of
- // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a
- // blacklist supplied by a third party (but might?)
- if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
+ // if we have a cache miss and the caller has specified bypassCache = false, assume that a cache miss
+ // means that the user is not blacklisted. we will only specify bypassCache = false when we're checking
+ // in a hot path, which at the time of this writing is only when determining whether to search shares for a
+ // request. we will check again before sending the results with bypassCache = true, and we should always
+ // follow this pattern when using bypassCache = false (specifically, check again before sending something)
+ if (!bypassCache)
{
- return true;
+ return false;
}
- // check the managed blacklist loaded from a third party blacklist file
- if (ipAddress is not null && Blacklist.Contains(ipAddress))
+ var blacklisted = IsBlacklistedInternal(username, ipAddress);
+
+ BlacklistDecisionCache.Set(
+ key: username,
+ value: blacklisted,
+ options: new MemoryCacheEntryOptions
+ {
+ AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10),
+ Size = 1,
+ });
+
+ return blacklisted;
+
+ bool IsBlacklistedInternal(string username, IPAddress iPAddress = null)
{
- return true;
- }
+ // first, check to see if the name appears explicitly in the config
+ var blacklist = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted;
- return false;
+ if (blacklist.Members.Contains(username))
+ {
+ return true;
+ }
+
+ // check to see if the username matches any patterns
+ if (CompiledBlacklistPatterns.Any(pattern => pattern.IsMatch(username)))
+ {
+ return true;
+ }
+
+ // check the user-curated list of blacklisted CIDRs that exists along with the list of
+ // blacklisted usernames. these CIDRs should be one-offs and would not be expected to appear in a
+ // blacklist supplied by a third party (but might?)
+ if (ipAddress is not null && blacklist.Cidrs.Select(c => IPAddressRange.Parse(c)).Any(range => range.Contains(ipAddress)))
+ {
+ return true;
+ }
+
+ // check the managed blacklist loaded from a third party blacklist file
+ if (ipAddress is not null && Blacklist.Contains(ipAddress))
+ {
+ return true;
+ }
+
+ return false;
+ }
}
/// <summary>
@@ -419,6 +491,19 @@ namespace slskd.Users
LastOptionsHash = optionsHash;
}
+ // recompile blacklist patterns, regardless of whether they changed (this cheap to do)
+ var regexOptions = RegexOptions.Compiled;
+
+ if (!OptionsMonitor.CurrentValue.Flags.CaseSensitiveRegEx)
+ {
+ regexOptions |= RegexOptions.IgnoreCase;
+ }
+
+ CompiledBlacklistPatterns = OptionsMonitor.CurrentValue.Transfers.Groups.Blacklisted.Patterns
+ .Select(f => new Regex(f, regexOptions))
+ .ToList()
+ .AsReadOnly();
+
var blacklistOptionsHash = Compute.Sha1Hash(options.Blacklist.ToJson());
// there's no forced re-config of the blacklist; either the config changed or it didn't.
@@ -464,6 +549,9 @@ namespace slskd.Users
LastBlacklistOptionsHash = blacklistOptionsHash;
}
+
+ // invalidate cached blacklist decisions
+ BlacklistDecisionCache.Clear();
}
private void Reset()