From 9a56fc5b4865cf045e1b36fdb588c158fb88d26c Mon Sep 17 00:00:00 2001 From: Tom Date: Sun, 15 Nov 2026 18:56:35 +0100 Subject: [PATCH] Remove trap paths and known hosts: catch everything on the trap port Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 + README.md | 8 +- deploy/unraid/compose.yaml | 2 +- docs/configuration.md | 3 - docs/overview.md | 10 +- docs/reverse-proxy.md | 41 +---- src/Flypaper.Core/Settings/RuntimeSettings.cs | 4 - .../Settings/RuntimeSettingsInput.cs | 2 - .../Settings/RuntimeSettingsParser.cs | 77 +-------- src/Flypaper.Core/Settings/SettingKeys.cs | 4 - src/Flypaper.Core/Settings/SettingsList.cs | 15 -- src/Flypaper.Http/FlypaperHttpExtensions.cs | 32 ++-- src/Flypaper.Http/HttpTrapOptions.cs | 8 - src/Flypaper.Http/Matching/TrapMatch.cs | 8 - src/Flypaper.Http/Matching/TrapMatcher.cs | 74 --------- .../Middleware/FlypaperMiddleware.cs | 7 - ...5175305_RemoveTrapPathSettings.Designer.cs | 151 ++++++++++++++++++ .../20261115175305_RemoveTrapPathSettings.cs | 22 +++ .../Pages/Settings/SettingsModel.cs | 4 - .../Pages/Settings/SettingsPage.razor | 19 +-- src/Flypaper.Web/Program.cs | 1 + src/Flypaper.Web/appsettings.json | 19 +-- .../Core/RuntimeSettingsParserTests.cs | 45 +----- test/Flypaper.Tests/Fakes/ListLogger.cs | 15 ++ test/Flypaper.Tests/Http/HealthProbeTests.cs | 3 +- .../Http/PortSeparationTests.cs | 52 +++--- .../Http/RemovedSettingsTests.cs | 41 +++++ test/Flypaper.Tests/Http/TrapMatcherTests.cs | 42 ----- test/Flypaper.Tests/Storage/MigrationTests.cs | 16 ++ .../Storage/SettingsOverrideTests.cs | 62 ++----- unraid/flypaper.xml | 3 +- 31 files changed, 335 insertions(+), 462 deletions(-) delete mode 100644 src/Flypaper.Core/Settings/SettingsList.cs delete mode 100644 src/Flypaper.Http/Matching/TrapMatch.cs delete mode 100644 src/Flypaper.Http/Matching/TrapMatcher.cs create mode 100644 src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.Designer.cs create mode 100644 src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.cs create mode 100644 test/Flypaper.Tests/Fakes/ListLogger.cs create mode 100644 test/Flypaper.Tests/Http/RemovedSettingsTests.cs delete mode 100644 test/Flypaper.Tests/Http/TrapMatcherTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index be04ade..0951106 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,13 @@ All notable changes to Flypaper are documented in this file. The format follows ## [Unreleased] +### Removed + +- Trap paths and known hosts, with their settings, the `Flypaper__Http__KnownHosts` and + `Flypaper__Http__TrapPaths` variables and the matching logic: every request on the trap port + is caught, only `/health` from private addresses is answered. Saved overrides are deleted on + start; the old variables are ignored with a warning in the log. + ## [0.2.0] - 2026-11-15 ### Added diff --git a/README.md b/README.md index ac5adcf..01b3244 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ the dashboard shows you who knocked: country, network provider and what they wer flowchart LR bot["Scanner bot"] -->|"GET /.env
Host: 203.0.113.7"| proxy["Reverse proxy"] proxy -->|"known site"| apps["Your apps"] - proxy -->|"unknown host or trap path
+ X-Real-IP"| flypaper["Flypaper"] + proxy -->|"unknown host
+ X-Real-IP"| flypaper["Flypaper"] flypaper -.->|"endless HTML,
a few bytes at a time"| bot flypaper --> db[("SQLite:
catches, settings")] you["You (LAN)"] -->|"dashboard, port 8081"| flypaper @@ -87,8 +87,7 @@ server { } ``` -Nginx Proxy Manager, Caddy, Traefik and bait paths on your real domains: -[docs/reverse-proxy.md](docs/reverse-proxy.md). +Nginx Proxy Manager, Caddy and Traefik: [docs/reverse-proxy.md](docs/reverse-proxy.md). ## Configuration @@ -98,10 +97,9 @@ Nothing is required. The most useful optional environment variables: |---|---| | `Flypaper__Admin__Password` | Fixes the dashboard password instead of setting it on first visit | | `Flypaper__Http__TrustedProxies__0` | Proxy IP or CIDR allowed to set `X-Real-IP` (default: private networks) | -| `Flypaper__Http__KnownHosts__0` | Host that is caught only on trap paths | | `TZ` | Time zone for the dashboard | -Trap paths, limits and retention are changed on the dashboard's settings page. All variables +Limits and retention are changed on the dashboard's settings page. All variables and settings: [docs/configuration.md](docs/configuration.md). ## Security diff --git a/deploy/unraid/compose.yaml b/deploy/unraid/compose.yaml index b4b8533..f02959a 100644 --- a/deploy/unraid/compose.yaml +++ b/deploy/unraid/compose.yaml @@ -3,7 +3,7 @@ # .gitea/workflows/deploy.yml, not pasted into the Compose Manager. # # NPM reaches the trap as flypaper:8080 over the external network proxynet (default -# site for unknown hosts, trap paths on the real domains). The dashboard has its own +# site for unknown hosts). The dashboard has its own # port 8081, published only to the LAN: http://192.168.1.14:44307. # # `restart: always`, not `unless-stopped`: Unraid stops every container explicitly diff --git a/docs/configuration.md b/docs/configuration.md index b1bbb0e..574b1bf 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -15,7 +15,6 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...). |---|---|---| | `Flypaper__Admin__Password` | Fixes the dashboard password and disables the first-visit setup and the password change | set on first visit | | `Flypaper__Http__TrustedProxies__0` | IP or CIDR of the reverse proxy allowed to set `X-Real-IP` / `X-Forwarded-For`; replaces the default | private networks | -| `Flypaper__Http__KnownHosts__0` | Hosts that are caught only on trap paths (`*.example.com` allowed), see [reverse proxy](reverse-proxy.md#what-to-send-to-flypaper) | none | | `Flypaper__Mcp__Token` | Fixed bearer token for the [MCP endpoint](mcp.md), in addition to tokens created on the settings page | none | | `Flypaper__Ports__Trap` / `Flypaper__Ports__Dashboard` | Container ports | `8080` / `8081` | | `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` | @@ -35,8 +34,6 @@ reset button removes all saved values. | Setting | Default | |---|---| -| Trap paths (exact, or prefix with a trailing `*`) | `/.env`, `/.env.*`, `/.git/*`, `/.aws/*`, `/.DS_Store`, `/wp-login.php`, `/wp-admin/*`, `/xmlrpc.php`, `/phpmyadmin/*`, `/vendor/phpunit/*`, `/server-status`, `/actuator/*`, `/cgi-bin/*`, `/boaform/*` | -| Extra known hosts (merged with `KnownHosts`) | none | | Maximum hold time per catch | `01:00:00` | | Maximum connections overall | `1000` | | Maximum connections per IP | `10` | diff --git a/docs/overview.md b/docs/overview.md index 796836f..69cabb7 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -11,15 +11,14 @@ else, and every catch is logged with its origin for you to look at. flowchart LR bot["Scanner bot"] -->|"GET /.env
Host: 203.0.113.7"| proxy["Reverse proxy"] proxy -->|"known site"| apps["Your apps"] - proxy -->|"unknown host or trap path
+ X-Real-IP"| flypaper["Flypaper"] + proxy -->|"unknown host
+ X-Real-IP"| flypaper["Flypaper"] flypaper -.->|"endless HTML,
a few bytes at a time"| bot flypaper --> db[("SQLite:
catches, settings")] you["You (LAN)"] -->|"dashboard, port 8081"| flypaper ``` 1. Your reverse proxy keeps serving your real sites. Everything it has no site for (the - default/catch-all server) goes to Flypaper, optionally also a few bait paths on your real - domains. + default/catch-all server) goes to Flypaper. 2. Flypaper listens on two ports. Port `8080` is the trap: everything that arrives there is caught. Port `8081` serves the dashboard and never traps; keep it inside your LAN. 3. A caught request gets `200 OK` and an endless, plausible-looking HTML page: random chunks @@ -31,15 +30,14 @@ flowchart LR ## Features -- **Traps** for unknown hosts (catch-all) and for configurable trap paths such as `/.env`, - `/.git/*` or `/wp-login.php` +- **Trap** for everything that reaches the trap port: whatever host or path a bot asks for - **Slow delivery** of endless generated HTML with irregular timing - **Limits**: maximum connections overall and per IP, maximum hold time per catch - **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest catches with expandable details; login with an admin password - **GeoIP**: country, city and ASN per catch from DB-IP Lite, downloaded and refreshed monthly; existing catches are filled in once the databases are available -- **Settings page**: trap paths, extra known hosts, limits and retention, changed at runtime +- **Settings page**: limits and retention, changed at runtime without a restart - **Retention**: old catches are deleted daily (90 days by default); catches from private networks are not stored by default; buttons to delete private or all catches diff --git a/docs/reverse-proxy.md b/docs/reverse-proxy.md index ec8a681..4968297 100644 --- a/docs/reverse-proxy.md +++ b/docs/reverse-proxy.md @@ -20,17 +20,9 @@ bot never sees it. Flypaper sends `X-Accel-Buffering: no`, which nginx honors. ## What to send to Flypaper -- **The catch-all server.** Requests for hosts you don't serve (mostly the bare IP) go to - Flypaper. This is where almost all scanners end up. -- **Optionally, trap paths on your real domains.** Forward only the bait paths, e.g. `/.env` - or `/wp-login.php`, from your real sites to Flypaper. Every request on the trap port is - caught, so nothing else is needed. - -*Known hosts* (optional) change this for hosts you list: on the trap port, a known host is -caught only on the configured trap paths, and its other paths get a plain `404` without being -logged. That is useful if your proxy forwards more than the bait paths of a real domain, for -example a whole location. Unknown hosts are always caught. The dashboard is never reachable -on the trap port. +Send your proxy's catch-all server to Flypaper: requests for hosts you don't serve (mostly the +bare IP). This is where almost all scanners end up. Everything that reaches the trap port is +caught, whatever host or path it asks for; the dashboard is never reachable there. **An HTTPS catch-all is rarely worth it.** Scanners of unknown hosts mostly speak plain HTTP to the bare IP, and an HTTPS catch-all would need a certificate for names you don't own. Let the @@ -73,20 +65,6 @@ Put Flypaper into the same Docker network as NPM (the examples use the container 3. Test and reload: `docker exec nginx -t`, then `docker exec nginx -s reload`. -4. Optional trap paths on a real domain: in the proxy host's **Advanced** tab add - - ```nginx - location ~* ^/(\.env|\.git/|wp-login\.php|xmlrpc\.php) { - resolver 127.0.0.11 valid=30s; - set $flypaper http://flypaper:8080; - proxy_pass $flypaper; - proxy_set_header Host $host; - proxy_set_header X-Real-IP $remote_addr; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_buffering off; - } - ``` - To undo the catch-all, delete `custom/http.conf` and reload. ## Plain nginx @@ -122,16 +100,6 @@ With Flypaper on the same host, nothing else is needed: loopback is trusted by d flush_interval -1 } } - -# Optional trap paths on a real site -example.com { - @trap path /.env /.git/* /wp-login.php /xmlrpc.php - reverse_proxy @trap flypaper:8080 { - header_up X-Real-IP {remote_host} - flush_interval -1 - } - reverse_proxy your-app:8080 -} ``` ## Traefik @@ -146,8 +114,5 @@ labels: traefik.http.routers.flypaper-catchall.rule: "HostRegexp(`.+`)" traefik.http.routers.flypaper-catchall.entrypoints: web traefik.http.routers.flypaper-catchall.priority: "1" - # Optional trap paths on a real site - traefik.http.routers.flypaper-bait.rule: "Host(`example.com`) && (Path(`/.env`) || PathPrefix(`/.git/`) || Path(`/wp-login.php`))" - traefik.http.routers.flypaper-bait.priority: "1000" traefik.http.services.flypaper.loadbalancer.server.port: "8080" ``` diff --git a/src/Flypaper.Core/Settings/RuntimeSettings.cs b/src/Flypaper.Core/Settings/RuntimeSettings.cs index f7c61bb..4669bab 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettings.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettings.cs @@ -3,21 +3,17 @@ using System.Globalization; namespace Flypaper.Core.Settings; public sealed record RuntimeSettings( - IReadOnlyList TrapPaths, int MaxConnections, int MaxConnectionsPerIp, TimeSpan MaxHoldDuration, - IReadOnlyList ExtraKnownHosts, int RetentionDays, bool IgnorePrivateNetworks) { public IReadOnlyDictionary ToConfiguration() => new Dictionary { - [SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths), [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.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture), [SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false" }; diff --git a/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs b/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs index 55f77d0..ff600ad 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettingsInput.cs @@ -1,10 +1,8 @@ namespace Flypaper.Core.Settings; public sealed record RuntimeSettingsInput( - string? TrapPaths, string? MaxConnections, string? MaxConnectionsPerIp, string? MaxHoldDuration, - string? ExtraKnownHosts, string? RetentionDays, bool IgnorePrivateNetworks); diff --git a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs index 70d0f71..e6b52ac 100644 --- a/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs +++ b/src/Flypaper.Core/Settings/RuntimeSettingsParser.cs @@ -1,28 +1,19 @@ using System.Globalization; -using System.Text.RegularExpressions; namespace Flypaper.Core.Settings; -public static partial class RuntimeSettingsParser +public static class RuntimeSettingsParser { - private const int MaxListEntries = 500; - 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 MinHold = TimeSpan.FromSeconds(1); private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7); - [GeneratedRegex(@"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.\-]*[A-Za-z0-9])?$")] - private static partial Regex HostPattern(); - public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input) { var errors = new Dictionary(); - var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors); - var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors); var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors); var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors); var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors); @@ -40,80 +31,14 @@ public static partial class RuntimeSettingsParser } var settings = new RuntimeSettings( - paths!, maxConnections!.Value, perIp!.Value, hold!.Value, - hosts!, retention!.Value, input.IgnorePrivateNetworks); return new RuntimeSettingsParseResult(settings, errors); } - private static string[]? ParseList( - string? raw, - string field, - Func validate, - Dictionary errors) - { - var lines = (raw ?? string.Empty) - .Split(['\r', '\n'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); - - if (lines.Length > MaxListEntries) - { - errors[field] = $"Höchstens {MaxListEntries} Einträge."; - return null; - } - - var problems = new List(); - for (var i = 0; i < lines.Length; i++) - { - if (validate(lines[i]) is { } problem) - { - problems.Add($"„{lines[i]}“: {problem}"); - } - } - - if (problems.Count > 0) - { - errors[field] = string.Join(" ", problems.Take(3)) + (problems.Count > 3 ? $" (+{problems.Count - 3} weitere)" : ""); - return null; - } - - return lines.Distinct(StringComparer.Ordinal).ToArray(); - } - - private static string? ValidatePath(string path) - { - if (path[0] != '/') - { - return "muss mit / beginnen."; - } - - if (path.Length > MaxPathLength) - { - return $"höchstens {MaxPathLength} Zeichen."; - } - - if (path.Any(char.IsWhiteSpace)) - { - return "darf keine Leerzeichen enthalten."; - } - - var star = path.IndexOf('*'); - return star >= 0 && star != path.Length - 1 ? "* ist nur am Ende erlaubt." : null; - } - - private static string? ValidateHost(string host) - { - if (host.Length > MaxHostLength) - { - return $"höchstens {MaxHostLength} Zeichen."; - } - - return HostPattern().IsMatch(host) ? null : "ungültiger Hostname (nur Name, ohne Schema, Port oder Pfad; Wildcard als *.beispiel.de)."; - } - private static TimeSpan? ParseTimeSpan( string? raw, string field, diff --git a/src/Flypaper.Core/Settings/SettingKeys.cs b/src/Flypaper.Core/Settings/SettingKeys.cs index 17c72f7..f85e4af 100644 --- a/src/Flypaper.Core/Settings/SettingKeys.cs +++ b/src/Flypaper.Core/Settings/SettingKeys.cs @@ -5,8 +5,6 @@ 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 TrapPaths = "Flypaper:Http:TrapPathsOverride"; - public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts"; public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks"; public const string RetentionDays = "Flypaper:Retention:Days"; @@ -15,8 +13,6 @@ public static class SettingKeys MaxConnections, MaxConnectionsPerIp, MaxHoldDuration, - TrapPaths, - ExtraKnownHosts, IgnorePrivateNetworks, RetentionDays }; diff --git a/src/Flypaper.Core/Settings/SettingsList.cs b/src/Flypaper.Core/Settings/SettingsList.cs deleted file mode 100644 index 2f95315..0000000 --- a/src/Flypaper.Core/Settings/SettingsList.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace Flypaper.Core.Settings; - -public static class SettingsList -{ - private static readonly char[] Separators = ['\r', '\n']; - - public static string[] Split(string? value) => - value is null - ? [] - : value.Split(Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) - .Distinct(StringComparer.Ordinal) - .ToArray(); - - public static string Join(IEnumerable items) => string.Join('\n', items); -} diff --git a/src/Flypaper.Http/FlypaperHttpExtensions.cs b/src/Flypaper.Http/FlypaperHttpExtensions.cs index bd3a156..a43b608 100644 --- a/src/Flypaper.Http/FlypaperHttpExtensions.cs +++ b/src/Flypaper.Http/FlypaperHttpExtensions.cs @@ -1,13 +1,11 @@ using System.Net; using System.Net.Sockets; -using Flypaper.Core.Settings; -using Flypaper.Http.Matching; using Flypaper.Http.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Flypaper.Http; @@ -16,20 +14,18 @@ public static class FlypaperHttpExtensions { private static readonly string[] DefaultTrustedProxies = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; + private static readonly string[] RemovedSettings = + [ + "Flypaper:Http:KnownHosts", + "Flypaper:Http:TrapPaths", + "Flypaper:Http:ExtraKnownHosts", + "Flypaper:Http:TrapPathsOverride" + ]; + public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration) { services.Configure(configuration.GetSection(HttpTrapOptions.SectionName)); services.Configure(configuration.GetSection(PortOptions.SectionName)); - services.PostConfigure(options => - { - if (options.TrapPathsOverride is not null) - { - options.TrapPaths = SettingsList.Split(options.TrapPathsOverride); - } - - options.KnownHosts = options.KnownHosts.Concat(SettingsList.Split(options.ExtraKnownHosts)).Distinct(StringComparer.OrdinalIgnoreCase).ToArray(); - }); - services.TryAddSingleton(); services.AddOptions() .Configure>((forwarded, trap) => @@ -55,6 +51,16 @@ public static class FlypaperHttpExtensions return app; } + public static void WarnAboutRemovedSettings(IConfiguration configuration, ILogger logger) + { + foreach (var key in RemovedSettings.Where(key => configuration.GetSection(key).Exists())) + { + logger.LogWarning( + "Setting {Key} is set but no longer has any effect: every request on the trap port is caught", + key.Replace(":", "__", StringComparison.Ordinal)); + } + } + private static int HostBits(string address) => IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32; } diff --git a/src/Flypaper.Http/HttpTrapOptions.cs b/src/Flypaper.Http/HttpTrapOptions.cs index acc09fc..9070080 100644 --- a/src/Flypaper.Http/HttpTrapOptions.cs +++ b/src/Flypaper.Http/HttpTrapOptions.cs @@ -6,13 +6,5 @@ public sealed class HttpTrapOptions public const string HealthPath = "/health"; - public string[] KnownHosts { get; set; } = []; - - public string[] TrapPaths { get; set; } = []; - public string[] TrustedProxies { get; set; } = []; - - public string? TrapPathsOverride { get; set; } - - public string? ExtraKnownHosts { get; set; } } diff --git a/src/Flypaper.Http/Matching/TrapMatch.cs b/src/Flypaper.Http/Matching/TrapMatch.cs deleted file mode 100644 index 87ced41..0000000 --- a/src/Flypaper.Http/Matching/TrapMatch.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace Flypaper.Http.Matching; - -public enum TrapMatch -{ - None, - UnknownHost, - TrapPath -} diff --git a/src/Flypaper.Http/Matching/TrapMatcher.cs b/src/Flypaper.Http/Matching/TrapMatcher.cs deleted file mode 100644 index 94218c9..0000000 --- a/src/Flypaper.Http/Matching/TrapMatcher.cs +++ /dev/null @@ -1,74 +0,0 @@ -using Microsoft.Extensions.Options; - -namespace Flypaper.Http.Matching; - -public sealed class TrapMatcher : IDisposable -{ - private readonly IDisposable? _subscription; - private volatile Snapshot _snapshot; - - public TrapMatcher(IOptionsMonitor options) - { - _snapshot = new Snapshot(options.CurrentValue); - _subscription = options.OnChange(updated => _snapshot = new Snapshot(updated)); - } - - public TrapMatch Match(string? host, string? path) - { - var snapshot = _snapshot; - if (!snapshot.IsKnownHost(host)) - { - return TrapMatch.UnknownHost; - } - - return snapshot.IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None; - } - - public void Dispose() => _subscription?.Dispose(); - - private sealed class Snapshot - { - private readonly HashSet _hosts = new(StringComparer.OrdinalIgnoreCase); - private readonly List _hostSuffixes = []; - private readonly HashSet _paths = new(StringComparer.OrdinalIgnoreCase); - private readonly List _pathPrefixes = []; - - public Snapshot(HttpTrapOptions options) - { - foreach (var host in options.KnownHosts.Where(h => !string.IsNullOrWhiteSpace(h))) - { - if (host.StartsWith("*.", StringComparison.Ordinal)) - { - _hostSuffixes.Add(host[1..]); - } - else - { - _hosts.Add(host); - } - } - - foreach (var path in options.TrapPaths.Where(p => !string.IsNullOrWhiteSpace(p))) - { - if (path.EndsWith('*')) - { - _pathPrefixes.Add(path[..^1]); - } - else - { - _paths.Add(TrimTrailingSlash(path)); - } - } - } - - public bool IsKnownHost(string? host) => - !string.IsNullOrEmpty(host) - && (_hosts.Contains(host) - || _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))); - - public bool IsTrapPath(string path) => - _paths.Contains(TrimTrailingSlash(path)) - || _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); - - private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path; - } -} diff --git a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs index fd4da5d..98bdc7d 100644 --- a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs +++ b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs @@ -3,7 +3,6 @@ using Flypaper.Core.Abstractions; using Flypaper.Core.Models; using Flypaper.Core.Networking; using Flypaper.Core.Runtime; -using Flypaper.Http.Matching; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Features; @@ -13,7 +12,6 @@ namespace Flypaper.Http.Middleware; internal sealed class FlypaperMiddleware( RequestDelegate next, - TrapMatcher matcher, TrapRunner runner, IOptions ports, TimeProvider timeProvider) @@ -27,11 +25,6 @@ internal sealed class FlypaperMiddleware( } var request = context.Request; - if (matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None) - { - context.Response.StatusCode = StatusCodes.Status404NotFound; - return; - } var session = new TrapSession( Guid.NewGuid(), diff --git a/src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.Designer.cs b/src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.Designer.cs new file mode 100644 index 0000000..188d575 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.Designer.cs @@ -0,0 +1,151 @@ +// +using System; +using Flypaper.Storage; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + [DbContext(typeof(FlypaperDbContext))] + [Migration("20261115175305_RemoveTrapPathSettings")] + partial class RemoveTrapPathSettings + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("McpTokens"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b => + { + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("Settings"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Asn") + .HasColumnType("INTEGER"); + + b.Property("BytesSent") + .HasColumnType("INTEGER"); + + b.Property("City") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ClientInfo") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("Country") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CountryCode") + .HasMaxLength(2) + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Provider") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SessionId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("Strategy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Target") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Asn"); + + b.HasIndex("CountryCode"); + + b.HasIndex("RemoteIp"); + + b.HasIndex("StartedAt"); + + b.ToTable("TrapEvents"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.cs b/src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.cs new file mode 100644 index 0000000..4a59b44 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261115175305_RemoveTrapPathSettings.cs @@ -0,0 +1,22 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + /// + public partial class RemoveTrapPathSettings : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql("DELETE FROM \"Settings\" WHERE \"Key\" IN ('Flypaper:Http:ExtraKnownHosts', 'Flypaper:Http:TrapPathsOverride');"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs b/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs index 8970759..e4fa3f2 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs +++ b/src/Flypaper.Web/Components/Pages/Settings/SettingsModel.cs @@ -2,16 +2,12 @@ namespace Flypaper.Web.Components.Pages.Settings; public sealed class SettingsModel { - public string? TrapPaths { get; set; } - public string? MaxConnections { get; set; } public string? MaxConnectionsPerIp { get; set; } public string? MaxHoldDuration { get; set; } - public string? ExtraKnownHosts { get; set; } - public string? RetentionDays { get; set; } public bool IgnorePrivateNetworks { get; set; } diff --git a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor index 0cc60fe..5dc7fec 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor +++ b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor @@ -9,7 +9,6 @@ @using Microsoft.Data.Sqlite @using Microsoft.Extensions.Options @inject IOptionsMonitor Core -@inject IOptionsMonitor Http @inject IOptionsMonitor Retention @inject IConfiguration Configuration @inject RuntimeSettingsStore Store @@ -39,14 +38,6 @@ else if (Saved == "reset")

Anpassbar

- - - - - - - -
@@ -100,8 +91,7 @@ else if (Saved == "reset") - - + @@ -129,11 +119,9 @@ else if (Saved == "reset") private async Task Save() { var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput( - Model!.TrapPaths, - Model.MaxConnections, + Model!.MaxConnections, Model.MaxConnectionsPerIp, Model.MaxHoldDuration, - Model.ExtraKnownHosts, Model.RetentionDays, Model.IgnorePrivateNetworks)); @@ -156,11 +144,8 @@ else if (Saved == "reset") private SettingsModel CurrentValues() { var core = Core.CurrentValue; - var http = Http.CurrentValue; return new SettingsModel { - TrapPaths = SettingsList.Join(http.TrapPaths), - ExtraKnownHosts = SettingsList.Join(SettingsList.Split(http.ExtraKnownHosts)), MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture), MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture), MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture), diff --git a/src/Flypaper.Web/Program.cs b/src/Flypaper.Web/Program.cs index 4c2c71a..2084763 100644 --- a/src/Flypaper.Web/Program.cs +++ b/src/Flypaper.Web/Program.cs @@ -55,6 +55,7 @@ builder.Services.AddAuthorizationBuilder() var app = builder.Build(); app.Logger.LogInformation("Flypaper {Version} starting", AppVersion.Current); +FlypaperHttpExtensions.WarnAboutRemovedSettings(app.Configuration, app.Logger); await app.Services.MigrateFlypaperDatabaseAsync(); app.UseFlypaper(); diff --git a/src/Flypaper.Web/appsettings.json b/src/Flypaper.Web/appsettings.json index c989605..4d63f85 100644 --- a/src/Flypaper.Web/appsettings.json +++ b/src/Flypaper.Web/appsettings.json @@ -23,24 +23,7 @@ "MaxConnectionsPerIp": 10, "MaxHoldDuration": "01:00:00", "Http": { - "KnownHosts": [], - "TrustedProxies": [], - "TrapPaths": [ - "/.env", - "/.env.*", - "/.git/*", - "/.aws/*", - "/.DS_Store", - "/wp-login.php", - "/wp-admin/*", - "/xmlrpc.php", - "/phpmyadmin/*", - "/vendor/phpunit/*", - "/server-status", - "/actuator/*", - "/cgi-bin/*", - "/boaform/*" - ] + "TrustedProxies": [] } } } diff --git a/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs b/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs index b9538bf..d7625da 100644 --- a/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs +++ b/test/Flypaper.Tests/Core/RuntimeSettingsParserTests.cs @@ -5,24 +5,15 @@ namespace Flypaper.Tests.Core; public sealed class RuntimeSettingsParserTests { - private static readonly RuntimeSettingsInput Valid = new( - "/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env", - "200", - "5", - "00:30:00", - "example.com\n*.example.org", - "90", - true); + private static readonly RuntimeSettingsInput Valid = new("200", "5", "00:30:00", "90", true); [Fact] - public void Parses_valid_input_and_normalizes_lists() + public void Parses_valid_input() { var result = RuntimeSettingsParser.Parse(Valid); result.Errors.ShouldBeEmpty(); var settings = result.Settings.ShouldNotBeNull(); - settings.TrapPaths.ShouldBe(["/.env", "/wp-admin/*", "/xmlrpc.php"]); - settings.ExtraKnownHosts.ShouldBe(["example.com", "*.example.org"]); settings.MaxConnections.ShouldBe(200); settings.MaxConnectionsPerIp.ShouldBe(5); settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30)); @@ -54,38 +45,6 @@ public sealed class RuntimeSettingsParserTests settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false"); } - [Fact] - public void Accepts_empty_lists() - { - var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = "", ExtraKnownHosts = null }); - - result.Settings.ShouldNotBeNull().TrapPaths.ShouldBeEmpty(); - } - - [Theory] - [InlineData("env")] - [InlineData("/with space")] - [InlineData("/a*b")] - public void Rejects_invalid_trap_paths(string path) - { - var result = RuntimeSettingsParser.Parse(Valid with { TrapPaths = $"/ok\n{path}" }); - - result.Settings.ShouldBeNull(); - result.Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.TrapPaths)]); - } - - [Theory] - [InlineData("https://example.com")] - [InlineData("example.com/path")] - [InlineData("example.com:8080")] - [InlineData("-bad.com")] - public void Rejects_invalid_hosts(string host) - { - var result = RuntimeSettingsParser.Parse(Valid with { ExtraKnownHosts = host }); - - result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.ExtraKnownHosts)); - } - [Theory] [InlineData("10")] [InlineData("abc")] diff --git a/test/Flypaper.Tests/Fakes/ListLogger.cs b/test/Flypaper.Tests/Fakes/ListLogger.cs new file mode 100644 index 0000000..e1a851d --- /dev/null +++ b/test/Flypaper.Tests/Fakes/ListLogger.cs @@ -0,0 +1,15 @@ +using Microsoft.Extensions.Logging; + +namespace Flypaper.Tests.Fakes; + +internal sealed class ListLogger : ILogger +{ + public List<(LogLevel Level, string Message)> Entries { get; } = []; + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) => + Entries.Add((logLevel, formatter(state, exception))); +} diff --git a/test/Flypaper.Tests/Http/HealthProbeTests.cs b/test/Flypaper.Tests/Http/HealthProbeTests.cs index 3210231..1b4e0ff 100644 --- a/test/Flypaper.Tests/Http/HealthProbeTests.cs +++ b/test/Flypaper.Tests/Http/HealthProbeTests.cs @@ -48,8 +48,7 @@ public sealed class HealthProbeTests var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { - ["Flypaper:MaxConnections"] = "0", - ["Flypaper:Http:KnownHosts:0"] = "dashboard.lan" + ["Flypaper:MaxConnections"] = "0" }) .Build(); diff --git a/test/Flypaper.Tests/Http/PortSeparationTests.cs b/test/Flypaper.Tests/Http/PortSeparationTests.cs index fcbfade..392dfd9 100644 --- a/test/Flypaper.Tests/Http/PortSeparationTests.cs +++ b/test/Flypaper.Tests/Http/PortSeparationTests.cs @@ -1,6 +1,7 @@ using System.Net; using Flypaper.Core; using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; using Flypaper.Http; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -31,42 +32,49 @@ public sealed class PortSeparationTests [Theory] [InlineData("unknown.example", "/")] [InlineData("203.0.113.7", "/settings")] + [InlineData("example.com", "/")] [InlineData("example.com", "/.env")] + [InlineData("example.com", "/login")] + [InlineData("", "/wp-login.php")] [InlineData("unknown.example", "/mcp")] - [InlineData("203.0.113.7", "/mcp")] - public async Task Trap_port_traps_unknown_hosts_and_trap_paths(string host, string path) - { - var (reachedApp, status) = await SendAsync(TrapPort, host, path); - - reachedApp.ShouldBeFalse(); - status.ShouldBe(StatusCodes.Status404NotFound); - } - - [Theory] - [InlineData("/")] - [InlineData("/settings")] - [InlineData("/login")] - [InlineData("/mcp")] - public async Task Trap_port_answers_other_paths_of_known_hosts_with_plain_404(string path) + [InlineData("203.0.113.7", "/health")] + public async Task Trap_port_catches_every_host_and_path(string host, string path) { var sink = Substitute.For(); - var (reachedApp, status) = await SendAsync(TrapPort, "example.com", path, sink); + var (reachedApp, status) = await SendAsync(TrapPort, host, path, sink); reachedApp.ShouldBeFalse(); status.ShouldBe(StatusCodes.Status404NotFound); - sink.DidNotReceiveWithAnyArgs().Publish(default!); + sink.Received(1).Publish(Arg.Is(e => e.Outcome == TrapOutcome.Rejected)); } - private static async Task<(bool ReachedApp, int Status)> SendAsync(int localPort, string host, string path, ITrapEventSink? sink = null) + [Fact] + public async Task Removed_settings_change_nothing() { - var configuration = new ConfigurationBuilder() - .AddInMemoryCollection(new Dictionary + var (reachedApp, _) = await SendAsync( + TrapPort, + "example.com", + "/", + extraSettings: new Dictionary { - ["Flypaper:MaxConnections"] = "0", ["Flypaper:Http:KnownHosts:0"] = "example.com", ["Flypaper:Http:TrapPaths:0"] = "/.env" - }) + }); + + reachedApp.ShouldBeFalse(); + } + + private static async Task<(bool ReachedApp, int Status)> SendAsync( + int localPort, + string host, + string path, + ITrapEventSink? sink = null, + Dictionary? extraSettings = null) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { ["Flypaper:MaxConnections"] = "0" }) + .AddInMemoryCollection(extraSettings ?? []) .Build(); var services = new ServiceCollection() diff --git a/test/Flypaper.Tests/Http/RemovedSettingsTests.cs b/test/Flypaper.Tests/Http/RemovedSettingsTests.cs new file mode 100644 index 0000000..7848f01 --- /dev/null +++ b/test/Flypaper.Tests/Http/RemovedSettingsTests.cs @@ -0,0 +1,41 @@ +using Flypaper.Http; +using Flypaper.Tests.Fakes; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; +using Shouldly; + +namespace Flypaper.Tests.Http; + +public sealed class RemovedSettingsTests +{ + [Fact] + public void Warns_about_each_removed_setting_that_is_still_set() + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Flypaper:Http:KnownHosts:0"] = "example.com", + ["Flypaper:Http:TrapPaths:0"] = "/.env", + ["Flypaper:Http:TrustedProxies:0"] = "172.19.0.0/16" + }) + .Build(); + var logger = new ListLogger(); + + FlypaperHttpExtensions.WarnAboutRemovedSettings(configuration, logger); + + logger.Entries.Count.ShouldBe(2); + logger.Entries.ShouldAllBe(e => e.Level == LogLevel.Warning); + logger.Entries.ShouldContain(e => e.Message.Contains("Flypaper__Http__KnownHosts")); + logger.Entries.ShouldContain(e => e.Message.Contains("Flypaper__Http__TrapPaths")); + } + + [Fact] + public void Stays_silent_without_removed_settings() + { + var logger = new ListLogger(); + + FlypaperHttpExtensions.WarnAboutRemovedSettings(new ConfigurationBuilder().Build(), logger); + + logger.Entries.ShouldBeEmpty(); + } +} diff --git a/test/Flypaper.Tests/Http/TrapMatcherTests.cs b/test/Flypaper.Tests/Http/TrapMatcherTests.cs deleted file mode 100644 index a72fc6e..0000000 --- a/test/Flypaper.Tests/Http/TrapMatcherTests.cs +++ /dev/null @@ -1,42 +0,0 @@ -using Flypaper.Http; -using Flypaper.Http.Matching; -using Flypaper.Tests.Fakes; -using Shouldly; - -namespace Flypaper.Tests.Http; - -public sealed class TrapMatcherTests -{ - private readonly TrapMatcher _matcher = new(TestOptions.Monitor(new HttpTrapOptions - { - KnownHosts = ["example.com", "*.example.org"], - TrapPaths = ["/.env", "/.git/*", "/wp-login.php"] - })); - - [Theory] - [InlineData("example.com", "/")] - [InlineData("EXAMPLE.com", "/index.html")] - [InlineData("app.example.org", "/api/items")] - [InlineData("example.com", "/.envelope")] - [InlineData("example.com", "/.git")] - public void Lets_normal_requests_pass(string host, string path) => - _matcher.Match(host, path).ShouldBe(TrapMatch.None); - - [Theory] - [InlineData("example.com", "/.env")] - [InlineData("example.com", "/.ENV")] - [InlineData("example.com", "/.env/")] - [InlineData("example.com", "/.git/config")] - [InlineData("app.example.org", "/wp-login.php")] - public void Traps_configured_paths(string host, string path) => - _matcher.Match(host, path).ShouldBe(TrapMatch.TrapPath); - - [Theory] - [InlineData("unknown.net", "/")] - [InlineData("203.0.113.7", "/")] - [InlineData("example.org", "/")] - [InlineData("", "/")] - [InlineData(null, "/")] - public void Traps_unknown_hosts(string? host, string path) => - _matcher.Match(host, path).ShouldBe(TrapMatch.UnknownHost); -} diff --git a/test/Flypaper.Tests/Storage/MigrationTests.cs b/test/Flypaper.Tests/Storage/MigrationTests.cs index 86104f1..248639d 100644 --- a/test/Flypaper.Tests/Storage/MigrationTests.cs +++ b/test/Flypaper.Tests/Storage/MigrationTests.cs @@ -43,6 +43,22 @@ public sealed class MigrationTests : IDisposable .ShouldBe(["GET /boaform/admin/formLogin", "GET example.com/.env"]); } + [Fact] + public async Task Removes_obsolete_trap_path_and_known_host_overrides() + { + await using var db = new FlypaperDbContext(new DbContextOptionsBuilder().UseSqlite($"Data Source={_dbPath}").Options); + await db.GetService().MigrateAsync("AddMcpTokens"); + await db.Database.ExecuteSqlRawAsync( + """ + INSERT INTO "Settings" ("Key", "Value") + VALUES ('Flypaper:Http:ExtraKnownHosts', 'example.com'), ('Flypaper:Http:TrapPathsOverride', '/.env'), ('Flypaper:MaxConnections', '50') + """); + + await db.Database.MigrateAsync(); + + (await db.Settings.Select(s => s.Key).ToListAsync()).ShouldBe(["Flypaper:MaxConnections"]); + } + public void Dispose() { SqliteConnection.ClearAllPools(); diff --git a/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs b/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs index 5c0cf11..be399bb 100644 --- a/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs +++ b/test/Flypaper.Tests/Storage/SettingsOverrideTests.cs @@ -1,9 +1,9 @@ using Flypaper.Core; using Flypaper.Core.Settings; using Flypaper.Http; -using Flypaper.Http.Matching; using Flypaper.Storage; using Flypaper.Storage.Entities; +using Flypaper.Storage.Maintenance; using Flypaper.Storage.Settings; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; @@ -28,8 +28,8 @@ public sealed class SettingsOverrideTests : IDisposable await db.Database.MigrateAsync(); db.Settings.AddRange( new SettingEntity { Key = SettingKeys.MaxConnections, Value = "5" }, - new SettingEntity { Key = SettingKeys.TrapPaths, Value = "/custom\n/other/*" }, - new SettingEntity { Key = SettingKeys.ExtraKnownHosts, Value = "extra.example" }, + new SettingEntity { Key = SettingKeys.RetentionDays, Value = "30" }, + new SettingEntity { Key = "Flypaper:Http:TrustedProxies:0", Value = "203.0.113.0/24" }, new SettingEntity { Key = "Flypaper:Admin:Password", Value = "evil" }); await db.SaveChangesAsync(); } @@ -38,14 +38,12 @@ public sealed class SettingsOverrideTests : IDisposable await host.Services.MigrateFlypaperDatabaseAsync(); var core = host.Services.GetRequiredService>().CurrentValue; - var http = host.Services.GetRequiredService>().CurrentValue; var configuration = host.Services.GetRequiredService(); core.MaxConnections.ShouldBe(5); core.MaxConnectionsPerIp.ShouldBe(10); - http.TrapPaths.ShouldBe(["/custom", "/other/*"]); - http.KnownHosts.ShouldBe(["dashboard.lan", "extra.example"]); - http.TrustedProxies.ShouldBe(["172.18.0.0/16"]); + host.Services.GetRequiredService>().CurrentValue.Days.ShouldBe(30); + host.Services.GetRequiredService>().CurrentValue.TrustedProxies.ShouldBe(["172.18.0.0/16"]); configuration["Flypaper:Admin:Password"].ShouldBe("secret"); } @@ -56,61 +54,31 @@ public sealed class SettingsOverrideTests : IDisposable await host.Services.MigrateFlypaperDatabaseAsync(); host.Services.GetRequiredService>().CurrentValue.MaxConnections.ShouldBe(100); - host.Services.GetRequiredService>().CurrentValue.TrapPaths.ShouldBe(["/.env"]); } [Fact] - public async Task Saving_reloads_trap_matcher_and_reset_restores_startup_values() + public async Task Saving_reloads_options_and_reset_restores_startup_values() { var host = BuildHost(); await host.Services.MigrateFlypaperDatabaseAsync(); - var matcher = host.Services.GetRequiredService(); + var options = host.Services.GetRequiredService>(); var store = host.Services.GetRequiredService(); - matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None); - matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath); - matcher.Match("extra.example", "/").ShouldBe(TrapMatch.UnknownHost); + await store.SaveAsync(new RuntimeSettings(50, 4, TimeSpan.FromMinutes(10), 90, false)); - await store.SaveAsync(new RuntimeSettings( - ["/custom"], - 50, - 4, - TimeSpan.FromMinutes(10), - ["extra.example"], - 90, - true)); - - matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.TrapPath); - matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None); - matcher.Match("extra.example", "/").ShouldBe(TrapMatch.None); + options.CurrentValue.MaxConnections.ShouldBe(50); + options.CurrentValue.MaxConnectionsPerIp.ShouldBe(4); + options.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(10)); + options.CurrentValue.IgnorePrivateNetworks.ShouldBeFalse(); (await store.HasOverridesAsync()).ShouldBeTrue(); await store.ResetAsync(); - matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None); - matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath); + options.CurrentValue.MaxConnections.ShouldBe(100); + options.CurrentValue.IgnorePrivateNetworks.ShouldBeTrue(); (await store.HasOverridesAsync()).ShouldBeFalse(); } - [Fact] - public async Task Saved_empty_trap_path_list_disables_path_traps() - { - var host = BuildHost(); - await host.Services.MigrateFlypaperDatabaseAsync(); - var matcher = host.Services.GetRequiredService(); - - await host.Services.GetRequiredService().SaveAsync(new RuntimeSettings( - [], - 50, - 4, - TimeSpan.FromMinutes(10), - [], - 90, - true)); - - matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None); - } - private IHost BuildHost() { var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true }); @@ -119,8 +87,6 @@ public sealed class SettingsOverrideTests : IDisposable ["ConnectionStrings:Flypaper"] = $"Data Source={_dbPath}", ["Flypaper:MaxConnections"] = "100", ["Flypaper:MaxConnectionsPerIp"] = "10", - ["Flypaper:Http:TrapPaths:0"] = "/.env", - ["Flypaper:Http:KnownHosts:0"] = "dashboard.lan", ["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16", ["Flypaper:Admin:Password"] = "secret" }); diff --git a/unraid/flypaper.xml b/unraid/flypaper.xml index 1446c99..8bca5f5 100644 --- a/unraid/flypaper.xml +++ b/unraid/flypaper.xml @@ -10,7 +10,7 @@ https://gitea.anticarnist.de/Tom/Flypaper/issues https://gitea.anticarnist.de/Tom/Flypaper Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis. Instead of blocking bots, Flypaper answers them with an endless HTML page that trickles in a few bytes at a time, and logs every catch with its country and network provider.[br][br] -The trap port receives everything your reverse proxy has no site for (its catch-all / default server) and, optionally, bait paths such as /.env from your real domains. The dashboard has its own port: keep it inside your LAN. On first visit you set the admin password.[br][br] +The trap port receives everything your reverse proxy has no site for (its catch-all / default server); every request there is caught. The dashboard has its own port: keep it inside your LAN. On first visit you set the admin password.[br][br] The container starts as root only to hand the appdata folder to its app user (UID 1654), then drops privileges for good. Security: Network:Proxy http://[IP]:[PORT:8081]/ @@ -28,5 +28,4 @@ The container starts as root only to hand the appdata folder to its app user (UI /mnt/user/appdata/flypaper -
Datenbank@DatabasePath
Bekannte Hosts@Format(Configuration.GetSection("Flypaper:Http:KnownHosts").Get())
Vertrauenswürdige Proxies@Format(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get())
Vertrauenswürdige Proxies@(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get()?.Where(p => !string.IsNullOrWhiteSpace(p)).ToArray() is { Length: > 0 } proxies ? string.Join(", ", proxies) : "private Netze (Standard)")
Admin-Passwort@(Admin.UsesEnvironmentPassword ? "per Umgebungsvariable" : "im Dashboard festgelegt")
PortsFalle @Ports.Value.Trap, Dashboard @Ports.Value.Dashboard