Add link labyrinth, static robots.txt and robots bait paths
Build and deploy / build (push) Successful in 1m28s
Build and deploy / deploy (push) Successful in 20s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-16 23:57:52 +01:00
1 parent b7027e2a72
commit a25072e6fb
29 files changed
+774 -34

No files matched your search

+13 -1
View File
@@ -14,12 +14,24 @@ All notable changes to Flypaper are documented in this file. The format follows
### Added ### Added
- Link labyrinth: the HTML page (strategy `maze-drip`, with `link <n>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 - 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 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 catches and hold time per strategy and filters the list on click. The MCP `top` tool accepts
`strategies` as a dimension. `strategies` as a dimension.
- Content matches the requested path: `.env`, `*.json`, `*.xml` (sitemaps), `*.yml`, `*.sql`, - 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` (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 instead of an HTML page (strategy names `env-drip`, `json-drip`, …). Switchable on the
settings page (`Flypaper__Drip__MatchPath`). settings page (`Flypaper__Drip__MatchPath`).
+3 -1
View File
@@ -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__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` | | `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
| `Flypaper__Drip__HeadStartSize` | Bytes sent immediately before dripping starts (`0` = off) | `1024` | | `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 | | `TZ` | Time zone for the dashboard | UTC |
The defaults of the runtime settings below can also be set this way, e.g. The defaults of the runtime settings below can also be set this way, e.g.
@@ -0,0 +1,6 @@
namespace Flypaper.Core.Abstractions;
public interface IHoldExtension
{
TimeSpan MinimumHold { get; }
}
@@ -6,5 +6,9 @@ public interface ITrapChannel
{ {
TrapSession Session { get; } TrapSession Session { get; }
string? Path => null;
string? Host => null;
ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct); ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct);
} }
@@ -21,6 +21,16 @@ public static class FlypaperCoreExtensions
services.TryAddSingleton<IRandomSource, SystemRandomSource>(); services.TryAddSingleton<IRandomSource, SystemRandomSource>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>());
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, RobotsStaticStrategy>());
foreach (var kind in Enum.GetValues<MazeKind>())
{
services.AddSingleton<ITarpitStrategy>(provider => new MazeDripStrategy(
kind,
provider.GetRequiredService<IOptionsMonitor<DripOptions>>(),
provider.GetRequiredService<IRandomSource>(),
provider.GetRequiredService<TimeProvider>()));
}
foreach (var profile in FileContent.Profiles) foreach (var profile in FileContent.Profiles)
{ {
services.AddSingleton<ITarpitStrategy>(provider => new FileDripStrategy( services.AddSingleton<ITarpitStrategy>(provider => new FileDripStrategy(
@@ -13,22 +13,42 @@ public sealed class ConfiguredStrategySelector(
public ITarpitStrategy? Select(TrapContext context) public ITarpitStrategy? Select(TrapContext context)
{ {
var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList(); 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 if (options.CurrentValue.MatchPath && FileContent.Match(context.Path) is { } profile
&& candidates.FirstOrDefault(strategy => strategy.Name == profile.Name) is { } fileStrategy) && candidates.FirstOrDefault(strategy => strategy.Name == profile.Name) is { } fileStrategy)
{ {
return 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 string[] wanted = options.CurrentValue.Content switch
{ {
DripContent.Text => [TextDripStrategy.StrategyName], DripContent.Text => [TextDripStrategy.StrategyName],
DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName], DripContent.Alternating => [page, TextDripStrategy.StrategyName],
_ => [HtmlDripStrategy.StrategyName] _ => [page]
}; };
var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList(); var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList();
return matching.Count == 0 var chosen = matching.Count == 0
? candidates.FirstOrDefault() ? candidates.FirstOrDefault()
: matching[random.Next(0, matching.Count)]; : 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;
} }
} }
@@ -9,6 +9,10 @@ internal sealed class CountingTrapChannel(ITrapChannel inner) : ITrapChannel
public TrapSession Session => inner.Session; public TrapSession Session => inner.Session;
public string? Path => inner.Path;
public string? Host => inner.Host;
public long BytesSent => Interlocked.Read(ref _bytesSent); public long BytesSent => Interlocked.Read(ref _bytesSent);
public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct) public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
+7 -1
View File
@@ -31,7 +31,13 @@ public sealed partial class TrapRunner(
using var _ = lease; using var _ = lease;
var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name; 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); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
CountingTrapChannel? channel = null; CountingTrapChannel? channel = null;
@@ -11,6 +11,8 @@ public sealed record HoldMethodSettings(
int MaxChunkSize, int MaxChunkSize,
int HeadStartSize, int HeadStartSize,
bool MatchPath, bool MatchPath,
int LinkSpacing,
string BaitPaths,
TimeSpan MaxHoldDuration) TimeSpan MaxHoldDuration)
{ {
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize); public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
@@ -24,6 +26,8 @@ public sealed record HoldMethodSettings(
[SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture), [SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripHeadStartSize] = HeadStartSize.ToString(CultureInfo.InvariantCulture), [SettingKeys.DripHeadStartSize] = HeadStartSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripMatchPath] = MatchPath ? "true" : "false", [SettingKeys.DripMatchPath] = MatchPath ? "true" : "false",
[SettingKeys.DripLinkSpacing] = LinkSpacing.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripBaitPaths] = BaitPaths,
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture) [SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
}; };
@@ -42,6 +46,8 @@ public sealed record HoldMethodInput(
string? MaxChunkSize, string? MaxChunkSize,
string? HeadStartSize, string? HeadStartSize,
bool MatchPath, bool MatchPath,
string? LinkSpacing,
string? BaitPaths,
string? MaxHoldDuration); string? MaxHoldDuration);
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors); public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
@@ -14,6 +14,7 @@ public static class RuntimeSettingsParser
private const int MaxDelayMs = 30_000; private const int MaxDelayMs = 30_000;
private const int MaxChunkSize = 4096; private const int MaxChunkSize = 4096;
private const int MaxHeadStartSize = 65_536; private const int MaxHeadStartSize = 65_536;
private const int MaxLinkSpacing = 4096;
public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input) 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 minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 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 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); var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
if (minDelay > maxDelay) if (minDelay > maxDelay)
@@ -85,10 +88,32 @@ public static class RuntimeSettingsParser
maxChunk!.Value, maxChunk!.Value,
headStart!.Value, headStart!.Value,
input.MatchPath, input.MatchPath,
linkSpacing!.Value,
baits!,
hold!.Value), hold!.Value),
errors); errors);
} }
private static string? ParseBaitPaths(string? raw, string field, Dictionary<string, string> 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<string>().Distinct().ToList();
if (distinct.Count > BaitPaths.MaxCount)
{
errors[field] = $"Höchstens {BaitPaths.MaxCount} Pfade.";
return null;
}
return string.Join(',', distinct);
}
private static TimeSpan? ParseTimeSpan( private static TimeSpan? ParseTimeSpan(
string? raw, string? raw,
string field, string field,
+3 -1
View File
@@ -14,12 +14,14 @@ public static class SettingKeys
public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize"; public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize";
public const string DripHeadStartSize = "Flypaper:Drip:HeadStartSize"; public const string DripHeadStartSize = "Flypaper:Drip:HeadStartSize";
public const string DripMatchPath = "Flypaper:Drip:MatchPath"; 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<string> General = public static readonly IReadOnlyList<string> General =
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays]; [MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
public static readonly IReadOnlyList<string> HoldMethod = public static readonly IReadOnlyList<string> HoldMethod =
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, MaxHoldDuration]; [DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration];
public static readonly IReadOnlySet<string> All = public static readonly IReadOnlySet<string> All =
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase); new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
+52
View File
@@ -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<string> 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<string> Parse(string? raw) =>
Split(raw).Select(Normalize).OfType<string>().Distinct().Take(MaxCount).ToList();
public static bool Matches(IReadOnlyList<string> 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));
}
}
@@ -17,4 +17,8 @@ public sealed class DripOptions
public int HeadStartSize { get; set; } = 1024; public int HeadStartSize { get; set; } = 1024;
public bool MatchPath { get; set; } = true; public bool MatchPath { get; set; } = true;
public int LinkSpacing { get; set; } = 160;
public string BaitPaths { get; set; } = Strategies.BaitPaths.Default;
} }
+5 -3
View File
@@ -22,13 +22,13 @@ public abstract class DripStrategy(
var head = current.HeadStartSize > 0 ? $" head {current.HeadStartSize}B" : ""; var head = current.HeadStartSize > 0 ? $" head {current.HeadStartSize}B" : "";
return string.Create( return string.Create(
CultureInfo.InvariantCulture, 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) public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
{ {
var current = options.CurrentValue; 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); var head = DripSchedule.TakeHead(fragments, current.HeadStartSize);
if (head.Length > 0) if (head.Length > 0)
@@ -44,5 +44,7 @@ public abstract class DripStrategy(
} }
} }
protected abstract IEnumerable<string> Content(IRandomSource random); protected virtual string Extra(DripOptions options) => "";
protected abstract IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options);
} }
+1 -14
View File
@@ -11,12 +11,9 @@ public sealed record FileProfile(
public static class FileContent public static class FileContent
{ {
private static readonly string[] Sections = ["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files"];
public static readonly IReadOnlyList<FileProfile> Profiles = public static readonly IReadOnlyList<FileProfile> Profiles =
[ [
new("git-drip", "text/plain; charset=utf-8", path => path.Contains("/.git/", StringComparison.Ordinal), GitConfig), 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("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("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), new("env-drip", "text/plain; charset=utf-8", path => IsEnv(LastSegment(path)), Env),
@@ -131,7 +128,7 @@ public static class FileContent
while (true) while (true)
{ {
var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}"); var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}");
yield return $" <url>\n <loc>https://example.com/{Pick(random, Sections)}/{LoremText.Phrase(random, 2).Replace(' ', '-')}</loc>\n <lastmod>{date}</lastmod>\n </url>\n"; yield return $" <url>\n <loc>https://example.com/{Pick(random, MazeContent.Roots)}/{LoremText.Phrase(random, 2).Replace(' ', '-')}</loc>\n <lastmod>{date}</lastmod>\n </url>\n";
} }
} }
@@ -170,16 +167,6 @@ public static class FileContent
} }
} }
private static IEnumerable<string> 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) private static string Hex(IRandomSource random, int length)
{ {
var chars = new char[length]; var chars = new char[length];
@@ -13,5 +13,5 @@ public sealed class FileDripStrategy(
public override string MediaType => profile.MediaType; public override string MediaType => profile.MediaType;
protected override IEnumerable<string> Content(IRandomSource random) => profile.Generate(random); protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => profile.Generate(random);
} }
@@ -14,5 +14,5 @@ public sealed class HtmlDripStrategy(
public override string MediaType => "text/html; charset=utf-8"; public override string MediaType => "text/html; charset=utf-8";
protected override IEnumerable<string> Content(IRandomSource random) => HtmlContent.Generate(random); protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => HtmlContent.Generate(random);
} }
+231
View File
@@ -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<string> 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 $$"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{title}}</title>
<style>body{margin:0 auto;max-width:52rem;padding:1.5rem;font:16px/1.6 system-ui,sans-serif}nav a{margin-right:1rem}</style>
</head>
<body>
<header>
<h1>{{title}}</h1>
""";
yield return Navigation(random, site);
yield return "</header>\n<main>\n<h2>Related pages</h2>\n" + List(random, site, random.Next(7, 11));
yield return "<p>";
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 $"</p>\n{List(random, site, random.Next(3, 6))}<p>";
break;
case 1:
yield return $"</p>\n<h3>{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 6)))}</h3>\n<p>";
break;
}
}
}
public static IEnumerable<string> 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 $$"""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of {{shown}}</title>
</head>
<body>
<h1>Index of {{shown}}</h1>
<pre>Name{{new string(' ', 46)}}Last modified Size
<hr><a href="../">Parent Directory</a> -
""";
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 $"<a href=\"{href}\">{name}</a>{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("<nav>\n");
var count = random.Next(8, 12);
for (var i = 0; i < count; i++)
{
builder.Append($"<a href=\"{Href(random, site, rootOnly: i % 2 == 0)}\">{LoremText.Capitalize(LoremText.Word(random))}</a>\n");
}
return builder.Append("</nav>\n").ToString();
}
private static string List(IRandomSource random, Site site, int items)
{
var builder = new StringBuilder("<ul>\n");
for (var i = 0; i < items; i++)
{
builder.Append($"<li>{Anchor(random, site)}</li>\n");
}
return builder.Append("</ul>\n").ToString();
}
private static string Anchor(IRandomSource random, Site site) =>
$"<a href=\"{Href(random, site)}\">{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 5)))}</a>";
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<string>();
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; }
}
}
@@ -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<DripOptions> 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<string> 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);
}
@@ -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<DripOptions> 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"));
}
@@ -14,5 +14,5 @@ public sealed class TextDripStrategy(
public override string MediaType => "text/plain; charset=utf-8"; public override string MediaType => "text/plain; charset=utf-8";
protected override IEnumerable<string> Content(IRandomSource random) => TextContent.Generate(random); protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => TextContent.Generate(random);
} }
+4
View File
@@ -8,6 +8,10 @@ internal sealed class HttpTrapChannel(TrapSession session, HttpResponse response
{ {
public TrapSession Session => session; 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<byte> data, CancellationToken ct) public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
{ {
await response.Body.WriteAsync(data, ct); await response.Body.WriteAsync(data, ct);
@@ -16,5 +16,9 @@ public sealed class HoldMethodModel
public bool MatchPath { get; set; } public bool MatchPath { get; set; }
public string? LinkSpacing { get; set; }
public string? BaitPaths { get; set; }
public string? MaxHoldDuration { get; set; } public string? MaxHoldDuration { get; set; }
} }
@@ -59,11 +59,20 @@
<SettingsField Label="Schneller Start" For="drip-head-start" Unit="Bytes" Hint="0 bis 65536, sofort ohne Pause gesendet" Errors="_errors" Key="@nameof(HoldMethodModel.HeadStartSize)"> <SettingsField Label="Schneller Start" For="drip-head-start" Unit="Bytes" Hint="0 bis 65536, sofort ohne Pause gesendet" Errors="_errors" Key="@nameof(HoldMethodModel.HeadStartSize)">
<InputText id="drip-head-start" @bind-Value="Model!.HeadStartSize" inputmode="numeric" /> <InputText id="drip-head-start" @bind-Value="Model!.HeadStartSize" inputmode="numeric" />
</SettingsField> </SettingsField>
<SettingsField Label="Link-Abstand" For="drip-link-spacing" Unit="Bytes" Hint="0 bis 4096, Text zwischen zwei Links, 0 = Labyrinth aus" Errors="_errors" Key="@nameof(HoldMethodModel.LinkSpacing)">
<InputText id="drip-link-spacing" @bind-Value="Model!.LinkSpacing" inputmode="numeric" />
</SettingsField>
<SettingsField Label="Maximale Haltedauer" For="hold" Hint="hh:mm:ss, höchstens 7 Tage" Errors="_errors" Key="@nameof(HoldMethodModel.MaxHoldDuration)"> <SettingsField Label="Maximale Haltedauer" For="hold" Hint="hh:mm:ss, höchstens 7 Tage" Errors="_errors" Key="@nameof(HoldMethodModel.MaxHoldDuration)">
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" /> <InputText id="hold" @bind-Value="Model!.MaxHoldDuration" />
</SettingsField> </SettingsField>
</div> </div>
<div class="fields">
<SettingsField Label="Köder-Pfade in der robots.txt" For="drip-bait-paths" Wide="true" Hint="Kommagetrennt, höchstens 8, leer = keine. Nirgends verlinkt; Anfragen darauf heißen robots-bait und werden 24 Stunden gehalten." Errors="_errors" Key="@nameof(HoldMethodModel.BaitPaths)">
<InputText id="drip-bait-paths" @bind-Value="Model!.BaitPaths" />
</SettingsField>
</div>
<label class="switch-row"> <label class="switch-row">
<InputCheckbox class="switch" @bind-Value="Model!.MatchPath" /> <InputCheckbox class="switch" @bind-Value="Model!.MatchPath" />
<span> <span>
@@ -92,7 +101,7 @@
@code { @code {
private static readonly (string Value, string Title, string Text)[] Choices = private static readonly (string Value, string Title, string Text)[] Choices =
[ [
(nameof(DripContent.Html), "HTML-Fülltext", "Eine endlose Webseite mit Überschriften, Absätzen und Links. Wirkt auf Crawler am echtesten."), (nameof(DripContent.Html), "HTML-Fülltext", "Eine endlose Webseite mit Überschriften, Absätzen und vielen Links, die wieder in die Falle führen (Link-Labyrinth). Wirkt auf Crawler am echtesten."),
(nameof(DripContent.Text), "Zufallstext", "Schlichter Text ohne Markup, ausgeliefert als text/plain."), (nameof(DripContent.Text), "Zufallstext", "Schlichter Text ohne Markup, ausgeliefert als text/plain."),
(nameof(DripContent.Alternating), "Wechselnd", "Pro Fang zufällig eine der beiden. Gut, um zu vergleichen, was Bots länger hält.") (nameof(DripContent.Alternating), "Wechselnd", "Pro Fang zufällig eine der beiden. Gut, um zu vergleichen, was Bots länger hält.")
]; ];
@@ -138,6 +147,8 @@
Model.MaxChunkSize, Model.MaxChunkSize,
Model.HeadStartSize, Model.HeadStartSize,
Model.MatchPath, Model.MatchPath,
Model.LinkSpacing,
Model.BaitPaths,
Model.MaxHoldDuration)); Model.MaxHoldDuration));
if (result.Settings is null) if (result.Settings is null)
@@ -168,6 +179,8 @@
MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture), MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture),
HeadStartSize = drip.HeadStartSize.ToString(CultureInfo.InvariantCulture), HeadStartSize = drip.HeadStartSize.ToString(CultureInfo.InvariantCulture),
MatchPath = drip.MatchPath, MatchPath = drip.MatchPath,
LinkSpacing = drip.LinkSpacing.ToString(CultureInfo.InvariantCulture),
BaitPaths = drip.BaitPaths,
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture) MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
}; };
} }
+22 -4
View File
@@ -18,7 +18,6 @@ public sealed class FileContentTests
[InlineData("/docker-compose.yml", "yaml-drip")] [InlineData("/docker-compose.yml", "yaml-drip")]
[InlineData("/backup/db.sql", "sql-drip")] [InlineData("/backup/db.sql", "sql-drip")]
[InlineData("/.git/config", "git-drip")] [InlineData("/.git/config", "git-drip")]
[InlineData("/robots.txt", "robots-drip")]
[InlineData("/SDK/webLanguage", "hikvision-drip")] [InlineData("/SDK/webLanguage", "hikvision-drip")]
[InlineData("/ISAPI/System/deviceInfo", "hikvision-drip")] [InlineData("/ISAPI/System/deviceInfo", "hikvision-drip")]
[InlineData("/wp-login.php", "wordpress-drip")] [InlineData("/wp-login.php", "wordpress-drip")]
@@ -42,7 +41,6 @@ public sealed class FileContentTests
[InlineData("/docker-compose.yml", "version:")] [InlineData("/docker-compose.yml", "version:")]
[InlineData("/dump.sql", "-- MySQL dump")] [InlineData("/dump.sql", "-- MySQL dump")]
[InlineData("/.git/config", "[core]")] [InlineData("/.git/config", "[core]")]
[InlineData("/robots.txt", "User-agent:")]
[InlineData("/SDK/webLanguage", "<?xml")] [InlineData("/SDK/webLanguage", "<?xml")]
[InlineData("/wp-login.php", "<!DOCTYPE html>")] [InlineData("/wp-login.php", "<!DOCTYPE html>")]
public void Generates_an_endless_file_that_starts_like_the_real_thing(string path, string start) public void Generates_an_endless_file_that_starts_like_the_real_thing(string path, string start)
@@ -62,8 +60,24 @@ public sealed class FileContentTests
var context = new TrapContext(session, "GET /.env", Path: "/.env"); var context = new TrapContext(session, "GET /.env", Path: "/.env");
Selector(matchPath: true).Select(context).ShouldNotBeNull().Name.ShouldBe("env-drip"); Selector(matchPath: true).Select(context).ShouldNotBeNull().Name.ShouldBe("env-drip");
Selector(matchPath: true).Select(context with { Path = "/" }).ShouldNotBeNull().Name.ShouldBe("html-drip"); Selector(matchPath: true).Select(context with { Path = "/" }).ShouldNotBeNull().Name.ShouldBe("maze-drip");
Selector(matchPath: false).Select(context).ShouldNotBeNull().Name.ShouldBe("html-drip"); Selector(matchPath: false).Select(context).ShouldNotBeNull().Name.ShouldBe("maze-drip");
}
[Fact]
public async Task Robots_txt_is_served_completely_and_at_once_even_without_path_matching()
{
var session = new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow);
var context = new TrapContext(session, "GET /robots.txt", Path: "/Robots.txt");
var strategy = Selector(matchPath: false).Select(context).ShouldNotBeNull();
var channel = new FakeTrapChannel();
await strategy.RunAsync(channel, CancellationToken.None);
strategy.Name.ShouldBe("robots-static");
channel.Writes.Count.ShouldBe(1);
Encoding.UTF8.GetString(channel.Writes.Single())
.ShouldBe("User-agent: *\nDisallow: /\nDisallow: /backup-2024/\nDisallow: /admin-old/\nDisallow: /internal/db-export/\nDisallow: /old-site/\n");
} }
[Fact] [Fact]
@@ -89,7 +103,11 @@ public sealed class FileContentTests
return new ConfiguredStrategySelector( return new ConfiguredStrategySelector(
[ [
new HtmlDripStrategy(options, random, TimeProvider.System), new HtmlDripStrategy(options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
new TextDripStrategy(options, random, TimeProvider.System), new TextDripStrategy(options, random, TimeProvider.System),
new RobotsStaticStrategy(options),
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System),
.. FileContent.Profiles.Select(profile => new FileDripStrategy(profile, options, random, TimeProvider.System)) .. FileContent.Profiles.Select(profile => new FileDripStrategy(profile, options, random, TimeProvider.System))
], ],
options, options,
@@ -6,7 +6,7 @@ namespace Flypaper.Tests.Core;
public sealed class HoldMethodParserTests public sealed class HoldMethodParserTests
{ {
private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "2048", true, "01:00:00"); private static readonly HoldMethodInput Valid = new("Alternating", "50", "1000", "1", "64", "2048", true, "80", "/Backup-2024, /admin-old/x", "01:00:00");
[Fact] [Fact]
public void Parses_valid_input() public void Parses_valid_input()
@@ -20,6 +20,8 @@ public sealed class HoldMethodParserTests
settings.MaxChunkSize.ShouldBe(64); settings.MaxChunkSize.ShouldBe(64);
settings.HeadStartSize.ShouldBe(2048); settings.HeadStartSize.ShouldBe(2048);
settings.MatchPath.ShouldBeTrue(); settings.MatchPath.ShouldBeTrue();
settings.LinkSpacing.ShouldBe(80);
settings.BaitPaths.ShouldBe("/backup-2024/,/admin-old/x/");
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1)); settings.MaxHoldDuration.ShouldBe(TimeSpan.FromHours(1));
settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true); settings.ToConfiguration().Keys.ShouldBe(SettingKeys.HoldMethod, ignoreOrder: true);
} }
@@ -71,6 +73,34 @@ public sealed class HoldMethodParserTests
public void Rejects_head_start_out_of_range(string value) => public void Rejects_head_start_out_of_range(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { HeadStartSize = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.HeadStartSize)]); RuntimeSettingsParser.ParseHoldMethod(Valid with { HeadStartSize = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.HeadStartSize)]);
[Theory]
[InlineData("0")]
[InlineData("4096")]
public void Accepts_link_spacing_bounds(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { LinkSpacing = value }).Settings.ShouldNotBeNull();
[Theory]
[InlineData("-1")]
[InlineData("4097")]
[InlineData("")]
public void Rejects_link_spacing_out_of_range(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { LinkSpacing = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.LinkSpacing)]);
[Theory]
[InlineData("")]
[InlineData("/a/,/b/")]
public void Accepts_bait_paths(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { BaitPaths = value }).Settings.ShouldNotBeNull();
[Theory]
[InlineData("backup")]
[InlineData("/robots.txt")]
[InlineData("/wiki/old/")]
[InlineData("/a b<>/")]
[InlineData("/a/,/b/,/c/,/d/,/e/,/f/,/g/,/h/,/i/")]
public void Rejects_invalid_bait_paths(string value) =>
RuntimeSettingsParser.ParseHoldMethod(Valid with { BaitPaths = value }).Errors.Keys.ShouldBe([nameof(HoldMethodInput.BaitPaths)]);
[Theory] [Theory]
[InlineData("10")] [InlineData("10")]
[InlineData("00:00:00")] [InlineData("00:00:00")]
@@ -0,0 +1,217 @@
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Flypaper.Core.Models;
using Flypaper.Core.Runtime;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed partial class MazeContentTests
{
[GeneratedRegex("href=\"([^\"]*)\"")]
private static partial Regex Href();
private static List<string> Links(string html) => Href().Matches(html).Select(match => match.Groups[1].Value).ToList();
[Fact]
public void Head_start_already_carries_many_links()
{
using var fragments = MazeContent.Page(new SeededRandomSource(1), "/wiki/lorem", "example.com", 160).GetEnumerator();
var head = Encoding.UTF8.GetString(DripSchedule.TakeHead(fragments, 1024).Span);
head.Length.ShouldBeGreaterThanOrEqualTo(1024);
Links(head).Count.ShouldBeGreaterThanOrEqualTo(10);
}
[Fact]
public void Keeps_delivering_links_at_the_configured_spacing()
{
var body = string.Concat(MazeContent.Page(new SeededRandomSource(2), "/wiki/lorem", "example.com", 160).Skip(4).Take(40));
var tight = string.Concat(MazeContent.Page(new SeededRandomSource(2), "/wiki/lorem", "example.com", 40).Skip(4).Take(40));
var bytesPerLink = Encoding.UTF8.GetByteCount(body) / (double)Links(body).Count;
var tightBytesPerLink = Encoding.UTF8.GetByteCount(tight) / (double)Links(tight).Count;
bytesPerLink.ShouldBeInRange(100, 450);
tightBytesPerLink.ShouldBeLessThan(bytesPerLink);
}
[Theory]
[InlineData("/")]
[InlineData("/index.php")]
[InlineData("//images/images/cache.php")]
public void Pages_outside_the_roots_only_link_into_the_disallowed_roots(string path)
{
var page = string.Concat(MazeContent.Page(new SeededRandomSource(3), path, "example.com", 80).Take(300));
var baseUri = new Uri("http://example.com" + path);
foreach (var href in Links(page))
{
var target = new Uri(baseUri, href);
target.Host.ShouldBe("example.com");
MazeContent.Roots.ShouldContain(target.AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries).First());
}
}
[Fact]
public void Listings_below_a_root_never_leave_the_root()
{
var listing = string.Concat(MazeContent.Listing(new SeededRandomSource(3), "/files/lorem/", "example.com").Take(200));
var baseUri = new Uri("http://example.com/files/lorem/");
foreach (var href in Links(listing).Where(href => href != "../"))
{
new Uri(baseUri, href).AbsolutePath.Split('/', StringSplitOptions.RemoveEmptyEntries).First().ShouldBeOneOf(MazeContent.Roots);
}
}
[Fact]
public void Relative_links_below_a_root_never_leave_the_root()
{
var page = string.Concat(MazeContent.Page(new SeededRandomSource(4), "/blog/2025/03/lorem", "example.com", 80).Take(300));
var baseUri = new Uri("http://example.com/blog/2025/03/lorem");
foreach (var href in Links(page).Where(href => !href.StartsWith('/') && !href.StartsWith("http", StringComparison.Ordinal)))
{
new Uri(baseUri, href).AbsolutePath.ShouldStartWith("/blog/");
}
}
[Fact]
public void Mixes_relative_and_absolute_links_and_limits_depth()
{
var links = Links(string.Concat(MazeContent.Page(new SeededRandomSource(5), "/docs/lorem", "example.com", 80).Take(300)));
links.ShouldContain(href => href.StartsWith("http://example.com/docs/", StringComparison.Ordinal));
links.ShouldContain(href => href.StartsWith("/docs/", StringComparison.Ordinal));
links.ShouldContain(href => !href.StartsWith('/') && !href.StartsWith("http", StringComparison.Ordinal));
links.ShouldContain(href => href.StartsWith("/blog/20", StringComparison.Ordinal));
var deepPath = "/docs/" + string.Join('/', Enumerable.Repeat("x", 8)) + "/";
var deep = Links(string.Concat(MazeContent.Page(new SeededRandomSource(6), deepPath, null, 80).Take(300)));
deep.ShouldContain("../");
deep.ShouldNotContain(href => href.StartsWith("http", StringComparison.Ordinal));
}
[Fact]
public void Ignores_a_hostile_host_header()
{
var page = string.Concat(MazeContent.Page(new SeededRandomSource(7), "/wiki/a", "evil\"><script>", 80).Take(100));
page.ShouldNotContain("<script>");
Links(page).ShouldNotContain(href => href.StartsWith("http", StringComparison.Ordinal));
}
[Fact]
public void Listing_looks_like_a_directory_index_and_escapes_the_path()
{
var text = string.Concat(MazeContent.Listing(new SeededRandomSource(8), "/backup/<b>/", "example.com").Take(60));
text.ShouldContain("<title>Index of /backup/&lt;b&gt;/</title>");
text.ShouldContain("<a href=\"../\">Parent Directory</a>");
Links(text).Count.ShouldBeGreaterThan(40);
}
[Theory]
[InlineData("/wiki/", "index-drip")]
[InlineData("/", "maze-drip")]
[InlineData("/wiki/lorem", "maze-drip")]
public void Selector_uses_listing_only_for_directories(string path, string expected)
{
var context = new TrapContext(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), Path: path);
Selector(160).Select(context).ShouldNotBeNull().Name.ShouldBe(expected);
Selector(0).Select(context).ShouldNotBeNull().Name.ShouldBe("html-drip");
}
[Fact]
public async Task Strategy_sends_links_in_the_head_start_and_names_its_spacing()
{
var options = TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromSeconds(30), MaxDelay = TimeSpan.FromSeconds(30) });
var strategy = new MazeDripStrategy(MazeKind.Page, options, new SeededRandomSource(9), TimeProvider.System);
var channel = new FakeTrapChannel { Path = "/wiki/lorem", Host = "example.com" };
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(200));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
Links(Encoding.UTF8.GetString(channel.Writes.First())).Count.ShouldBeGreaterThanOrEqualTo(10);
strategy.Describe().ShouldBe("maze-drip 30000-30000ms 1-64B head 1024B link 160B");
strategy.MediaType.ShouldStartWith("text/html");
}
[Theory]
[InlineData("/backup-2024/", true)]
[InlineData("/Backup-2024/old/dump.zip", true)]
[InlineData("/backup-2024", true)]
[InlineData("/internal/db-export/x", true)]
[InlineData("/internal/", false)]
[InlineData("/backup-20245/", false)]
[InlineData("/backup/", false)]
public void Bait_paths_and_everything_below_get_robots_bait(string path, bool bait)
{
var context = new TrapContext(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), Path: path);
Selector(160).Select(context).ShouldNotBeNull().Name.ShouldBe(bait ? "robots-bait" : path.EndsWith('/') ? "index-drip" : "maze-drip");
Selector(0).Select(context).ShouldNotBeNull().Name.ShouldBe(bait ? "robots-bait" : "html-drip");
}
[Fact]
public void Bait_paths_are_never_linked_from_the_maze()
{
var text = string.Concat(MazeContent.Page(new SeededRandomSource(12), "/", "example.com", 40).Take(400))
+ string.Concat(MazeContent.Listing(new SeededRandomSource(12), "/files/", "example.com").Take(400));
foreach (var bait in BaitPaths.Parse(BaitPaths.Default))
{
text.ShouldNotContain(bait.TrimEnd('/'));
}
}
[Fact]
public void Bait_strategy_extends_the_hold_and_keeps_the_maze_content()
{
var options = TestOptions.Monitor(new DripOptions());
var bait = new MazeDripStrategy(MazeKind.Bait, options, new SeededRandomSource(1), TimeProvider.System);
bait.MinimumHold.ShouldBe(TimeSpan.FromHours(24));
bait.Describe().ShouldStartWith("robots-bait ");
new MazeDripStrategy(MazeKind.Page, options, new SeededRandomSource(1), TimeProvider.System).MinimumHold.ShouldBe(TimeSpan.Zero);
}
[Fact]
public void Empty_bait_paths_switch_the_bait_off()
{
var context = new TrapContext(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), Path: "/backup-2024/");
var options = TestOptions.Monitor(new DripOptions { BaitPaths = "" });
var random = new SeededRandomSource(1);
var selector = new ConfiguredStrategySelector(
[
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System)
],
options,
random);
selector.Select(context).ShouldNotBeNull().Name.ShouldBe("index-drip");
}
private static ConfiguredStrategySelector Selector(int spacing)
{
var options = TestOptions.Monitor(new DripOptions { LinkSpacing = spacing });
var random = new SeededRandomSource(11);
return new ConfiguredStrategySelector(
[
new HtmlDripStrategy(options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Page, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Listing, options, random, TimeProvider.System),
new MazeDripStrategy(MazeKind.Bait, options, random, TimeProvider.System)
],
options,
random);
}
}
@@ -9,6 +9,10 @@ internal sealed class FakeTrapChannel : ITrapChannel
{ {
public TrapSession Session { get; } = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Loopback, DateTimeOffset.UtcNow); public TrapSession Session { get; } = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Loopback, DateTimeOffset.UtcNow);
public string? Path { get; init; }
public string? Host { get; init; }
public ConcurrentQueue<byte[]> Writes { get; } = new(); public ConcurrentQueue<byte[]> Writes { get; } = new();
public ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct) public ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
@@ -89,7 +89,7 @@ public sealed class SettingsOverrideTests : IDisposable
var store = host.Services.GetRequiredService<RuntimeSettingsStore>(); var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
string[] holdKeys = [.. SettingKeys.HoldMethod]; string[] holdKeys = [.. SettingKeys.HoldMethod];
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, TimeSpan.FromMinutes(5))); await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "/trap-a/", TimeSpan.FromMinutes(5)));
await store.SaveAsync(new RuntimeSettings(50, 4, 90, true)); await store.SaveAsync(new RuntimeSettings(50, 4, 90, true));
drip.CurrentValue.Content.ShouldBe(DripContent.Text); drip.CurrentValue.Content.ShouldBe(DripContent.Text);
@@ -97,11 +97,17 @@ public sealed class SettingsOverrideTests : IDisposable
drip.CurrentValue.MaxChunkSize.ShouldBe(16); drip.CurrentValue.MaxChunkSize.ShouldBe(16);
drip.CurrentValue.HeadStartSize.ShouldBe(256); drip.CurrentValue.HeadStartSize.ShouldBe(256);
drip.CurrentValue.MatchPath.ShouldBeFalse(); drip.CurrentValue.MatchPath.ShouldBeFalse();
drip.CurrentValue.LinkSpacing.ShouldBe(0);
drip.CurrentValue.BaitPaths.ShouldBe("/trap-a/");
core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(5)); core.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(5));
core.CurrentValue.MaxConnections.ShouldBe(50); core.CurrentValue.MaxConnections.ShouldBe(50);
(await store.HasOverridesAsync(holdKeys)).ShouldBeTrue(); (await store.HasOverridesAsync(holdKeys)).ShouldBeTrue();
await store.SaveAsync(new HoldMethodSettings(DripContent.Text, TimeSpan.FromMilliseconds(200), TimeSpan.FromSeconds(2), 8, 16, 256, false, 0, "", TimeSpan.FromMinutes(5)));
drip.CurrentValue.BaitPaths.ShouldBe("");
await store.ResetAsync(holdKeys); await store.ResetAsync(holdKeys);
drip.CurrentValue.BaitPaths.ShouldBe(BaitPaths.Default);
drip.CurrentValue.Content.ShouldBe(DripContent.Html); drip.CurrentValue.Content.ShouldBe(DripContent.Html);
drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50)); drip.CurrentValue.MinDelay.ShouldBe(TimeSpan.FromMilliseconds(50));