diff --git a/CHANGELOG.md b/CHANGELOG.md index 0951106..79ce456 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,21 @@ All notable changes to Flypaper are documented in this file. The format follows ## [Unreleased] +### Added + +- Settings section "Haltemethode": content (HTML filler text, random plain text or alternating + per catch), pause and chunk size ranges and the maximum hold time, with an estimate of the + bandwidth per trapped connection and its own reset button. Changes apply to the next catch + without a restart. +- Plain-text drip strategy (`text-drip`), served as `text/plain`. +- Each catch stores its strategy with the parameters in use, e.g. `text-drip 50-1000ms 1-64B`; + MCP results include it as `strategy`. + +### Changed + +- The maximum hold time moved from the general settings to "Haltemethode". +- Saving one settings section no longer resets the values saved in another. + ### Removed - Trap paths and known hosts, with their settings, the `Flypaper__Http__KnownHosts` and diff --git a/README.md b/README.md index 01b3244..1826909 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Nothing is required. The most useful optional environment variables: | `Flypaper__Http__TrustedProxies__0` | Proxy IP or CIDR allowed to set `X-Real-IP` (default: private networks) | | `TZ` | Time zone for the dashboard | -Limits and retention are changed on the dashboard's settings page. All variables +Hold method, limits and retention are changed on the dashboard's settings page. All variables and settings: [docs/configuration.md](docs/configuration.md). ## Security diff --git a/docs/configuration.md b/docs/configuration.md index 574b1bf..691459f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -20,6 +20,7 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...). | `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` | | `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` | | `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` | +| `Flypaper__Drip__Content` | Hold method: `Html`, `Text` or `Alternating` | `Html` | | `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` | | `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` | | `TZ` | Time zone for the dashboard | UTC | @@ -30,11 +31,14 @@ The defaults of the runtime settings below can also be set this way, e.g. ## Runtime settings Changed on the dashboard's settings page, stored in the database, effective immediately. The -reset button removes all saved values. +general reset button removes all saved values; the hold method section has its own reset. | Setting | Default | |---|---| -| Maximum hold time per catch | `01:00:00` | +| Hold method: content (HTML filler text, random plain text, or alternating per catch) | HTML filler text | +| Hold method: pause between chunks, min and max (10 ms to 30 s) | 50 ms / 1000 ms | +| Hold method: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes | +| Hold method: maximum hold time per catch | `01:00:00` | | Maximum connections overall | `1000` | | Maximum connections per IP | `10` | | Keep catches (days, `0` = forever) | `90` | diff --git a/docs/overview.md b/docs/overview.md index 69cabb7..252f068 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -31,13 +31,14 @@ flowchart LR ## Features - **Trap** for everything that reaches the trap port: whatever host or path a bot asks for -- **Slow delivery** of endless generated HTML with irregular timing +- **Slow delivery** of endless generated HTML or plain text (or both, alternating per catch) + with irregular timing; content, pauses, chunk sizes and hold time are set in the dashboard - **Limits**: maximum connections overall and per IP, maximum hold time per catch - **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest catches with expandable details; login with an admin password - **GeoIP**: country, city and ASN per catch from DB-IP Lite, downloaded and refreshed monthly; existing catches are filled in once the databases are available -- **Settings page**: limits and retention, changed at runtime +- **Settings page**: hold method, limits and retention, changed at runtime without a restart - **Retention**: old catches are deleted daily (90 days by default); catches from private networks are not stored by default; buttons to delete private or all catches diff --git a/src/Flypaper.Core/Abstractions/IStrategyDetails.cs b/src/Flypaper.Core/Abstractions/IStrategyDetails.cs new file mode 100644 index 0000000..59a7222 --- /dev/null +++ b/src/Flypaper.Core/Abstractions/IStrategyDetails.cs @@ -0,0 +1,8 @@ +namespace Flypaper.Core.Abstractions; + +public interface IStrategyDetails +{ + string MediaType { get; } + + string Describe(); +} diff --git a/src/Flypaper.Core/FlypaperCoreExtensions.cs b/src/Flypaper.Core/FlypaperCoreExtensions.cs index c54af9e..12fda55 100644 --- a/src/Flypaper.Core/FlypaperCoreExtensions.cs +++ b/src/Flypaper.Core/FlypaperCoreExtensions.cs @@ -19,7 +19,8 @@ public static class FlypaperCoreExtensions services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddEnumerable(ServiceDescriptor.Singleton()); - services.TryAddSingleton(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); diff --git a/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs b/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs new file mode 100644 index 0000000..5821d7e --- /dev/null +++ b/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs @@ -0,0 +1,28 @@ +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; +using Flypaper.Core.Strategies; +using Microsoft.Extensions.Options; + +namespace Flypaper.Core.Runtime; + +public sealed class ConfiguredStrategySelector( + IEnumerable strategies, + IOptionsMonitor options, + IRandomSource random) : ITrapStrategySelector +{ + public ITarpitStrategy? Select(TrapContext context) + { + var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList(); + string[] wanted = options.CurrentValue.Content switch + { + DripContent.Text => [TextDripStrategy.StrategyName], + DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName], + _ => [HtmlDripStrategy.StrategyName] + }; + + var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList(); + return matching.Count == 0 + ? candidates.FirstOrDefault() + : matching[random.Next(0, matching.Count)]; + } +} diff --git a/src/Flypaper.Core/Runtime/ProtocolStrategySelector.cs b/src/Flypaper.Core/Runtime/ProtocolStrategySelector.cs deleted file mode 100644 index 39f933c..0000000 --- a/src/Flypaper.Core/Runtime/ProtocolStrategySelector.cs +++ /dev/null @@ -1,10 +0,0 @@ -using Flypaper.Core.Abstractions; -using Flypaper.Core.Models; - -namespace Flypaper.Core.Runtime; - -public sealed class ProtocolStrategySelector(IEnumerable strategies) : ITrapStrategySelector -{ - public ITarpitStrategy? Select(TrapContext context) => - strategies.FirstOrDefault(strategy => strategy.Supports(context.Session.Protocol)); -} diff --git a/src/Flypaper.Core/Runtime/TrapRunner.cs b/src/Flypaper.Core/Runtime/TrapRunner.cs index 95e7265..24c5610 100644 --- a/src/Flypaper.Core/Runtime/TrapRunner.cs +++ b/src/Flypaper.Core/Runtime/TrapRunner.cs @@ -17,7 +17,7 @@ public sealed partial class TrapRunner( { public async Task RunAsync( TrapContext context, - Func> openChannel, + Func> openChannel, CancellationToken ct) { var session = context.Session; @@ -30,6 +30,7 @@ public sealed partial class TrapRunner( } using var _ = lease; + var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name; using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token); @@ -37,7 +38,7 @@ public sealed partial class TrapRunner( var outcome = TrapOutcome.Completed; try { - channel = new CountingTrapChannel(await openChannel(linked.Token)); + channel = new CountingTrapChannel(await openChannel(strategy, linked.Token)); await strategy.RunAsync(channel, linked.Token); } catch (OperationCanceledException) when (linked.IsCancellationRequested) @@ -51,7 +52,7 @@ public sealed partial class TrapRunner( outcome = TrapOutcome.ClientAborted; } - Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome); + Publish(context, description, channel?.BytesSent ?? 0, outcome); return outcome; } diff --git a/src/Flypaper.Core/Settings/HoldMethodSettings.cs b/src/Flypaper.Core/Settings/HoldMethodSettings.cs new file mode 100644 index 0000000..0cd176e --- /dev/null +++ b/src/Flypaper.Core/Settings/HoldMethodSettings.cs @@ -0,0 +1,41 @@ +using System.Globalization; +using Flypaper.Core.Strategies; + +namespace Flypaper.Core.Settings; + +public sealed record HoldMethodSettings( + DripContent Content, + TimeSpan MinDelay, + TimeSpan MaxDelay, + int MinChunkSize, + int MaxChunkSize, + TimeSpan MaxHoldDuration) +{ + public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize); + + public IReadOnlyDictionary ToConfiguration() => new Dictionary + { + [SettingKeys.DripContent] = Content.ToString(), + [SettingKeys.DripMinDelay] = MinDelay.ToString("c", CultureInfo.InvariantCulture), + [SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture), + [SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture), + [SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture), + [SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture) + }; + + public static double AverageBytesPerSecond(TimeSpan minDelay, TimeSpan maxDelay, int minChunkSize, int maxChunkSize) + { + var averageDelay = (minDelay + maxDelay).TotalSeconds / 2; + return averageDelay <= 0 ? 0 : (minChunkSize + maxChunkSize) / 2d / averageDelay; + } +} + +public sealed record HoldMethodInput( + string? Content, + string? MinDelayMs, + string? MaxDelayMs, + string? MinChunkSize, + string? MaxChunkSize, + string? MaxHoldDuration); + +public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary Errors); diff --git a/src/Flypaper.Core/Settings/RuntimeSettings.cs b/src/Flypaper.Core/Settings/RuntimeSettings.cs index 4669bab..64de6aa 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettings.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettings.cs @@ -5,7 +5,6 @@ namespace Flypaper.Core.Settings; public sealed record RuntimeSettings( int MaxConnections, int MaxConnectionsPerIp, - TimeSpan MaxHoldDuration, int RetentionDays, bool IgnorePrivateNetworks) { @@ -13,7 +12,6 @@ public sealed record RuntimeSettings( { [SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture), [SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture), - [SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture), [SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture), [SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false" }; diff --git a/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs b/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs index ff600ad..c97d1aa 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs @@ -3,6 +3,5 @@ namespace Flypaper.Core.Settings; public sealed record RuntimeSettingsInput( string? MaxConnections, string? MaxConnectionsPerIp, - string? MaxHoldDuration, string? RetentionDays, bool IgnorePrivateNetworks); diff --git a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs index e6b52ac..551f62a 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs @@ -1,4 +1,5 @@ using System.Globalization; +using Flypaper.Core.Strategies; namespace Flypaper.Core.Settings; @@ -9,12 +10,14 @@ public static class RuntimeSettingsParser private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1); private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7); + private const int MinDelayMs = 10; + private const int MaxDelayMs = 30_000; + private const int MaxChunkSize = 4096; public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input) { var errors = new Dictionary(); - var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors); var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors); var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors); var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors); @@ -33,12 +36,55 @@ public static class RuntimeSettingsParser var settings = new RuntimeSettings( maxConnections!.Value, perIp!.Value, - hold!.Value, retention!.Value, input.IgnorePrivateNetworks); return new RuntimeSettingsParseResult(settings, errors); } + public static HoldMethodParseResult ParseHoldMethod(HoldMethodInput input) + { + var errors = new Dictionary(); + + DripContent? content = Enum.TryParse(input.Content, ignoreCase: true, out var parsed) && Enum.IsDefined(parsed) + ? parsed + : null; + if (content is null) + { + errors[nameof(input.Content)] = "Bitte eine Methode wählen."; + } + + var minDelay = ParseInt(input.MinDelayMs, nameof(input.MinDelayMs), MinDelayMs, MaxDelayMs, errors); + var maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors); + var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors); + var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 1, MaxChunkSize, errors); + var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors); + + if (minDelay > maxDelay) + { + errors[nameof(input.MaxDelayMs)] = "Darf nicht kleiner sein als das Minimum."; + } + + if (minChunk > maxChunk) + { + errors[nameof(input.MaxChunkSize)] = "Darf nicht kleiner sein als das Minimum."; + } + + if (errors.Count > 0) + { + return new HoldMethodParseResult(null, errors); + } + + return new HoldMethodParseResult( + new HoldMethodSettings( + content!.Value, + TimeSpan.FromMilliseconds(minDelay!.Value), + TimeSpan.FromMilliseconds(maxDelay!.Value), + minChunk!.Value, + maxChunk!.Value, + hold!.Value), + errors); + } + private static TimeSpan? ParseTimeSpan( string? raw, string field, diff --git a/src/Flypaper.Core/Settings/SettingKeys.cs b/src/Flypaper.Core/Settings/SettingKeys.cs index f85e4af..da29e87 100644 --- a/src/Flypaper.Core/Settings/SettingKeys.cs +++ b/src/Flypaper.Core/Settings/SettingKeys.cs @@ -7,13 +7,18 @@ public static class SettingKeys public const string MaxHoldDuration = "Flypaper:MaxHoldDuration"; public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks"; public const string RetentionDays = "Flypaper:Retention:Days"; + public const string DripContent = "Flypaper:Drip:Content"; + public const string DripMinDelay = "Flypaper:Drip:MinDelay"; + public const string DripMaxDelay = "Flypaper:Drip:MaxDelay"; + public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize"; + public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize"; - public static readonly IReadOnlySet All = new HashSet(StringComparer.OrdinalIgnoreCase) - { - MaxConnections, - MaxConnectionsPerIp, - MaxHoldDuration, - IgnorePrivateNetworks, - RetentionDays - }; + public static readonly IReadOnlyList General = + [MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays]; + + public static readonly IReadOnlyList HoldMethod = + [DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, MaxHoldDuration]; + + public static readonly IReadOnlySet All = + new HashSet(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase); } diff --git a/src/Flypaper.Core/Strategies/DripContent.cs b/src/Flypaper.Core/Strategies/DripContent.cs new file mode 100644 index 0000000..bbcf16e --- /dev/null +++ b/src/Flypaper.Core/Strategies/DripContent.cs @@ -0,0 +1,8 @@ +namespace Flypaper.Core.Strategies; + +public enum DripContent +{ + Html, + Text, + Alternating +} diff --git a/src/Flypaper.Core/Strategies/DripOptions.cs b/src/Flypaper.Core/Strategies/DripOptions.cs index 111717c..391c972 100644 --- a/src/Flypaper.Core/Strategies/DripOptions.cs +++ b/src/Flypaper.Core/Strategies/DripOptions.cs @@ -4,6 +4,8 @@ public sealed class DripOptions { public const string SectionName = "Flypaper:Drip"; + public DripContent Content { get; set; } = DripContent.Html; + public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50); public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1); diff --git a/src/Flypaper.Core/Strategies/DripStrategy.cs b/src/Flypaper.Core/Strategies/DripStrategy.cs new file mode 100644 index 0000000..877f031 --- /dev/null +++ b/src/Flypaper.Core/Strategies/DripStrategy.cs @@ -0,0 +1,38 @@ +using System.Globalization; +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; +using Microsoft.Extensions.Options; + +namespace Flypaper.Core.Strategies; + +public abstract class DripStrategy( + IOptionsMonitor options, + IRandomSource random, + TimeProvider timeProvider) : ITarpitStrategy, IStrategyDetails +{ + public abstract string Name { get; } + + public abstract string MediaType { get; } + + public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http; + + public string Describe() + { + var current = options.CurrentValue; + return string.Create( + CultureInfo.InvariantCulture, + $"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B"); + } + + public async Task RunAsync(ITrapChannel channel, CancellationToken ct) + { + foreach (var step in DripSchedule.Create(Content(random), random, options.CurrentValue)) + { + ct.ThrowIfCancellationRequested(); + await channel.WriteAsync(step.Chunk, ct); + await Task.Delay(step.Delay, timeProvider, ct); + } + } + + protected abstract IEnumerable Content(IRandomSource random); +} diff --git a/src/Flypaper.Core/Strategies/HtmlContent.cs b/src/Flypaper.Core/Strategies/HtmlContent.cs index 81e24b8..a7d960f 100644 --- a/src/Flypaper.Core/Strategies/HtmlContent.cs +++ b/src/Flypaper.Core/Strategies/HtmlContent.cs @@ -14,24 +14,6 @@ public static class HtmlContent a { color: #0b5cad; } """; - private static readonly string[] Vocabulary = - [ - "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", - "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim", - "veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea", - "commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse", - "cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident", - "sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent", - "luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum", - "lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi", - "senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus", - "ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque", - "viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis", - "posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida", - "dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam", - "accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus" - ]; - private static readonly string[] Sections = ["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"]; @@ -78,7 +60,7 @@ public static class HtmlContent var count = random.Next(3, 7); for (var i = 0; i < count; i++) { - builder.Append($"{Capitalize(Pick(random, Vocabulary))}\n"); + builder.Append($"{LoremText.Capitalize(LoremText.Word(random))}\n"); } return builder.Append("\n").ToString(); @@ -145,8 +127,8 @@ public static class HtmlContent continue; } - var word = Pick(random, Vocabulary); - builder.Append(i == 0 ? Capitalize(word) : word); + var word = LoremText.Word(random); + builder.Append(i == 0 ? LoremText.Capitalize(word) : word); } return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString(); @@ -154,17 +136,13 @@ public static class HtmlContent private static string Link(IRandomSource random, int words) { - var text = Phrase(random, words); + var text = LoremText.Phrase(random, words); var slug = text.Replace(' ', '-'); return $"{text}"; } - private static string Title(IRandomSource random, int min, int max) => Capitalize(Phrase(random, random.Next(min, max + 1))); - - private static string Phrase(IRandomSource random, int count) => - string.Join(' ', Enumerable.Range(0, count).Select(_ => Pick(random, Vocabulary))); + private static string Title(IRandomSource random, int min, int max) => LoremText.Capitalize(LoremText.Phrase(random, random.Next(min, max + 1))); private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)]; - private static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..]; } diff --git a/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs b/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs index 0f0d9a5..af3791c 100644 --- a/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs +++ b/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs @@ -1,5 +1,4 @@ using Flypaper.Core.Abstractions; -using Flypaper.Core.Models; using Microsoft.Extensions.Options; namespace Flypaper.Core.Strategies; @@ -7,19 +6,13 @@ namespace Flypaper.Core.Strategies; public sealed class HtmlDripStrategy( IOptionsMonitor options, IRandomSource random, - TimeProvider timeProvider) : ITarpitStrategy + TimeProvider timeProvider) : DripStrategy(options, random, timeProvider) { - public string Name => "html-drip"; + public const string StrategyName = "html-drip"; - public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http; + public override string Name => StrategyName; - public async Task RunAsync(ITrapChannel channel, CancellationToken ct) - { - foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue)) - { - ct.ThrowIfCancellationRequested(); - await channel.WriteAsync(step.Chunk, ct); - await Task.Delay(step.Delay, timeProvider, ct); - } - } + public override string MediaType => "text/html; charset=utf-8"; + + protected override IEnumerable Content(IRandomSource random) => HtmlContent.Generate(random); } diff --git a/src/Flypaper.Core/Strategies/LoremText.cs b/src/Flypaper.Core/Strategies/LoremText.cs new file mode 100644 index 0000000..842df02 --- /dev/null +++ b/src/Flypaper.Core/Strategies/LoremText.cs @@ -0,0 +1,50 @@ +using System.Text; +using Flypaper.Core.Abstractions; + +namespace Flypaper.Core.Strategies; + +internal static class LoremText +{ + private static readonly string[] Vocabulary = + [ + "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod", + "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim", + "veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea", + "commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse", + "cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident", + "sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent", + "luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum", + "lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi", + "senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus", + "ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque", + "viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis", + "posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida", + "dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam", + "accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus" + ]; + + public static string Word(IRandomSource random) => Vocabulary[random.Next(0, Vocabulary.Length)]; + + public static string Phrase(IRandomSource random, int count) => + string.Join(' ', Enumerable.Range(0, count).Select(_ => Word(random))); + + public static string Sentence(IRandomSource random) + { + var builder = new StringBuilder(); + var words = random.Next(4, 21); + for (var i = 0; i < words; i++) + { + if (i > 0) + { + builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " "); + } + + var word = Word(random); + builder.Append(i == 0 ? Capitalize(word) : word); + } + + return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString(); + } + + public static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..]; +} diff --git a/src/Flypaper.Core/Strategies/TextContent.cs b/src/Flypaper.Core/Strategies/TextContent.cs new file mode 100644 index 0000000..51ba9a2 --- /dev/null +++ b/src/Flypaper.Core/Strategies/TextContent.cs @@ -0,0 +1,27 @@ +using System.Text; +using Flypaper.Core.Abstractions; + +namespace Flypaper.Core.Strategies; + +public static class TextContent +{ + public static IEnumerable Generate(IRandomSource random) + { + while (true) + { + var builder = new StringBuilder(); + var sentences = random.Next(1, 7); + for (var i = 0; i < sentences; i++) + { + if (i > 0) + { + builder.Append(' '); + } + + builder.Append(LoremText.Sentence(random)); + } + + yield return builder.Append(random.Next(0, 4) == 0 ? "\n\n" : "\n").ToString(); + } + } +} diff --git a/src/Flypaper.Core/Strategies/TextDripStrategy.cs b/src/Flypaper.Core/Strategies/TextDripStrategy.cs new file mode 100644 index 0000000..89b6c88 --- /dev/null +++ b/src/Flypaper.Core/Strategies/TextDripStrategy.cs @@ -0,0 +1,18 @@ +using Flypaper.Core.Abstractions; +using Microsoft.Extensions.Options; + +namespace Flypaper.Core.Strategies; + +public sealed class TextDripStrategy( + IOptionsMonitor options, + IRandomSource random, + TimeProvider timeProvider) : DripStrategy(options, random, timeProvider) +{ + public const string StrategyName = "text-drip"; + + public override string Name => StrategyName; + + public override string MediaType => "text/plain; charset=utf-8"; + + protected override IEnumerable Content(IRandomSource random) => TextContent.Generate(random); +} diff --git a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs index 98bdc7d..61c7a8d 100644 --- a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs +++ b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs @@ -39,7 +39,7 @@ internal sealed class FlypaperMiddleware( var outcome = await runner.RunAsync( trapContext, - ct => OpenChannelAsync(context, session, ct), + (strategy, ct) => OpenChannelAsync(context, session, strategy, ct), context.RequestAborted); if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted) @@ -59,6 +59,7 @@ internal sealed class FlypaperMiddleware( private static async ValueTask OpenChannelAsync( HttpContext context, TrapSession session, + ITarpitStrategy strategy, CancellationToken ct) { var minDataRate = context.Features.Get(); @@ -71,7 +72,7 @@ internal sealed class FlypaperMiddleware( var response = context.Response; response.StatusCode = StatusCodes.Status200OK; - response.ContentType = "text/html; charset=utf-8"; + response.ContentType = strategy is IStrategyDetails details ? details.MediaType : "text/html; charset=utf-8"; response.Headers.CacheControl = "no-store"; response.Headers["X-Accel-Buffering"] = "no"; await response.StartAsync(ct); diff --git a/src/Flypaper.Storage/Queries/CatchQueries.cs b/src/Flypaper.Storage/Queries/CatchQueries.cs index b4dfd8e..e5853e6 100644 --- a/src/Flypaper.Storage/Queries/CatchQueries.cs +++ b/src/Flypaper.Storage/Queries/CatchQueries.cs @@ -166,6 +166,7 @@ public sealed class CatchQueries(IDbContextFactory dbContextF e.DurationMs / 1000d, e.BytesSent, e.Outcome, + e.Strategy, e.RemoteIp, e.CountryCode, e.Country, diff --git a/src/Flypaper.Storage/Queries/CatchRecords.cs b/src/Flypaper.Storage/Queries/CatchRecords.cs index 169c647..e290477 100644 --- a/src/Flypaper.Storage/Queries/CatchRecords.cs +++ b/src/Flypaper.Storage/Queries/CatchRecords.cs @@ -9,6 +9,7 @@ public sealed record CatchRecord( double DurationSeconds, long BytesSent, TrapOutcome Outcome, + string Strategy, string Ip, string? CountryCode, string? Country, diff --git a/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs b/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs index 0cf03aa..54b4010 100644 --- a/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs +++ b/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs @@ -12,33 +12,42 @@ public sealed partial class RuntimeSettingsStore( { private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray(); - public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) + public Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) => + SaveValuesAsync(settings.ToConfiguration(), ct); + + public Task SaveAsync(HoldMethodSettings settings, CancellationToken ct = default) => + SaveValuesAsync(settings.ToConfiguration(), ct); + + public async Task ResetAsync(IReadOnlyCollection? keys = null, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + await RuntimeSettings(db, keys).ExecuteDeleteAsync(ct); + Reload(); + } + + public async Task HasOverridesAsync(IReadOnlyCollection? keys = null, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await RuntimeSettings(db, keys).AnyAsync(ct); + } + + private async Task SaveValuesAsync(IReadOnlyDictionary values, CancellationToken ct) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var transaction = await db.Database.BeginTransactionAsync(ct); - await RuntimeSettings(db).ExecuteDeleteAsync(ct); - db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value })); + await RuntimeSettings(db, values.Keys.ToArray()).ExecuteDeleteAsync(ct); + db.Settings.AddRange(values.Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value })); await db.SaveChangesAsync(ct); await transaction.CommitAsync(ct); Reload(); } - public async Task ResetAsync(CancellationToken ct = default) + private static IQueryable RuntimeSettings(FlypaperDbContext db, IReadOnlyCollection? keys = null) { - await using var db = await dbContextFactory.CreateDbContextAsync(ct); - await RuntimeSettings(db).ExecuteDeleteAsync(ct); - Reload(); + var selected = keys?.Where(key => SettingKeys.All.Contains(key)).ToArray() ?? RuntimeKeys; + return db.Settings.Where(setting => selected.Contains(setting.Key)); } - public async Task HasOverridesAsync(CancellationToken ct = default) - { - await using var db = await dbContextFactory.CreateDbContextAsync(ct); - return await RuntimeSettings(db).AnyAsync(ct); - } - - private static IQueryable RuntimeSettings(FlypaperDbContext db) => - db.Settings.Where(setting => RuntimeKeys.Contains(setting.Key)); - private void Reload() { if (!source.TryReload()) diff --git a/src/Flypaper.Web/Components/Pages/Settings/HoldMethodModel.cs b/src/Flypaper.Web/Components/Pages/Settings/HoldMethodModel.cs new file mode 100644 index 0000000..7d84fef --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Settings/HoldMethodModel.cs @@ -0,0 +1,16 @@ +namespace Flypaper.Web.Components.Pages.Settings; + +public sealed class HoldMethodModel +{ + public string? Content { get; set; } + + public string? MinDelayMs { get; set; } + + public string? MaxDelayMs { get; set; } + + public string? MinChunkSize { get; set; } + + public string? MaxChunkSize { get; set; } + + public string? MaxHoldDuration { get; set; } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/HoldMethodSection.razor b/src/Flypaper.Web/Components/Pages/Settings/HoldMethodSection.razor new file mode 100644 index 0000000..860fa2f --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Settings/HoldMethodSection.razor @@ -0,0 +1,156 @@ +@using System.Globalization +@using Flypaper.Core +@using Flypaper.Core.Settings +@using Flypaper.Core.Strategies +@using Flypaper.Storage.Settings +@using Microsoft.Extensions.Options +@inject IOptionsMonitor Drip +@inject IOptionsMonitor Core +@inject RuntimeSettingsStore Store +@inject NavigationManager Navigation + +
+
+

