diff options
| -rw-r--r-- | config/slskd.example.yml | 3 | ||||
| -rw-r--r-- | docs/config.md | 28 | ||||
| -rw-r--r-- | src/slskd/Core/Blacklist.cs | 341 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 66 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 8 | ||||
| -rw-r--r-- | src/slskd/Users/UserService.cs | 124 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Common/BlacklistTests.cs | 130 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt | 7 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Data/Blacklist/dat.txt | 7 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Data/Blacklist/empty.txt | 13 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Data/Blacklist/junk.txt | 3 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt | 7 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj | 18 |
13 files changed, 718 insertions, 37 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 4e34098b..f4839e6d 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -120,6 +120,9 @@ # members: # - alice # - bob +# blacklist: +# enabled: true +# file: <path to file containing CIDRs to blacklist> # filters: # search: # request: diff --git a/docs/config.md b/docs/config.md index 924e4de9..f81fe8c0 100644 --- a/docs/config.md +++ b/docs/config.md @@ -415,7 +415,7 @@ groups: failures: 30 ``` -## Blacklist +## User Blacklist A fourth built-in group, `blacklisted`, is used to disallow other users from various activities. @@ -425,10 +425,12 @@ Blacklisted users are prevented from: - Retrieving directory contents - Enqueueing downloads -Users can be blacklisted by adding their username to the `members` list. Additionally, users can be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. +Users can be blacklisted by adding their username to the `members` list. Additionally, users can be blacklisted by IP address, or range of addresses by adding a CIDR entry to the `cidrs` list. Users added to the blacklist will be blocked from enqueueing any new files. Any existing active or queued transfers will need to be cancelled manually. +A managed blacklist file may also be used to achieve the same effects. Read more about this in the [Managed Blacklist](#managed-blacklist) section below. + **YAML** ```yaml groups: @@ -504,6 +506,27 @@ groups: - bob ``` +## Managed Blacklist + +A managed blacklist (also called a blocklist) can be specified to disallow interaction with known undesireable actors. Users whose IP address metches an entry on this list are functionally the same as users added to the [User Blacklist](#user-blacklist) described above and are disallowed any interactions with shares or files. + +Blacklists/blocklists designed for use with other P2P applications (such as BitTorrent) are supported; specifically the P2P, DAT, and CIDR formats. + +When enabled, the specified file is validated by reading the first few lines of the file to automatically detect the format. If the file doesn't exist, can't be read, the format can't be detected, or if it contains any lines that don't match the format, the application will exit. Similarly, if the file changes while the application is running and there's an issue, the application will exit. + +Note that the contents of the blacklist are stored in memory to ensure performance, and this will increase the amount of memory used, potentially significantly if the blacklist is large. + +| Command-Line | Environment Variable | Description | +| -------------------- | -------------------- | ------------------------------ | +| `--enable-blacklist` | `BLACKLIST` | Enable the managed blacklist | +| `--blacklist-file` | `BLACKLIST_FILE` | The path to the blacklist file | + +```yaml +blacklist: + enabled: true + file: <path to file containing CIDRs to blacklist> +``` + # Chat Rooms and Private Messaging ## Auto-Joining Rooms @@ -514,7 +537,6 @@ The list can be specified via command line (e.g. --rooms <room1> --rooms <room2> Additionally, when the client is disconnected, any rooms that were joined at the time of the disconnect are rejoined upon reconnect, as long as the app hasn't been restarted in between. - | Command-Line | Environment Variable | Description | | ------------- | ---------------------| ----------------------------------------| | `--rooms` | `ROOMS` | A list of chat rooms to join on startup | diff --git a/src/slskd/Core/Blacklist.cs b/src/slskd/Core/Blacklist.cs new file mode 100644 index 00000000..76f0b37f --- /dev/null +++ b/src/slskd/Core/Blacklist.cs @@ -0,0 +1,341 @@ +// <copyright file="Blacklist.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.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Threading.Tasks; +using NetTools; +using Serilog; + +/// <summary> +/// Blacklist file formats. +/// </summary> +public enum BlacklistFormat +{ + /// <summary> + /// Automatically detect format based on contents. + /// </summary> + AutoDetect, + + /// <summary> + /// CIDR format. <see href="https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing"/>. + /// </summary> + /// <example> + /// <code> + /// 1.2.4.0/24 + /// 1.2.8.0/24 + /// 1.9.96.105/32 + /// </code> + /// </example> + CIDR, + + /// <summary> + /// P2P format. <see href="https://sourceforge.net/p/peerguardian/wiki/dev-blocklist-format-p2p/"/>. + /// </summary> + /// <example> + /// <code> + /// China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + /// China Internet Information Center (CNNIC):1.2.8.0-1.2.8.255 + /// Botnet on Telekom Malaysia:1.9.96.105-1.9.96.105 + /// </code> + /// </example> + P2P, + + /// <summary> + /// DAT format. <see href="https://sourceforge.net/p/peerguardian/wiki/dev-blocklist-format-dat/"/>. + /// </summary> + /// <example> + /// <code> + /// 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + /// 001.002.008.000 - 001.002.008.255 , 000 , China Internet Information Center (CNNIC) + /// 001.009.096.105 - 001.009.096.105 , 000 , Botnet on Telekom Malaysia + /// </code> + /// </example> + DAT, +} + +/// <summary> +/// A managed blacklist for CIDRs. +/// </summary> +public class Blacklist +{ + /// <summary> + /// Gets the total number of loaded CIDRs. + /// </summary> + public long Count => Cache.Sum(kvp => kvp.Value.Length); + + private ILogger Log { get; set; } = Serilog.Log.ForContext<Blacklist>(); + private ConcurrentDictionary<int, (uint First, uint Last)[]> Cache { get; set; } = new(); + + /// <summary> + /// Examines the contents of the specified <paramref name="filename"/> and attempts to determine the format. + /// </summary> + /// <param name="filename">The fully qualified path to the file to examine.</param> + /// <returns>The detected format.</returns> + /// <exception cref="IOException">Thrown if the specified filename can't be accessed.</exception> + /// <exception cref="FormatException">Thrown if the format can't be determined.</exception> + public static async Task<BlacklistFormat> DetectFormat(string filename) + { + using var reader = new StreamReader(filename, options: new FileStreamOptions + { + Access = FileAccess.Read, + Mode = FileMode.Open, + Share = FileShare.Read, + }); + + string line = default; + + // read the first non-empty, non-commented line from the file + while ((line = await reader.ReadLineAsync()) != null) + { + if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) + { + continue; + } + + try + { + // CIDR format: 1.2.4.0/24 + if (IPAddressRange.TryParse(line, out _)) + { + return BlacklistFormat.CIDR; + } + } + catch + { + } + + try + { + // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + if (IPAddressRange.TryParse(line.Split(':')[1], out _)) + { + return BlacklistFormat.P2P; + } + } + catch + { + } + + try + { + // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + if (IPAddressRange.TryParse(line.Split(",")[0], out _)) + { + return BlacklistFormat.DAT; + } + } + catch + { + } + } + + throw new FormatException("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported"); + } + + /// <summary> + /// Clears the contents of the Blacklist. + /// </summary> + public virtual void Clear() => Cache.Clear(); + + /// <summary> + /// Loads the contents of the specified <paramref name="filename"/> into the Blacklist. + /// </summary> + /// <remarks> + /// The existing Blacklist contents are replaced atomically. + /// </remarks> + /// <param name="filename">The fully qualified path to the file to load.</param> + /// <param name="format">The optional blacklist file format.</param> + /// <returns>The operation context.</returns> + /// <exception cref="IOException">Thrown if the specified filename can't be accessed.</exception> + /// <exception cref="FormatException"> + /// Thrown if any of the lines in the file do not match the specified or auto-detected <paramref name="format"/>. + /// </exception> + /// <exception cref="FormatException"> + /// Thrown if the specified <paramref name="format"/> is <see cref="BlacklistFormat.AutoDetect"/> and the format could not be detected. + /// </exception> + public virtual async Task Load(string filename, BlacklistFormat format = BlacklistFormat.AutoDetect) + { + if (format == BlacklistFormat.AutoDetect) + { + Log.Debug("Attempting to auto-detect blacklist fomat from contents..."); + format = await DetectFormat(filename); // FormatException if unsuccessful + Log.Debug("Detected blacklist format {Format}", format); + } + + var sw = new Stopwatch(); + sw.Start(); + Log.Debug("Loading blacklist"); + + using var reader = new StreamReader(filename, options: new FileStreamOptions + { + Access = FileAccess.Read, + Mode = FileMode.Open, + Share = FileShare.Read, + BufferSize = 262144, // 256kib, assumes most blacklists will be > 1mb + }); + + var dict = new ConcurrentDictionary<int, List<(uint First, uint Last)>>(); + string line = default; + int lineNumber = 0; + + while ((line = await reader.ReadLineAsync()) != null) + { + lineNumber++; + + if (string.IsNullOrWhiteSpace(line) || line.StartsWith('#')) + { + continue; + } + + IPAddressRange cidr = default; + + /* + parse CIDR from string using specified or detected format + note: we should never get this far without format being one of CIDR, P2P, DAT + */ + + try + { + // CIDR format: 1.2.4.0/24 + if (format == BlacklistFormat.CIDR) + { + cidr = IPAddressRange.Parse(line); + } + + // P2P format: China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 + else if (format == BlacklistFormat.P2P) + { + cidr = IPAddressRange.Parse(line.Split(':').Last()); + } + + // DAT format: 001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) + else if (format == BlacklistFormat.DAT) + { + // the IPAddressRange library doesn't like leading zeros, so we have to remove them + static string TrimLeadingZerosFromEachOctet(string ip) + => string.Join('.', ip.Split('.').Select(octet => octet == "000" ? "0" : octet.TrimStart('0'))); + + // 001.002.004.000-001.002.004.255 + var range = line.Split(",").First().Replace(" ", string.Empty); + + // [1.2.4.0, 1.2.4.255] + var ips = range.Split("-") + .Select(TrimLeadingZerosFromEachOctet); + + cidr = IPAddressRange.Parse(string.Join('-', ips)); + } + } + catch (Exception ex) + { + throw new FormatException($"Failed to parse {format} blacklist line {lineNumber} '{line}': {ex.Message}"); + } + + // grab the first octet of the first and last addresses in the range + var first = int.Parse(cidr.Begin.ToString().Split('.')[0]); + var last = int.Parse(cidr.End.ToString().Split('.')[0]); + + var entry = (ToUint32(cidr.Begin), ToUint32(cidr.End)); + + // CIDRs with a mask of /7 and lower span multiple octets, so we must add these CIDRs to the list for each octet + for (int i = 0; i <= last - first; i++) + { + dict.AddOrUpdate( + key: first + i, // first octet + addValueFactory: (_) => new List<(uint, uint)> { entry }, // if we haven't seen this octet yet, initialize the list + updateValueFactory: (_, list) => + { + list.Add(entry); // if we've seen it already, append + return list; + }); + } + } + + // copy working dictionary to a temporary cache to: + // * deduplicate entries + // * sort arrays by first IP to enable binary search (future?) + // * convert List<> to array to increase access speed + var tempCache = new ConcurrentDictionary<int, (uint First, uint Last)[]>(); + + foreach (var key in dict.Keys) + { + tempCache[key] = dict[key] + .Distinct() + .OrderBy(x => x.First) + .ToArray(); + } + + // swap the temporary cache for the "real" cache, enabling a bumpless update + Cache = tempCache; + + sw.Stop(); + Log.Debug("Blacklist loaded in {Duration}ms", sw.ElapsedMilliseconds); + } + + /// <summary> + /// Returns a value indicating whether the specified <paramref name="ip"/> is contained witin the blacklist. + /// </summary> + /// <param name="ip">The IP address to check.</param> + /// <returns>A value indicating whether the specified IP is contained within the blacklist.</returns> + public virtual bool Contains(IPAddress ip) + { + // grab the first octet + int first = ip.GetAddressBytes()[0]; + + // check to see if *any* CIDRs covering this offset are in the blacklist + // best case scenario for performance if not, roughly O(1) + if (!Cache.TryGetValue(first, out (uint, uint)[] cidrs)) + { + return false; + } + + // conver the entire IP to a uint + var ipAsUint32 = ToUint32(ip); + + // check the list for this octet sequentially until the first match + foreach (var cidr in cidrs) + { + if (ipAsUint32 >= cidr.Item1 && ipAsUint32 <= cidr.Item2) + { + return true; + } + } + + // not in the list + // worst case scenario for performance, O(n) where n = list length + return false; + } + + private uint ToUint32(IPAddress ip) + { + byte[] bytes = ip.GetAddressBytes(); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(bytes); + } + + return BitConverter.ToUInt32(bytes, 0); + } +}
\ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index cfe78eb1..81dc09f6 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -24,6 +24,7 @@ namespace slskd using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics; + using System.IO; using System.Linq; using System.Text.Json.Serialization; using System.Text.RegularExpressions; @@ -234,6 +235,12 @@ namespace slskd public GroupsOptions Groups { get; init; } = new GroupsOptions(); /// <summary> + /// Gets blacklist options. + /// </summary> + [Validate] + public BlacklistOptions Blacklist { get; init; } = new BlacklistOptions(); + + /// <summary> /// Gets filter options. /// </summary> [Validate] @@ -1099,6 +1106,61 @@ namespace slskd } /// <summary> + /// Blacklist options. + /// </summary> + public class BlacklistOptions : IValidatableObject + { + /// <summary> + /// Gets a value indicating whether blacklist file support should be enabled. + /// </summary> + [Argument(default, "enable-blacklist")] + [EnvironmentVariable("BLACKLIST")] + [Description("enable blacklist file support")] + [RequiresRestart] + public bool Enabled { get; init; } + + /// <summary> + /// Gets the path to the blacklist file. + /// </summary> + [Argument(default, "blacklist-file")] + [EnvironmentVariable("BLACKLIST_FILE")] + [Description("path to blacklist file")] + [FileExists(FileAccess.Read)] + public string File { get; init; } + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (!Enabled) + { + return results; + } + + // loading/validating the entire list will be costly on low spec systems + // just make sure that we can detect a valid format and leave it at that + // if there's a problem with any of the entries, the load will fail and + // kill the application + try + { + // async not supported here, .Result is all we have + _ = slskd.Blacklist.DetectFormat(File).Result; + } + catch + { + results.Add(new ValidationResult("Failed to detect blacklist format. Only CIDR, P2P and DAT formats are supported")); + } + + return results; + } + } + + /// <summary> /// Filter options. /// </summary> public class FiltersOptions @@ -1845,7 +1907,7 @@ namespace slskd [Argument(default, "https-cert-pfx")] [EnvironmentVariable("HTTPS_CERT_PFX")] [Description("path to X509 certificate .pfx")] - [FileExists] + [FileExists(FileAccess.Read)] [RequiresRestart] public string Pfx { get; init; } @@ -2078,4 +2140,4 @@ namespace slskd } } } -}
\ No newline at end of file +} diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d7f6caca..918ca828 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -242,6 +242,12 @@ namespace slskd private static bool ShowVersion { get; set; } /// <summary> + /// Panic. + /// </summary> + /// <param name="code">An optional exit code.</param> + public static void Exit(int code = 1) => Environment.Exit(code); + + /// <summary> /// Entrypoint. /// </summary> /// <param name="args">Command line arguments.</param> @@ -576,7 +582,9 @@ namespace slskd services.AddTransient<IShareRepositoryFactory, SqliteShareRepositoryFactory>(); services.AddSingleton<ISearchService, SearchService>(); + services.AddSingleton<IUserService, UserService>(); + services.AddSingleton<IRoomService, RoomService>(); services.AddSingleton<ITransferService, TransferService>(); diff --git a/src/slskd/Users/UserService.cs b/src/slskd/Users/UserService.cs index 5b15b671..e278ccc7 100644 --- a/src/slskd/Users/UserService.cs +++ b/src/slskd/Users/UserService.cs @@ -1,4 +1,4 @@ -// <copyright file="UserService.cs" company="slskd Team"> +// <copyright file="UserService.cs" company="slskd Team"> // Copyright (c) slskd Team. All rights reserved. // // This program is free software: you can redistribute it and/or modify @@ -91,8 +91,16 @@ namespace slskd.Users _ = GetStatisticsAsync(userStatus.Username); }; - Client.Connected += (_, _) => Reset(); + // it's important for us to force a reconfig at login to discard any users that were previously tracked + // specific scenario being; up and running for some time, offline for some time (days?), reconnect, are users still online? have stats changed? + // to avoid needing to go through and exhaustively check each user in the tracking dictionary, just delete it and let it be built back up + // any user we are downloading from will be tracked again when pending downloads are re-requested Client.LoggedIn += (_, _) => Configure(OptionsMonitor.CurrentValue, force: true); + + // working hand-in-hand with the forced reconfig on login, reset clears everything upon connect; clearing the way + // for the reconfig at login to rebuild it. i think. yeah, that sounds right. we don't ever want Configure() to reset anything + // so the connect is distinctly different from reconfig at login. + Client.Connected += (_, _) => Reset(); Client.PrivilegedUserListReceived += (_, list) => Client_PrivilegedUserListReceived(list); Configure(OptionsMonitor.CurrentValue); @@ -110,8 +118,10 @@ namespace slskd.Users private ISoulseekClient Client { get; } private string LastOptionsHash { get; set; } + private string LastBlacklistOptionsHash { get; set; } private ILogger Log { get; set; } = Serilog.Log.ForContext<UserService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } + private Blacklist Blacklist { get; } = new Blacklist(); /// <summary> /// Gets or sets the internal cache of User data. @@ -273,11 +283,20 @@ namespace slskd.Users 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; } @@ -347,45 +366,86 @@ namespace slskd.Users { var optionsHash = Compute.Sha1Hash(options.Groups.UserDefined.ToJson()); - if (optionsHash == LastOptionsHash && !force) - { - return; - } - - // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously - // configured but have now been removed - var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); - var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); - var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); - - // clear the configured group for anyone that was removed from config, or that was added transiently - foreach (var username in usernamesRemoved) - { - UserDictionary.AddOrUpdate( - key: username, - addValue: new User() { Username = username }, - updateValueFactory: (key, user) => user with { Username = username, Group = null }); - } - - // sort by priority, descending. this will cause the highest priority group for the user to be persisted when the - // operation is complete. - foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) + if (optionsHash != LastOptionsHash || force) { - foreach (var username in group.Value.Members) + // get a list of tracked names that haven't been explicitly added to any group, including those that were previlously + // configured but have now been removed + var usernamesBeforeUpdate = UserDictionary.Keys.ToList(); + var usernamesAfterUpdate = options.Groups.UserDefined.SelectMany(g => g.Value.Members); + var usernamesRemoved = usernamesBeforeUpdate.Except(usernamesAfterUpdate); + + // clear the configured group for anyone that was removed from config, or that was added transiently + foreach (var username in usernamesRemoved) { UserDictionary.AddOrUpdate( key: username, - addValue: new User() { Username = username, Group = group.Key }, - updateValueFactory: (key, user) => user with { Username = username, Group = group.Key }); + addValue: new User() { Username = username }, + updateValueFactory: (key, user) => user with { Username = username, Group = null }); + } - if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) + // sort by priority, descending. this will cause the highest priority group for the user to be persisted when the + // operation is complete. + foreach (var group in options.Groups.UserDefined.OrderByDescending(kvp => kvp.Value.Upload.Priority)) + { + foreach (var username in group.Value.Members) { - _ = WatchAsync(username); + UserDictionary.AddOrUpdate( + key: username, + addValue: new User() { Username = username, Group = group.Key }, + updateValueFactory: (key, user) => user with { Username = username, Group = group.Key }); + + if (Client.State.HasFlag(SoulseekClientStates.Connected) && Client.State.HasFlag(SoulseekClientStates.LoggedIn)) + { + _ = WatchAsync(username); + } } } + + LastOptionsHash = optionsHash; } - LastOptionsHash = optionsHash; + var blacklistOptionsHash = Compute.Sha1Hash(options.Blacklist.ToJson()); + + // there's no forced re-config of the blacklist; either the config changed or it didn't. + // if the underlying file changed, users can toggle the blacklist off and on or restart + // the application. these sorts of blacklists should be relatively static (i think) + if (blacklistOptionsHash != LastBlacklistOptionsHash) + { + Log.Debug("Blacklist options changed: {JSON}", options.Blacklist.ToJson()); + + if (!options.Blacklist.Enabled) + { + Log.Debug("Blacklist disabled; clearing contents"); + Blacklist.Clear(); + Log.Information("Blacklist disabled"); + } + else + { + // the option validation logic should have ensured the file format could be auto-detected and that the file + // contained no formatting errors. this should only fail on transient I/O errors. + _ = Task.Run(() => Blacklist.Load(options.Blacklist.File, BlacklistFormat.AutoDetect)) + .ContinueWith(task => + { + // if the task faulted, the load of the file failed, and the user isn't getting the + // intended protection from the blacklist. in this case we can: + // 1) log an error and continue, potentially against the desires of the user + // 2) kill the application and force the user to deal with the cause + // a user taking advantage of the blacklist feature would absolutely want to know if it wasn't working, + // so we're taking door #2. + if (task.IsFaulted) + { + Log.Fatal(task.Exception, "Fatal error loading blacklist from file {File}: {Message}", options.Blacklist.File, task.Exception?.Message); + Program.Exit(1); + } + else + { + Log.Information("Blacklist updated with {Count} CIDRs from file {File}", Blacklist.Count, options.Blacklist.File); + } + }); + } + + LastBlacklistOptionsHash = blacklistOptionsHash; + } } private void Reset() @@ -410,4 +470,4 @@ namespace slskd.Users updateValueFactory: (key, user) => user with { Username = username, Status = status }); } } -}
\ No newline at end of file +} diff --git a/tests/slskd.Tests.Unit/Common/BlacklistTests.cs b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs new file mode 100644 index 00000000..9f21dde8 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/BlacklistTests.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Threading.Tasks; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public class BlacklistTests +{ + private List<(string, bool)> IPs = new List<(string, bool)>() + { + ("1.2.4.0", true), + ("1.2.4.128", true), + ("1.2.4.255", true), + ("1.2.8.0", true), + ("1.2.8.128", true), + ("1.2.8.255", true), + ("1.9.96.104", false), + ("1.9.96.105", true), + ("1.9.102.250", false), + ("1.9.102.251", true), + ("1.9.106.186", true), + ("1.9.106.187", false), + ("192.168.1.1", false), + ("4.4.4.4", false), + ("123.234.111.123", false), + }; + + [Theory] + [InlineData("Data/Blacklist/cidr.txt", BlacklistFormat.CIDR)] + [InlineData("Data/Blacklist/dat.txt", BlacklistFormat.DAT)] + [InlineData("Data/Blacklist/p2p.txt", BlacklistFormat.P2P)] + public async Task DetectFormat_Detects(string filename, BlacklistFormat expected) + { + var result = await Blacklist.DetectFormat(filename); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Data/Blacklist/junk.txt", typeof(FormatException))] + [InlineData("Data/Blacklist/empty.txt", typeof(FormatException))] + [InlineData("Data/does.not.exist.txt", typeof(IOException))] + public async Task DetectFormat_Throws(string filename, Type exType) + { + var ex = await Record.ExceptionAsync(() => Blacklist.DetectFormat(filename)); + + Assert.NotNull(ex); + Assert.IsAssignableFrom(exType, ex); + } + + [Theory] + [InlineData("Data/Blacklist/junk.txt", BlacklistFormat.CIDR, typeof(FormatException))] + [InlineData("Data/does.not.exist.txt", BlacklistFormat.DAT, typeof(IOException))] + public async Task Load_throws(string filename, BlacklistFormat format, Type exType) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename, format)); + + Assert.NotNull(ex); + Assert.IsAssignableFrom(exType, ex); + } + + [Theory] + [InlineData("Data/Blacklist/cidr.txt", BlacklistFormat.CIDR)] + [InlineData("Data/Blacklist/dat.txt", BlacklistFormat.DAT)] + [InlineData("Data/Blacklist/p2p.txt", BlacklistFormat.P2P)] + public async Task Load_Loads(string filename, BlacklistFormat format) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename, format)); + + Assert.Null(ex); + + // the test files are assumed to all contain 5 entries + Assert.Equal(5, bl.Count); + } + + [Theory] + [InlineData("Data/Blacklist/cidr.txt", BlacklistFormat.CIDR)] + public async Task Load_Then_Clear(string filename, BlacklistFormat format) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename, format)); + + Assert.Null(ex); + + // the test files are assumed to all contain 5 entries + Assert.Equal(5, bl.Count); + + bl.Clear(); + + Assert.Equal(0, bl.Count); + } + + [Theory] + [InlineData("Data/Blacklist/cidr.txt")] + [InlineData("Data/Blacklist/dat.txt")] + [InlineData("Data/Blacklist/p2p.txt")] + public async Task Load_AutoDetects_And_Loads(string filename) + { + var bl = new Blacklist(); + var ex = await Record.ExceptionAsync(() => bl.Load(filename)); + + Assert.Null(ex); + + // the test files are assumed to all contain 5 entries + Assert.Equal(5, bl.Count); + } + + [Theory] + [InlineData("Data/Blacklist/cidr.txt")] + [InlineData("Data/Blacklist/dat.txt")] + [InlineData("Data/Blacklist/p2p.txt")] + public async Task CIDR_Contains(string filename) + { + var bl = new Blacklist(); + await bl.Load(filename); + + foreach (var ip in IPs) + { + if (bl.Contains(IPAddress.Parse(ip.Item1)) != ip.Item2) + { + throw new Exception($"Expected contains for {ip.Item1} to be {ip.Item2} but it wasn't"); + } + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt b/tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt new file mode 100644 index 00000000..850a2074 --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/cidr.txt @@ -0,0 +1,7 @@ +# here's a comment + +1.2.4.0/24 +1.2.8.0/24 +1.9.96.105/32 +1.9.102.251/32 +1.9.106.186/32
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/dat.txt b/tests/slskd.Tests.Unit/Data/Blacklist/dat.txt new file mode 100644 index 00000000..9386a98f --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/dat.txt @@ -0,0 +1,7 @@ +# here's a comment + +001.002.004.000 - 001.002.004.255 , 000 , China Internet Information Center (CNNIC) +001.002.008.000 - 001.002.008.255 , 000 , China Internet Information Center (CNNIC) +001.009.096.105 - 001.009.096.105 , 000 , Botnet on Telekom Malaysia +001.009.102.251 - 001.009.102.251 , 000 , Botnet on Telekom Malaysia +001.009.106.186 - 001.009.106.186 , 000 , Botnet on Telekom Malaysia
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/empty.txt b/tests/slskd.Tests.Unit/Data/Blacklist/empty.txt new file mode 100644 index 00000000..a50080e3 --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/empty.txt @@ -0,0 +1,13 @@ +# only a comment and some blank lines + + + + + + + + + + + +# end
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/junk.txt b/tests/slskd.Tests.Unit/Data/Blacklist/junk.txt new file mode 100644 index 00000000..b42f309e --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/junk.txt @@ -0,0 +1,3 @@ +{ + "foo": "bar" +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt b/tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt new file mode 100644 index 00000000..fb18aa83 --- /dev/null +++ b/tests/slskd.Tests.Unit/Data/Blacklist/p2p.txt @@ -0,0 +1,7 @@ +# here's a comment + +China Internet Information Center (CNNIC):1.2.4.0-1.2.4.255 +China Internet Information Center (CNNIC):1.2.8.0-1.2.8.255 +Botnet on Telekom Malaysia:1.9.96.105-1.9.96.105 +Botnet on Telekom Malaysia:1.9.102.251-1.9.102.251 +Botnet on Telekom Malaysia:1.9.106.186-1.9.106.186
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj index 127e0c1d..04b18bb7 100644 --- a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj +++ b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj @@ -25,4 +25,22 @@ <ProjectReference Include="..\..\src\slskd\slskd.csproj" />
</ItemGroup>
+ <ItemGroup>
+ <None Update="Data\Blacklist\cidr.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ <None Update="Data\Blacklist\dat.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ <None Update="Data\Blacklist\p2p.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ <None Update="Data\Blacklist\empty.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ <None Update="Data\Blacklist\junk.txt">
+ <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
+ </None>
+ </ItemGroup>
+
</Project>
|
