Add data management, randomized HTML drip and public README

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

No files matched your search

+4 -4
View File
@@ -1,10 +1,10 @@
# Builds the image on every push to main, pushes it to the Gitea registry (tagged # Builds the image on every push to main, pushes it to the Gitea registry (tagged
# :latest AND the short commit SHA, for rollback) and deploys the stack on Unraid # :latest AND the short commit SHA, for rollback) and deploys the stack on Unraid
# from the repo's compose.yaml. # from deploy/unraid/compose.yaml (Tom's personal Unraid setup).
# #
# The deploy works because the act_runner runs ON Unraid and hands its Docker # The deploy works because the act_runner runs ON Unraid and hands its Docker
# socket to the job: every `docker` command here talks to the Unraid daemon, so # socket to the job: every `docker` command here talks to the Unraid daemon, so
# absolute paths in compose.yaml (the /data bind mount) are host paths. # absolute paths in that compose file (the /data bind mount) are host paths.
# #
# Required repository secrets (Gitea -> repo -> Settings -> Actions -> Secrets): # Required repository secrets (Gitea -> repo -> Settings -> Actions -> Secrets):
# REGISTRY_USER the registry username (e.g. Tom) # REGISTRY_USER the registry username (e.g. Tom)
@@ -107,8 +107,8 @@ jobs:
env: env:
FLYPAPER_ADMIN_PASSWORD: ${{ secrets.FLYPAPER_ADMIN_PASSWORD }} FLYPAPER_ADMIN_PASSWORD: ${{ secrets.FLYPAPER_ADMIN_PASSWORD }}
run: | run: |
docker compose -f compose.yaml pull docker compose -f deploy/unraid/compose.yaml pull
docker compose -f compose.yaml up -d --wait --remove-orphans docker compose -f deploy/unraid/compose.yaml up -d --wait --remove-orphans
# /health answers 200 only when the app runs AND reads its database. It is # /health answers 200 only when the app runs AND reads its database. It is
# checked from inside proxynet, the same way NPM reaches the app. The probe # checked from inside proxynet, the same way NPM reaches the app. The probe
+324 -26
View File
@@ -2,42 +2,340 @@
Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis. Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis.
## Deployment Every server on the internet gets a steady stream of bots probing for `/.env`, `/.git/config`,
`/wp-login.php` and friends, usually sent to the bare IP address or to host names that don't
exist. Blocklists play whack-a-mole with addresses that change daily. Flypaper takes the
opposite approach: it lets the bot in and then answers very, very slowly. While a scanner waits
for an endless HTML page that trickles in a few bytes at a time, it isn't scanning someone
else, and every catch is logged with its origin for you to look at.
Every push to `main` (except docs and `.md` files) runs `.gitea/workflows/deploy.yml` on the ## How it works
act_runner on Unraid: it builds the image, pushes it to
`gitea.anticarnist.de/tom/flypaper` (`:latest` and `:<short-sha>`), deploys `compose.yaml`
and waits for `/health`. A manual run is possible from the Actions tab (`workflow_dispatch`).
### Secrets ```mermaid
flowchart LR
bot["Scanner bot"] -->|"GET /.env<br/>Host: 203.0.113.7"| proxy["Reverse proxy"]
proxy -->|"known site"| apps["Your apps"]
proxy -->|"unknown host or trap path<br/>+ X-Real-IP"| flypaper["Flypaper"]
flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot
flypaper --> db[("SQLite:<br/>catches, settings")]
you["You (LAN)"] -->|"dashboard host"| flypaper
```
Gitea → repo → Settings → Actions → Secrets: 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.
2. Flypaper looks at the `Host` header. A request for a host it doesn't know, or for a trap path,
is caught. Requests for a known host (the dashboard's) pass through to the dashboard.
3. A caught request gets `200 OK` and an endless, plausible-looking HTML page: random chunks
of 1 to 64 bytes with random pauses of 50 ms to 1 s in between.
4. A connection governor caps the number of catches overall and per IP and ends every catch
after a maximum hold time. If there is no free slot, the request gets a quick `404`.
5. When a catch ends, Flypaper logs one line and stores the event in SQLite, enriched with
country, city and network provider (ASN) from the free DB-IP databases.
| Secret | Purpose | ## Features
- **Traps** for unknown hosts (catch-all) and for configurable trap paths such as `/.env`,
`/.git/*` or `/wp-login.php`
- **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
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
- **One log line per catch**, so `docker logs` alone shows whether the trap works
- **Health endpoint** `/health` for container health checks (answers only to private
addresses)
## Quick start
There is no public image; build it from source.
```bash
git clone <repository-url> flypaper
cd flypaper
```
Create a `compose.yaml` next to the `Dockerfile`:
```yaml
services:
flypaper:
build: .
image: flypaper:local
container_name: flypaper
restart: unless-stopped
ports:
- "8080:8080"
environment:
TZ: Europe/Berlin
# Host names that reach the dashboard. Every other Host header is trapped.
Flypaper__Http__KnownHosts__0: localhost
# The reverse proxy that sets X-Real-IP (IP or CIDR), see below.
Flypaper__Http__TrustedProxies__0: 172.16.0.0/12
Flypaper__Admin__Password: ${FLYPAPER_ADMIN_PASSWORD:?set FLYPAPER_ADMIN_PASSWORD}
volumes:
- flypaper-data:/data
volumes:
flypaper-data:
```
```bash
FLYPAPER_ADMIN_PASSWORD='a-long-random-password' docker compose up -d --build
```
- Dashboard: <http://localhost:8080>, log in with the password.
- See the trap in action (any unknown host works):
```bash
curl -N -H "Host: example.invalid" http://localhost:8080/
```
This catch comes from a private address and is therefore not stored; the log line ends with
`(not stored)`.
The container runs as a non-root user (UID 1654) and keeps everything under `/data`: the SQLite
database, the Data Protection keys for logins and the GeoIP databases. A named volume gets
the right owner automatically; for a bind mount, `chown 1654:1654` the host folder first.
The files in [`deploy/unraid/`](deploy/unraid) and `.gitea/workflows/deploy.yml` are the
author's personal deployment (Gitea Actions to Unraid). They are an example only and not
needed to run Flypaper.
## Behind a reverse proxy
Flypaper is meant to sit behind the reverse proxy that already owns ports 80/443. Two rules
apply to every proxy:
- **Set `X-Real-IP`** (and `X-Forwarded-For`) to the client address.
- **Trust the proxy in Flypaper**: `Flypaper__Http__TrustedProxies__0` must contain the
proxy's IP or subnet. Headers from anyone else are ignored, so bots can't fake their
address. For a Docker network:
```bash
docker network inspect <network> -f '{{(index .IPAM.Config 0).Subnet}}'
```
Also turn off response buffering for Flypaper, otherwise the proxy collects the drip and the
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. Your domains are unknown to Flypaper,
so these requests are caught as well.
Never forward a whole domain that is listed as a known host: its other paths would show the
dashboard login.
### Nginx Proxy Manager
Put Flypaper into the same Docker network as NPM (the examples use the container name
`flypaper`).
1. **Settings → Default Site → Congratulations Page.** With this setting NPM writes no
default server of its own. Any other choice (404, redirect, HTML) creates one, and nginx
refuses to start with two default servers.
2. Create `/data/nginx/custom/http.conf` in the NPM container (on the host: inside NPM's
data volume):
```nginx
# Catch-all: every HTTP request whose Host matches no proxy host goes to Flypaper.
server {
listen 80 default_server; # the HTTP port NPM listens on inside its container
listen [::]:80 default_server;
server_name _;
location / {
# A variable makes nginx resolve the name per request, so NPM still starts
# (and serves your sites) while the Flypaper container is down.
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_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_read_timeout 1h;
}
}
```
3. Test and reload: `docker exec <npm-container> nginx -t`, then
`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.
### Plain nginx
Same idea: remove any existing `default_server` (on Debian/Ubuntu often
`sites-enabled/default`) and add
```nginx
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
location / {
proxy_pass http://127.0.0.1:8080; # or a variable + resolver for a Docker name, see above
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;
proxy_read_timeout 1h;
}
}
```
With Flypaper on the same host, `TrustedProxies` can stay empty: loopback is trusted by default.
### Caddy
```caddyfile
# Catch-all for every host on port 80 without its own site block
:80 {
reverse_proxy flypaper:8080 {
header_up X-Real-IP {remote_host}
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 sets `X-Real-Ip` and `X-Forwarded-For` by default. Labels on the Flypaper container
(Traefik v3):
```yaml
labels:
traefik.enable: "true"
# Lowest priority: matches only hosts no other router claims
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"
```
## Configuration
### Environment variables
Read at startup. List entries need an index (`__0`, `__1`, ...).
| Variable | Purpose | Default |
|---|---|---|
| `Flypaper__Http__KnownHosts__0` | Host names that reach the dashboard (`*.example.com` allowed). Every other host is trapped. | none |
| `Flypaper__Http__TrustedProxies__0` | IP or CIDR of the reverse proxy allowed to set `X-Real-IP` / `X-Forwarded-For` | loopback only |
| `Flypaper__Admin__Password` | Dashboard password. Without it the dashboard stays locked. | none |
| `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` |
| `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` |
| `Flypaper__Drip__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
| `TZ` | Time zone for the dashboard | UTC |
The defaults of the runtime settings below can also be set this way, e.g.
`Flypaper__MaxConnections`. Values saved on the settings page override them.
### Runtime settings
Changed on the dashboard's settings page, stored in the database, effective immediately. The
reset button removes all saved values.
| Setting | Default |
|---|---| |---|---|
| `REGISTRY_USER` | Registry username | | 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/*` |
| `REGISTRY_TOKEN` | Gitea access token with `package:write` (not the password) | | Extra known hosts (merged with `KnownHosts`) | none |
| `FLYPAPER_ADMIN_PASSWORD` | Dashboard login password | | Maximum hold time per catch | `01:00:00` |
| Maximum connections overall | `1000` |
| Maximum connections per IP | `10` |
| Keep catches (days, `0` = forever) | `90` |
| Don't store catches from private networks | on |
### Data ## Security notes
`/mnt/user/appdata/flypaper` on Unraid, mounted as `/data`: - **Keep the dashboard internal.** Only list internal names or LAN addresses as known hosts
and never route a known host through your public proxy.
- **Use a strong admin password.** The login runs over plain HTTP unless you put the
dashboard behind TLS yourself.
- **The limits protect you, not the bots.** Every catch holds a socket in Flypaper and in your
proxy for up to the maximum hold time. Keep `MaxConnections` well below what your proxy can
handle (nginx: `worker_connections`), and keep the per-IP limit low so a single scanner
can't fill all slots.
- **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 proxy reject unknown TLS handshakes instead (nginx: `ssl_reject_handshake on;`).
- **Privacy.** Flypaper stores IP addresses, requested URLs and user agents. Keep retention
short if that matters in your jurisdiction.
- `flypaper.db`: trap events and the settings saved in the dashboard ## Development
- `keys/`: Data Protection keys, so logins survive a restart
The container runs as UID 1654. The workflow creates the folder and sets its owner on Requires the .NET 10 SDK.
every deploy.
### Access ```bash
dotnet build
dotnet test
dotnet run --project src/Flypaper.Web
```
- Dashboard: `http://192.168.1.14:44307` (LAN only, login with `FLYPAPER_ADMIN_PASSWORD`) `dotnet run` starts in the Development environment: the dashboard is at
- Trap: NPM forwards to `flypaper:8080` over `proxynet`. Every Host header other than the <http://localhost:5248> (known host `localhost`, password `dev`), the database is
dashboard host lands in the trap, as do the trap paths on known hosts. `src/Flypaper.Web/flypaper.db`, and GeoIP is off unless `Flypaper__GeoIp__Directory` is set.
- `/health` answers only to private addresses; from public addresses it is a trap like any `docker build -t flypaper .` builds the image.
other path.
### Rollback | Project | Contents |
|---|---|
| `Flypaper.Core` | Protocol-independent core: sessions, governor, strategies, settings |
| `Flypaper.Http` | ASP.NET Core middleware, trap matching, forwarded headers |
| `Flypaper.GeoIp` | DB-IP download and lookups |
| `Flypaper.Storage` | EF Core with SQLite, event writer, retention, dashboard queries |
| `Flypaper.Web` | Host, dashboard and settings (Blazor static SSR) |
| `Flypaper.Tests` | xUnit, NSubstitute, Shouldly |
Pin the image in `compose.yaml` to a previous `:<short-sha>` and push, or deploy that tag ## Attribution
manually on Unraid.
- [IP Geolocation by DB-IP](https://db-ip.com), licensed under
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). The dashboard shows this
attribution in its footer.
- The world map is generated from [Natural Earth](https://www.naturalearthdata.com) data
(public domain).
## License
To be decided. The project does not have a license yet.
+44
View File
@@ -0,0 +1,44 @@
# Personal deployment: Unraid
This folder is Tom's own setup. It is kept as an example; the main [README](../../README.md)
describes a generic installation.
Every push to `main` (except docs and `.md` files) runs `.gitea/workflows/deploy.yml` on the
act_runner on Unraid: it builds the image, pushes it to
`gitea.anticarnist.de/tom/flypaper` (`:latest` and `:<short-sha>`), deploys
`deploy/unraid/compose.yaml` and waits for `/health`. A manual run is possible from the Actions
tab (`workflow_dispatch`).
## Secrets
Gitea → repo → Settings → Actions → Secrets:
| Secret | Purpose |
|---|---|
| `REGISTRY_USER` | Registry username |
| `REGISTRY_TOKEN` | Gitea access token with `package:write` (not the password) |
| `FLYPAPER_ADMIN_PASSWORD` | Dashboard login password |
## Data
`/mnt/user/appdata/flypaper` on Unraid, mounted as `/data`:
- `flypaper.db`: trap events and the settings saved in the dashboard
- `keys/`: Data Protection keys, so logins survive a restart
- `geoip/`: DB-IP databases, downloaded on first start and refreshed monthly
The container runs as UID 1654. The workflow creates the folder and sets its owner on every
deploy.
## Access
- Dashboard: `http://192.168.1.14:44307` (LAN only, login with `FLYPAPER_ADMIN_PASSWORD`)
- Trap: NPM forwards to `flypaper:8080` over `proxynet`. Every Host header other than the
dashboard host lands in the trap, as do the trap paths on known hosts.
- `/health` answers only to private addresses; from public addresses it is a trap like any
other path.
## Rollback
Pin the image in `compose.yaml` to a previous `:<short-sha>` and push, or deploy that tag
manually on Unraid.
+3 -2
View File
@@ -1,5 +1,6 @@
# Production stack on Unraid. Deployed as is by .gitea/workflows/deploy.yml, not # Tom's production stack on Unraid -- a personal deployment, not needed to run
# pasted into the Compose Manager. # Flypaper elsewhere (see the README for a generic setup). Deployed as is by
# .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 is reached # site for unknown hosts, trap paths on the real domains). The dashboard is reached
@@ -0,0 +1,6 @@
namespace Flypaper.Core.Abstractions;
public interface IRandomSource
{
int Next(int minValue, int maxValue);
}
@@ -0,0 +1,8 @@
using Flypaper.Core.Models;
namespace Flypaper.Core.Abstractions;
public interface ITrapStrategySelector
{
ITarpitStrategy? Select(TrapContext context);
}
+3 -1
View File
@@ -17,7 +17,9 @@ public static class FlypaperCoreExtensions
services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(TimeProvider.System);
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>(); services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, DripStrategy>()); services.TryAddSingleton<IRandomSource, SystemRandomSource>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
services.TryAddSingleton<ITrapStrategySelector, ProtocolStrategySelector>();
services.TryAddSingleton<TrapRunner>(); services.TryAddSingleton<TrapRunner>();
services.TryAddSingleton<IIpEnricher, NullIpEnricher>(); services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
+2
View File
@@ -9,4 +9,6 @@ public sealed class FlypaperOptions
public int MaxConnectionsPerIp { get; set; } = 10; public int MaxConnectionsPerIp { get; set; } = 10;
public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1); public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1);
public bool IgnorePrivateNetworks { get; set; } = true;
} }
@@ -0,0 +1,10 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
namespace Flypaper.Core.Runtime;
public sealed class ProtocolStrategySelector(IEnumerable<ITarpitStrategy> strategies) : ITrapStrategySelector
{
public ITarpitStrategy? Select(TrapContext context) =>
strategies.FirstOrDefault(strategy => strategy.Supports(context.Session.Protocol));
}
@@ -0,0 +1,8 @@
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Runtime;
internal sealed class SystemRandomSource : IRandomSource
{
public int Next(int minValue, int maxValue) => Random.Shared.Next(minValue, maxValue);
}
+18 -9
View File
@@ -1,6 +1,7 @@
using System.Net; using System.Net;
using Flypaper.Core.Abstractions; using Flypaper.Core.Abstractions;
using Flypaper.Core.Models; using Flypaper.Core.Models;
using Flypaper.Core.Networking;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -8,7 +9,7 @@ namespace Flypaper.Core.Runtime;
public sealed partial class TrapRunner( public sealed partial class TrapRunner(
IConnectionGovernor governor, IConnectionGovernor governor,
IEnumerable<ITarpitStrategy> strategies, ITrapStrategySelector strategies,
ITrapEventSink sink, ITrapEventSink sink,
IOptionsMonitor<FlypaperOptions> options, IOptionsMonitor<FlypaperOptions> options,
TimeProvider timeProvider, TimeProvider timeProvider,
@@ -20,7 +21,7 @@ public sealed partial class TrapRunner(
CancellationToken ct) CancellationToken ct)
{ {
var session = context.Session; var session = context.Session;
var strategy = strategies.FirstOrDefault(s => s.Supports(session.Protocol)); var strategy = strategies.Select(context);
if (strategy is null || !governor.TryAcquire(session, out var lease)) if (strategy is null || !governor.TryAcquire(session, out var lease))
{ {
@@ -69,9 +70,12 @@ public sealed partial class TrapRunner(
context.Target, context.Target,
context.ClientInfo); context.ClientInfo);
var store = !(options.CurrentValue.IgnorePrivateNetworks && PrivateNetworks.Contains(trapEvent.RemoteIp));
var storageNote = store ? "" : " (not stored)";
if (outcome == TrapOutcome.Rejected) if (outcome == TrapOutcome.Rejected)
{ {
LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo); LogRejected(trapEvent.RemoteIp, trapEvent.Target, trapEvent.ClientInfo, storageNote);
} }
else else
{ {
@@ -81,22 +85,27 @@ public sealed partial class TrapRunner(
trapEvent.Duration.TotalSeconds, trapEvent.Duration.TotalSeconds,
trapEvent.BytesSent, trapEvent.BytesSent,
trapEvent.Outcome, trapEvent.Outcome,
trapEvent.ClientInfo); trapEvent.ClientInfo,
storageNote);
} }
sink.Publish(trapEvent); if (store)
{
sink.Publish(trapEvent);
}
} }
[LoggerMessage(Level = LogLevel.Information, [LoggerMessage(Level = LogLevel.Information,
Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"")] Message = "Trapped {RemoteIp} {Target} {DurationSeconds:F1}s {BytesSent}B {Outcome} \"{UserAgent}\"{StorageNote}")]
private partial void LogTrapped( private partial void LogTrapped(
IPAddress remoteIp, IPAddress remoteIp,
string? target, string? target,
double durationSeconds, double durationSeconds,
long bytesSent, long bytesSent,
TrapOutcome outcome, TrapOutcome outcome,
string? userAgent); string? userAgent,
string storageNote);
[LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"")] [LoggerMessage(Level = LogLevel.Information, Message = "Rejected {RemoteIp} {Target} \"{UserAgent}\"{StorageNote}")]
private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent); private partial void LogRejected(IPAddress remoteIp, string? target, string? userAgent, string storageNote);
} }
@@ -4,19 +4,21 @@ namespace Flypaper.Core.Settings;
public sealed record RuntimeSettings( public sealed record RuntimeSettings(
IReadOnlyList<string> TrapPaths, IReadOnlyList<string> TrapPaths,
TimeSpan DripInterval,
int MaxConnections, int MaxConnections,
int MaxConnectionsPerIp, int MaxConnectionsPerIp,
TimeSpan MaxHoldDuration, TimeSpan MaxHoldDuration,
IReadOnlyList<string> ExtraKnownHosts) IReadOnlyList<string> ExtraKnownHosts,
int RetentionDays,
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.TrapPaths] = SettingsList.Join(TrapPaths),
[SettingKeys.DripInterval] = DripInterval.ToString("c", CultureInfo.InvariantCulture),
[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.ExtraKnownHosts] = SettingsList.Join(ExtraKnownHosts),
[SettingKeys.RetentionDays] = RetentionDays.ToString(CultureInfo.InvariantCulture),
[SettingKeys.IgnorePrivateNetworks] = IgnorePrivateNetworks ? "true" : "false"
}; };
} }
@@ -2,8 +2,9 @@ namespace Flypaper.Core.Settings;
public sealed record RuntimeSettingsInput( public sealed record RuntimeSettingsInput(
string? TrapPaths, string? TrapPaths,
string? DripInterval,
string? MaxConnections, string? MaxConnections,
string? MaxConnectionsPerIp, string? MaxConnectionsPerIp,
string? MaxHoldDuration, string? MaxHoldDuration,
string? ExtraKnownHosts); string? ExtraKnownHosts,
string? RetentionDays,
bool IgnorePrivateNetworks);
@@ -9,9 +9,8 @@ public static partial class RuntimeSettingsParser
private const int MaxPathLength = 256; private const int MaxPathLength = 256;
private const int MaxHostLength = 253; private const int MaxHostLength = 253;
private const int MaxLimit = 100_000; private const int MaxLimit = 100_000;
private const int MaxRetentionDays = 3650;
private static readonly TimeSpan MinInterval = TimeSpan.FromMilliseconds(100);
private static readonly TimeSpan MaxInterval = TimeSpan.FromHours(1);
private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1); private static readonly TimeSpan MinHold = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7); private static readonly TimeSpan MaxHold = TimeSpan.FromDays(7);
@@ -24,10 +23,10 @@ public static partial class RuntimeSettingsParser
var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors); var paths = ParseList(input.TrapPaths, nameof(input.TrapPaths), ValidatePath, errors);
var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors); var hosts = ParseList(input.ExtraKnownHosts, nameof(input.ExtraKnownHosts), ValidateHost, errors);
var interval = ParseTimeSpan(input.DripInterval, nameof(input.DripInterval), MinInterval, MaxInterval, errors);
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors); var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), errors); var maxConnections = ParseInt(input.MaxConnections, nameof(input.MaxConnections), 1, MaxLimit, errors);
var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), errors); var perIp = ParseInt(input.MaxConnectionsPerIp, nameof(input.MaxConnectionsPerIp), 1, MaxLimit, errors);
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
if (maxConnections is { } total && perIp is { } single && single > total if (maxConnections is { } total && perIp is { } single && single > total
&& !errors.ContainsKey(nameof(input.MaxConnectionsPerIp))) && !errors.ContainsKey(nameof(input.MaxConnectionsPerIp)))
@@ -40,7 +39,14 @@ public static partial class RuntimeSettingsParser
return new RuntimeSettingsParseResult(null, errors); return new RuntimeSettingsParseResult(null, errors);
} }
var settings = new RuntimeSettings(paths!, interval!.Value, maxConnections!.Value, perIp!.Value, hold!.Value, hosts!); var settings = new RuntimeSettings(
paths!,
maxConnections!.Value,
perIp!.Value,
hold!.Value,
hosts!,
retention!.Value,
input.IgnorePrivateNetworks);
return new RuntimeSettingsParseResult(settings, errors); return new RuntimeSettingsParseResult(settings, errors);
} }
@@ -137,7 +143,7 @@ public static partial class RuntimeSettingsParser
return value; return value;
} }
private static int? ParseInt(string? raw, string field, Dictionary<string, string> errors) private static int? ParseInt(string? raw, string field, int min, int max, Dictionary<string, string> errors)
{ {
var text = raw?.Trim(); var text = raw?.Trim();
if (string.IsNullOrEmpty(text)) if (string.IsNullOrEmpty(text))
@@ -146,9 +152,9 @@ public static partial class RuntimeSettingsParser
return null; return null;
} }
if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value is < 1 or > MaxLimit) if (!int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var value) || value < min || value > max)
{ {
errors[field] = $"Ganze Zahl zwischen 1 und {MaxLimit}."; errors[field] = $"Ganze Zahl zwischen {min} und {max}.";
return null; return null;
} }
+5 -3
View File
@@ -5,17 +5,19 @@ 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 DripInterval = "Flypaper:Drip:Interval";
public const string TrapPaths = "Flypaper:Http:TrapPathsOverride"; public const string TrapPaths = "Flypaper:Http:TrapPathsOverride";
public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts"; public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts";
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
public const string RetentionDays = "Flypaper:Retention:Days";
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase) public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ {
MaxConnections, MaxConnections,
MaxConnectionsPerIp, MaxConnectionsPerIp,
MaxHoldDuration, MaxHoldDuration,
DripInterval,
TrapPaths, TrapPaths,
ExtraKnownHosts ExtraKnownHosts,
IgnorePrivateNetworks,
RetentionDays
}; };
} }
+7 -1
View File
@@ -4,5 +4,11 @@ public sealed class DripOptions
{ {
public const string SectionName = "Flypaper:Drip"; public const string SectionName = "Flypaper:Drip";
public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(10); public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
public int MinChunkSize { get; set; } = 1;
public int MaxChunkSize { get; set; } = 64;
} }
@@ -0,0 +1,52 @@
using System.Text;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public static class DripSchedule
{
public static IEnumerable<DripStep> Create(IEnumerable<string> content, IRandomSource random, DripOptions options)
{
var minChunk = Math.Max(1, options.MinChunkSize);
var maxChunk = Math.Max(minChunk, options.MaxChunkSize);
var minDelay = (int)Math.Max(0, options.MinDelay.TotalMilliseconds);
var maxDelay = Math.Max(minDelay, (int)options.MaxDelay.TotalMilliseconds);
using var fragments = content.GetEnumerator();
var pending = Array.Empty<byte>();
var offset = 0;
while (true)
{
var chunk = new byte[random.Next(minChunk, maxChunk + 1)];
var filled = 0;
while (filled < chunk.Length)
{
if (offset == pending.Length)
{
if (!fragments.MoveNext())
{
break;
}
pending = Encoding.UTF8.GetBytes(fragments.Current);
offset = 0;
continue;
}
var count = Math.Min(chunk.Length - filled, pending.Length - offset);
pending.AsSpan(offset, count).CopyTo(chunk.AsSpan(filled));
offset += count;
filled += count;
}
if (filled == 0)
{
yield break;
}
yield return new DripStep(chunk.AsMemory(0, filled), TimeSpan.FromMilliseconds(random.Next(minDelay, maxDelay + 1)));
}
}
}
+3
View File
@@ -0,0 +1,3 @@
namespace Flypaper.Core.Strategies;
public readonly record struct DripStep(ReadOnlyMemory<byte> Chunk, TimeSpan Delay);
@@ -1,26 +0,0 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class DripStrategy(IOptionsMonitor<DripOptions> options, TimeProvider timeProvider) : ITarpitStrategy
{
private static readonly byte[] Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"u8.ToArray();
public string Name => "drip";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
{
var buffer = new byte[1];
while (true)
{
ct.ThrowIfCancellationRequested();
buffer[0] = Alphabet[Random.Shared.Next(Alphabet.Length)];
await channel.WriteAsync(buffer, ct);
await Task.Delay(options.CurrentValue.Interval, timeProvider, ct);
}
}
}
+170
View File
@@ -0,0 +1,170 @@
using System.Text;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public static class HtmlContent
{
private const string Css = """
body { margin: 0 auto; max-width: 52rem; padding: 1.5rem; font: 16px/1.6 system-ui, sans-serif; color: #222; }
header { border-bottom: 1px solid #ddd; margin-bottom: 1.5rem; }
nav a { margin-right: 1rem; color: #0b5cad; text-decoration: none; }
h1, h2, h3 { line-height: 1.25; }
article { margin-bottom: 2rem; }
a { color: #0b5cad; }
""";
private static readonly string[] Vocabulary =
[
"lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "sed", "do", "eiusmod",
"tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", "enim", "ad", "minim",
"veniam", "quis", "nostrud", "exercitation", "ullamco", "laboris", "nisi", "aliquip", "ex", "ea",
"commodo", "consequat", "duis", "aute", "irure", "in", "reprehenderit", "voluptate", "velit", "esse",
"cillum", "fugiat", "nulla", "pariatur", "excepteur", "sint", "occaecat", "cupidatat", "non", "proident",
"sunt", "culpa", "qui", "officia", "deserunt", "mollit", "anim", "id", "est", "laborum", "praesent",
"luctus", "vitae", "semper", "facilisis", "integer", "nec", "odio", "mauris", "massa", "vestibulum",
"lacinia", "arcu", "eget", "nunc", "tristique", "fermentum", "pellentesque", "habitant", "morbi",
"senectus", "netus", "malesuada", "fames", "turpis", "egestas", "porttitor", "rhoncus", "dapibus",
"ornare", "sapien", "volutpat", "blandit", "aliquam", "etiam", "erat", "velit", "scelerisque",
"viverra", "orci", "sagittis", "eu", "tellus", "cras", "pulvinar", "mattis", "pharetra", "convallis",
"posuere", "morbi", "leo", "urna", "molestie", "at", "elementum", "sodales", "neque", "gravida",
"dictum", "fusce", "ultrices", "placerat", "euismod", "quam", "suspendisse", "potenti", "nullam",
"accumsan", "tincidunt", "varius", "sollicitudin", "imperdiet", "hendrerit", "bibendum", "cursus"
];
private static readonly string[] Sections =
["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"];
private static readonly string[] Titles =
["Welcome", "Documentation", "Knowledge Base", "Support Center", "Release Notes", "Resources", "Archive", "Developer Portal"];
public static IEnumerable<string> Generate(IRandomSource random)
{
var title = $"{Pick(random, Titles)} · {Title(random, 2, 3)}";
yield return $"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title}</title>
<style>
{Css}
</style>
</head>
<body>
<header>
<h1>{title}</h1>
""";
yield return Navigation(random);
yield return "</header>\n<main>\n";
while (true)
{
yield return random.Next(0, 10) switch
{
< 5 => Article(random),
< 7 => LinkList(random),
< 9 => Paragraph(random),
_ => $"<h3>{Title(random, 2, 6)}</h3>\n{Paragraph(random)}"
};
}
}
private static string Navigation(IRandomSource random)
{
var builder = new StringBuilder("<nav>\n");
var count = random.Next(3, 7);
for (var i = 0; i < count; i++)
{
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{Capitalize(Pick(random, Vocabulary))}</a>\n");
}
return builder.Append("</nav>\n").ToString();
}
private static string Article(IRandomSource random)
{
var builder = new StringBuilder($"<article>\n<h2>{Title(random, 3, 9)}</h2>\n");
var paragraphs = random.Next(1, 6);
for (var i = 0; i < paragraphs; i++)
{
builder.Append(Paragraph(random));
}
return builder.Append("</article>\n").ToString();
}
private static string LinkList(IRandomSource random)
{
var ordered = random.Next(0, 2) == 0;
var builder = new StringBuilder(ordered ? "<ol>\n" : "<ul>\n");
var items = random.Next(3, 10);
for (var i = 0; i < items; i++)
{
builder.Append($"<li>{Link(random, random.Next(2, 6))}</li>\n");
}
return builder.Append(ordered ? "</ol>\n" : "</ul>\n").ToString();
}
private static string Paragraph(IRandomSource random)
{
var builder = new StringBuilder("<p>");
var sentences = random.Next(2, 9);
for (var i = 0; i < sentences; i++)
{
if (i > 0)
{
builder.Append(' ');
}
builder.Append(Sentence(random));
}
return builder.Append("</p>\n").ToString();
}
private static string Sentence(IRandomSource random)
{
var builder = new StringBuilder();
var words = random.Next(4, 21);
var linkAt = random.Next(0, 8) == 0 ? random.Next(1, words) : -1;
for (var i = 0; i < words; i++)
{
if (i > 0)
{
builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " ");
}
if (i == linkAt)
{
builder.Append(Link(random, random.Next(1, 4)));
continue;
}
var word = Pick(random, Vocabulary);
builder.Append(i == 0 ? Capitalize(word) : word);
}
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
}
private static string Link(IRandomSource random, int words)
{
var text = Phrase(random, words);
var slug = text.Replace(' ', '-');
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>";
}
private static string Title(IRandomSource random, int min, int max) => Capitalize(Phrase(random, random.Next(min, max + 1)));
private static string Phrase(IRandomSource random, int count) =>
string.Join(' ', Enumerable.Range(0, count).Select(_ => Pick(random, Vocabulary)));
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
private static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
}
@@ -0,0 +1,25 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class HtmlDripStrategy(
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : ITarpitStrategy
{
public string Name => "html-drip";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
{
foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue))
{
ct.ThrowIfCancellationRequested();
await channel.WriteAsync(step.Chunk, ct);
await Task.Delay(step.Delay, timeProvider, ct);
}
}
}
@@ -1,6 +1,7 @@
using Flypaper.Core.Abstractions; using Flypaper.Core.Abstractions;
using Flypaper.Storage.Dashboard; using Flypaper.Storage.Dashboard;
using Flypaper.Storage.Events; using Flypaper.Storage.Events;
using Flypaper.Storage.Maintenance;
using Flypaper.Storage.Settings; using Flypaper.Storage.Settings;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@@ -19,6 +20,7 @@ public static class FlypaperStorageExtensions
builder.Configuration.Add(source); builder.Configuration.Add(source);
builder.Services.AddSingleton(source); builder.Services.AddSingleton(source);
builder.Services.AddSingleton<RuntimeSettingsStore>(); builder.Services.AddSingleton<RuntimeSettingsStore>();
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
builder.Services.AddFlypaperStorage(connectionString); builder.Services.AddFlypaperStorage(connectionString);
return builder; return builder;
@@ -32,6 +34,8 @@ public static class FlypaperStorageExtensions
services.AddHostedService<TrapEventWriter>(); services.AddHostedService<TrapEventWriter>();
services.AddHostedService<OriginBackfill>(); services.AddHostedService<OriginBackfill>();
services.AddSingleton<DashboardQueries>(); services.AddSingleton<DashboardQueries>();
services.AddSingleton<TrapDataMaintenance>();
services.AddHostedService<RetentionCleanup>();
return services; return services;
} }
@@ -0,0 +1,62 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Flypaper.Storage.Maintenance;
internal sealed partial class RetentionCleanup(
TrapDataMaintenance maintenance,
IOptionsMonitor<RetentionOptions> options,
TimeProvider timeProvider,
ILogger<RetentionCleanup> logger) : BackgroundService
{
private const int VacuumThreshold = 5_000;
private static readonly TimeSpan Interval = TimeSpan.FromDays(1);
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (true)
{
try
{
await CleanupAsync(stoppingToken);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogCleanupFailed(ex);
}
await Task.Delay(Interval, timeProvider, stoppingToken);
}
}
internal async Task<int> CleanupAsync(CancellationToken ct)
{
var days = options.CurrentValue.Days;
if (days <= 0)
{
return 0;
}
var cutoff = timeProvider.GetUtcNow().UtcDateTime.AddDays(-days);
var deleted = await maintenance.DeleteOlderThanAsync(cutoff, ct);
if (deleted == 0)
{
return 0;
}
LogDeleted(deleted, days);
if (deleted >= VacuumThreshold)
{
await maintenance.VacuumAsync(ct);
}
return deleted;
}
[LoggerMessage(Level = LogLevel.Information, Message = "Deleted {Count} trap events older than {Days} days")]
private partial void LogDeleted(int count, int days);
[LoggerMessage(Level = LogLevel.Warning, Message = "Retention cleanup failed")]
private partial void LogCleanupFailed(Exception exception);
}
@@ -0,0 +1,8 @@
namespace Flypaper.Storage.Maintenance;
public sealed class RetentionOptions
{
public const string SectionName = "Flypaper:Retention";
public int Days { get; set; } = 90;
}
@@ -0,0 +1,64 @@
using System.Net;
using Flypaper.Core.Networking;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Maintenance;
public sealed class TrapDataMaintenance(IDbContextFactory<FlypaperDbContext> dbContextFactory)
{
private const int DeleteChunkSize = 500;
public async Task<TrapDataStats> GetStatsAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var count = await db.TrapEvents.CountAsync(ct);
var oldest = count == 0 ? (DateTime?)null : await db.TrapEvents.MinAsync(e => e.StartedAt, ct);
return new TrapDataStats(count, oldest, DatabaseSize(db));
}
public async Task<int> DeleteOlderThanAsync(DateTime cutoffUtc, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapEvents.Where(e => e.StartedAt < cutoffUtc).ExecuteDeleteAsync(ct);
}
public async Task<int> DeletePrivateAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var privateIps = (await db.TrapEvents.Select(e => e.RemoteIp).Distinct().ToListAsync(ct))
.Where(ip => IPAddress.TryParse(ip, out var address) && PrivateNetworks.Contains(address))
.ToList();
var deleted = 0;
foreach (var chunk in privateIps.Chunk(DeleteChunkSize))
{
deleted += await db.TrapEvents.Where(e => chunk.Contains(e.RemoteIp)).ExecuteDeleteAsync(ct);
}
return deleted;
}
public async Task<int> DeleteAllAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapEvents.ExecuteDeleteAsync(ct);
}
public async Task VacuumAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
await db.Database.ExecuteSqlRawAsync("VACUUM", ct);
}
private static long? DatabaseSize(FlypaperDbContext db)
{
var path = db.Database.GetDbConnection().DataSource;
if (string.IsNullOrEmpty(path) || !File.Exists(path))
{
return null;
}
var wal = new FileInfo(path + "-wal");
return new FileInfo(path).Length + (wal.Exists ? wal.Length : 0);
}
}
@@ -0,0 +1,3 @@
namespace Flypaper.Storage.Maintenance;
public sealed record TrapDataStats(int Count, DateTime? Oldest, long? DatabaseBytes);
@@ -0,0 +1,121 @@
// <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("20261114150222_RemoveDripIntervalSetting")]
partial class RemoveDripIntervalSetting
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
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 RemoveDripIntervalSetting : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DELETE FROM \"Settings\" WHERE \"Key\" = 'Flypaper:Drip:Interval';");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
@@ -0,0 +1,11 @@
namespace Flypaper.Web.Components.Pages.Settings;
public sealed class DeletePrivateModel
{
public bool Confirmed { get; set; }
}
public sealed class DeleteAllModel
{
public string? Confirmation { get; set; }
}
@@ -4,8 +4,6 @@ public sealed class SettingsModel
{ {
public string? TrapPaths { get; set; } public string? TrapPaths { get; set; }
public string? DripInterval { get; set; }
public string? MaxConnections { get; set; } public string? MaxConnections { get; set; }
public string? MaxConnectionsPerIp { get; set; } public string? MaxConnectionsPerIp { get; set; }
@@ -13,4 +11,8 @@ public sealed class SettingsModel
public string? MaxHoldDuration { get; set; } public string? MaxHoldDuration { get; set; }
public string? ExtraKnownHosts { get; set; } public string? ExtraKnownHosts { get; set; }
public string? RetentionDays { get; set; }
public bool IgnorePrivateNetworks { get; set; }
} }
@@ -1,16 +1,16 @@
@page "/settings" @page "/settings"
@using Flypaper.Core @using Flypaper.Core
@using Flypaper.Core.Settings @using Flypaper.Core.Settings
@using Flypaper.Core.Strategies
@using Flypaper.Http @using Flypaper.Http
@using Flypaper.Storage.Maintenance
@using Flypaper.Storage.Settings @using Flypaper.Storage.Settings
@using Flypaper.Web.Auth @using Flypaper.Web.Auth
@using System.Globalization @using System.Globalization
@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<DripOptions> Drip
@inject IOptionsMonitor<HttpTrapOptions> Http @inject IOptionsMonitor<HttpTrapOptions> Http
@inject IOptionsMonitor<RetentionOptions> Retention
@inject IConfiguration Configuration @inject IConfiguration Configuration
@inject RuntimeSettingsStore Store @inject RuntimeSettingsStore Store
@inject AdminAuthenticator Admin @inject AdminAuthenticator Admin
@@ -35,7 +35,7 @@ else if (Saved == "reset")
<div class="banner ok">Auf Standard zurückgesetzt.</div> <div class="banner ok">Auf Standard zurückgesetzt.</div>
} }
<EditForm Model="Model" FormName="settings" OnSubmit="Save" 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> <label for="trap-paths">Fallenpfade <span class="muted">(einer pro Zeile, mit / am Anfang, * am Ende als Präfix)</span></label>
@@ -47,11 +47,6 @@ else if (Saved == "reset")
<FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" /> <FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" />
<div class="grid"> <div class="grid">
<div>
<label for="drip">Tröpfel-Intervall <span class="muted">(hh:mm:ss)</span></label>
<InputText id="drip" @bind-Value="Model!.DripInterval" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.DripInterval)" />
</div>
<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>
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" /> <InputText id="hold" @bind-Value="Model!.MaxHoldDuration" class="mono" />
@@ -67,14 +62,24 @@ else if (Saved == "reset")
<InputText id="per-ip" @bind-Value="Model!.MaxConnectionsPerIp" class="mono" /> <InputText id="per-ip" @bind-Value="Model!.MaxConnectionsPerIp" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnectionsPerIp)" /> <FieldError Errors="_errors" Field="@nameof(SettingsModel.MaxConnectionsPerIp)" />
</div> </div>
<div>
<label for="retention">Fänge aufbewahren <span class="muted">(Tage, 0 = unbegrenzt)</span></label>
<InputText id="retention" @bind-Value="Model!.RetentionDays" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.RetentionDays)" />
</div>
</div> </div>
<label class="check">
<InputCheckbox @bind-Value="Model!.IgnorePrivateNetworks" />
Fänge aus privaten Netzen nicht speichern <span class="muted">(die Falle greift trotzdem)</span>
</label>
<div class="actions"> <div class="actions">
<button type="submit">Speichern</button> <button type="submit">Speichern</button>
</div> </div>
</EditForm> </EditForm>
<EditForm Model="_resetModel" FormName="reset" OnSubmit="Reset" class="card form"> <EditForm Model="_resetModel" FormName="reset" OnSubmit="Reset" action="/settings" class="card form">
<h2>Standard</h2> <h2>Standard</h2>
<p class="muted">Löscht alle gespeicherten Änderungen. Danach gelten wieder die Werte aus Umgebungsvariablen und appsettings.</p> <p class="muted">Löscht alle gespeicherten Änderungen. Danach gelten wieder die Werte aus Umgebungsvariablen und appsettings.</p>
<div class="actions"> <div class="actions">
@@ -82,6 +87,8 @@ else if (Saved == "reset")
</div> </div>
</EditForm> </EditForm>
<TrapDataSection />
<section class="card"> <section class="card">
<h2>Nur per Umgebungsvariable</h2> <h2>Nur per Umgebungsvariable</h2>
<p class="muted">Gelten ab Containerstart und lassen sich hier nicht ändern.</p> <p class="muted">Gelten ab Containerstart und lassen sich hier nicht ändern.</p>
@@ -117,11 +124,12 @@ else if (Saved == "reset")
{ {
var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput( var result = RuntimeSettingsParser.Parse(new RuntimeSettingsInput(
Model!.TrapPaths, Model!.TrapPaths,
Model.DripInterval,
Model.MaxConnections, Model.MaxConnections,
Model.MaxConnectionsPerIp, Model.MaxConnectionsPerIp,
Model.MaxHoldDuration, Model.MaxHoldDuration,
Model.ExtraKnownHosts)); Model.ExtraKnownHosts,
Model.RetentionDays,
Model.IgnorePrivateNetworks));
if (result.Settings is null) if (result.Settings is null)
{ {
@@ -147,10 +155,11 @@ else if (Saved == "reset")
{ {
TrapPaths = SettingsList.Join(http.TrapPaths), TrapPaths = SettingsList.Join(http.TrapPaths),
ExtraKnownHosts = SettingsList.Join(SettingsList.Split(http.ExtraKnownHosts)), ExtraKnownHosts = SettingsList.Join(SettingsList.Split(http.ExtraKnownHosts)),
DripInterval = Drip.CurrentValue.Interval.ToString("c", CultureInfo.InvariantCulture),
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),
RetentionDays = Retention.CurrentValue.Days.ToString(CultureInfo.InvariantCulture),
IgnorePrivateNetworks = core.IgnorePrivateNetworks
}; };
} }
@@ -0,0 +1,96 @@
@using Flypaper.Storage.Maintenance
@inject TrapDataMaintenance Maintenance
@inject NavigationManager Navigation
<section class="card form">
<h2>Daten</h2>
@if (Deleted is { } deleted)
{
<div class="banner ok">@deleted.ToString("N0") @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</div>
}
<table>
<tbody>
<tr><th>Fänge</th><td>@_stats?.Count.ToString("N0")</td></tr>
<tr><th>Ältester Fang</th><td>@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "–")</td></tr>
<tr><th>Größe der Datenbank</th><td>@Formatting.Bytes(_stats?.DatabaseBytes)</td></tr>
</tbody>
</table>
<p class="muted">Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.</p>
<EditForm Model="DeletePrivate" FormName="delete-private" OnSubmit="DeletePrivateAsync" action="/settings" class="danger-zone">
<h3>Fänge aus privaten Netzen löschen</h3>
<p class="muted">Loopback, 10/8, 172.16/12, 192.168/16, Link-Local und ULA, zum Beispiel lokale Testaufrufe.</p>
<label class="check">
<InputCheckbox @bind-Value="DeletePrivate!.Confirmed" />
Ich bin sicher
</label>
<FieldError Errors="_errors" Field="@nameof(DeletePrivateModel.Confirmed)" />
<div class="actions">
<button type="submit" class="secondary">Private Fänge löschen</button>
</div>
</EditForm>
<EditForm Model="DeleteAll" FormName="delete-all" OnSubmit="DeleteAllAsync" action="/settings" class="danger-zone">
<h3>Alle Fänge löschen</h3>
<label for="delete-all-confirmation">Zum Bestätigen <strong>LÖSCHEN</strong> eingeben</label>
<InputText id="delete-all-confirmation" @bind-Value="DeleteAll!.Confirmation" autocomplete="off" />
<FieldError Errors="_errors" Field="@nameof(DeleteAllModel.Confirmation)" />
<div class="actions">
<button type="submit" class="danger">Alle Fänge löschen</button>
</div>
</EditForm>
</section>
@code {
private const string ConfirmationWord = "LÖSCHEN";
private TrapDataStats? _stats;
private Dictionary<string, string> _errors = [];
[SupplyParameterFromForm(FormName = "delete-private")] private DeletePrivateModel? DeletePrivate { get; set; }
[SupplyParameterFromForm(FormName = "delete-all")] private DeleteAllModel? DeleteAll { get; set; }
[SupplyParameterFromQuery(Name = "deleted")] private int? Deleted { get; set; }
protected override async Task OnInitializedAsync()
{
DeletePrivate ??= new DeletePrivateModel();
DeleteAll ??= new DeleteAllModel();
_stats = await Maintenance.GetStatsAsync();
}
private async Task DeletePrivateAsync()
{
if (!DeletePrivate!.Confirmed)
{
_errors[nameof(DeletePrivateModel.Confirmed)] = "Bitte bestätigen.";
return;
}
await FinishAsync(await Maintenance.DeletePrivateAsync());
}
private async Task DeleteAllAsync()
{
if (DeleteAll!.Confirmation?.Trim() != ConfirmationWord)
{
_errors[nameof(DeleteAllModel.Confirmation)] = $"Bitte genau {ConfirmationWord} eingeben.";
return;
}
await FinishAsync(await Maintenance.DeleteAllAsync());
}
private async Task FinishAsync(int deleted)
{
if (deleted > 0)
{
await Maintenance.VacuumAsync();
}
Navigation.NavigateTo($"/settings?deleted={deleted}");
}
}
@@ -15,5 +15,14 @@ public static class Formatting
? string.Concat(countryCode.ToUpperInvariant().Select(c => char.ConvertFromUtf32(0x1F1E6 + c - 'A'))) ? string.Concat(countryCode.ToUpperInvariant().Select(c => char.ConvertFromUtf32(0x1F1E6 + c - 'A')))
: ""; : "";
public static string Bytes(long? bytes) => bytes switch
{
null => "–",
>= 1024 * 1024 * 1024 => $"{bytes / (1024d * 1024 * 1024):0.0} GB",
>= 1024 * 1024 => $"{bytes / (1024d * 1024):0.0} MB",
>= 1024 => $"{bytes / 1024d:0} KB",
_ => $"{bytes} B"
};
public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd(); public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd();
} }
@@ -6,9 +6,6 @@
} }
}, },
"Flypaper": { "Flypaper": {
"Drip": {
"Interval": "00:00:01"
},
"Http": { "Http": {
"KnownHosts": [ "KnownHosts": [
"localhost" "localhost"
-3
View File
@@ -22,9 +22,6 @@
"MaxConnections": 1000, "MaxConnections": 1000,
"MaxConnectionsPerIp": 10, "MaxConnectionsPerIp": 10,
"MaxHoldDuration": "01:00:00", "MaxHoldDuration": "01:00:00",
"Drip": {
"Interval": "00:00:10"
},
"Http": { "Http": {
"KnownHosts": [], "KnownHosts": [],
"TrustedProxies": [], "TrustedProxies": [],
+34
View File
@@ -451,3 +451,37 @@ tr.open .detail {
.footer a { .footer a {
color: inherit; color: inherit;
} }
.check {
display: flex;
align-items: center;
gap: 8px;
font-weight: 400;
}
.check input {
width: auto;
accent-color: var(--accent);
}
.danger-zone {
display: flex;
flex-direction: column;
gap: 6px;
margin-top: 16px;
padding-top: 16px;
border-top: 1px solid var(--border);
}
.danger-zone h3 {
margin: 0;
font-size: 14px;
}
.danger-zone p {
margin: 0;
}
button.danger {
background: var(--bad);
}
@@ -0,0 +1,55 @@
using System.Text;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class DripScheduleTests
{
private static readonly DripOptions Options = new()
{
MinDelay = TimeSpan.FromMilliseconds(50),
MaxDelay = TimeSpan.FromSeconds(1),
MinChunkSize = 1,
MaxChunkSize = 64
};
[Fact]
public void Uses_random_chunk_sizes_and_delays_within_bounds()
{
var random = new SeededRandomSource(11);
var steps = DripSchedule.Create(HtmlContent.Generate(random), random, Options).Take(2000).ToList();
steps.ShouldAllBe(step => step.Chunk.Length >= 1 && step.Chunk.Length <= 64);
steps.ShouldAllBe(step => step.Delay >= TimeSpan.FromMilliseconds(50) && step.Delay <= TimeSpan.FromSeconds(1));
steps.Select(step => step.Chunk.Length).Distinct().Count().ShouldBeGreaterThan(40);
steps.Select(step => step.Delay).Distinct().Count().ShouldBeGreaterThan(500);
}
[Fact]
public void Delivers_the_content_unchanged_and_in_order()
{
var content = new[] { "<!doctype html>", "<p>hällo ", "world</p>", "\n" };
var steps = DripSchedule.Create(content, new SeededRandomSource(12), Options).ToList();
Encoding.UTF8.GetString(steps.SelectMany(step => step.Chunk.ToArray()).ToArray()).ShouldBe(string.Concat(content));
}
[Fact]
public void Ends_when_content_ends()
{
DripSchedule.Create([], new SeededRandomSource(13), Options).ShouldBeEmpty();
}
[Fact]
public void Tolerates_inverted_bounds()
{
var options = new DripOptions { MinDelay = TimeSpan.FromSeconds(2), MaxDelay = TimeSpan.FromSeconds(1), MinChunkSize = 10, MaxChunkSize = 5 };
var step = DripSchedule.Create(["0123456789abcdef"], new SeededRandomSource(14), options).First();
step.Chunk.Length.ShouldBe(10);
step.Delay.ShouldBe(TimeSpan.FromSeconds(2));
}
}
@@ -1,43 +0,0 @@
using Flypaper.Core.Models;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class DripStrategyTests
{
[Fact]
public async Task Drips_single_bytes_until_cancelled()
{
var strategy = CreateStrategy(TimeSpan.FromMilliseconds(20));
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBeInRange(3, 20);
channel.Writes.ShouldAllBe(write => write.Length == 1);
}
[Fact]
public async Task Writes_first_byte_immediately()
{
var strategy = CreateStrategy(TimeSpan.FromMinutes(1));
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBe(1);
}
[Theory]
[InlineData(TrapProtocol.Http, true)]
[InlineData(TrapProtocol.Ssh, false)]
public void Supports_only_http(TrapProtocol protocol, bool expected) =>
CreateStrategy(TimeSpan.FromSeconds(1)).Supports(protocol).ShouldBe(expected);
private static DripStrategy CreateStrategy(TimeSpan interval) =>
new(TestOptions.Monitor(new DripOptions { Interval = interval }), TimeProvider.System);
}
@@ -0,0 +1,58 @@
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class HtmlContentTests
{
[Fact]
public void Starts_with_a_complete_html_head()
{
var head = HtmlContent.Generate(new SeededRandomSource(1)).First();
head.ShouldStartWith("<!doctype html>");
head.ShouldContain("<head>");
head.ShouldContain("<title>");
head.ShouldContain("<style>");
head.ShouldContain("</head>");
head.ShouldContain("<body>");
}
[Fact]
public void Keeps_generating_varied_body_content()
{
var body = string.Concat(HtmlContent.Generate(new SeededRandomSource(2)).Skip(1).Take(400));
body.ShouldContain("<main>");
body.ShouldContain("<h2>");
body.ShouldContain("<p>");
body.ShouldContain("<li><a href=\"/");
body.ShouldNotContain("</html>");
body.Length.ShouldBeGreaterThan(50_000);
}
[Fact]
public void Varies_sentence_and_paragraph_lengths()
{
var paragraphs = string.Concat(HtmlContent.Generate(new SeededRandomSource(3)).Take(300))
.Split("<p>", StringSplitOptions.RemoveEmptyEntries)
.Skip(1)
.Select(p => p[..p.IndexOf("</p>", StringComparison.Ordinal)])
.ToList();
paragraphs.Select(p => p.Length).Distinct().Count().ShouldBeGreaterThan(paragraphs.Count / 2);
paragraphs.Select(p => p.Count(c => c is '.' or '?')).Distinct().Count().ShouldBeGreaterThan(3);
}
[Fact]
public void Is_deterministic_for_the_same_random_source()
{
var first = string.Concat(HtmlContent.Generate(new SeededRandomSource(4)).Take(50));
var second = string.Concat(HtmlContent.Generate(new SeededRandomSource(4)).Take(50));
var other = string.Concat(HtmlContent.Generate(new SeededRandomSource(5)).Take(50));
second.ShouldBe(first);
other.ShouldNotBe(first);
}
}
@@ -0,0 +1,35 @@
using System.Text;
using Flypaper.Core.Models;
using Flypaper.Core.Strategies;
using Flypaper.Tests.Fakes;
using Shouldly;
namespace Flypaper.Tests.Core;
public sealed class HtmlDripStrategyTests
{
[Fact]
public async Task Drips_html_in_small_chunks_until_cancelled()
{
var strategy = CreateStrategy();
var channel = new FakeTrapChannel();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300));
await Should.ThrowAsync<OperationCanceledException>(() => strategy.RunAsync(channel, cts.Token));
channel.Writes.Count.ShouldBeGreaterThan(5);
channel.Writes.ShouldAllBe(write => write.Length >= 1 && write.Length <= 64);
Encoding.UTF8.GetString(channel.Writes.SelectMany(write => write).ToArray()).ShouldStartWith("<!doctype html>");
}
[Theory]
[InlineData(TrapProtocol.Http, true)]
[InlineData(TrapProtocol.Ssh, false)]
public void Supports_only_http(TrapProtocol protocol, bool expected) =>
CreateStrategy().Supports(protocol).ShouldBe(expected);
private static HtmlDripStrategy CreateStrategy() => new(
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(1), MaxDelay = TimeSpan.FromMilliseconds(5) }),
new SeededRandomSource(21),
TimeProvider.System);
}
@@ -7,11 +7,12 @@ public sealed class RuntimeSettingsParserTests
{ {
private static readonly RuntimeSettingsInput Valid = new( private static readonly RuntimeSettingsInput Valid = new(
"/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env", "/.env\n/wp-admin/*\r\n /xmlrpc.php \n/.env",
"00:00:05",
"200", "200",
"5", "5",
"00:30:00", "00:30:00",
"example.com\n*.example.org"); "example.com\n*.example.org",
"90",
true);
[Fact] [Fact]
public void Parses_valid_input_and_normalizes_lists() public void Parses_valid_input_and_normalizes_lists()
@@ -22,10 +23,35 @@ public sealed class RuntimeSettingsParserTests
var settings = result.Settings.ShouldNotBeNull(); var settings = result.Settings.ShouldNotBeNull();
settings.TrapPaths.ShouldBe(["/.env", "/wp-admin/*", "/xmlrpc.php"]); settings.TrapPaths.ShouldBe(["/.env", "/wp-admin/*", "/xmlrpc.php"]);
settings.ExtraKnownHosts.ShouldBe(["example.com", "*.example.org"]); settings.ExtraKnownHosts.ShouldBe(["example.com", "*.example.org"]);
settings.DripInterval.ShouldBe(TimeSpan.FromSeconds(5));
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));
settings.RetentionDays.ShouldBe(90);
settings.IgnorePrivateNetworks.ShouldBeTrue();
}
[Theory]
[InlineData("0", 0)]
[InlineData("365", 365)]
[InlineData("3650", 3650)]
public void Accepts_retention_days_including_unlimited(string value, int expected) =>
RuntimeSettingsParser.Parse(Valid with { RetentionDays = value }).Settings.ShouldNotBeNull().RetentionDays.ShouldBe(expected);
[Theory]
[InlineData("-1")]
[InlineData("3651")]
[InlineData("x")]
[InlineData("")]
public void Rejects_invalid_retention_days(string value) =>
RuntimeSettingsParser.Parse(Valid with { RetentionDays = value }).Errors.Keys.ShouldBe([nameof(RuntimeSettingsInput.RetentionDays)]);
[Fact]
public void Keeps_private_network_choice()
{
var settings = RuntimeSettingsParser.Parse(Valid with { IgnorePrivateNetworks = false }).Settings.ShouldNotBeNull();
settings.IgnorePrivateNetworks.ShouldBeFalse();
settings.ToConfiguration()[SettingKeys.IgnorePrivateNetworks].ShouldBe("false");
} }
[Fact] [Fact]
@@ -65,12 +91,12 @@ public sealed class RuntimeSettingsParserTests
[InlineData("abc")] [InlineData("abc")]
[InlineData("")] [InlineData("")]
[InlineData("00:00:00")] [InlineData("00:00:00")]
[InlineData("02:00:00")] [InlineData("8.00:00:00")]
public void Rejects_invalid_drip_intervals(string value) public void Rejects_invalid_hold_durations(string value)
{ {
var result = RuntimeSettingsParser.Parse(Valid with { DripInterval = value }); var result = RuntimeSettingsParser.Parse(Valid with { MaxHoldDuration = value });
result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.DripInterval)); result.Errors.ShouldContainKey(nameof(RuntimeSettingsInput.MaxHoldDuration));
} }
[Theory] [Theory]
+48 -8
View File
@@ -47,7 +47,7 @@ public sealed class TrapRunnerTests
outcome.ShouldBe(TrapOutcome.Timeout); outcome.ShouldBe(TrapOutcome.Timeout);
lease.Received(1).Dispose(); lease.Received(1).Dispose();
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => _sink.Received(1).Publish(Arg.Is<TrapEvent>(e =>
e.Outcome == TrapOutcome.Timeout && e.BytesSent == _channel.Writes.Count && e.BytesSent > 0)); e.Outcome == TrapOutcome.Timeout && e.BytesSent == _channel.Writes.Sum(w => w.Length) && e.BytesSent > 0));
} }
[Fact] [Fact]
@@ -59,7 +59,44 @@ public sealed class TrapRunnerTests
var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token); var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token);
outcome.ShouldBe(TrapOutcome.ClientAborted); outcome.ShouldBe(TrapOutcome.ClientAborted);
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "drip")); _sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "html-drip"));
}
[Theory]
[InlineData("192.168.1.20")]
[InlineData("172.19.0.1")]
[InlineData("127.0.0.1")]
public async Task Traps_but_does_not_store_private_ips_by_default(string ip)
{
AllowAcquire();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(ip), Open, cts.Token);
outcome.ShouldBe(TrapOutcome.ClientAborted);
_channel.Writes.ShouldNotBeEmpty();
_sink.DidNotReceiveWithAnyArgs().Publish(default!);
}
[Fact]
public async Task Does_not_store_rejected_private_ips_by_default()
{
_governor.TryAcquire(Arg.Any<TrapSession>(), out Arg.Any<IDisposable?>()).Returns(false);
await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(Context("10.0.0.5"), Open, CancellationToken.None);
_sink.DidNotReceiveWithAnyArgs().Publish(default!);
}
[Fact]
public async Task Stores_private_ips_when_option_is_off()
{
AllowAcquire();
using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100));
await CreateRunner(TimeSpan.FromMinutes(1), ignorePrivateNetworks: false).RunAsync(Context("192.168.1.20"), Open, cts.Token);
_sink.Received(1).Publish(Arg.Is<TrapEvent>(e => e.RemoteIp.Equals(IPAddress.Parse("192.168.1.20"))));
} }
private IDisposable AllowAcquire() private IDisposable AllowAcquire()
@@ -76,18 +113,21 @@ public sealed class TrapRunnerTests
private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel); private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_channel);
private TrapRunner CreateRunner(TimeSpan maxHoldDuration) private TrapRunner CreateRunner(TimeSpan maxHoldDuration, bool ignorePrivateNetworks = true)
{ {
var drip = new DripStrategy(TestOptions.Monitor(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System); var drip = new HtmlDripStrategy(
TestOptions.Monitor(new DripOptions { MinDelay = TimeSpan.FromMilliseconds(5), MaxDelay = TimeSpan.FromMilliseconds(20) }),
new SeededRandomSource(7),
TimeProvider.System);
return new TrapRunner( return new TrapRunner(
_governor, _governor,
[drip], new ProtocolStrategySelector([drip]),
_sink, _sink,
TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }), TestOptions.Monitor(new FlypaperOptions { MaxHoldDuration = maxHoldDuration, IgnorePrivateNetworks = ignorePrivateNetworks }),
TimeProvider.System, TimeProvider.System,
NullLogger<TrapRunner>.Instance); NullLogger<TrapRunner>.Instance);
} }
private static TrapContext Context() => private static TrapContext Context(string ip = "203.0.113.9") =>
new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), "GET /.env"); new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse(ip), DateTimeOffset.UtcNow), "GET /.env");
} }
@@ -0,0 +1,10 @@
using Flypaper.Core.Abstractions;
namespace Flypaper.Tests.Fakes;
internal sealed class SeededRandomSource(int seed) : IRandomSource
{
private readonly Random _random = new(seed);
public int Next(int minValue, int maxValue) => _random.Next(minValue, maxValue);
}
@@ -0,0 +1,36 @@
using Flypaper.Storage;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Shouldly;
namespace Flypaper.Tests.Storage;
public sealed class MigrationTests : IDisposable
{
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-migration-{Guid.NewGuid():N}.db");
[Fact]
public async Task Removes_obsolete_drip_interval_override_from_existing_databases()
{
await using var db = new FlypaperDbContext(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite($"Data Source={_dbPath}").Options);
var migrator = db.GetService<IMigrator>();
await migrator.MigrateAsync("AddOrigin");
await db.Database.ExecuteSqlRawAsync(
"INSERT INTO \"Settings\" (\"Key\", \"Value\") VALUES ('Flypaper:Drip:Interval', '00:00:10'), ('Flypaper:MaxConnections', '50')");
await db.Database.MigrateAsync();
(await db.Settings.Select(s => s.Key).ToListAsync()).ShouldBe(["Flypaper:MaxConnections"]);
}
public void Dispose()
{
SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
{
File.Delete(_dbPath + suffix);
}
}
}
@@ -1,6 +1,5 @@
using Flypaper.Core; using Flypaper.Core;
using Flypaper.Core.Settings; using Flypaper.Core.Settings;
using Flypaper.Core.Strategies;
using Flypaper.Http; using Flypaper.Http;
using Flypaper.Http.Matching; using Flypaper.Http.Matching;
using Flypaper.Storage; using Flypaper.Storage;
@@ -74,16 +73,16 @@ public sealed class SettingsOverrideTests : IDisposable
await store.SaveAsync(new RuntimeSettings( await store.SaveAsync(new RuntimeSettings(
["/custom"], ["/custom"],
TimeSpan.FromSeconds(3),
50, 50,
4, 4,
TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10),
["extra.example"])); ["extra.example"],
90,
true));
matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.TrapPath); matcher.Match("dashboard.lan", "/custom").ShouldBe(TrapMatch.TrapPath);
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None); matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
matcher.Match("extra.example", "/").ShouldBe(TrapMatch.None); matcher.Match("extra.example", "/").ShouldBe(TrapMatch.None);
host.Services.GetRequiredService<IOptionsMonitor<DripOptions>>().CurrentValue.Interval.ShouldBe(TimeSpan.FromSeconds(3));
(await store.HasOverridesAsync()).ShouldBeTrue(); (await store.HasOverridesAsync()).ShouldBeTrue();
await store.ResetAsync(); await store.ResetAsync();
@@ -102,11 +101,12 @@ public sealed class SettingsOverrideTests : IDisposable
await host.Services.GetRequiredService<RuntimeSettingsStore>().SaveAsync(new RuntimeSettings( await host.Services.GetRequiredService<RuntimeSettingsStore>().SaveAsync(new RuntimeSettings(
[], [],
TimeSpan.FromSeconds(3),
50, 50,
4, 4,
TimeSpan.FromMinutes(10), TimeSpan.FromMinutes(10),
[])); [],
90,
true));
matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None); matcher.Match("dashboard.lan", "/.env").ShouldBe(TrapMatch.None);
} }
@@ -0,0 +1,144 @@
using System.Net;
using Flypaper.Core.Models;
using Flypaper.Storage;
using Flypaper.Storage.Entities;
using Flypaper.Storage.Maintenance;
using Flypaper.Tests.Fakes;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
namespace Flypaper.Tests.Storage;
public sealed class TrapDataMaintenanceTests : IDisposable
{
private static readonly DateTimeOffset Now = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-maintenance-{Guid.NewGuid():N}.db");
private readonly IDbContextFactory<FlypaperDbContext> _dbContextFactory;
private readonly TrapDataMaintenance _maintenance;
public TrapDataMaintenanceTests()
{
_dbContextFactory = new TestDbContextFactory($"Data Source={_dbPath}");
using var db = _dbContextFactory.CreateDbContext();
db.Database.Migrate();
_maintenance = new TrapDataMaintenance(_dbContextFactory);
}
[Fact]
public async Task Deletes_only_events_from_private_networks()
{
await SeedAsync(
("203.0.113.9", 1),
("192.168.1.20", 1),
("172.19.0.1", 1),
("127.0.0.1", 1),
("fd00::1", 1),
("fe80::1", 1),
("172.32.0.1", 1),
("8.8.8.8", 1));
(await _maintenance.DeletePrivateAsync()).ShouldBe(5);
(await RemainingIpsAsync()).ShouldBe(["203.0.113.9", "172.32.0.1", "8.8.8.8"], ignoreOrder: true);
}
[Fact]
public async Task Deletes_all_events_but_keeps_settings()
{
await SeedAsync(("203.0.113.9", 1), ("8.8.8.8", 2));
await using (var db = await _dbContextFactory.CreateDbContextAsync())
{
db.Settings.Add(new SettingEntity { Key = "Flypaper:MaxConnections", Value = "5" });
await db.SaveChangesAsync();
}
(await _maintenance.DeleteAllAsync()).ShouldBe(2);
await _maintenance.VacuumAsync();
await using var check = await _dbContextFactory.CreateDbContextAsync();
(await check.TrapEvents.CountAsync()).ShouldBe(0);
(await check.Settings.CountAsync()).ShouldBe(1);
}
[Fact]
public async Task Reports_count_oldest_event_and_file_size()
{
await SeedAsync(("203.0.113.9", 10), ("8.8.8.8", 3));
var stats = await _maintenance.GetStatsAsync();
stats.Count.ShouldBe(2);
stats.Oldest.ShouldBe(Now.UtcDateTime.AddDays(-10));
stats.DatabaseBytes.ShouldNotBeNull().ShouldBeGreaterThan(0);
}
[Fact]
public async Task Retention_deletes_events_older_than_configured_days()
{
await SeedAsync(("203.0.113.9", 100), ("203.0.113.10", 91), ("203.0.113.11", 89), ("203.0.113.12", 1));
(await CreateCleanup(days: 90).CleanupAsync(CancellationToken.None)).ShouldBe(2);
(await RemainingIpsAsync()).ShouldBe(["203.0.113.11", "203.0.113.12"], ignoreOrder: true);
}
[Fact]
public async Task Retention_of_zero_days_keeps_everything()
{
await SeedAsync(("203.0.113.9", 4000));
(await CreateCleanup(days: 0).CleanupAsync(CancellationToken.None)).ShouldBe(0);
(await RemainingIpsAsync()).ShouldBe(["203.0.113.9"]);
}
private RetentionCleanup CreateCleanup(int days) => new(
_maintenance,
TestOptions.Monitor(new RetentionOptions { Days = days }),
new FixedTimeProvider(Now),
NullLogger<RetentionCleanup>.Instance);
private async Task SeedAsync(params (string Ip, int DaysAgo)[] events)
{
await using var db = await _dbContextFactory.CreateDbContextAsync();
foreach (var (ip, daysAgo) in events)
{
var started = Now.AddDays(-daysAgo);
db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent(
Guid.NewGuid(),
TrapProtocol.Http,
IPAddress.Parse(ip),
"drip",
started,
started.AddSeconds(5),
5,
TrapOutcome.ClientAborted)));
}
await db.SaveChangesAsync();
}
private async Task<List<string>> RemainingIpsAsync()
{
await using var db = await _dbContextFactory.CreateDbContextAsync();
return await db.TrapEvents.Select(e => e.RemoteIp).ToListAsync();
}
public void Dispose()
{
SqliteConnection.ClearAllPools();
foreach (var suffix in new[] { "", "-wal", "-shm" })
{
File.Delete(_dbPath + suffix);
}
}
private sealed class TestDbContextFactory(string connectionString) : IDbContextFactory<FlypaperDbContext>
{
public FlypaperDbContext CreateDbContext() =>
new(new DbContextOptionsBuilder<FlypaperDbContext>().UseSqlite(connectionString).Options);
}
}