Haltemethode

+ @if (_hasOverrides) + { + Überschrieben + } +
+ + @if (Saved == "saved") + { + + } + else if (Saved == "reset") + { + + } + + + + + + + + + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+ + + +
+
+ +

+ Pause 10 ms bis 30 s, Paket 1 bis 4096 Bytes. Ø ca. @Bandwidth Bytes/s pro gefangener Verbindung. +

+ +
+ +
+
+ + +
+ +
+
+
+ + + +@code { + private readonly object _resetModel = new(); + private IReadOnlyDictionary _errors = new Dictionary(); + private bool _hasOverrides; + + [SupplyParameterFromForm(FormName = "hold-method")] private HoldMethodModel? Model { get; set; } + + [SupplyParameterFromQuery(Name = "hold")] private string? Saved { get; set; } + + private string Bandwidth + { + get + { + var ok = int.TryParse(Model?.MinDelayMs, out var minDelay) & int.TryParse(Model?.MaxDelayMs, out var maxDelay) + & int.TryParse(Model?.MinChunkSize, out var minChunk) & int.TryParse(Model?.MaxChunkSize, out var maxChunk); + if (!ok) + { + return "–"; + } + + var bytesPerSecond = HoldMethodSettings.AverageBytesPerSecond( + TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay), minChunk, maxChunk); + return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", CultureInfo.GetCultureInfo("de-DE")); + } + } + + protected override async Task OnInitializedAsync() + { + Model ??= CurrentValues(); + _hasOverrides = await Store.HasOverridesAsync(SettingKeys.HoldMethod.ToArray()); + } + + private async Task SaveAsync() + { + var result = RuntimeSettingsParser.ParseHoldMethod(new HoldMethodInput( + Model!.Content, + Model.MinDelayMs, + Model.MaxDelayMs, + Model.MinChunkSize, + Model.MaxChunkSize, + Model.MaxHoldDuration)); + + if (result.Settings is null) + { + _errors = result.Errors; + return; + } + + await Store.SaveAsync(result.Settings); + Navigation.NavigateTo("/settings?hold=saved#hold-method"); + } + + private async Task ResetAsync() + { + await Store.ResetAsync(SettingKeys.HoldMethod.ToArray()); + Navigation.NavigateTo("/settings?hold=reset#hold-method"); + } + + private HoldMethodModel CurrentValues() + { + var drip = Drip.CurrentValue; + return new HoldMethodModel + { + Content = drip.Content.ToString(), + MinDelayMs = ((int)drip.MinDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture), + MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture), + MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture), + MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture), + MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture) + }; + } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs b/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs index e4fa3f2..8518e5f 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs +++ b/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs @@ -6,8 +6,6 @@ public sealed class SettingsModel public string? MaxConnectionsPerIp { get; set; } - public string? MaxHoldDuration { get; set; } - public string? RetentionDays { get; set; } public bool IgnorePrivateNetworks { get; set; } diff --git a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor index 5dc7fec..e1021bb 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor +++ b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor @@ -35,15 +35,12 @@ else if (Saved == "reset") } + + -

Anpassbar

+

Allgemein

-
- - - -
@@ -121,7 +118,6 @@ else if (Saved == "reset") var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput( Model!.MaxConnections, Model.MaxConnectionsPerIp, - Model.MaxHoldDuration, Model.RetentionDays, Model.IgnorePrivateNetworks)); @@ -146,7 +142,6 @@ else if (Saved == "reset") var core = Core.CurrentValue; return new SettingsModel { - MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture), MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture), MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture), RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture), diff --git a/src/Flypaper.Web/Mcp/FlypaperTools.cs b/src/Flypaper.Web/Mcp/FlypaperTools.cs index cf32661..c8db7b1 100644 --- a/src/Flypaper.Web/Mcp/FlypaperTools.cs +++ b/src/Flypaper.Web/Mcp/FlypaperTools.cs @@ -169,6 +169,7 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove Round(record.DurationSeconds), record.BytesSent, record.Outcome.ToString(), + record.Strategy, record.Ip, record.CountryCode, CountryNames.Display(record.CountryCode, record.Country), diff --git a/src/Flypaper.Web/Mcp/McpResults.cs b/src/Flypaper.Web/Mcp/McpResults.cs index cc7a154..f12be10 100644 --- a/src/Flypaper.Web/Mcp/McpResults.cs +++ b/src/Flypaper.Web/Mcp/McpResults.cs @@ -7,6 +7,7 @@ public sealed record CatchItem( double DurationSeconds, long BytesSent, string Outcome, + string Strategy, string Ip, string? CountryCode, string? Country, diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css index 5172759..b9cf09b 100644 --- a/src/Flypaper.Web/wwwroot/app.css +++ b/src/Flypaper.Web/wwwroot/app.css @@ -636,3 +636,23 @@ button.danger { overflow-wrap: anywhere; user-select: all; } + +.section-head { + display: flex; + align-items: center; + gap: 8px; +} + +.section-head h2 { + margin: 0; +} + +select { + width: 100%; + padding: 8px 10px; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--bg); + color: var(--text); + font: inherit; +} diff --git a/src/Flypaper.Web/wwwroot/settings.js b/src/Flypaper.Web/wwwroot/settings.js new file mode 100644 index 0000000..39774ae --- /dev/null +++ b/src/Flypaper.Web/wwwroot/settings.js @@ -0,0 +1,23 @@ +(() => { + const value = id => Number.parseInt(document.getElementById(id)?.value ?? "", 10); + const output = document.getElementById("drip-bandwidth"); + if (!output) { + return; + } + + const update = () => { + const minDelay = value("drip-min-delay"); + const maxDelay = value("drip-max-delay"); + const minChunk = value("drip-min-chunk"); + const maxChunk = value("drip-max-chunk"); + const averageDelay = (minDelay + maxDelay) / 2000; + const bytesPerSecond = (minChunk + maxChunk) / 2 / averageDelay; + output.textContent = Number.isFinite(bytesPerSecond) && bytesPerSecond > 0 + ? bytesPerSecond.toLocaleString("de-DE", { maximumFractionDigits: bytesPerSecond < 10 ? 1 : 0 }) + : "–"; + }; + + for (const input of document.querySelectorAll("[data-bandwidth-input]")) { + input.addEventListener("input", update); + } +})(); diff --git a/test/Flypaper.Tests/Core/HoldMethodParserTests.cs b/test/Flypaper.Tests/Core/HoldMethodParserTests.cs new file mode 100644 index 0000000..eb86a1f --- /dev/null +++ b/test/Flypaper.Tests/Core/HoldMethodParserTests.cs @@ -0,0 +1,73 @@ +using Flypaper.Core.Settings; +using Flypaper.Core.Strategies; +using Shouldly; + +namespace Flypaper.Tests.Core; + +public sealed class HoldMethodParserTests +{ + private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "01:00:00"); + + [Fact] + public void Parses_valid_input() + { + var settings = RuntimeSettingsParser.ParseHoldMethod(Valid).Settings.ShouldNotBeNull(); + + settings.Content.ShouldBe(DripContent.Alternating); + settings.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50)); + settings.MaxDelay.ShouldBe(TimeSpan.FromSeconds(1)); + settings.MinChunkSize.ShouldBe(1); + settings.MaxChunkSize.ShouldBe(64); + settings.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1)); + settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true); + } + + [Theory] + [InlineData("html", DripContent.Html)] + [InlineData("Text", DripContent.Text)] + public void Accepts_content_case_insensitively(string value, DripContent expected) => + RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Settings.ShouldNotBeNull().Content.ShouldBe(expected); + + [Theory] + [InlineData("")] + [InlineData("fake-env")] + [InlineData("7")] + public void Rejects_unknown_content(string value) => + RuntimeSettingsParser.ParseHoldMethod(Valid with { Content = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.Content)]); + + [Theory] + [InlineData("9", "1000")] + [InlineData("50", "30001")] + [InlineData("x", "1000")] + public void Rejects_delays_out_of_range(string min, string max) => + RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = min, MaxDelayMs = max }).Settings.ShouldBeNull(); + + [Theory] + [InlineData("0", "64")] + [InlineData("1", "4097")] + public void Rejects_chunk_sizes_out_of_range(string min, string max) => + RuntimeSettingsParser.ParseHoldMethod(Valid with { MinChunkSize = min, MaxChunkSize = max }).Settings.ShouldBeNull(); + + [Fact] + public void Requires_minimum_not_above_maximum() + { + var errors = RuntimeSettingsParser.ParseHoldMethod(Valid with { MinDelayMs = "2000", MaxDelayMs = "1000", MinChunkSize = "100", MaxChunkSize = "10" }).Errors; + + errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxDelayMs), nameof(HoldMethodInput.MaxChunkSize)], ignoreOrder: true); + } + + [Theory] + [InlineData("10")] + [InlineData("00:00:00")] + [InlineData("8.00:00:00")] + public void Rejects_invalid_hold_durations(string value) => + RuntimeSettingsParser.ParseHoldMethod(Valid with { MaxHoldDuration = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.MaxHoldDuration)]); + + [Fact] + public void Computes_average_bandwidth() + { + HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromMilliseconds(50), TimeSpan.FromSeconds(1), 1, 64) + .ShouldBe(61.9, tolerance: 0.1); + HoldMethodSettings.AverageBytesPerSecond(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), 10, 10).ShouldBe(10); + } +} diff --git a/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs b/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs index d7625da..9572e76 100644 --- a/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs +++ b/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs @@ -5,7 +5,7 @@ namespace Flypaper.Tests.Core; public sealed class RuntimeSettingsParserTests { - private static readonly RuntimeSettingsInput Valid = new("200", "5", "00:30:00", "90", true); + private static readonly RuntimeSettingsInput Valid = new("200", "5", "90", true); [Fact] public void Parses_valid_input() @@ -16,7 +16,6 @@ public sealed class RuntimeSettingsParserTests var settings = result.Settings.ShouldNotBeNull(); settings.MaxConnections.ShouldBe(200); settings.MaxConnectionsPerIp.ShouldBe(5); - settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30)); settings.RetentionDays.ShouldBe(90); settings.IgnorePrivateNetworks.ShouldBeTrue(); } @@ -45,19 +44,6 @@ public sealed class RuntimeSettingsParserTests settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false"); } - [Theory] - [InlineData("10")] - [InlineData("abc")] - [InlineData("")] - [InlineData("00:00:00")] - [InlineData("8.00:00:00")] - public void Rejects_invalid_hold_durations(string value) - { - var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = value }); - - result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration)); - } - [Theory] [InlineData("0")] [InlineData("-3")] @@ -81,19 +67,11 @@ public sealed class RuntimeSettingsParserTests result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.MaxConnectionsPerIp)]); } - [Fact] - public void Rejects_hold_duration_out_of_range() - { - var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = "00:00:00.5" }); - - result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration)); - } - [Fact] public void Exposes_only_whitelisted_configuration_keys() { var keys = RuntimeSettingsParser.Parse(Valid).Settings.ShouldNotBeNull().ToConfiguration().Keys; - keys.ShouldBe(SettingKeys.All, ignoreOrder: true); + keys.ShouldBe(SettingKeys.General, ignoreOrder: true); } } diff --git a/test/Flypaper.Tests/Core/StrategySelectionTests.cs b/test/Flypaper.Tests/Core/StrategySelectionTests.cs new file mode 100644 index 0000000..511e2aa --- /dev/null +++ b/test/Flypaper.Tests/Core/StrategySelectionTests.cs @@ -0,0 +1,79 @@ +using System.Net; +using System.Text; +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; +using Flypaper.Core.Runtime; +using Flypaper.Core.Strategies; +using Flypaper.Tests.Fakes; +using Shouldly; + +namespace Flypaper.Tests.Core; + +public sealed class StrategySelectionTests +{ + private static readonly TrapContext Http = + new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow)); + + [Theory] + [InlineData(DripContent.Html, "html-drip")] + [InlineData(DripContent.Text, "text-drip")] + public void Selects_the_configured_content(DripContent content, string expected) => + Selector(content).Select(Http).ShouldNotBeNull().Name.ShouldBe(expected); + + [Fact] + public void Alternating_picks_both_strategies() + { + var selector = Selector(DripContent.Alternating); + + var names = Enumerable.Range(0, 50).Select(_ => selector.Select(Http)!.Name).Distinct().ToList(); + + names.ShouldBe(["html-drip", "text-drip"], ignoreOrder: true); + } + + [Fact] + public void Returns_nothing_for_unsupported_protocols() + { + var ssh = Http with { Session = Http.Session with { Protocol = TrapProtocol.Ssh } }; + + Selector(DripContent.Html).Select(ssh).ShouldBeNull(); + } + + [Fact] + public void Strategies_describe_themselves_with_their_parameters() + { + var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(100), MaxDelay = TimeSpan.FromMilliseconds(250), MinChunkSize = 2, MaxChunkSize = 8 }); + var text = new TextDripStrategy(options, new SeededRandomSource(1), TimeProvider.System); + + text.Describe().ShouldBe("text-drip 100-250ms 2-8B"); + text.MediaType.ShouldStartWith("text/plain"); + new HtmlDripStrategy(options, new SeededRandomSource(1), TimeProvider.System).MediaType.ShouldStartWith("text/html"); + } + + [Fact] + public async Task Text_strategy_drips_plain_text() + { + var strategy = new TextDripStrategy( + TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(2), MinChunkSize = 32, MaxChunkSize = 64 }), + new SeededRandomSource(3), + TimeProvider.System); + var channel = new FakeTrapChannel(); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200)); + + await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token)); + + var text = Encoding.UTF8.GetString(channel.Writes.SelectMany(w => w).ToArray()); + text.Length.ShouldBeGreaterThan(200); + text.ShouldNotContain("<"); + text.ShouldContain("\n"); + } + + private static ConfiguredStrategySelector Selector(DripContent content) + { + var options = TestOptions.Monitor(new DripOptions { Content = content }); + var random = new SeededRandomSource(11); + return new ConfiguredStrategySelector( + [new HtmlDripStrategy(options, random, TimeProvider.System), new TextDripStrategy(options, random, TimeProvider.System)], + options, + random); + } +} diff --git a/test/Flypaper.Tests/Core/TrapRunnerTests.cs b/test/Flypaper.Tests/Core/TrapRunnerTests.cs index 62355cf..fe09370 100644 --- a/test/Flypaper.Tests/Core/TrapRunnerTests.cs +++ b/test/Flypaper.Tests/Core/TrapRunnerTests.cs @@ -25,7 +25,7 @@ public sealed class TrapRunnerTests var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync( Context(), - _ => + (_, _) => { opened = true; return ValueTask.FromResult(_channel); @@ -59,7 +59,7 @@ public sealed class TrapRunnerTests var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token); outcome.ShouldBe(TrapOutcome.ClientAborted); - _sink.Received(1).Publish(Arg.Is(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip")); + _sink.Received(1).Publish(Arg.Is(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip 5-20ms 1-64B")); } [Theory] @@ -111,17 +111,16 @@ public sealed class TrapRunnerTests return lease; } - private ValueTask Open(CancellationToken ct) => ValueTask.FromResult(_channel); + private ValueTask Open(ITarpitStrategy strategy, CancellationToken ct) => ValueTask.FromResult(_channel); private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true) { - var drip = new HtmlDripStrategy( - TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) }), - new SeededRandomSource(7), - TimeProvider.System); + var dripOptions = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) }); + var random = new SeededRandomSource(7); + var drip = new HtmlDripStrategy(dripOptions, random, TimeProvider.System); return new TrapRunner( _governor, - new ProtocolStrategySelector([drip]), + new ConfiguredStrategySelector([drip], dripOptions, random), _sink, TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }), TimeProvider.System, diff --git a/test/Flypaper.Tests/Http/ContentTypeTests.cs b/test/Flypaper.Tests/Http/ContentTypeTests.cs new file mode 100644 index 0000000..0431039 --- /dev/null +++ b/test/Flypaper.Tests/Http/ContentTypeTests.cs @@ -0,0 +1,49 @@ +using System.Net; +using Flypaper.Core; +using Flypaper.Core.Abstractions; +using Flypaper.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Shouldly; + +namespace Flypaper.Tests.Http; + +public sealed class ContentTypeTests +{ + [Theory] + [InlineData("Html", "text/html; charset=utf-8")] + [InlineData("Text", "text/plain; charset=utf-8")] + public async Task Trap_answers_with_the_media_type_of_the_selected_strategy(string content, string expected) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Flypaper:MaxHoldDuration"] = "00:00:00.100", + ["Flypaper:Drip:Content"] = content, + ["Flypaper:Drip:MinDelay"] = "00:00:00.005", + ["Flypaper:Drip:MaxDelay"] = "00:00:00.010" + }) + .Build(); + var services = new ServiceCollection() + .AddLogging() + .AddSingleton(Substitute.For()) + .AddFlypaperCore(configuration) + .AddFlypaperHttp(configuration) + .BuildServiceProvider(); + + var app = new ApplicationBuilder(services); + app.UseFlypaper(); + var context = new DefaultHttpContext { RequestServices = services }; + context.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9"); + context.Connection.LocalPort = 8080; + context.Request.Path = "/"; + + await app.Build()(context); + + context.Response.StatusCode.ShouldBe(StatusCodes.Status200OK); + context.Response.ContentType.ShouldBe(expected); + } +} diff --git a/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs b/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs index be399bb..623dd3a 100644 --- a/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs +++ b/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs @@ -1,5 +1,6 @@ using Flypaper.Core; using Flypaper.Core.Settings; +using Flypaper.Core.Strategies; using Flypaper.Http; using Flypaper.Storage; using Flypaper.Storage.Entities; @@ -64,11 +65,10 @@ public sealed class SettingsOverrideTests : IDisposable var options = host.Services.GetRequiredService>(); var store = host.Services.GetRequiredService(); - await store.SaveAsync(new RuntimeSettings(50, 4, TimeSpan.FromMinutes(10), 90, false)); + await store.SaveAsync(new RuntimeSettings(50, 4, 90, false)); options.CurrentValue.MaxConnections.ShouldBe(50); options.CurrentValue.MaxConnectionsPerIp.ShouldBe(4); - options.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(10)); options.CurrentValue.IgnorePrivateNetworks.ShouldBeFalse(); (await store.HasOverridesAsync()).ShouldBeTrue(); @@ -79,6 +79,36 @@ public sealed class SettingsOverrideTests : IDisposable (await store.HasOverridesAsync()).ShouldBeFalse(); } + [Fact] + public async Task Hold_method_is_saved_and_reset_separately_from_general_settings() + { + var host = BuildHost(); + await host.Services.MigrateFlypaperDatabaseAsync(); + var core = host.Services.GetRequiredService>(); + var drip = host.Services.GetRequiredService>(); + var store = host.Services.GetRequiredService(); + string[] holdKeys = [.. SettingKeys.HoldMethod]; + + await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, TimeSpan.FromMinutes(5))); + await store.SaveAsync(new RuntimeSettings(50, 4, 90, true)); + + drip.CurrentValue.Content.ShouldBe(DripContent.Text); + drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(200)); + drip.CurrentValue.MaxChunkSize.ShouldBe(16); + core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(5)); + core.CurrentValue.MaxConnections.ShouldBe(50); + (await store.HasOverridesAsync(holdKeys)).ShouldBeTrue(); + + await store.ResetAsync(holdKeys); + + drip.CurrentValue.Content.ShouldBe(DripContent.Html); + drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50)); + core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1)); + core.CurrentValue.MaxConnections.ShouldBe(50); + (await store.HasOverridesAsync(holdKeys)).ShouldBeFalse(); + (await store.HasOverridesAsync()).ShouldBeTrue(); + } + private IHost BuildHost() { var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });