diff --git a/CHANGELOG.md b/CHANGELOG.md index c32e1f7..73f5f5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,12 +14,24 @@ All notable changes to Flypaper are documented in this file. The format follows ### Added +- Link labyrinth: the HTML page (strategy `maze-drip`, with `link B` suffix) carries about ten links + already in the head start and then a new link every `LinkSpacing` bytes (default 160, `0` = old + `html-drip`). Links match the requested path and host (`/wiki/…`, `/docs/v2/…`, `/blog/2025/03/…`, + `/backup/2025/03/`), mix relative and absolute URLs and always lead to another labyrinth page. + Paths ending in `/` get an Apache-style „Index of /…“ listing (`index-drip`). `/robots.txt` is + served at once and complete (`User-agent: *`, `Disallow: /`, strategy `robots-static`), so well-behaved + crawlers stay out and only bots ignoring it get lost. Link spacing is adjustable on the settings page. +- Robots bait: below `Disallow: /` the robots.txt lists a few unlinked, plausible paths (default + `/backup-2024/`, `/admin-old/`, `/internal/db-export/`, `/old-site/`; `Flypaper__Drip__BaitPaths`, + editable on the settings page, empty = off). Requests to them and everything below get the labyrinth + as strategy `robots-bait` and are held for at least 24 hours, so catches show who read the + robots.txt and ignored it. The labyrinth never links to these paths. - Dashboard: the catch list has a new „Strategie“ column (hidden on narrower screens, shown in the expanded row) and the search covers it. A new „Strategien“ tab in the Top 10 card shows catches and hold time per strategy and filters the list on click. The MCP `top` tool accepts `strategies` as a dimension. - Content matches the requested path: `.env`, `*.json`, `*.xml` (sitemaps), `*.yml`, `*.sql`, - `/.git/…`, `robots.txt`, Hikvision `/SDK/…` and `/ISAPI/…` (XML) and `wp-login.php` + `/.git/…`, Hikvision `/SDK/…` and `/ISAPI/…` (XML) and `wp-login.php` (WordPress login page) get an endless, matching file with the right `Content-Type` instead of an HTML page (strategy names `env-drip`, `json-drip`, …). Switchable on the settings page (`Flypaper__Drip__MatchPath`). diff --git a/docs/configuration.md b/docs/configuration.md index 7c1fd01..fe2849c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -24,7 +24,9 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...). | `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` | | `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` | | `Flypaper__Drip__HeadStartSize` | Bytes sent immediately before dripping starts (`0` = off) | `1024` | -| `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `robots.txt`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` | +| `Flypaper__Drip__LinkSpacing` | Link labyrinth: bytes of text between two links in the HTML page (`0` = off, plain `html-drip`) | `160` | +| `Flypaper__Drip__BaitPaths` | Comma-separated decoy paths listed in `robots.txt` (max. 8, empty = off); requests to them get `robots-bait` and are held for at least 24 h | `/backup-2024/,/admin-old/,/internal/db-export/,/old-site/` | +| `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` | | `TZ` | Time zone for the dashboard | UTC | The defaults of the runtime settings below can also be set this way, e.g. diff --git a/src/Flypaper.Core/Abstractions/IHoldExtension.cs b/src/Flypaper.Core/Abstractions/IHoldExtension.cs new file mode 100644 index 0000000..00d20a6 --- /dev/null +++ b/src/Flypaper.Core/Abstractions/IHoldExtension.cs @@ -0,0 +1,6 @@ +namespace Flypaper.Core.Abstractions; + +public interface IHoldExtension +{ + TimeSpan MinimumHold { get; } +} diff --git a/src/Flypaper.Core/Abstractions/ITrapChannel.cs b/src/Flypaper.Core/Abstractions/ITrapChannel.cs index fe8082f..9093a4c 100644 --- a/src/Flypaper.Core/Abstractions/ITrapChannel.cs +++ b/src/Flypaper.Core/Abstractions/ITrapChannel.cs @@ -6,5 +6,9 @@ public interface ITrapChannel { TrapSession Session { get; } + string? Path => null; + + string? Host => null; + ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken ct); } diff --git a/src/Flypaper.Core/FlypaperCoreExtensions.cs b/src/Flypaper.Core/FlypaperCoreExtensions.cs index ac033f8..3cf5939 100644 --- a/src/Flypaper.Core/FlypaperCoreExtensions.cs +++ b/src/Flypaper.Core/FlypaperCoreExtensions.cs @@ -21,6 +21,16 @@ public static class FlypaperCoreExtensions services.TryAddSingleton(); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + foreach (var kind in Enum.GetValues()) + { + services.AddSingleton(provider => new MazeDripStrategy( + kind, + provider.GetRequiredService>(), + provider.GetRequiredService(), + provider.GetRequiredService())); + } + foreach (var profile in FileContent.Profiles) { services.AddSingleton(provider => new FileDripStrategy( diff --git a/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs b/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs index c1d8bf9..905aa75 100644 --- a/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs +++ b/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs @@ -13,22 +13,42 @@ public sealed class ConfiguredStrategySelector( public ITarpitStrategy? Select(TrapContext context) { var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList(); + if (string.Equals(context.Path, RobotsStaticStrategy.Path, StringComparison.OrdinalIgnoreCase) + && candidates.FirstOrDefault(strategy => strategy.Name == RobotsStaticStrategy.StrategyName) is { } robots) + { + return robots; + } + + if (BaitPaths.Matches(BaitPaths.Parse(options.CurrentValue.BaitPaths), context.Path) + && candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.BaitName) is { } bait) + { + return bait; + } + if (options.CurrentValue.MatchPath && FileContent.Match(context.Path) is { } profile && candidates.FirstOrDefault(strategy => strategy.Name == profile.Name) is { } fileStrategy) { return fileStrategy; } + var maze = options.CurrentValue.LinkSpacing > 0 + && candidates.Any(strategy => strategy.Name == MazeDripStrategy.PageName); + var page = maze ? MazeDripStrategy.PageName : HtmlDripStrategy.StrategyName; string[] wanted = options.CurrentValue.Content switch { DripContent.Text => [TextDripStrategy.StrategyName], - DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName], - _ => [HtmlDripStrategy.StrategyName] + DripContent.Alternating => [page, TextDripStrategy.StrategyName], + _ => [page] }; var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList(); - return matching.Count == 0 + var chosen = matching.Count == 0 ? candidates.FirstOrDefault() : matching[random.Next(0, matching.Count)]; + + return chosen?.Name == MazeDripStrategy.PageName && MazeContent.IsDirectory(context.Path) + && candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.ListingName) is { } listing + ? listing + : chosen; } } diff --git a/src/Flypaper.Core/Runtime/CountingTrapChannel.cs b/src/Flypaper.Core/Runtime/CountingTrapChannel.cs index ece9e57..311a1bc 100644 --- a/src/Flypaper.Core/Runtime/CountingTrapChannel.cs +++ b/src/Flypaper.Core/Runtime/CountingTrapChannel.cs @@ -9,6 +9,10 @@ internal sealed class CountingTrapChannel(ITrapChannel inner) : ITrapChannel public TrapSession Session => inner.Session; + public string? Path => inner.Path; + + public string? Host => inner.Host; + public long BytesSent => Interlocked.Read(ref _bytesSent); public async ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken ct) diff --git a/src/Flypaper.Core/Runtime/TrapRunner.cs b/src/Flypaper.Core/Runtime/TrapRunner.cs index 24c5610..cf8f080 100644 --- a/src/Flypaper.Core/Runtime/TrapRunner.cs +++ b/src/Flypaper.Core/Runtime/TrapRunner.cs @@ -31,7 +31,13 @@ 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); + var holdDuration = options.CurrentValue.MaxHoldDuration; + if (strategy is IHoldExtension extension && extension.MinimumHold > holdDuration) + { + holdDuration = extension.MinimumHold; + } + + using var hold = new CancellationTokenSource(holdDuration, timeProvider); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token); CountingTrapChannel? channel = null; diff --git a/src/Flypaper.Core/Settings/HoldMethodSettings.cs b/src/Flypaper.Core/Settings/HoldMethodSettings.cs index 36e08a3..880ae73 100644 --- a/src/Flypaper.Core/Settings/HoldMethodSettings.cs +++ b/src/Flypaper.Core/Settings/HoldMethodSettings.cs @@ -11,6 +11,8 @@ public sealed record HoldMethodSettings( int MaxChunkSize, int HeadStartSize, bool MatchPath, + int LinkSpacing, + string BaitPaths, TimeSpan MaxHoldDuration) { public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize); @@ -24,6 +26,8 @@ public sealed record HoldMethodSettings( [SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture), [SettingKeys.DripHeadStartSize] = HeadStartSize.ToString(CultureInfo.InvariantCulture), [SettingKeys.DripMatchPath] = MatchPath ? "true" : "false", + [SettingKeys.DripLinkSpacing] = LinkSpacing.ToString(CultureInfo.InvariantCulture), + [SettingKeys.DripBaitPaths] = BaitPaths, [SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture) }; @@ -42,6 +46,8 @@ public sealed record HoldMethodInput( string? MaxChunkSize, string? HeadStartSize, bool MatchPath, + string? LinkSpacing, + string? BaitPaths, string? MaxHoldDuration); public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary Errors); diff --git a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs index 85eae90..2900a31 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs @@ -14,6 +14,7 @@ public static class RuntimeSettingsParser private const int MaxDelayMs = 30_000; private const int MaxChunkSize = 4096; private const int MaxHeadStartSize = 65_536; + private const int MaxLinkSpacing = 4096; public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input) { @@ -59,6 +60,8 @@ public static class RuntimeSettingsParser var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors); var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 1, MaxChunkSize, errors); var headStart = ParseInt(input.HeadStartSize, nameof(input.HeadStartSize), 0, MaxHeadStartSize, errors); + var linkSpacing = ParseInt(input.LinkSpacing, nameof(input.LinkSpacing), 0, MaxLinkSpacing, errors); + var baits = ParseBaitPaths(input.BaitPaths, nameof(input.BaitPaths), errors); var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors); if (minDelay > maxDelay) @@ -85,10 +88,32 @@ public static class RuntimeSettingsParser maxChunk!.Value, headStart!.Value, input.MatchPath, + linkSpacing!.Value, + baits!, hold!.Value), errors); } + private static string? ParseBaitPaths(string? raw, string field, Dictionary errors) + { + var entries = BaitPaths.Split(raw); + var normalized = entries.Select(BaitPaths.Normalize).ToList(); + if (normalized.Any(entry => entry is null)) + { + errors[field] = "Pfade wie /backup-2024/, ohne Leerzeichen; nicht /robots.txt und nicht unter den Labyrinth-Ordnern (wiki, docs, blog, backup …)."; + return null; + } + + var distinct = normalized.OfType().Distinct().ToList(); + if (distinct.Count > BaitPaths.MaxCount) + { + errors[field] = $"Höchstens {BaitPaths.MaxCount} Pfade."; + return null; + } + + return string.Join(',', distinct); + } + 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 0be7ea7..c69f48f 100644 --- a/src/Flypaper.Core/Settings/SettingKeys.cs +++ b/src/Flypaper.Core/Settings/SettingKeys.cs @@ -14,12 +14,14 @@ public static class SettingKeys public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize"; public const string DripHeadStartSize = "Flypaper:Drip:HeadStartSize"; public const string DripMatchPath = "Flypaper:Drip:MatchPath"; + public const string DripBaitPaths = "Flypaper:Drip:BaitPaths"; + public const string DripLinkSpacing = "Flypaper:Drip:LinkSpacing"; public static readonly IReadOnlyList General = [MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays]; public static readonly IReadOnlyList HoldMethod = - [DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, MaxHoldDuration]; + [DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration]; public static readonly IReadOnlySet All = new HashSet(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase); diff --git a/src/Flypaper.Core/Strategies/BaitPaths.cs b/src/Flypaper.Core/Strategies/BaitPaths.cs new file mode 100644 index 0000000..8700484 --- /dev/null +++ b/src/Flypaper.Core/Strategies/BaitPaths.cs @@ -0,0 +1,52 @@ +using System.Text.RegularExpressions; + +namespace Flypaper.Core.Strategies; + +public static partial class BaitPaths +{ + public const int MaxCount = 8; + + public const string Default = "/backup-2024/,/admin-old/,/internal/db-export/,/old-site/"; + + [GeneratedRegex("^/[A-Za-z0-9._~-]+(/[A-Za-z0-9._~-]+)*/?$")] + private static partial Regex Valid(); + + public static IReadOnlyList Split(string? raw) => + (raw ?? "").Split([',', ';', ' ', '\n', '\r', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + + public static string? Normalize(string entry) + { + if (!Valid().IsMatch(entry) || entry.Length > 100) + { + return null; + } + + var normalized = entry.ToLowerInvariant(); + if (!normalized.EndsWith('/')) + { + normalized += "/"; + } + + var first = normalized.Split('/', StringSplitOptions.RemoveEmptyEntries)[0]; + return normalized == RobotsStaticStrategy.Path + "/" || Array.IndexOf(MazeContent.Roots, first) >= 0 ? null : normalized; + } + + public static IReadOnlyList Parse(string? raw) => + Split(raw).Select(Normalize).OfType().Distinct().Take(MaxCount).ToList(); + + public static bool Matches(IReadOnlyList baits, string? path) + { + if (string.IsNullOrEmpty(path) || baits.Count == 0) + { + return false; + } + + var normalized = path.ToLowerInvariant(); + if (!normalized.EndsWith('/')) + { + normalized += "/"; + } + + return baits.Any(bait => normalized.StartsWith(bait, StringComparison.Ordinal)); + } +} diff --git a/src/Flypaper.Core/Strategies/DripOptions.cs b/src/Flypaper.Core/Strategies/DripOptions.cs index dd89bd8..d5f0da4 100644 --- a/src/Flypaper.Core/Strategies/DripOptions.cs +++ b/src/Flypaper.Core/Strategies/DripOptions.cs @@ -17,4 +17,8 @@ public sealed class DripOptions public int HeadStartSize { get; set; } = 1024; public bool MatchPath { get; set; } = true; + + public int LinkSpacing { get; set; } = 160; + + public string BaitPaths { get; set; } = Strategies.BaitPaths.Default; } diff --git a/src/Flypaper.Core/Strategies/DripStrategy.cs b/src/Flypaper.Core/Strategies/DripStrategy.cs index 61e18a9..feac196 100644 --- a/src/Flypaper.Core/Strategies/DripStrategy.cs +++ b/src/Flypaper.Core/Strategies/DripStrategy.cs @@ -22,13 +22,13 @@ public abstract class DripStrategy( var head = current.HeadStartSize > 0 ? $" head {current.HeadStartSize}B" : ""; return string.Create( CultureInfo.InvariantCulture, - $"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B{head}"); + $"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B{head}{Extra(current)}"); } public async Task RunAsync(ITrapChannel channel, CancellationToken ct) { var current = options.CurrentValue; - using var fragments = Content(random).GetEnumerator(); + using var fragments = Content(random, channel, current).GetEnumerator(); var head = DripSchedule.TakeHead(fragments, current.HeadStartSize); if (head.Length > 0) @@ -44,5 +44,7 @@ public abstract class DripStrategy( } } - protected abstract IEnumerable Content(IRandomSource random); + protected virtual string Extra(DripOptions options) => ""; + + protected abstract IEnumerable Content(IRandomSource random, ITrapChannel channel, DripOptions options); } diff --git a/src/Flypaper.Core/Strategies/FileContent.cs b/src/Flypaper.Core/Strategies/FileContent.cs index 43d4cac..4b3ee50 100644 --- a/src/Flypaper.Core/Strategies/FileContent.cs +++ b/src/Flypaper.Core/Strategies/FileContent.cs @@ -11,12 +11,9 @@ public sealed record FileProfile( public static class FileContent { - private static readonly string[] Sections = ["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files"]; - public static readonly IReadOnlyList Profiles = [ new("git-drip", "text/plain; charset=utf-8", path => path.Contains("/.git/", StringComparison.Ordinal), GitConfig), - new("robots-drip", "text/plain; charset=utf-8", path => LastSegment(path) == "robots.txt", Robots), new("wordpress-drip", "text/html; charset=UTF-8", path => LastSegment(path) == "wp-login.php", WordPressLogin), new("hikvision-drip", "application/xml", path => path.StartsWith("/sdk/", StringComparison.Ordinal) || path.StartsWith("/isapi/", StringComparison.Ordinal), Hikvision), new("env-drip", "text/plain; charset=utf-8", path => IsEnv(LastSegment(path)), Env), @@ -131,7 +128,7 @@ public static class FileContent while (true) { var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}"); - yield return $" \n https://example.com/{Pick(random, Sections)}/{LoremText.Phrase(random, 2).Replace(' ', '-')}\n {date}\n \n"; + yield return $" \n https://example.com/{Pick(random, MazeContent.Roots)}/{LoremText.Phrase(random, 2).Replace(' ', '-')}\n {date}\n \n"; } } @@ -170,16 +167,6 @@ public static class FileContent } } - private static IEnumerable Robots(IRandomSource random) - { - yield return "User-agent: *\nCrawl-delay: 2\nSitemap: https://example.com/sitemap.xml\n"; - - while (true) - { - yield return $"Disallow: /{Pick(random, Sections)}/{LoremText.Word(random)}/\n"; - } - } - private static string Hex(IRandomSource random, int length) { var chars = new char[length]; diff --git a/src/Flypaper.Core/Strategies/FileDripStrategy.cs b/src/Flypaper.Core/Strategies/FileDripStrategy.cs index 0da7caf..cacaebd 100644 --- a/src/Flypaper.Core/Strategies/FileDripStrategy.cs +++ b/src/Flypaper.Core/Strategies/FileDripStrategy.cs @@ -13,5 +13,5 @@ public sealed class FileDripStrategy( public override string MediaType => profile.MediaType; - protected override IEnumerable Content(IRandomSource random) => profile.Generate(random); + protected override IEnumerable Content(IRandomSource random, ITrapChannel channel, DripOptions options) => profile.Generate(random); } diff --git a/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs b/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs index af3791c..418d0fd 100644 --- a/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs +++ b/src/Flypaper.Core/Strategies/HtmlDripStrategy.cs @@ -14,5 +14,5 @@ public sealed class HtmlDripStrategy( public override string MediaType => "text/html; charset=utf-8"; - protected override IEnumerable Content(IRandomSource random) => HtmlContent.Generate(random); + protected override IEnumerable Content(IRandomSource random, ITrapChannel channel, DripOptions options) => HtmlContent.Generate(random); } diff --git a/src/Flypaper.Core/Strategies/MazeContent.cs b/src/Flypaper.Core/Strategies/MazeContent.cs new file mode 100644 index 0000000..13c9eef --- /dev/null +++ b/src/Flypaper.Core/Strategies/MazeContent.cs @@ -0,0 +1,231 @@ +using System.Globalization; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; +using Flypaper.Core.Abstractions; + +namespace Flypaper.Core.Strategies; + +public static partial class MazeContent +{ + public static readonly string[] Roots = + ["wiki", "docs", "blog", "backup", "archive", "files", "kb", "guides", "releases", "news", "help", "support", "products"]; + + private const int MaxDepth = 6; + + public static bool IsDirectory(string? path) => path is { Length: > 1 } && path[^1] == '/'; + + public static IEnumerable Page(IRandomSource random, string? path, string? host, int spacing) + { + var site = new Site(path, host); + var siteName = site.Host ?? "Portal"; + var title = $"{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 4)))} · {siteName}"; + + yield return $$""" + + + + + + {{title}} + + + +
+

