Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a46727bab3 | ||
|
|
302b40c172 | ||
|
|
7c11bf211e |
No files matched your search
+24
-1
@@ -6,6 +6,27 @@ All notable changes to Flypaper are documented in this file. The format follows
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [0.9.0] - 2026-11-26
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Signposts in fake files: `.env` (`BACKUP_URL`, `ADMIN_URL`, `CONFIG_URL`), JSON and YAML (`backup_url`,
|
||||||
|
`api_base`), SQL dumps (comment naming the previous dump) and the Git config (remote URL) point back into the
|
||||||
|
trap. They sit in the first, undelayed chunk and carry the marker of the serving catch, so a later request
|
||||||
|
shows which catch the address came from, even from another IP. Switch: `Flypaper__Drip__Signposts`
|
||||||
|
(default `true`), no dashboard setting. No database change.
|
||||||
|
- MCP: every catch has a `marker`, and `list_catches` accepts `marker` to find the catch that handed out a
|
||||||
|
signpost.
|
||||||
|
|
||||||
|
## [0.8.0] - 2026-11-22
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Dashboard: the overview lists the bots held in the trap right now („Gerade in der Falle“) with IP (links to its
|
||||||
|
catches), origin, target, strategy, user agent, time held and bytes sent. The list is kept in memory only and
|
||||||
|
refreshes with the page (every 30 s).
|
||||||
|
- MCP: read-only tool `list_active` returns the same list (with provider, city and ASN); empty after a restart.
|
||||||
|
|
||||||
## [0.7.0] - 2026-11-21
|
## [0.7.0] - 2026-11-21
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
@@ -242,7 +263,9 @@ First release.
|
|||||||
- Unraid Docker template; when started as root, the container hands `/data` to its app user
|
- Unraid Docker template; when started as root, the container hands `/data` to its app user
|
||||||
and drops privileges.
|
and drops privileges.
|
||||||
|
|
||||||
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.7.0...main
|
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.9.0...main
|
||||||
|
[0.9.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.9.0
|
||||||
|
[0.8.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.8.0
|
||||||
[0.7.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.7.0
|
[0.7.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.7.0
|
||||||
[0.6.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.6.0
|
[0.6.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.6.0
|
||||||
[0.5.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.2
|
[0.5.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.2
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...).
|
|||||||
| `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__LinkSpacing` | Link labyrinth: bytes of text between two links in the HTML page (`0` = off, plain `html-drip`) | `160` |
|
| `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__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__Signposts` | Fake `.env`, JSON, YAML, SQL and Git files carry signpost URLs back into the trap (on the requested host, relative if the host is unusable); each URL holds the marker of the catch that served it (first 12 hex characters of its session id) | `true` |
|
||||||
| `Flypaper__Drip__Lure` | First visit of an unknown IP to `/` or `/favicon.ico` gets an instant WordPress-looking page or icon (`lure-page`, `lure-icon`) and is not held; every later request is trapped as usual | `true` |
|
| `Flypaper__Drip__Lure` | First visit of an unknown IP to `/` or `/favicon.ico` gets an instant WordPress-looking page or icon (`lure-page`, `lure-icon`) and is not held; every later request is trapped as usual | `true` |
|
||||||
| `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` |
|
| `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 |
|
||||||
|
|||||||
+2
-1
@@ -61,8 +61,9 @@ seconds. A *period* is a number with `m`, `h`, `d` or `w` (e.g. `1h`, `24h`, `7d
|
|||||||
|
|
||||||
| Tool | Parameters | Returns |
|
| Tool | Parameters | Returns |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
|
| `list_active` | – | Bots held in the trap right now with origin, URL, user agent, strategy, time held and bytes sent (memory only) |
|
||||||
| `get_stats` | `period` (default `24h`) | Catches, rejected connections, unique IPs, total and average hold time, traps active now, longest catch |
|
| `get_stats` | `period` (default `24h`) | Catches, rejected connections, unique IPs, total and average hold time, traps active now, longest catch |
|
||||||
| `list_catches` | `since`, `until` (ISO 8601), `country` (ISO code), `provider` (`AS4134` or part of the name), `ip`, `target_contains`, `limit` (default 50, max 500) | Events, newest first, including rejected ones |
|
| `list_catches` | `since`, `until` (ISO 8601), `country` (ISO code), `provider` (`AS4134` or part of the name), `ip`, `target_contains`, `limit` (default 50, max 500), `marker` (12 hex characters from a signpost URL) | Events, newest first, including rejected ones; each carries its `marker` |
|
||||||
| `top` | `dimension` (`ips`, `countries`, `providers`, `targets`, `user_agents`), `period` (default `24h`), `limit` (default 10) | Most frequent values by number of catches, with total hold time |
|
| `top` | `dimension` (`ips`, `countries`, `providers`, `targets`, `user_agents`), `period` (default `24h`), `limit` (default 10) | Most frequent values by number of catches, with total hold time |
|
||||||
| `longest_catches` | `period` (default `7d`), `limit` (default 10) | Catches that held a bot the longest |
|
| `longest_catches` | `period` (default `7d`), `limit` (default 10) | Catches that held a bot the longest |
|
||||||
| `lookup_ip` | `ip` | Origin, provider, totals, first and last seen, and its events (newest first, at most 500); local data only |
|
| `lookup_ip` | `ip` | Origin, provider, totals, first and last seen, and its events (newest first, at most 500); local data only |
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
using Flypaper.Core.Models;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
public interface IActiveTraps
|
||||||
|
{
|
||||||
|
IActiveTrapHandle Begin(TrapContext context, string strategy);
|
||||||
|
|
||||||
|
IReadOnlyList<ActiveTrap> Snapshot();
|
||||||
|
}
|
||||||
|
|
||||||
|
public interface IActiveTrapHandle : IDisposable
|
||||||
|
{
|
||||||
|
void Attach(Func<long> bytesSent);
|
||||||
|
}
|
||||||
@@ -18,6 +18,7 @@ public static class FlypaperCoreExtensions
|
|||||||
|
|
||||||
services.TryAddSingleton(TimeProvider.System);
|
services.TryAddSingleton(TimeProvider.System);
|
||||||
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||||
|
services.TryAddSingleton<IActiveTraps, ActiveTrapRegistry>();
|
||||||
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, RobotsStaticStrategy>());
|
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, RobotsStaticStrategy>());
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Models;
|
||||||
|
|
||||||
|
public sealed record ActiveTrap(Guid Id, IPAddress Ip, string? Target, string? ClientInfo, string Strategy, DateTimeOffset StartedAt, long BytesSent);
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Runtime;
|
||||||
|
|
||||||
|
public sealed class ActiveTrapRegistry(TimeProvider timeProvider) : IActiveTraps
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<Guid, Entry> _entries = new();
|
||||||
|
|
||||||
|
public IActiveTrapHandle Begin(TrapContext context, string strategy)
|
||||||
|
{
|
||||||
|
var entry = new Entry(this, context, strategy, timeProvider.GetUtcNow());
|
||||||
|
_entries[context.Session.Id] = entry;
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IReadOnlyList<ActiveTrap> Snapshot() =>
|
||||||
|
_entries.Values.Select(entry => entry.ToActiveTrap()).OrderBy(trap => trap.StartedAt).ToList();
|
||||||
|
|
||||||
|
private sealed class Entry(ActiveTrapRegistry owner, TrapContext context, string strategy, DateTimeOffset startedAt) : IActiveTrapHandle
|
||||||
|
{
|
||||||
|
private Func<long>? _bytesSent;
|
||||||
|
|
||||||
|
public void Attach(Func<long> bytesSent) => _bytesSent = bytesSent;
|
||||||
|
|
||||||
|
public ActiveTrap ToActiveTrap() => new(
|
||||||
|
context.Session.Id,
|
||||||
|
context.Session.RemoteIp,
|
||||||
|
context.Target,
|
||||||
|
context.ClientInfo,
|
||||||
|
strategy,
|
||||||
|
startedAt,
|
||||||
|
_bytesSent?.Invoke() ?? 0);
|
||||||
|
|
||||||
|
public void Dispose() => owner._entries.TryRemove(context.Session.Id, out _);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,7 @@ public sealed partial class TrapRunner(
|
|||||||
IConnectionGovernor governor,
|
IConnectionGovernor governor,
|
||||||
ITrapStrategySelector strategies,
|
ITrapStrategySelector strategies,
|
||||||
ITrapEventSink sink,
|
ITrapEventSink sink,
|
||||||
|
IActiveTraps activeTraps,
|
||||||
IRepeatOffenderLookup repeatOffenders,
|
IRepeatOffenderLookup repeatOffenders,
|
||||||
IOptionsMonitor<FlypaperOptions> options,
|
IOptionsMonitor<FlypaperOptions> options,
|
||||||
TimeProvider timeProvider,
|
TimeProvider timeProvider,
|
||||||
@@ -46,6 +47,7 @@ public sealed partial class TrapRunner(
|
|||||||
description += " repeat";
|
description += " repeat";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
using var active = activeTraps.Begin(context, description);
|
||||||
using var hold = new CancellationTokenSource(holdDuration, timeProvider);
|
using var hold = new CancellationTokenSource(holdDuration, timeProvider);
|
||||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
|
||||||
|
|
||||||
@@ -54,6 +56,8 @@ public sealed partial class TrapRunner(
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
||||||
|
var counting = channel;
|
||||||
|
active.Attach(() => counting.BytesSent);
|
||||||
await strategy.RunAsync(channel, linked.Token);
|
await strategy.RunAsync(channel, linked.Token);
|
||||||
}
|
}
|
||||||
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
||||||
|
|||||||
@@ -18,6 +18,8 @@ public sealed class DripOptions
|
|||||||
|
|
||||||
public int LinkSpacing { get; set; } = 160;
|
public int LinkSpacing { get; set; } = 160;
|
||||||
|
|
||||||
|
public bool Signposts { get; set; } = true;
|
||||||
|
|
||||||
public bool Lure { get; set; } = true;
|
public bool Lure { get; set; } = true;
|
||||||
|
|
||||||
public string BaitPaths { get; set; } = Strategies.BaitPaths.Default;
|
public string BaitPaths { get; set; } = Strategies.BaitPaths.Default;
|
||||||
|
|||||||
@@ -7,20 +7,20 @@ public sealed record FileProfile(
|
|||||||
string Name,
|
string Name,
|
||||||
string MediaType,
|
string MediaType,
|
||||||
Func<string, bool> Matches,
|
Func<string, bool> Matches,
|
||||||
Func<IRandomSource, IEnumerable<string>> Generate);
|
Func<IRandomSource, SignpostLinks?, IEnumerable<string>> Generate);
|
||||||
|
|
||||||
public static class FileContent
|
public static class FileContent
|
||||||
{
|
{
|
||||||
public static readonly IReadOnlyList<FileProfile> Profiles =
|
public static readonly IReadOnlyList<FileProfile> Profiles =
|
||||||
[
|
[
|
||||||
new("git-drip", "text/plain; charset=utf-8", IsGit, GitConfig),
|
new("git-drip", "text/plain; charset=utf-8", IsGit, GitConfig),
|
||||||
new("svn-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.svn"), Svn),
|
new("svn-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.svn"), (random, _) => Svn(random)),
|
||||||
new("hg-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.hg"), Mercurial),
|
new("hg-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.hg"), (random, _) => Mercurial(random)),
|
||||||
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", (random, _) => WordPressLogin(random)),
|
||||||
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), (random, _) => Hikvision(random)),
|
||||||
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),
|
||||||
new("json-drip", "application/json", path => path.EndsWith(".json", StringComparison.Ordinal), Json),
|
new("json-drip", "application/json", path => path.EndsWith(".json", StringComparison.Ordinal), Json),
|
||||||
new("xml-drip", "application/xml", path => path.EndsWith(".xml", StringComparison.Ordinal), Xml),
|
new("xml-drip", "application/xml", path => path.EndsWith(".xml", StringComparison.Ordinal), (random, _) => Xml(random)),
|
||||||
new("yaml-drip", "text/plain; charset=utf-8", path => path.EndsWith(".yml", StringComparison.Ordinal) || path.EndsWith(".yaml", StringComparison.Ordinal), Yaml),
|
new("yaml-drip", "text/plain; charset=utf-8", path => path.EndsWith(".yml", StringComparison.Ordinal) || path.EndsWith(".yaml", StringComparison.Ordinal), Yaml),
|
||||||
new("sql-drip", "text/plain; charset=utf-8", path => path.EndsWith(".sql", StringComparison.Ordinal), Sql)
|
new("sql-drip", "text/plain; charset=utf-8", path => path.EndsWith(".sql", StringComparison.Ordinal), Sql)
|
||||||
];
|
];
|
||||||
@@ -46,10 +46,13 @@ public static class FileContent
|
|||||||
private static bool IsEnv(string name) =>
|
private static bool IsEnv(string name) =>
|
||||||
name.StartsWith(".env", StringComparison.Ordinal) || name.EndsWith(".env", StringComparison.Ordinal) || name == "env";
|
name.StartsWith(".env", StringComparison.Ordinal) || name.EndsWith(".env", StringComparison.Ordinal) || name == "env";
|
||||||
|
|
||||||
private static IEnumerable<string> Env(IRandomSource random)
|
private static IEnumerable<string> Env(IRandomSource random, SignpostLinks? links)
|
||||||
{
|
{
|
||||||
yield return $"APP_NAME=Portal\nAPP_ENV=production\nAPP_DEBUG=false\nAPP_URL=https://example.com\nAPP_KEY=base64:{Hex(random, 32)}\n\n"
|
var appUrl = links is { BaseUrl.Length: > 0 } ? links.BaseUrl : "https://example.com";
|
||||||
+ $"DB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=app\nDB_USERNAME=app\nDB_PASSWORD={Hex(random, 16)}\n\n";
|
var signposts = links is null ? "" : $"BACKUP_URL={links.Backup}\nADMIN_URL={links.Admin}\nCONFIG_URL={links.Settings}\n\n";
|
||||||
|
yield return $"APP_NAME=Portal\nAPP_ENV=production\nAPP_DEBUG=false\nAPP_URL={appUrl}\nAPP_KEY=base64:{Hex(random, 32)}\n\n"
|
||||||
|
+ $"DB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=app\nDB_USERNAME=app\nDB_PASSWORD={Hex(random, 16)}\n\n"
|
||||||
|
+ signposts;
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
@@ -117,9 +120,10 @@ public static class FileContent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IEnumerable<string> Json(IRandomSource random)
|
private static IEnumerable<string> Json(IRandomSource random, SignpostLinks? links)
|
||||||
{
|
{
|
||||||
yield return "{\n \"name\": \"portal\",\n \"version\": \"1.4.2\",\n \"private\": true,\n \"entries\": [\n";
|
var signposts = links is null ? "" : $" \"backup_url\": \"{links.Backup}\",\n \"api_base\": \"{links.Settings}\",\n";
|
||||||
|
yield return "{\n \"name\": \"portal\",\n \"version\": \"1.4.2\",\n \"private\": true,\n" + signposts + " \"entries\": [\n";
|
||||||
|
|
||||||
var id = 1;
|
var id = 1;
|
||||||
while (true)
|
while (true)
|
||||||
@@ -139,9 +143,10 @@ public static class FileContent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IEnumerable<string> Yaml(IRandomSource random)
|
private static IEnumerable<string> Yaml(IRandomSource random, SignpostLinks? links)
|
||||||
{
|
{
|
||||||
yield return "version: \"3.8\"\nservices:\n";
|
var signposts = links is null ? "" : $"x-backup:\n backup_url: {links.Backup}\n api_base: {links.Settings}\n";
|
||||||
|
yield return "version: \"3.8\"\n" + signposts + "services:\n";
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
@@ -149,9 +154,10 @@ public static class FileContent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IEnumerable<string> Sql(IRandomSource random)
|
private static IEnumerable<string> Sql(IRandomSource random, SignpostLinks? links)
|
||||||
{
|
{
|
||||||
yield return "-- MySQL dump 10.13 Distrib 8.0.36, for Linux (x86_64)\n--\n-- Host: localhost Database: app\n-- ------------------------------------------------------\n\n"
|
var signpost = links is null ? "" : $"-- Previous full dump: {links.Backup}\n";
|
||||||
|
yield return "-- MySQL dump 10.13 Distrib 8.0.36, for Linux (x86_64)\n--\n-- Host: localhost Database: app\n" + signpost + "-- ------------------------------------------------------\n\n"
|
||||||
+ "DROP TABLE IF EXISTS `users`;\nCREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(64) NOT NULL,\n `token` varchar(64) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n\n"
|
+ "DROP TABLE IF EXISTS `users`;\nCREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(64) NOT NULL,\n `token` varchar(64) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n\n"
|
||||||
+ "LOCK TABLES `users` WRITE;\n";
|
+ "LOCK TABLES `users` WRITE;\n";
|
||||||
|
|
||||||
@@ -162,10 +168,11 @@ public static class FileContent
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static IEnumerable<string> GitConfig(IRandomSource random)
|
private static IEnumerable<string> GitConfig(IRandomSource random, SignpostLinks? links)
|
||||||
{
|
{
|
||||||
|
var remote = links?.Repository ?? "https://example.com/portal.git";
|
||||||
yield return "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n"
|
yield return "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n"
|
||||||
+ "[remote \"origin\"]\n\turl = https://example.com/portal.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n";
|
+ $"[remote \"origin\"]\n\turl = {remote}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n";
|
||||||
|
|
||||||
while (true)
|
while (true)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -13,5 +13,6 @@ public sealed class FileDripStrategy(
|
|||||||
|
|
||||||
public override string MediaType => profile.MediaType;
|
public override string MediaType => profile.MediaType;
|
||||||
|
|
||||||
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => profile.Generate(random);
|
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) =>
|
||||||
|
profile.Generate(random, options.Signposts ? SignpostLinks.For(channel) : null);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using Flypaper.Core.Abstractions;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public sealed partial record SignpostLinks(string BaseUrl, string Marker)
|
||||||
|
{
|
||||||
|
public const int MarkerLength = 12;
|
||||||
|
|
||||||
|
public string Backup => $"{BaseUrl}/backup/db-{Marker}.sql";
|
||||||
|
|
||||||
|
public string Admin => $"{BaseUrl}/admin-{Marker}/";
|
||||||
|
|
||||||
|
public string Settings => $"{BaseUrl}/storage/settings-{Marker}.json";
|
||||||
|
|
||||||
|
public string Repository => $"{BaseUrl}/git-{Marker}/portal.git";
|
||||||
|
|
||||||
|
public static string MarkerOf(Guid sessionId) => sessionId.ToString("N")[..MarkerLength];
|
||||||
|
|
||||||
|
public static SignpostLinks For(ITrapChannel channel)
|
||||||
|
{
|
||||||
|
var baseUrl = channel.Host is { } host && HostPattern().IsMatch(host) ? $"http://{host}" : "";
|
||||||
|
return new SignpostLinks(baseUrl, MarkerOf(channel.Session.Id));
|
||||||
|
}
|
||||||
|
|
||||||
|
[GeneratedRegex(@"^[A-Za-z0-9.-]{1,253}\z")]
|
||||||
|
private static partial Regex HostPattern();
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using Flypaper.Core.Models;
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Core.Strategies;
|
||||||
using Flypaper.Storage.Entities;
|
using Flypaper.Storage.Entities;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
@@ -61,6 +62,13 @@ public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextF
|
|||||||
events = events.Where(e => e.Target != null && e.Target.ToLower().Contains(text));
|
events = events.Where(e => e.Target != null && e.Target.ToLower().Contains(text));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrWhiteSpace(filter.Marker))
|
||||||
|
{
|
||||||
|
var marker = filter.Marker.Trim();
|
||||||
|
var prefix = $"{marker[..8]}-{marker[8..]}%";
|
||||||
|
events = events.Where(e => EF.Functions.Like(e.SessionId.ToString(), prefix));
|
||||||
|
}
|
||||||
|
|
||||||
var rows = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(Clamp(filter.Limit)).ToListAsync(ct);
|
var rows = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(Clamp(filter.Limit)).ToListAsync(ct);
|
||||||
return rows.Select(ToRecord).ToList();
|
return rows.Select(ToRecord).ToList();
|
||||||
}
|
}
|
||||||
@@ -176,7 +184,8 @@ public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextF
|
|||||||
e.Asn,
|
e.Asn,
|
||||||
e.Provider,
|
e.Provider,
|
||||||
e.Target,
|
e.Target,
|
||||||
e.ClientInfo);
|
e.ClientInfo,
|
||||||
|
SignpostLinks.MarkerOf(e.SessionId));
|
||||||
|
|
||||||
private sealed class TopRow
|
private sealed class TopRow
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -17,7 +17,8 @@ public sealed record CatchRecord(
|
|||||||
long? Asn,
|
long? Asn,
|
||||||
string? Provider,
|
string? Provider,
|
||||||
string? Target,
|
string? Target,
|
||||||
string? UserAgent);
|
string? UserAgent,
|
||||||
|
string Marker);
|
||||||
|
|
||||||
public sealed record CatchFilter(
|
public sealed record CatchFilter(
|
||||||
DateTime? Since = null,
|
DateTime? Since = null,
|
||||||
@@ -26,7 +27,8 @@ public sealed record CatchFilter(
|
|||||||
string? Provider = null,
|
string? Provider = null,
|
||||||
string? Ip = null,
|
string? Ip = null,
|
||||||
string? TargetContains = null,
|
string? TargetContains = null,
|
||||||
int Limit = 50);
|
int Limit = 50,
|
||||||
|
string? Marker = null);
|
||||||
|
|
||||||
public sealed record CatchStats(
|
public sealed record CatchStats(
|
||||||
int Catches,
|
int Catches,
|
||||||
|
|||||||
@@ -9,6 +9,8 @@
|
|||||||
@inject DashboardQueries Queries
|
@inject DashboardQueries Queries
|
||||||
@inject ExplanationRuleStore Explanations
|
@inject ExplanationRuleStore Explanations
|
||||||
@inject IConnectionGovernor Governor
|
@inject IConnectionGovernor Governor
|
||||||
|
@inject IActiveTraps ActiveTraps
|
||||||
|
@inject IIpEnricher Enricher
|
||||||
@inject IOptions<PortOptions> Ports
|
@inject IOptions<PortOptions> Ports
|
||||||
|
|
||||||
<PageTitle>Flypaper</PageTitle>
|
<PageTitle>Flypaper</PageTitle>
|
||||||
@@ -53,6 +55,58 @@
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
@if (_active.Count > 0)
|
||||||
|
{
|
||||||
|
<section class="card recent-card active-card">
|
||||||
|
<div class="card-head">
|
||||||
|
<h2>Gerade in der Falle <span class="count">· @Formatting.Number(_active.Count)</span></h2>
|
||||||
|
<span class="hint">Seit dem Laden der Seite weiter festgehalten</span>
|
||||||
|
</div>
|
||||||
|
<div class="scroll">
|
||||||
|
<table class="recent-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="c-ip">IP</th>
|
||||||
|
<th class="c-origin">Herkunft</th>
|
||||||
|
<th class="c-target">Ziel</th>
|
||||||
|
<th class="c-strategy">Strategie</th>
|
||||||
|
<th class="c-agent">User-Agent</th>
|
||||||
|
<th class="c-duration num">Seit</th>
|
||||||
|
<th class="c-bytes num">Bytes</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
@foreach (var trap in _active)
|
||||||
|
{
|
||||||
|
var origin = Enricher.Lookup(trap.Ip);
|
||||||
|
var target = Formatting.Target(trap.Target);
|
||||||
|
var strategy = StrategyNames.Describe(trap.Strategy);
|
||||||
|
var ip = trap.Ip.ToString();
|
||||||
|
<tr>
|
||||||
|
<td class="c-ip mono"><a href="@(new DashboardFilter { Ip = ip }.Href(DashboardFilter.Anchor))" title="Fänge dieser IP anzeigen">@ip</a></td>
|
||||||
|
<td class="c-origin" title="@origin?.Provider">
|
||||||
|
@if (origin?.CountryCode is { } countryCode)
|
||||||
|
{
|
||||||
|
@($"{Formatting.Flag(countryCode)} {countryCode}")
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
<span class="muted">–</span>
|
||||||
|
}
|
||||||
|
</td>
|
||||||
|
<td class="c-target mono" title="@target">@target</td>
|
||||||
|
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName</td>
|
||||||
|
<td class="c-agent" title="@trap.ClientInfo">@trap.ClientInfo</td>
|
||||||
|
<td class="c-duration num">@Formatting.Duration(_loadedAtUtc - trap.StartedAt)</td>
|
||||||
|
<td class="c-bytes num">@Formatting.Number(trap.BytesSent)</td>
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
}
|
||||||
|
|
||||||
@if (data.TotalCatches == 0)
|
@if (data.TotalCatches == 0)
|
||||||
{
|
{
|
||||||
<section class="card onboarding">
|
<section class="card onboarding">
|
||||||
@@ -269,6 +323,8 @@
|
|||||||
private DashboardFilter _filter = new();
|
private DashboardFilter _filter = new();
|
||||||
private RuleSet _rules = RuleSet.Empty;
|
private RuleSet _rules = RuleSet.Empty;
|
||||||
private DateTime _loadedAt;
|
private DateTime _loadedAt;
|
||||||
|
private DateTimeOffset _loadedAtUtc;
|
||||||
|
private IReadOnlyList<ActiveTrap> _active = [];
|
||||||
|
|
||||||
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
|
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
|
||||||
|
|
||||||
@@ -296,6 +352,8 @@
|
|||||||
_rules = await Explanations.GetRuleSetAsync();
|
_rules = await Explanations.GetRuleSetAsync();
|
||||||
_data = await Queries.GetAsync();
|
_data = await Queries.GetAsync();
|
||||||
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter() with { SearchStrategies = StrategyNames.Matching(_filter.Q) });
|
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter() with { SearchStrategies = StrategyNames.Matching(_filter.Q) });
|
||||||
|
_active = ActiveTraps.Snapshot();
|
||||||
|
_loadedAtUtc = DateTimeOffset.UtcNow;
|
||||||
_loadedAt = DateTime.Now;
|
_loadedAt = DateTime.Now;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ using System.ComponentModel.DataAnnotations;
|
|||||||
using System.Globalization;
|
using System.Globalization;
|
||||||
using System.Net;
|
using System.Net;
|
||||||
using Flypaper.Core.Abstractions;
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Strategies;
|
||||||
using Flypaper.Storage.Queries;
|
using Flypaper.Storage.Queries;
|
||||||
using Flypaper.Web.Components.Shared;
|
using Flypaper.Web.Components.Shared;
|
||||||
using ModelContextProtocol;
|
using ModelContextProtocol;
|
||||||
@@ -11,7 +12,7 @@ using ModelContextProtocol.Server;
|
|||||||
namespace Flypaper.Web.Mcp;
|
namespace Flypaper.Web.Mcp;
|
||||||
|
|
||||||
[McpServerToolType]
|
[McpServerToolType]
|
||||||
public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor governor, TimeProvider timeProvider)
|
public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor governor, IActiveTraps activeTraps, IIpEnricher enricher, TimeProvider timeProvider)
|
||||||
{
|
{
|
||||||
private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 1h, 24h, 7d; or all.";
|
private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 1h, 24h, 7d; or all.";
|
||||||
|
|
||||||
@@ -35,8 +36,33 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
|||||||
stats.Longest is null ? null : ToItem(stats.Longest));
|
stats.Longest is null ? null : ToItem(stats.Longest));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[McpServerTool(Name = "list_active", Title = "Bots in the trap right now", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
|
[Description("Bots held in the trap right now, longest running first: IP, origin, requested URL, user agent, strategy, how long they have been held and bytes sent so far. Held in memory only, so it is empty after a restart.")]
|
||||||
|
public ActiveTrapListResult ListActive()
|
||||||
|
{
|
||||||
|
var now = timeProvider.GetUtcNow();
|
||||||
|
var traps = activeTraps.Snapshot().Select(trap =>
|
||||||
|
{
|
||||||
|
var origin = enricher.Lookup(trap.Ip);
|
||||||
|
return new ActiveTrapItem(
|
||||||
|
trap.StartedAt.UtcDateTime,
|
||||||
|
Round((now - trap.StartedAt).TotalSeconds),
|
||||||
|
trap.BytesSent,
|
||||||
|
trap.Strategy,
|
||||||
|
trap.Ip.ToString(),
|
||||||
|
origin?.CountryCode,
|
||||||
|
CountryNames.Display(origin?.CountryCode, origin?.Country),
|
||||||
|
origin?.City,
|
||||||
|
Asn(origin?.Asn),
|
||||||
|
origin?.Provider,
|
||||||
|
trap.Target,
|
||||||
|
trap.ClientInfo);
|
||||||
|
}).ToList();
|
||||||
|
return new ActiveTrapListResult(traps.Count, traps);
|
||||||
|
}
|
||||||
|
|
||||||
[McpServerTool(Name = "list_catches", Title = "List catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
[McpServerTool(Name = "list_catches", Title = "List catches", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||||
[Description("Trap events, newest first, optionally filtered. Includes rejected connections (outcome Rejected).")]
|
[Description("Trap events, newest first, optionally filtered. Includes rejected connections (outcome Rejected). Fake files contain signpost URLs carrying the marker of the catch that served them: use marker to find that catch, and target_contains with the same value to find who followed them.")]
|
||||||
public async Task<CatchListResult> ListCatches(
|
public async Task<CatchListResult> ListCatches(
|
||||||
[Description("Only events that started at or after this ISO 8601 time, e.g. 2026-11-15T08:00:00Z.")] string? since = null,
|
[Description("Only events that started at or after this ISO 8601 time, e.g. 2026-11-15T08:00:00Z.")] string? since = null,
|
||||||
[Description("Only events that started before this ISO 8601 time.")] string? until = null,
|
[Description("Only events that started before this ISO 8601 time.")] string? until = null,
|
||||||
@@ -45,6 +71,7 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
|||||||
[Description("Exact client IP address.")] string? ip = null,
|
[Description("Exact client IP address.")] string? ip = null,
|
||||||
[Description("Case-insensitive text the request (method, host and path) must contain, e.g. .env.")] string? target_contains = null,
|
[Description("Case-insensitive text the request (method, host and path) must contain, e.g. .env.")] string? target_contains = null,
|
||||||
[Description("Maximum number of events, 1 to 500.")] int limit = 50,
|
[Description("Maximum number of events, 1 to 500.")] int limit = 50,
|
||||||
|
[Description("12 hex characters taken from a signpost URL, e.g. 7f3a9c21b4e8: only the catch that handed out this signpost.")] string? marker = null,
|
||||||
CancellationToken ct = default)
|
CancellationToken ct = default)
|
||||||
{
|
{
|
||||||
var filter = new CatchFilter(
|
var filter = new CatchFilter(
|
||||||
@@ -54,7 +81,8 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
|||||||
provider,
|
provider,
|
||||||
ip is null ? null : ParseIp(ip),
|
ip is null ? null : ParseIp(ip),
|
||||||
target_contains,
|
target_contains,
|
||||||
limit);
|
limit,
|
||||||
|
marker is null ? null : ParseMarker(marker));
|
||||||
var catches = (await queries.ListAsync(filter, ct)).Select(ToItem).ToList();
|
var catches = (await queries.ListAsync(filter, ct)).Select(ToItem).ToList();
|
||||||
return new CatchListResult(catches.Count, catches);
|
return new CatchListResult(catches.Count, catches);
|
||||||
}
|
}
|
||||||
@@ -157,6 +185,14 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
|||||||
: throw new McpException($"{name} must be an ISO 8601 time, e.g. 2026-11-15T08:00:00Z.");
|
: throw new McpException($"{name} must be an ISO 8601 time, e.g. 2026-11-15T08:00:00Z.");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static string ParseMarker(string value)
|
||||||
|
{
|
||||||
|
var marker = value.Trim().ToLowerInvariant();
|
||||||
|
return marker.Length == SignpostLinks.MarkerLength && marker.All(char.IsAsciiHexDigit)
|
||||||
|
? marker
|
||||||
|
: throw new McpException($"marker must be {SignpostLinks.MarkerLength} hex characters, e.g. 7f3a9c21b4e8.");
|
||||||
|
}
|
||||||
|
|
||||||
private static string ParseIp(string value) =>
|
private static string ParseIp(string value) =>
|
||||||
IPAddress.TryParse(value.Trim(), out var address)
|
IPAddress.TryParse(value.Trim(), out var address)
|
||||||
? (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString()
|
? (address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address).ToString()
|
||||||
@@ -181,5 +217,6 @@ public sealed class FlypaperTools(CatchQueries queries, IConnectionGovernor gove
|
|||||||
Asn(record.Asn),
|
Asn(record.Asn),
|
||||||
record.Provider,
|
record.Provider,
|
||||||
record.Target,
|
record.Target,
|
||||||
record.UserAgent);
|
record.UserAgent,
|
||||||
|
record.Marker);
|
||||||
}
|
}
|
||||||
@@ -20,7 +20,7 @@ public static class McpExtensions
|
|||||||
"answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " +
|
"answered with an endless page a few bytes at a time and held as long as possible. Every such catch is " +
|
||||||
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
|
"stored with its time, client IP, country, network provider (ASN), requested URL, user agent, duration " +
|
||||||
"and bytes sent. Times are ISO 8601 UTC, durations in seconds. The tools list_catches, top, longest_catches, " +
|
"and bytes sent. Times are ISO 8601 UTC, durations in seconds. The tools list_catches, top, longest_catches, " +
|
||||||
"lookup_ip and get_stats only read that data. Explanation rules turn catches into plain German sentences " +
|
"lookup_ip, list_active (bots held right now) and get_stats only read that data. Explanation rules turn catches into plain German sentences " +
|
||||||
"shown in the dashboard (what a bot wanted, with which tool, how it ended); they are matched when a catch is " +
|
"shown in the dashboard (what a bot wanted, with which tool, how it ended); they are matched when a catch is " +
|
||||||
"displayed, so a new rule also explains old catches. Use list_unexplained to find catches without an " +
|
"displayed, so a new rule also explains old catches. Use list_unexplained to find catches without an " +
|
||||||
"explanation, test_explanation_rule to try a pattern, and list_explanation_rules to see what exists. The tools " +
|
"explanation, test_explanation_rule to try a pattern, and list_explanation_rules to see what exists. The tools " +
|
||||||
|
|||||||
@@ -15,7 +15,8 @@ public sealed record CatchItem(
|
|||||||
string? Asn,
|
string? Asn,
|
||||||
string? Provider,
|
string? Provider,
|
||||||
string? Target,
|
string? Target,
|
||||||
string? UserAgent);
|
string? UserAgent,
|
||||||
|
string Marker);
|
||||||
|
|
||||||
public sealed record StatsResult(
|
public sealed record StatsResult(
|
||||||
string Period,
|
string Period,
|
||||||
@@ -28,6 +29,22 @@ public sealed record StatsResult(
|
|||||||
int ActiveTraps,
|
int ActiveTraps,
|
||||||
CatchItem? LongestCatch);
|
CatchItem? LongestCatch);
|
||||||
|
|
||||||
|
public sealed record ActiveTrapItem(
|
||||||
|
DateTime StartedAt,
|
||||||
|
double DurationSeconds,
|
||||||
|
long BytesSent,
|
||||||
|
string Strategy,
|
||||||
|
string Ip,
|
||||||
|
string? CountryCode,
|
||||||
|
string? Country,
|
||||||
|
string? City,
|
||||||
|
string? Asn,
|
||||||
|
string? Provider,
|
||||||
|
string? Target,
|
||||||
|
string? UserAgent);
|
||||||
|
|
||||||
|
public sealed record ActiveTrapListResult(int Count, IReadOnlyList<ActiveTrapItem> Traps);
|
||||||
|
|
||||||
public sealed record CatchListResult(int Count, IReadOnlyList<CatchItem> Catches);
|
public sealed record CatchListResult(int Count, IReadOnlyList<CatchItem> Catches);
|
||||||
|
|
||||||
public sealed record TopResultItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
|
public sealed record TopResultItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using System.Net;
|
||||||
|
using Flypaper.Core.Models;
|
||||||
|
using Flypaper.Core.Runtime;
|
||||||
|
using Flypaper.Tests.Fakes;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Core;
|
||||||
|
|
||||||
|
public sealed class ActiveTrapRegistryTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset Start = new(2026, 11, 22, 10, 0, 0, TimeSpan.Zero);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Lists_running_traps_with_bytes_and_forgets_finished_ones()
|
||||||
|
{
|
||||||
|
var registry = new ActiveTrapRegistry(new FixedTimeProvider(Start));
|
||||||
|
var first = Context("203.0.113.1", "GET /.env");
|
||||||
|
var second = Context("203.0.113.2", "GET /");
|
||||||
|
|
||||||
|
var handle = registry.Begin(first, "env-drip");
|
||||||
|
registry.Begin(second, "maze-drip");
|
||||||
|
var bytes = 0L;
|
||||||
|
handle.Attach(() => bytes);
|
||||||
|
bytes = 4096;
|
||||||
|
|
||||||
|
var snapshot = registry.Snapshot();
|
||||||
|
|
||||||
|
snapshot.Select(t => t.Ip.ToString()).ShouldBe(["203.0.113.1", "203.0.113.2"], ignoreOrder: true);
|
||||||
|
snapshot.Single(t => t.Ip.ToString() == "203.0.113.1").BytesSent.ShouldBe(4096);
|
||||||
|
snapshot.Single(t => t.Ip.ToString() == "203.0.113.2").BytesSent.ShouldBe(0);
|
||||||
|
snapshot.ShouldAllBe(t => t.StartedAt == Start);
|
||||||
|
|
||||||
|
handle.Dispose();
|
||||||
|
|
||||||
|
registry.Snapshot().Select(t => t.Ip.ToString()).ShouldBe(["203.0.113.2"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static TrapContext Context(string ip, string target) =>
|
||||||
|
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse(ip), Start), target);
|
||||||
|
}
|
||||||
@@ -68,7 +68,7 @@ public sealed class FileContentTests
|
|||||||
{
|
{
|
||||||
var profile = FileContent.Match(path).ShouldNotBeNull();
|
var profile = FileContent.Match(path).ShouldNotBeNull();
|
||||||
|
|
||||||
var text = string.Concat(profile.Generate(new SeededRandomSource(5)).Take(200));
|
var text = string.Concat(profile.Generate(new SeededRandomSource(5), null).Take(200));
|
||||||
|
|
||||||
text.ShouldStartWith(start);
|
text.ShouldStartWith(start);
|
||||||
text.Length.ShouldBeGreaterThan(1000);
|
text.Length.ShouldBeGreaterThan(1000);
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using Flypaper.Core.Strategies;
|
||||||
|
using Flypaper.Tests.Fakes;
|
||||||
|
using Shouldly;
|
||||||
|
|
||||||
|
namespace Flypaper.Tests.Core;
|
||||||
|
|
||||||
|
public sealed class SignpostTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("env-drip", "BACKUP_URL=http://trap.example/backup/db-{m}.sql")]
|
||||||
|
[InlineData("env-drip", "ADMIN_URL=http://trap.example/admin-{m}/")]
|
||||||
|
[InlineData("env-drip", "CONFIG_URL=http://trap.example/storage/settings-{m}.json")]
|
||||||
|
[InlineData("json-drip", "\"backup_url\": \"http://trap.example/backup/db-{m}.sql\"")]
|
||||||
|
[InlineData("yaml-drip", "backup_url: http://trap.example/backup/db-{m}.sql")]
|
||||||
|
[InlineData("sql-drip", "-- Previous full dump: http://trap.example/backup/db-{m}.sql")]
|
||||||
|
[InlineData("git-drip", "url = http://trap.example/git-{m}/portal.git")]
|
||||||
|
public async Task Signposts_arrive_with_the_undelayed_head_and_carry_the_session_marker(string strategy, string expected)
|
||||||
|
{
|
||||||
|
var (head, channel) = await HeadAsync(strategy, "trap.example");
|
||||||
|
|
||||||
|
head.ShouldContain(expected.Replace("{m}", SignpostLinks.MarkerOf(channel.Session.Id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("[::1]")]
|
||||||
|
[InlineData("_")]
|
||||||
|
[InlineData("bad host\n")]
|
||||||
|
public async Task Unusable_hosts_give_relative_signposts(string? host)
|
||||||
|
{
|
||||||
|
var (head, channel) = await HeadAsync("env-drip", host);
|
||||||
|
|
||||||
|
head.ShouldContain($"BACKUP_URL=/backup/db-{SignpostLinks.MarkerOf(channel.Session.Id)}.sql");
|
||||||
|
head.ShouldContain("APP_URL=https://example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("env-drip")]
|
||||||
|
[InlineData("json-drip")]
|
||||||
|
[InlineData("yaml-drip")]
|
||||||
|
[InlineData("sql-drip")]
|
||||||
|
[InlineData("git-drip")]
|
||||||
|
public async Task Switch_removes_the_signposts(string strategy)
|
||||||
|
{
|
||||||
|
var (head, channel) = await HeadAsync(strategy, "trap.example", signposts: false);
|
||||||
|
|
||||||
|
head.ShouldNotContain(SignpostLinks.MarkerOf(channel.Session.Id));
|
||||||
|
head.ShouldNotContain("trap.example");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void Json_with_signposts_stays_well_formed()
|
||||||
|
{
|
||||||
|
var profile = FileContent.Profiles.First(p => p.Name == "json-drip");
|
||||||
|
var links = new SignpostLinks("http://trap.example", "7f3a9c21b4e8");
|
||||||
|
var text = string.Concat(profile.Generate(new SeededRandomSource(5), links).Take(5)).TrimEnd().TrimEnd(',') + "]}";
|
||||||
|
|
||||||
|
using var document = JsonDocument.Parse(text);
|
||||||
|
|
||||||
|
document.RootElement.GetProperty("api_base").GetString().ShouldBe("http://trap.example/storage/settings-7f3a9c21b4e8.json");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("/backup/db-7f3a9c21b4e8.sql", "sql-drip")]
|
||||||
|
[InlineData("/storage/settings-7f3a9c21b4e8.json", "json-drip")]
|
||||||
|
public void Followed_signposts_lead_to_the_next_fake_file(string path, string strategy) =>
|
||||||
|
FileContent.Match(path).ShouldNotBeNull().Name.ShouldBe(strategy);
|
||||||
|
|
||||||
|
private static async Task<(string Head, FakeTrapChannel Channel)> HeadAsync(string strategy, string? host, bool signposts = true)
|
||||||
|
{
|
||||||
|
var options = TestOptions.Monitor(new DripOptions
|
||||||
|
{
|
||||||
|
Signposts = signposts,
|
||||||
|
MinDelay = TimeSpan.FromSeconds(30),
|
||||||
|
MaxDelay = TimeSpan.FromSeconds(30)
|
||||||
|
});
|
||||||
|
var drip = new FileDripStrategy(FileContent.Profiles.First(p => p.Name == strategy), options, new SeededRandomSource(3), TimeProvider.System);
|
||||||
|
var channel = new FakeTrapChannel { Host = host };
|
||||||
|
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
|
||||||
|
|
||||||
|
await Should.ThrowAsync<OperationCanceledException>(() => drip.RunAsync(channel, cts.Token));
|
||||||
|
|
||||||
|
return (Encoding.UTF8.GetString(channel.Writes.First()), channel);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -179,6 +179,7 @@ public sealed class TrapRunnerTests
|
|||||||
_governor,
|
_governor,
|
||||||
new ConfiguredStrategySelector([drip], dripOptions, random),
|
new ConfiguredStrategySelector([drip], dripOptions, random),
|
||||||
_sink,
|
_sink,
|
||||||
|
new ActiveTrapRegistry(TimeProvider.System),
|
||||||
repeatOffenders ?? new NullRepeatLookup(),
|
repeatOffenders ?? new NullRepeatLookup(),
|
||||||
TestOptions.Monitor(new FlypaperOptions
|
TestOptions.Monitor(new FlypaperOptions
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Flypaper.Core.Abstractions;
|
using Flypaper.Core.Abstractions;
|
||||||
|
using Flypaper.Core.Runtime;
|
||||||
using Flypaper.Storage.Queries;
|
using Flypaper.Storage.Queries;
|
||||||
using Flypaper.Tests.Fakes;
|
using Flypaper.Tests.Fakes;
|
||||||
using Flypaper.Web.Mcp;
|
using Flypaper.Web.Mcp;
|
||||||
@@ -12,12 +13,52 @@ public sealed class FlypaperToolsTests : IDisposable
|
|||||||
{
|
{
|
||||||
private readonly McpTestData _data = new();
|
private readonly McpTestData _data = new();
|
||||||
private readonly FlypaperTools _tools;
|
private readonly FlypaperTools _tools;
|
||||||
|
private readonly ActiveTrapRegistry _active = new(new FixedTimeProvider(McpTestData.Now));
|
||||||
|
private readonly IIpEnricher _enricher = Substitute.For<IIpEnricher>();
|
||||||
|
|
||||||
public FlypaperToolsTests()
|
public FlypaperToolsTests()
|
||||||
{
|
{
|
||||||
var governor = Substitute.For<IConnectionGovernor>();
|
var governor = Substitute.For<IConnectionGovernor>();
|
||||||
governor.ActiveConnections.Returns(2);
|
governor.ActiveConnections.Returns(2);
|
||||||
_tools = new FlypaperTools(new CatchQueries(_data.Factory), governor, new FixedTimeProvider(McpTestData.Now));
|
_tools = new FlypaperTools(new CatchQueries(_data.Factory), governor, _active, _enricher, new FixedTimeProvider(McpTestData.Now));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void List_active_shows_running_traps_with_origin_and_bytes()
|
||||||
|
{
|
||||||
|
var address = System.Net.IPAddress.Parse("203.0.113.7");
|
||||||
|
_enricher.Lookup(address).Returns(new Flypaper.Core.Models.IpOrigin("DE", "Germany", "Berlin", 3320, "Telekom"));
|
||||||
|
var context = new Flypaper.Core.Models.TrapContext(
|
||||||
|
new Flypaper.Core.Models.TrapSession(Guid.NewGuid(), Flypaper.Core.Models.TrapProtocol.Http, address, McpTestData.Now.AddMinutes(-5)),
|
||||||
|
"GET /.env",
|
||||||
|
"curl/8.7.1");
|
||||||
|
_active.Begin(context, "env-drip").Attach(() => 2048);
|
||||||
|
|
||||||
|
var result = _tools.ListActive();
|
||||||
|
|
||||||
|
var trap = result.Traps.ShouldHaveSingleItem();
|
||||||
|
result.Count.ShouldBe(1);
|
||||||
|
trap.Ip.ShouldBe("203.0.113.7");
|
||||||
|
trap.CountryCode.ShouldBe("DE");
|
||||||
|
trap.Asn.ShouldBe("AS3320");
|
||||||
|
trap.Target.ShouldBe("GET /.env");
|
||||||
|
trap.BytesSent.ShouldBe(2048);
|
||||||
|
trap.DurationSeconds.ShouldBe(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void List_active_is_empty_without_traps() => _tools.ListActive().Count.ShouldBe(0);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task List_catches_finds_the_catch_behind_a_signpost_marker()
|
||||||
|
{
|
||||||
|
var origin = (await _tools.ListCatches()).Catches[2];
|
||||||
|
|
||||||
|
var found = await _tools.ListCatches(marker: origin.Marker.ToUpperInvariant());
|
||||||
|
|
||||||
|
origin.Marker.Length.ShouldBe(12);
|
||||||
|
found.Catches.ShouldHaveSingleItem().Id.ShouldBe(origin.Id);
|
||||||
|
await Should.ThrowAsync<McpException>(() => _tools.ListCatches(marker: "not-a-marker"));
|
||||||
}
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ public sealed class McpEndpointTests : IDisposable
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static readonly string[] ReadTools =
|
private static readonly string[] ReadTools =
|
||||||
["get_stats", "list_catches", "longest_catches", "lookup_ip", "top", "list_explanation_rules", "list_unexplained", "test_explanation_rule"];
|
["get_stats", "list_active", "list_catches", "longest_catches", "lookup_ip", "top", "list_explanation_rules", "list_unexplained", "test_explanation_rule"];
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task Rejects_requests_without_token()
|
public async Task Rejects_requests_without_token()
|
||||||
@@ -80,6 +80,7 @@ public sealed class McpEndpointTests : IDisposable
|
|||||||
{
|
{
|
||||||
{ "get_stats", """{"period":"all"}""" },
|
{ "get_stats", """{"period":"all"}""" },
|
||||||
{ "get_stats", """{"period":"24h"}""" },
|
{ "get_stats", """{"period":"24h"}""" },
|
||||||
|
{ "list_active", """{}""" },
|
||||||
{ "list_catches", """{}""" },
|
{ "list_catches", """{}""" },
|
||||||
{ "list_catches", """{"country":"CN","limit":1}""" },
|
{ "list_catches", """{"country":"CN","limit":1}""" },
|
||||||
{ "top", """{"dimension":"ips","period":"all"}""" },
|
{ "top", """{"dimension":"ips","period":"all"}""" },
|
||||||
|
|||||||
Reference in new issue
Block a user