Remove trap paths and known hosts: catch everything on the trap port

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
TomandClaude Opus 5.5 committed 2026-11-15 18:56:35 +01:00
1 parent b9f2b0443c
commit 9a56fc5b48
31 files changed
+335 -462

No files matched your search

+7
View File
@@ -6,6 +6,13 @@ All notable changes to Flypaper are documented in this file. The format follows
## [Unreleased] ## [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 ## [0.2.0] - 2026-11-15
### Added ### Added
+3 -5
View File
@@ -11,7 +11,7 @@ the dashboard shows you who knocked: country, network provider and what they wer
flowchart LR flowchart LR
bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"] bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"]
proxy -->|"known site"| apps["Your apps"] proxy -->|"known site"| apps["Your apps"]
proxy -->|"unknown host or trap path<br/>+ X-Real-IP"| flypaper["Flypaper"] proxy -->|"unknown host<br/>+ X-Real-IP"| flypaper["Flypaper"]
flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot
flypaper --> db[("SQLite:<br/>catches, settings")] flypaper --> db[("SQLite:<br/>catches, settings")]
you["You (LAN)"] -->|"dashboard, port 8081"| flypaper you["You (LAN)"] -->|"dashboard, port 8081"| flypaper
@@ -87,8 +87,7 @@ server {
} }
``` ```
Nginx Proxy Manager, Caddy, Traefik and bait paths on your real domains: Nginx Proxy Manager, Caddy and Traefik: [docs/reverse-proxy.md](docs/reverse-proxy.md).
[docs/reverse-proxy.md](docs/reverse-proxy.md).
## Configuration ## 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__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__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 | | `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). and settings: [docs/configuration.md](docs/configuration.md).
## Security ## Security
+1 -1
View File
@@ -3,7 +3,7 @@
# .gitea/workflows/deploy.yml, not pasted into the Compose Manager. # .gitea/workflows/deploy.yml, not pasted into the Compose Manager.
# #
# NPM reaches the trap as flypaper:8080 over the external network proxynet (default # 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. # port 8081, published only to the LAN: http://192.168.1.14:44307.
# #
# `restart: always`, not `unless-stopped`: Unraid stops every container explicitly # `restart: always`, not `unless-stopped`: Unraid stops every container explicitly
-3
View File
@@ -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__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__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__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` | | `Flypaper__Ports__Trap` / `Flypaper__Ports__Dashboard` | Container ports | `8080` / `8081` |
| `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` | | `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
@@ -35,8 +34,6 @@ reset button removes all saved values.
| Setting | Default | | 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 hold time per catch | `01:00:00` |
| Maximum connections overall | `1000` | | Maximum connections overall | `1000` |
| Maximum connections per IP | `10` | | Maximum connections per IP | `10` |
+4 -6
View File
@@ -11,15 +11,14 @@ else, and every catch is logged with its origin for you to look at.
flowchart LR flowchart LR
bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"] bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"]
proxy -->|"known site"| apps["Your apps"] proxy -->|"known site"| apps["Your apps"]
proxy -->|"unknown host or trap path<br/>+ X-Real-IP"| flypaper["Flypaper"] proxy -->|"unknown host<br/>+ X-Real-IP"| flypaper["Flypaper"]
flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot
flypaper --> db[("SQLite:<br/>catches, settings")] flypaper --> db[("SQLite:<br/>catches, settings")]
you["You (LAN)"] -->|"dashboard, port 8081"| flypaper you["You (LAN)"] -->|"dashboard, port 8081"| flypaper
``` ```
1. Your reverse proxy keeps serving your real sites. Everything it has no site for (the 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 default/catch-all server) goes to Flypaper.
domains.
2. Flypaper listens on two ports. Port `8080` is the trap: everything that arrives there is 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. 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 3. A caught request gets `200 OK` and an endless, plausible-looking HTML page: random chunks
@@ -31,15 +30,14 @@ flowchart LR
## Features ## Features
- **Traps** for unknown hosts (catch-all) and for configurable trap paths such as `/.env`, - **Trap** for everything that reaches the trap port: whatever host or path a bot asks for
`/.git/*` or `/wp-login.php`
- **Slow delivery** of endless generated HTML with irregular timing - **Slow delivery** of endless generated HTML with irregular timing
- **Limits**: maximum connections overall and per IP, maximum hold time per catch - **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 - **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest
catches with expandable details; login with an admin password catches with expandable details; login with an admin password
- **GeoIP**: country, city and ASN per catch from DB-IP Lite, downloaded and refreshed - **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 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 without a restart
- **Retention**: old catches are deleted daily (90 days by default); catches from private - **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 networks are not stored by default; buttons to delete private or all catches
+3 -38
View File
@@ -20,17 +20,9 @@ bot never sees it. Flypaper sends `X-Accel-Buffering: no`, which nginx honors.
## What to send to Flypaper ## What to send to Flypaper
- **The catch-all server.** Requests for hosts you don't serve (mostly the bare IP) go to Send your proxy's catch-all server to Flypaper: requests for hosts you don't serve (mostly the
Flypaper. This is where almost all scanners end up. bare IP). This is where almost all scanners end up. Everything that reaches the trap port is
- **Optionally, trap paths on your real domains.** Forward only the bait paths, e.g. `/.env` caught, whatever host or path it asks for; the dashboard is never reachable there.
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.
**An HTTPS catch-all is rarely worth it.** Scanners of unknown hosts mostly speak plain HTTP to **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 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 <npm-container> nginx -t`, then 3. Test and reload: `docker exec <npm-container> nginx -t`, then
`docker exec <npm-container> nginx -s reload`. `docker exec <npm-container> 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. To undo the catch-all, delete `custom/http.conf` and reload.
## Plain nginx ## Plain nginx
@@ -122,16 +100,6 @@ With Flypaper on the same host, nothing else is needed: loopback is trusted by d
flush_interval -1 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 ## Traefik
@@ -146,8 +114,5 @@ labels:
traefik.http.routers.flypaper-catchall.rule: "HostRegexp(`.+`)" traefik.http.routers.flypaper-catchall.rule: "HostRegexp(`.+`)"
traefik.http.routers.flypaper-catchall.entrypoints: web traefik.http.routers.flypaper-catchall.entrypoints: web
traefik.http.routers.flypaper-catchall.priority: "1" 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" traefik.http.services.flypaper.loadbalancer.server.port: "8080"
``` ```
@@ -3,21 +3,17 @@ using System.Globalization;
namespace Flypaper.Core.Settings; namespace Flypaper.Core.Settings;
public sealed record RuntimeSettings( public sealed record RuntimeSettings(
IReadOnlyList<string> TrapPaths,
int MaxConnections, int MaxConnections,
int MaxConnectionsPerIp, int MaxConnectionsPerIp,
TimeSpan MaxHoldDuration, TimeSpan MaxHoldDuration,
IReadOnlyList<string> ExtraKnownHosts,
int RetentionDays, int RetentionDays,
bool IgnorePrivateNetworks) bool IgnorePrivateNetworks)
{ {
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string> public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
{ {
[SettingKeys.TrapPaths] = SettingsList.Join(TrapPaths),
[SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture), [SettingKeys.MaxConnections] = MaxConnections.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture), [SettingKeys.MaxConnectionsPerIp] = MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture), [SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts),
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture), [SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false" [SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
}; };
@@ -1,10 +1,8 @@
namespace Flypaper.Core.Settings; namespace Flypaper.Core.Settings;
public sealed record RuntimeSettingsInput( public sealed record RuntimeSettingsInput(
string? TrapPaths,
string? MaxConnections, string? MaxConnections,
string? MaxConnectionsPerIp, string? MaxConnectionsPerIp,
string? MaxHoldDuration, string? MaxHoldDuration,
string? ExtraKnownHosts,
string? RetentionDays, string? RetentionDays,
bool IgnorePrivateNetworks); bool IgnorePrivateNetworks);
@@ -1,28 +1,19 @@
using System.Globalization; using System.Globalization;
using System.Text.RegularExpressions;
namespace Flypaper.Core.Settings; 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 MaxLimit = 100_000;
private const int MaxRetentionDays = 3650; private const int MaxRetentionDays = 3650;
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1); private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7); 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) public static RuntimeSettingsParseResult Parse(RuntimeSettingsInput input)
{ {
var errors = new Dictionary<string, string>(); var errors = new Dictionary<string, string>();
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 hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors); var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 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( var settings = new RuntimeSettings(
paths!,
maxConnections!.Value, maxConnections!.Value,
perIp!.Value, perIp!.Value,
hold!.Value, hold!.Value,
hosts!,
retention!.Value, retention!.Value,
input.IgnorePrivateNetworks); input.IgnorePrivateNetworks);
return new RuntimeSettingsParseResult(settings, errors); return new RuntimeSettingsParseResult(settings, errors);
} }
private static string[]? ParseList(
string? raw,
string field,
Func<string, string?> validate,
Dictionary<string, string> 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<string>();
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( private static TimeSpan? ParseTimeSpan(
string? raw, string? raw,
string field, string field,
@@ -5,8 +5,6 @@ public static class SettingKeys
public const string MaxConnections = "Flypaper:MaxConnections"; public const string MaxConnections = "Flypaper:MaxConnections";
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp"; public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration"; 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 IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
public const string RetentionDays = "Flypaper:Retention:Days"; public const string RetentionDays = "Flypaper:Retention:Days";
@@ -15,8 +13,6 @@ public static class SettingKeys
MaxConnections, MaxConnections,
MaxConnectionsPerIp, MaxConnectionsPerIp,
MaxHoldDuration, MaxHoldDuration,
TrapPaths,
ExtraKnownHosts,
IgnorePrivateNetworks, IgnorePrivateNetworks,
RetentionDays RetentionDays
}; };
@@ -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<string> items) => string.Join('\n', items);
}
+19 -13
View File
@@ -1,13 +1,11 @@
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using Flypaper.Core.Settings;
using Flypaper.Http.Matching;
using Flypaper.Http.Middleware; using Flypaper.Http.Middleware;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides; using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Flypaper.Http; 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[] 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) public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
{ {
services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName)); services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName));
services.Configure<PortOptions>(configuration.GetSection(PortOptions.SectionName)); services.Configure<PortOptions>(configuration.GetSection(PortOptions.SectionName));
services.PostConfigure<HttpTrapOptions>(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<TrapMatcher>();
services.AddOptions<ForwardedHeadersOptions>() services.AddOptions<ForwardedHeadersOptions>()
.Configure<IOptions<HttpTrapOptions>>((forwarded, trap) => .Configure<IOptions<HttpTrapOptions>>((forwarded, trap) =>
@@ -55,6 +51,16 @@ public static class FlypaperHttpExtensions
return app; 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) => private static int HostBits(string address) =>
IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32; IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32;
} }
-8
View File
@@ -6,13 +6,5 @@ public sealed class HttpTrapOptions
public const string HealthPath = "/health"; public const string HealthPath = "/health";
public string[] KnownHosts { get; set; } = [];
public string[] TrapPaths { get; set; } = [];
public string[] TrustedProxies { get; set; } = []; public string[] TrustedProxies { get; set; } = [];
public string? TrapPathsOverride { get; set; }
public string? ExtraKnownHosts { get; set; }
} }
-8
View File
@@ -1,8 +0,0 @@
namespace Flypaper.Http.Matching;
public enum TrapMatch
{
None,
UnknownHost,
TrapPath
}
-74
View File
@@ -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<HttpTrapOptions> 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<string> _hosts = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _hostSuffixes = [];
private readonly HashSet<string> _paths = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _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;
}
}
@@ -3,7 +3,6 @@ using Flypaper.Core.Abstractions;
using Flypaper.Core.Models; using Flypaper.Core.Models;
using Flypaper.Core.Networking; using Flypaper.Core.Networking;
using Flypaper.Core.Runtime; using Flypaper.Core.Runtime;
using Flypaper.Http.Matching;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
@@ -13,7 +12,6 @@ namespace Flypaper.Http.Middleware;
internal sealed class FlypaperMiddleware( internal sealed class FlypaperMiddleware(
RequestDelegate next, RequestDelegate next,
TrapMatcher matcher,
TrapRunner runner, TrapRunner runner,
IOptions<PortOptions> ports, IOptions<PortOptions> ports,
TimeProvider timeProvider) TimeProvider timeProvider)
@@ -27,11 +25,6 @@ internal sealed class FlypaperMiddleware(
} }
var request = context.Request; 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( var session = new TrapSession(
Guid.NewGuid(), Guid.NewGuid(),
@@ -0,0 +1,151 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("TEXT");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<string>("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<string>("Key")
.HasMaxLength(128)
.HasColumnType("TEXT");
b.Property<string>("Value")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Key");
b.ToTable("Settings");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<long?>("Asn")
.HasColumnType("INTEGER");
b.Property<long>("BytesSent")
.HasColumnType("INTEGER");
b.Property<string>("City")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("ClientInfo")
.HasMaxLength(2048)
.HasColumnType("TEXT");
b.Property<string>("Country")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("CountryCode")
.HasMaxLength(2)
.HasColumnType("TEXT");
b.Property<long>("DurationMs")
.HasColumnType("INTEGER");
b.Property<DateTime>("EndedAt")
.HasColumnType("TEXT");
b.Property<string>("Outcome")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Protocol")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Provider")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("RemoteIp")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<Guid>("SessionId")
.HasColumnType("TEXT");
b.Property<DateTime>("StartedAt")
.HasColumnType("TEXT");
b.Property<string>("Strategy")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<string>("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
}
}
}
@@ -0,0 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class RemoveTrapPathSettings : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM \"Settings\" WHERE \"Key\" IN ('Flypaper:Http:ExtraKnownHosts', 'Flypaper:Http:TrapPathsOverride');");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
@@ -2,16 +2,12 @@ namespace Flypaper.Web.Components.Pages.Settings;
public sealed class SettingsModel public sealed class SettingsModel
{ {
public string? TrapPaths { get; set; }
public string? MaxConnections { get; set; } public string? MaxConnections { get; set; }
public string? MaxConnectionsPerIp { get; set; } public string? MaxConnectionsPerIp { get; set; }
public string? MaxHoldDuration { get; set; } public string? MaxHoldDuration { get; set; }
public string? ExtraKnownHosts { get; set; }
public string? RetentionDays { get; set; } public string? RetentionDays { get; set; }
public bool IgnorePrivateNetworks { get; set; } public bool IgnorePrivateNetworks { get; set; }
@@ -9,7 +9,6 @@
@using Microsoft.Data.Sqlite @using Microsoft.Data.Sqlite
@using Microsoft.Extensions.Options @using Microsoft.Extensions.Options
@inject IOptionsMonitor<FlypaperOptions> Core @inject IOptionsMonitor<FlypaperOptions> Core
@inject IOptionsMonitor<HttpTrapOptions> Http
@inject IOptionsMonitor<RetentionOptions> Retention @inject IOptionsMonitor<RetentionOptions> Retention
@inject IConfiguration Configuration @inject IConfiguration Configuration
@inject RuntimeSettingsStore Store @inject RuntimeSettingsStore Store
@@ -39,14 +38,6 @@ else if (Saved == "reset")
<EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form"> <EditForm Model="Model" FormName="settings" OnSubmit="Save" action="/settings" class="card form">
<h2>Anpassbar</h2> <h2>Anpassbar</h2>
<label for="trap-paths">Fallenpfade <span class="muted">(einer pro Zeile, mit / am Anfang, * am Ende als Präfix)</span></label>
<InputTextArea id="trap-paths" @bind-Value="Model!.TrapPaths" rows="10" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.TrapPaths)" />
<label for="hosts">Bekannte Hosts <span class="muted">(einer pro Zeile, z. B. beispiel.de oder *.beispiel.de; werden auf dem Fallen-Port nur bei Fallenpfaden gefangen, sonst 404)</span></label>
<InputTextArea id="hosts" @bind-Value="Model!.ExtraKnownHosts" rows="4" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" />
<div class="grid"> <div class="grid">
<div> <div>
<label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label> <label for="hold">Maximale Haltedauer <span class="muted">(hh:mm:ss)</span></label>
@@ -100,8 +91,7 @@ else if (Saved == "reset")
<table> <table>
<tbody> <tbody>
<tr><th>Datenbank</th><td class="mono">@DatabasePath</td></tr> <tr><th>Datenbank</th><td class="mono">@DatabasePath</td></tr>
<tr><th>Bekannte Hosts</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:KnownHosts").Get<string[]>())</td></tr> <tr><th>Vertrauenswürdige Proxies</th><td class="mono">@(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get<string[]>()?.Where(p => !string.IsNullOrWhiteSpace(p)).ToArray() is { Length: > 0 } proxies ? string.Join(", ", proxies) : "private Netze (Standard)")</td></tr>
<tr><th>Vertrauenswürdige Proxies</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get<string[]>())</td></tr>
<tr><th>Admin-Passwort</th><td>@(Admin.UsesEnvironmentPassword ? "per Umgebungsvariable" : "im Dashboard festgelegt")</td></tr> <tr><th>Admin-Passwort</th><td>@(Admin.UsesEnvironmentPassword ? "per Umgebungsvariable" : "im Dashboard festgelegt")</td></tr>
<tr><th>Ports</th><td class="mono">Falle @Ports.Value.Trap, Dashboard @Ports.Value.Dashboard</td></tr> <tr><th>Ports</th><td class="mono">Falle @Ports.Value.Trap, Dashboard @Ports.Value.Dashboard</td></tr>
</tbody> </tbody>
@@ -129,11 +119,9 @@ else if (Saved == "reset")
private async Task Save() private async Task Save()
{ {
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput( var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
Model!.TrapPaths, Model!.MaxConnections,
Model.MaxConnections,
Model.MaxConnectionsPerIp, Model.MaxConnectionsPerIp,
Model.MaxHoldDuration, Model.MaxHoldDuration,
Model.ExtraKnownHosts,
Model.RetentionDays, Model.RetentionDays,
Model.IgnorePrivateNetworks)); Model.IgnorePrivateNetworks));
@@ -156,11 +144,8 @@ else if (Saved == "reset")
private SettingsModel CurrentValues() private SettingsModel CurrentValues()
{ {
var core = Core.CurrentValue; var core = Core.CurrentValue;
var http = Http.CurrentValue;
return new SettingsModel return new SettingsModel
{ {
TrapPaths = SettingsList.Join(http.TrapPaths),
ExtraKnownHosts = SettingsList.Join(SettingsList.Split(http.ExtraKnownHosts)),
MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture), MaxHoldDuration = core.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture), MaxConnections = core.MaxConnections.ToString(CultureInfo.InvariantCulture),
MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture), MaxConnectionsPerIp = core.MaxConnectionsPerIp.ToString(CultureInfo.InvariantCulture),
+1
View File
@@ -55,6 +55,7 @@ builder.Services.AddAuthorizationBuilder()
var app = builder.Build(); var app = builder.Build();
app.Logger.LogInformation("Flypaper {Version} starting", AppVersion.Current); app.Logger.LogInformation("Flypaper {Version} starting", AppVersion.Current);
FlypaperHttpExtensions.WarnAboutRemovedSettings(app.Configuration, app.Logger);
await app.Services.MigrateFlypaperDatabaseAsync(); await app.Services.MigrateFlypaperDatabaseAsync();
app.UseFlypaper(); app.UseFlypaper();
+1 -18
View File
@@ -23,24 +23,7 @@
"MaxConnectionsPerIp": 10, "MaxConnectionsPerIp": 10,
"MaxHoldDuration": "01:00:00", "MaxHoldDuration": "01:00:00",
"Http": { "Http": {
"KnownHosts": [], "TrustedProxies": []
"TrustedProxies": [],
"TrapPaths": [
"/.env",
"/.env.*",
"/.git/*",
"/.aws/*",
"/.DS_Store",
"/wp-login.php",
"/wp-admin/*",
"/xmlrpc.php",
"/phpmyadmin/*",
"/vendor/phpunit/*",
"/server-status",
"/actuator/*",
"/cgi-bin/*",
"/boaform/*"
]
} }
} }
} }
@@ -5,24 +5,15 @@ namespace Flypaper.Tests.Core;
public sealed class RuntimeSettingsParserTests public sealed class RuntimeSettingsParserTests
{ {
private static readonly RuntimeSettingsInput Valid = new( private static readonly RuntimeSettingsInput Valid = new("200", "5", "00:30:00", "90", true);
"/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env",
"200",
"5",
"00:30:00",
"example.com\n*.example.org",
"90",
true);
[Fact] [Fact]
public void Parses_valid_input_and_normalizes_lists() public void Parses_valid_input()
{ {
var result = RuntimeSettingsParser.Parse(Valid); var result = RuntimeSettingsParser.Parse(Valid);
result.Errors.ShouldBeEmpty(); result.Errors.ShouldBeEmpty();
var settings = result.Settings.ShouldNotBeNull(); 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.MaxConnections.ShouldBe(200);
settings.MaxConnectionsPerIp.ShouldBe(5); settings.MaxConnectionsPerIp.ShouldBe(5);
settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30)); settings.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(30));
@@ -54,38 +45,6 @@ public sealed class RuntimeSettingsParserTests
settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false"); 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] [Theory]
[InlineData("10")] [InlineData("10")]
[InlineData("abc")] [InlineData("abc")]
+15
View File
@@ -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>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) =>
Entries.Add((logLevel, formatter(state, exception)));
}
+1 -2
View File
@@ -48,8 +48,7 @@ public sealed class HealthProbeTests
var configuration = new ConfigurationBuilder() var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> .AddInMemoryCollection(new Dictionary<string, string?>
{ {
["Flypaper:MaxConnections"] = "0", ["Flypaper:MaxConnections"] = "0"
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan"
}) })
.Build(); .Build();
+30 -22
View File
@@ -1,6 +1,7 @@
using System.Net; using System.Net;
using Flypaper.Core; using Flypaper.Core;
using Flypaper.Core.Abstractions; using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Http; using Flypaper.Http;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
@@ -31,42 +32,49 @@ public sealed class PortSeparationTests
[Theory] [Theory]
[InlineData("unknown.example", "/")] [InlineData("unknown.example", "/")]
[InlineData("203.0.113.7", "/settings")] [InlineData("203.0.113.7", "/settings")]
[InlineData("example.com", "/")]
[InlineData("example.com", "/.env")] [InlineData("example.com", "/.env")]
[InlineData("example.com", "/login")]
[InlineData("", "/wp-login.php")]
[InlineData("unknown.example", "/mcp")] [InlineData("unknown.example", "/mcp")]
[InlineData("203.0.113.7", "/mcp")] [InlineData("203.0.113.7", "/health")]
public async Task Trap_port_traps_unknown_hosts_and_trap_paths(string host, string path) public async Task Trap_port_catches_every_host_and_path(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)
{ {
var sink = Substitute.For<ITrapEventSink>(); var sink = Substitute.For<ITrapEventSink>();
var (reachedApp, status) = await SendAsync(TrapPort, "example.com", path, sink); var (reachedApp, status) = await SendAsync(TrapPort, host, path, sink);
reachedApp.ShouldBeFalse(); reachedApp.ShouldBeFalse();
status.ShouldBe(StatusCodes.Status404NotFound); status.ShouldBe(StatusCodes.Status404NotFound);
sink.DidNotReceiveWithAnyArgs().Publish(default!); sink.Received(1).Publish(Arg.Is<TrapEvent>(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() var (reachedApp, _) = await SendAsync(
.AddInMemoryCollection(new Dictionary<string, string?> TrapPort,
"example.com",
"/",
extraSettings: new Dictionary<string, string?>
{ {
["Flypaper:MaxConnections"] = "0",
["Flypaper:Http:KnownHosts:0"] = "example.com", ["Flypaper:Http:KnownHosts:0"] = "example.com",
["Flypaper:Http:TrapPaths:0"] = "/.env" ["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<string, string?>? extraSettings = null)
{
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> { ["Flypaper:MaxConnections"] = "0" })
.AddInMemoryCollection(extraSettings ?? [])
.Build(); .Build();
var services = new ServiceCollection() var services = new ServiceCollection()
@@ -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<string, string?>
{
["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();
}
}
@@ -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);
}
@@ -43,6 +43,22 @@ public sealed class MigrationTests : IDisposable
.ShouldBe(["GET /boaform/admin/formLogin", "GET example.com/.env"]); .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<FlypaperDbContext>().UseSqlite($"Data Source={_dbPath}").Options);
await db.GetService<IMigrator>().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() public void Dispose()
{ {
SqliteConnection.ClearAllPools(); SqliteConnection.ClearAllPools();
@@ -1,9 +1,9 @@
using Flypaper.Core; using Flypaper.Core;
using Flypaper.Core.Settings; using Flypaper.Core.Settings;
using Flypaper.Http; using Flypaper.Http;
using Flypaper.Http.Matching;
using Flypaper.Storage; using Flypaper.Storage;
using Flypaper.Storage.Entities; using Flypaper.Storage.Entities;
using Flypaper.Storage.Maintenance;
using Flypaper.Storage.Settings; using Flypaper.Storage.Settings;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
@@ -28,8 +28,8 @@ public sealed class SettingsOverrideTests : IDisposable
await db.Database.MigrateAsync(); await db.Database.MigrateAsync();
db.Settings.AddRange( db.Settings.AddRange(
new SettingEntity { Key = SettingKeys.MaxConnections, Value = "5" }, new SettingEntity { Key = SettingKeys.MaxConnections, Value = "5" },
new SettingEntity { Key = SettingKeys.TrapPaths, Value = "/custom\n/other/*" }, new SettingEntity { Key = SettingKeys.RetentionDays, Value = "30" },
new SettingEntity { Key = SettingKeys.ExtraKnownHosts, Value = "extra.example" }, new SettingEntity { Key = "Flypaper:Http:TrustedProxies:0", Value = "203.0.113.0/24" },
new SettingEntity { Key = "Flypaper:Admin:Password", Value = "evil" }); new SettingEntity { Key = "Flypaper:Admin:Password", Value = "evil" });
await db.SaveChangesAsync(); await db.SaveChangesAsync();
} }
@@ -38,14 +38,12 @@ public sealed class SettingsOverrideTests : IDisposable
await host.Services.MigrateFlypaperDatabaseAsync(); await host.Services.MigrateFlypaperDatabaseAsync();
var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue; var core = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue;
var http = host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue;
var configuration = host.Services.GetRequiredService<IConfiguration>(); var configuration = host.Services.GetRequiredService<IConfiguration>();
core.MaxConnections.ShouldBe(5); core.MaxConnections.ShouldBe(5);
core.MaxConnectionsPerIp.ShouldBe(10); core.MaxConnectionsPerIp.ShouldBe(10);
http.TrapPaths.ShouldBe(["/custom", "/other/*"]); host.Services.GetRequiredService<IOptionsMonitor<RetentionOptions>>().CurrentValue.Days.ShouldBe(30);
http.KnownHosts.ShouldBe(["dashboard.lan", "extra.example"]); host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue.TrustedProxies.ShouldBe(["172.18.0.0/16"]);
http.TrustedProxies.ShouldBe(["172.18.0.0/16"]);
configuration["Flypaper:Admin:Password"].ShouldBe("secret"); configuration["Flypaper:Admin:Password"].ShouldBe("secret");
} }
@@ -56,61 +54,31 @@ public sealed class SettingsOverrideTests : IDisposable
await host.Services.MigrateFlypaperDatabaseAsync(); await host.Services.MigrateFlypaperDatabaseAsync();
host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue.MaxConnections.ShouldBe(100); host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>().CurrentValue.MaxConnections.ShouldBe(100);
host.Services.GetRequiredService<IOptionsMonitor<HttpTrapOptions>>().CurrentValue.TrapPaths.ShouldBe(["/.env"]);
} }
[Fact] [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(); var host = BuildHost();
await host.Services.MigrateFlypaperDatabaseAsync(); await host.Services.MigrateFlypaperDatabaseAsync();
var matcher = host.Services.GetRequiredService<TrapMatcher>(); var options = host.Services.GetRequiredService<IOptionsMonitor<FlypaperOptions>>();
var store = host.Services.GetRequiredService<RuntimeSettingsStore>(); var store = host.Services.GetRequiredService<RuntimeSettingsStore>();
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None); await store.SaveAsync(new RuntimeSettings(50, 4, TimeSpan.FromMinutes(10), 90, false));
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath);
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.UnknownHost);
await store.SaveAsync(new RuntimeSettings( options.CurrentValue.MaxConnections.ShouldBe(50);
["/custom"], options.CurrentValue.MaxConnectionsPerIp.ShouldBe(4);
50, options.CurrentValue.MaxHoldDuration.ShouldBe(TimeSpan.FromMinutes(10));
4, options.CurrentValue.IgnorePrivateNetworks.ShouldBeFalse();
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);
(await store.HasOverridesAsync()).ShouldBeTrue(); (await store.HasOverridesAsync()).ShouldBeTrue();
await store.ResetAsync(); await store.ResetAsync();
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.None); options.CurrentValue.MaxConnections.ShouldBe(100);
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.TrapPath); options.CurrentValue.IgnorePrivateNetworks.ShouldBeTrue();
(await store.HasOverridesAsync()).ShouldBeFalse(); (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<TrapMatcher>();
await host.Services.GetRequiredService<RuntimeSettingsStore>().SaveAsync(new RuntimeSettings(
[],
50,
4,
TimeSpan.FromMinutes(10),
[],
90,
true));
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
}
private IHost BuildHost() private IHost BuildHost()
{ {
var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true }); var builder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
@@ -119,8 +87,6 @@ public sealed class SettingsOverrideTests : IDisposable
["ConnectionStrings:Flypaper"] = $"Data Source={_dbPath}", ["ConnectionStrings:Flypaper"] = $"Data Source={_dbPath}",
["Flypaper:MaxConnections"] = "100", ["Flypaper:MaxConnections"] = "100",
["Flypaper:MaxConnectionsPerIp"] = "10", ["Flypaper:MaxConnectionsPerIp"] = "10",
["Flypaper:Http:TrapPaths:0"] = "/.env",
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan",
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16", ["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16",
["Flypaper:Admin:Password"] = "secret" ["Flypaper:Admin:Password"] = "secret"
}); });
+1 -2
View File
@@ -10,7 +10,7 @@
<Support>https://gitea.anticarnist.de/Tom/Flypaper/issues</Support> <Support>https://gitea.anticarnist.de/Tom/Flypaper/issues</Support>
<Project>https://gitea.anticarnist.de/Tom/Flypaper</Project> <Project>https://gitea.anticarnist.de/Tom/Flypaper</Project>
<Overview>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] <Overview>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.</Overview> The container starts as root only to hand the appdata folder to its app user (UID 1654), then drops privileges for good.</Overview>
<Category>Security: Network:Proxy</Category> <Category>Security: Network:Proxy</Category>
<WebUI>http://[IP]:[PORT:8081]/</WebUI> <WebUI>http://[IP]:[PORT:8081]/</WebUI>
@@ -28,5 +28,4 @@ The container starts as root only to hand the appdata folder to its app user (UI
<Config Name="Data" Target="/data" Default="/mnt/user/appdata/flypaper" Mode="rw" Description="Database, login keys and GeoIP databases." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/flypaper</Config> <Config Name="Data" Target="/data" Default="/mnt/user/appdata/flypaper" Mode="rw" Description="Database, login keys and GeoIP databases." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/flypaper</Config>
<Config Name="Admin password" Target="Flypaper__Admin__Password" Default="" Mode="" Description="Optional. Fixes the dashboard password and disables the first-visit setup. Leave empty to set it in the dashboard." Type="Variable" Display="advanced" Required="false" Mask="true"/> <Config Name="Admin password" Target="Flypaper__Admin__Password" Default="" Mode="" Description="Optional. Fixes the dashboard password and disables the first-visit setup. Leave empty to set it in the dashboard." Type="Variable" Display="advanced" Required="false" Mask="true"/>
<Config Name="Trusted proxy" Target="Flypaper__Http__TrustedProxies__0" Default="" Mode="" Description="Optional. IP or CIDR of the reverse proxy allowed to set X-Real-IP / X-Forwarded-For. Default: all private networks." Type="Variable" Display="advanced" Required="false" Mask="false"/> <Config Name="Trusted proxy" Target="Flypaper__Http__TrustedProxies__0" Default="" Mode="" Description="Optional. IP or CIDR of the reverse proxy allowed to set X-Real-IP / X-Forwarded-For. Default: all private networks." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Known host" Target="Flypaper__Http__KnownHosts__0" Default="" Mode="" Description="Optional. A host that is caught only on trap paths; its other paths get a plain 404." Type="Variable" Display="advanced" Required="false" Mask="false"/>
</Container> </Container>