{{title}}

+ + """; + yield return Navigation(random, site); + yield return "
\n
\n

Related pages

\n" + List(random, site, random.Next(7, 11)); + yield return "

"; + + var minFiller = Math.Max(1, spacing / 2); + var maxFiller = Math.Max(minFiller, spacing * 3 / 2); + while (true) + { + var words = Math.Max(2, random.Next(minFiller, maxFiller + 1) / 7); + yield return $"{LoremText.Capitalize(LoremText.Phrase(random, words))}. {Anchor(random, site)} "; + + switch (random.Next(0, 8)) + { + case 0: + yield return $"

\n{List(random, site, random.Next(3, 6))}

"; + break; + case 1: + yield return $"

\n

{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 6)))}

\n

"; + break; + } + } + } + + public static IEnumerable Listing(IRandomSource random, string? path, string? host) + { + var site = new Site(path, host); + var shown = WebUtility.HtmlEncode(site.DisplayPath); + var wide = site.Section is "backup" or "files" or "archive"; + + yield return $$""" + + + + Index of {{shown}} + + +

Index of {{shown}}

+
Name{{new string(' ', 46)}}Last modified      Size
+            
Parent Directory - + + """; + + while (true) + { + yield return Entry(random, site, wide); + } + } + + private static string Entry(IRandomSource random, Site site, bool wide) + { + var slug = Slug(random, site); + var directory = random.Next(0, 3) == 0; + var name = directory + ? slug + "/" + : wide + ? $"{slug}-{Date(random)[..10]}{Pick(random, [".tar.gz", ".zip", ".bak", ".gz"])}" + : $"{slug}{Pick(random, [".html", ".html", ".htm", ".txt"])}"; + var size = directory + ? "-" + : random.Next(0, 4) == 0 + ? string.Create(CultureInfo.InvariantCulture, $"{random.Next(1, 900)}.{random.Next(0, 10)}M") + : string.Create(CultureInfo.InvariantCulture, $"{random.Next(1, 900)}K"); + + var href = random.Next(0, 5) == 0 ? Absolute(random, site) : name; + var padding = new string(' ', Math.Max(1, 50 - name.Length)); + return $"{name}{padding}{Date(random)} {size}\n"; + } + + private static string Date(IRandomSource random) => + string.Create(CultureInfo.InvariantCulture, $"{random.Next(2022, 2027)}-{random.Next(1, 13):00}-{random.Next(1, 29):00} {random.Next(0, 24):00}:{random.Next(0, 60):00}"); + + private static string Navigation(IRandomSource random, Site site) + { + var builder = new StringBuilder("\n").ToString(); + } + + private static string List(IRandomSource random, Site site, int items) + { + var builder = new StringBuilder("
    \n"); + for (var i = 0; i < items; i++) + { + builder.Append($"
  • {Anchor(random, site)}
  • \n"); + } + + return builder.Append("
\n").ToString(); + } + + private static string Anchor(IRandomSource random, Site site) => + $"{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 5)))}"; + + private static string Href(IRandomSource random, Site site, bool rootOnly = false) + { + if (rootOnly) + { + return $"/{Pick(random, Roots)}/"; + } + + var kind = random.Next(0, 10); + if (site.Section is null) + { + kind = 5 + kind % 5; + } + else if (site.Depth >= MaxDepth && kind is 0 or 3) + { + kind = 4; + } + + return kind switch + { + 0 => $"{Slug(random, site)}/", + 1 or 2 => Slug(random, site), + 3 => $"{LoremText.Word(random)}/{Slug(random, site)}", + 4 => random.Next(0, 2) == 0 ? "../" : $"../{Slug(random, site)}", + < 8 => Absolute(random, site), + _ => site.Host is { } host ? $"http://{host}{Absolute(random, site)}" : Absolute(random, site) + }; + } + + private static string Absolute(IRandomSource random, Site site) + { + var root = site.Section is { } section && random.Next(0, 10) < 7 ? section : Pick(random, Roots); + var slug = Slug(random, site); + return root switch + { + "docs" => $"/docs/v{random.Next(1, 5)}/{slug}", + "blog" => string.Create(CultureInfo.InvariantCulture, $"/blog/{random.Next(2022, 2027)}/{random.Next(1, 13):00}/{slug}"), + "backup" => string.Create(CultureInfo.InvariantCulture, $"/backup/{random.Next(2022, 2027)}/{random.Next(1, 13):00}/"), + _ => random.Next(0, 3) == 0 ? $"/{root}/{slug}/" : $"/{root}/{slug}" + }; + } + + private static string Slug(IRandomSource random, Site site) + { + var words = new List(); + var count = random.Next(1, 4); + for (var i = 0; i < count; i++) + { + words.Add(LoremText.Word(random)); + } + + if (site.Topic is { } topic && random.Next(0, 4) == 0) + { + words[0] = topic; + } + + return string.Join('-', words); + } + + private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)]; + + [GeneratedRegex("^[A-Za-z0-9.-]{1,253}$")] + private static partial Regex HostPattern(); + + [GeneratedRegex("^[a-z]{3,}$")] + private static partial Regex TopicPattern(); + + private sealed class Site + { + public Site(string? path, string? host) + { + var normalized = (path ?? "/").ToLowerInvariant(); + var segments = normalized.Split('/', StringSplitOptions.RemoveEmptyEntries); + var endsWithSlash = normalized.EndsWith('/'); + + Section = segments.Length > 0 && Array.IndexOf(Roots, segments[0]) >= 0 ? segments[0] : null; + Depth = endsWithSlash ? segments.Length : Math.Max(0, segments.Length - 1); + Host = host is not null && HostPattern().IsMatch(host) ? host : null; + DisplayPath = normalized.Length > 200 ? normalized[..200] : normalized; + + if (!endsWithSlash && segments.Length > 0) + { + var word = segments[^1].Split('-', '.', '_')[0]; + Topic = TopicPattern().IsMatch(word) ? word : null; + } + } + + public string? Section { get; } + + public int Depth { get; } + + public string? Host { get; } + + public string? Topic { get; } + + public string DisplayPath { get; } + } +} diff --git a/src/Flypaper.Core/Strategies/MazeDripStrategy.cs b/src/Flypaper.Core/Strategies/MazeDripStrategy.cs new file mode 100644 index 0000000..ab8af7d --- /dev/null +++ b/src/Flypaper.Core/Strategies/MazeDripStrategy.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using Flypaper.Core.Abstractions; +using Microsoft.Extensions.Options; + +namespace Flypaper.Core.Strategies; + +public enum MazeKind +{ + Page, + Listing, + Bait +} + +public sealed class MazeDripStrategy( + MazeKind kind, + IOptionsMonitor options, + IRandomSource random, + TimeProvider timeProvider) : DripStrategy(options, random, timeProvider), IHoldExtension +{ + public const string PageName = "maze-drip"; + + public const string ListingName = "index-drip"; + + public const string BaitName = "robots-bait"; + + public override string Name => kind switch + { + MazeKind.Listing => ListingName, + MazeKind.Bait => BaitName, + _ => PageName + }; + + public override string MediaType => "text/html; charset=utf-8"; + + public TimeSpan MinimumHold => kind == MazeKind.Bait ? TimeSpan.FromHours(24) : TimeSpan.Zero; + + protected override string Extra(DripOptions options) => + string.Create(CultureInfo.InvariantCulture, $" link {options.LinkSpacing}B"); + + protected override IEnumerable Content(IRandomSource random, ITrapChannel channel, DripOptions options) => + kind == MazeKind.Listing || kind == MazeKind.Bait && MazeContent.IsDirectory(channel.Path) + ? MazeContent.Listing(random, channel.Path, channel.Host) + : MazeContent.Page(random, channel.Path, channel.Host, options.LinkSpacing); +} diff --git a/src/Flypaper.Core/Strategies/RobotsStaticStrategy.cs b/src/Flypaper.Core/Strategies/RobotsStaticStrategy.cs new file mode 100644 index 0000000..697d99d --- /dev/null +++ b/src/Flypaper.Core/Strategies/RobotsStaticStrategy.cs @@ -0,0 +1,27 @@ +using System.Text; +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; +using Microsoft.Extensions.Options; + +namespace Flypaper.Core.Strategies; + +public sealed class RobotsStaticStrategy(IOptionsMonitor options) : ITarpitStrategy, IStrategyDetails +{ + public const string StrategyName = "robots-static"; + + public const string Path = "/robots.txt"; + + public string Name => StrategyName; + + public string MediaType => "text/plain; charset=utf-8"; + + public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http; + + public string Describe() => Name; + + public async Task RunAsync(ITrapChannel channel, CancellationToken ct) => + await channel.WriteAsync(Encoding.UTF8.GetBytes(Body()), ct); + + public string Body() => + "User-agent: *\nDisallow: /\n" + string.Concat(BaitPaths.Parse(options.CurrentValue.BaitPaths).Select(bait => $"Disallow: {bait}\n")); +} diff --git a/src/Flypaper.Core/Strategies/TextDripStrategy.cs b/src/Flypaper.Core/Strategies/TextDripStrategy.cs index 89b6c88..23209ab 100644 --- a/src/Flypaper.Core/Strategies/TextDripStrategy.cs +++ b/src/Flypaper.Core/Strategies/TextDripStrategy.cs @@ -14,5 +14,5 @@ public sealed class TextDripStrategy( public override string MediaType => "text/plain; charset=utf-8"; - protected override IEnumerable Content(IRandomSource random) => TextContent.Generate(random); + protected override IEnumerable Content(IRandomSource random, ITrapChannel channel, DripOptions options) => TextContent.Generate(random); } diff --git a/src/Flypaper.Http/HttpTrapChannel.cs b/src/Flypaper.Http/HttpTrapChannel.cs index 1d55edb..71b0923 100644 --- a/src/Flypaper.Http/HttpTrapChannel.cs +++ b/src/Flypaper.Http/HttpTrapChannel.cs @@ -8,6 +8,10 @@ internal sealed class HttpTrapChannel(TrapSession session, HttpResponse response { public TrapSession Session => session; + public string? Path => response.HttpContext.Request.Path.Value; + + public string? Host => response.HttpContext.Request.Host.Host; + public async ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken ct) { await response.Body.WriteAsync(data, ct); diff --git a/src/Flypaper.Web/Components/Pages/Settings/HoldMethodModel.cs b/src/Flypaper.Web/Components/Pages/Settings/HoldMethodModel.cs index 7add2b5..c972197 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/HoldMethodModel.cs +++ b/src/Flypaper.Web/Components/Pages/Settings/HoldMethodModel.cs @@ -16,5 +16,9 @@ public sealed class HoldMethodModel public bool MatchPath { get; set; } + public string? LinkSpacing { get; set; } + + public string? BaitPaths { 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 index 7048e6e..2c7bf4e 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/HoldMethodSection.razor +++ b/src/Flypaper.Web/Components/Pages/Settings/HoldMethodSection.razor @@ -59,11 +59,20 @@ + + + +
+ + + +
+