Add data management, randomized HTML drip and public README

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-14 16:08:45 +01:00
1 parent 3671019e60
commit f5d8ca7484
46 files changed
+1601 -172

No files matched your search

@@ -0,0 +1,6 @@
namespace Flypaper.Core.Abstractions;
public interface IRandomSource
{
int Next(int minValue, int maxValue);
}
@@ -0,0 +1,8 @@
using Flypaper.Core.Models;
namespace Flypaper.Core.Abstractions;
public interface ITrapStrategySelector
{
ITarpitStrategy? Select(TrapContext context);
}
+3 -1
View File
@@ -17,7 +17,9 @@ public static class FlypaperCoreExtensions
services.TryAddSingleton(TimeProvider.System);
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, DripStrategy>());
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
services.TryAddSingleton<ITrapStrategySelector, ProtocolStrategySelector>();
services.TryAddSingleton<TrapRunner>();
services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
+2
View File
@@ -9,4 +9,6 @@ public sealed class FlypaperOptions
public int MaxConnectionsPerIp { get; set; } = 10;
public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1);
public bool IgnorePrivateNetworks { get; set; } = true;
}
@@ -0,0 +1,10 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
namespace Flypaper.Core.Runtime;
public sealed class ProtocolStrategySelector(IEnumerable<ITarpitStrategy> strategies) : ITrapStrategySelector
{
public ITarpitStrategy? Select(TrapContext context) =>
strategies.FirstOrDefault(strategy => strategy.Supports(context.Session.Protocol));
}
@@ -0,0 +1,8 @@
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Runtime;
internal sealed class SystemRandomSource : IRandomSource
{
public int Next(int minValue, int maxValue) => Random.Shared.Next(minValue, maxValue);
}
+18 -9
View File
@@ -1,6 +1,7 @@
using System.Net;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Core.Networking;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
@@ -8,7 +9,7 @@ namespace Flypaper.Core.Runtime;
public sealed partial class TrapRunner(
IConnectionGovernor governor,
IEnumerable<ITarpitStrategy> strategies,
ITrapStrategySelector strategies,
ITrapEventSink sink,
IOptionsMonitor<FlypaperOptions> options,
TimeProvider timeProvider,
@@ -20,7 +21,7 @@ public sealed partial class TrapRunner(
CancellationToken ct)
{
var session = context.Session;
var strategy = strategies.FirstOrDefault(s => s.Supports(session.Protocol));
var strategy = strategies.Select(context);
if (strategy is null || !governor.TryAcquire(session, out var lease))
{
@@ -69,9 +70,12 @@ public sealed partial class TrapRunner(
context.Target,
context.ClientInfo);
var store = !(options.CurrentValue.IgnorePrivateNetworks && PrivateNetworks.Contains(trapEvent.RemoteIp));
var storageNote = store ? "" : " (not stored)";
if (outcome == TrapOutcome.Rejected)
{
LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo);
LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo, storageNote);
}
else
{
@@ -81,22 +85,27 @@ public sealed partial class TrapRunner(
trapEvent.Duration.TotalSeconds,
trapEvent.BytesSent,
trapEvent.Outcome,
trapEvent.ClientInfo);
trapEvent.ClientInfo,
storageNote);
}
sink.Publish(trapEvent);
if (store)
{
sink.Publish(trapEvent);
}
}
[LoggerMessage(Level = LogLevel.Information,
Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"")]
Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"{StorageNote}")]
private partial void LogTrapped(
IPAddress remoteIp,
string? target,
double durationSeconds,
long bytesSent,
TrapOutcome outcome,
string? userAgent);
string? userAgent,
string storageNote);
[LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"")]
private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent);
[LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"{StorageNote}")]
private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent, string storageNote);
}
@@ -4,19 +4,21 @@ namespace Flypaper.Core.Settings;
public sealed record RuntimeSettings(
IReadOnlyList<string> TrapPaths,
TimeSpan DripInterval,
int MaxConnections,
int MaxConnectionsPerIp,
TimeSpan MaxHoldDuration,
IReadOnlyList<string> ExtraKnownHosts)
IReadOnlyList<string> ExtraKnownHosts,
int RetentionDays,
bool IgnorePrivateNetworks)
{
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
{
[SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths),
[SettingKeys.DripInterval] = DripInterval.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts)
[SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts),
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
};
}
@@ -2,8 +2,9 @@ namespace Flypaper.Core.Settings;
public sealed record RuntimeSettingsInput(
string? TrapPaths,
string? DripInterval,
string? MaxConnections,
string? MaxConnectionsPerIp,
string? MaxHoldDuration,
string? ExtraKnownHosts);
string? ExtraKnownHosts,
string? RetentionDays,
bool IgnorePrivateNetworks);
@@ -9,9 +9,8 @@ public static partial class RuntimeSettingsParser
private const int MaxPathLength = 256;
private const int MaxHostLength = 253;
private const int MaxLimit = 100_000;
private const int MaxRetentionDays = 3650;
private static readonly TimeSpan MinInterval = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan MaxInterval = TimeSpan.FromHours(1);
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
@@ -24,10 +23,10 @@ public static partial class RuntimeSettingsParser
var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors);
var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors);
var interval = ParseTimeSpan(input.DripInterval, nameof(input.DripInterval), MinInterval, MaxInterval, errors);
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), errors);
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 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);
if (maxConnections is { } total && perIp is { } single && single > total
&& !errors.ContainsKey(nameof(input.MaxConnectionsPerIp)))
@@ -40,7 +39,14 @@ public static partial class RuntimeSettingsParser
return new RuntimeSettingsParseResult(null, errors);
}
var settings = new RuntimeSettings(paths!, interval!.Value, maxConnections!.Value, perIp!.Value, hold!.Value, hosts!);
var settings = new RuntimeSettings(
paths!,
maxConnections!.Value,
perIp!.Value,
hold!.Value,
hosts!,
retention!.Value,
input.IgnorePrivateNetworks);
return new RuntimeSettingsParseResult(settings, errors);
}
@@ -137,7 +143,7 @@ public static partial class RuntimeSettingsParser
return value;
}
private static int? ParseInt(string? raw, string field, Dictionary<string, string> errors)
private static int? ParseInt(string? raw, string field, int min, int max, Dictionary<string, string> errors)
{
var text = raw?.Trim();
if (string.IsNullOrEmpty(text))
@@ -146,9 +152,9 @@ public static partial class RuntimeSettingsParser
return null;
}
if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value is < 1 or > MaxLimit)
if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value < min || value > max)
{
errors[field] = $"Ganze Zahl zwischen 1 und {MaxLimit}.";
errors[field] = $"Ganze Zahl zwischen {min} und {max}.";
return null;
}
+5 -3
View File
@@ -5,17 +5,19 @@ public static class SettingKeys
public const string MaxConnections = "Flypaper:MaxConnections";
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
public const string DripInterval = "Flypaper:Drip:Interval";
public const string TrapPaths = "Flypaper:Http:TrapPathsOverride";
public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts";
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
public const string RetentionDays = "Flypaper:Retention:Days";
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
MaxConnections,
MaxConnectionsPerIp,
MaxHoldDuration,
DripInterval,
TrapPaths,
ExtraKnownHosts
ExtraKnownHosts,
IgnorePrivateNetworks,
RetentionDays
};
}
+7 -1
View File
@@ -4,5 +4,11 @@ public sealed class DripOptions
{
public const string SectionName = "Flypaper:Drip";
public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(10);
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
public int MinChunkSize { get; set; } = 1;
public int MaxChunkSize { get; set; } = 64;
}
@@ -0,0 +1,52 @@
using System.Text;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public static class DripSchedule
{
public static IEnumerable<DripStep> Create(IEnumerable<string> content, IRandomSource random, DripOptions options)
{
var minChunk = Math.Max(1, options.MinChunkSize);
var maxChunk = Math.Max(minChunk, options.MaxChunkSize);
var minDelay = (int)Math.Max(0, options.MinDelay.TotalMilliseconds);
var maxDelay = Math.Max(minDelay, (int)options.MaxDelay.TotalMilliseconds);
using var fragments = content.GetEnumerator();
var pending = Array.Empty<byte>();
var offset = 0;
while (true)
{
var chunk = new byte[random.Next(minChunk, maxChunk + 1)];
var filled = 0;
while (filled < chunk.Length)
{
if (offset == pending.Length)
{
if (!fragments.MoveNext())
{
break;
}
pending = Encoding.UTF8.GetBytes(fragments.Current);
offset = 0;
continue;
}
var count = Math.Min(chunk.Length - filled, pending.Length - offset);
pending.AsSpan(offset, count).CopyTo(chunk.AsSpan(filled));
offset += count;
filled += count;
}
if (filled == 0)
{
yield break;
}
yield return new DripStep(chunk.AsMemory(0, filled), TimeSpan.FromMilliseconds(random.Next(minDelay, maxDelay + 1)));
}
}
}
+3
View File
@@ -0,0 +1,3 @@
namespace Flypaper.Core.Strategies;
public readonly record struct DripStep(ReadOnlyMemory<byte> Chunk, TimeSpan Delay);
@@ -1,26 +0,0 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class DripStrategy(IOptionsMonitor<DripOptions> options, TimeProvider timeProvider) : ITarpitStrategy
{
private static readonly byte[] Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"u8.ToArray();
public string Name => "drip";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
{
var buffer = new byte[1];
while (true)
{
ct.ThrowIfCancellationRequested();
buffer[0] = Alphabet[Random.Shared.Next(Alphabet.Length)];
await channel.WriteAsync(buffer, ct);
await Task.Delay(options.CurrentValue.Interval, timeProvider, ct);
}
}
}
+170
View File
@@ -0,0 +1,170 @@
using System.Text;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public static class HtmlContent
{
private const string Css = """
body { margin: 0 auto; max-width: 52rem; padding: 1.5rem; font: 16px/1.6 system-ui, sans-serif; color: #222; }
header { border-bottom: 1px solid #ddd; margin-bottom: 1.5rem; }
nav a { margin-right: 1rem; color: #0b5cad; text-decoration: none; }
h1, h2, h3 { line-height: 1.25; }
article { margin-bottom: 2rem; }
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"];
private static readonly string[] Titles =
["Welcome", "Documentation", "Knowledge Base", "Support Center", "Release Notes", "Resources", "Archive", "Developer Portal"];
public static IEnumerable<string> Generate(IRandomSource random)
{
var title = $"{Pick(random, Titles)} · {Title(random, 2, 3)}";
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>
{Css}
</style>
</head>
<body>
<header>
<h1>{title}</h1>
""";
yield return Navigation(random);
yield return "</header>\n<main>\n";
while (true)
{
yield return random.Next(0, 10) switch
{
< 5 => Article(random),
< 7 => LinkList(random),
< 9 => Paragraph(random),
_ => $"<h3>{Title(random, 2, 6)}</h3>\n{Paragraph(random)}"
};
}
}
private static string Navigation(IRandomSource random)
{
var builder = new StringBuilder("<nav>\n");
var count = random.Next(3, 7);
for (var i = 0; i < count; i++)
{
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{Capitalize(Pick(random, Vocabulary))}</a>\n");
}
return builder.Append("</nav>\n").ToString();
}
private static string Article(IRandomSource random)
{
var builder = new StringBuilder($"<article>\n<h2>{Title(random, 3, 9)}</h2>\n");
var paragraphs = random.Next(1, 6);
for (var i = 0; i < paragraphs; i++)
{
builder.Append(Paragraph(random));
}
return builder.Append("</article>\n").ToString();
}
private static string LinkList(IRandomSource random)
{
var ordered = random.Next(0, 2) == 0;
var builder = new StringBuilder(ordered ? "<ol>\n" : "<ul>\n");
var items = random.Next(3, 10);
for (var i = 0; i < items; i++)
{
builder.Append($"<li>{Link(random, random.Next(2, 6))}</li>\n");
}
return builder.Append(ordered ? "</ol>\n" : "</ul>\n").ToString();
}
private static string Paragraph(IRandomSource random)
{
var builder = new StringBuilder("<p>");
var sentences = random.Next(2, 9);
for (var i = 0; i < sentences; i++)
{
if (i > 0)
{
builder.Append(' ');
}
builder.Append(Sentence(random));
}
return builder.Append("</p>\n").ToString();
}
private static string Sentence(IRandomSource random)
{
var builder = new StringBuilder();
var words = random.Next(4, 21);
var linkAt = random.Next(0, 8) == 0 ? random.Next(1, words) : -1;
for (var i = 0; i < words; i++)
{
if (i > 0)
{
builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " ");
}
if (i == linkAt)
{
builder.Append(Link(random, random.Next(1, 4)));
continue;
}
var word = Pick(random, Vocabulary);
builder.Append(i == 0 ? Capitalize(word) : word);
}
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
}
private static string Link(IRandomSource random, int words)
{
var text = Phrase(random, words);
var slug = text.Replace(' ', '-');
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>";
}
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 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..];
}
@@ -0,0 +1,25 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class HtmlDripStrategy(
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : ITarpitStrategy
{
public string Name => "html-drip";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
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);
}
}
}