37 Commits
Author SHA1 Message Date
TomandClaude Sonnet 5.5 c2ecb14b4a Flag commands that attackers try to inject
Build and deploy / build (push) Successful in 1m32s
Release / image (push) Successful in 1m54s
Build and deploy / deploy (push) Successful in 30s
Release / release (push) Successful in 7s
Path, headers and body of every catch are checked; command and target
server are stored, shown defanged in the dashboard and via MCP
list_commands. Changelog prepared for 0.11.0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-27 21:22:19 +01:00
TomandClaude Sonnet 5.5 b559f83550 Record request headers and bodies and show them per catch
Build and deploy / build (push) Successful in 1m29s
Release / image (push) Successful in 1m53s
Build and deploy / deploy (push) Successful in 30s
Release / release (push) Successful in 6s
Headers and the first 8 KB of the body are stored unmasked for 30 days,
read alongside the response so the trap answers as before. MCP get_request
and the expanded catch row show them. Changelog prepared for 0.10.0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 21:47:28 +01:00
TomandClaude Sonnet 5.5 a46727bab3 Prepare changelog for 0.9.0
Build and deploy / build (push) Successful in 1m36s
Release / image (push) Successful in 1m59s
Build and deploy / deploy (push) Successful in 39s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 21:25:24 +01:00
TomandClaude Sonnet 5.5 302b40c172 Put signposts back into the trap into the fake files
.env, JSON, YAML, SQL and Git config carry URLs marked with the serving
catch, so a later request shows where the address came from. MCP exposes
the marker. Switch: Flypaper__Drip__Signposts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-26 21:24:04 +01:00
TomandClaude Sonnet 5.5 7c11bf211e Show the bots held in the trap right now
Build and deploy / build (push) Successful in 1m36s
Release / image (push) Successful in 1m59s
Build and deploy / deploy (push) Successful in 31s
Release / release (push) Successful in 7s
Dashboard table "Gerade in der Falle" and MCP tool list_active, backed by an
in-memory registry of running traps. Changelog prepared for 0.8.0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 01:59:07 +01:00
TomandClaude Sonnet 5.5 35aba56255 Prepare changelog for 0.7.0
Release / image (push) Successful in 1m56s
Release / release (push) Successful in 8s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 14:24:08 +01:00
TomandClaude Sonnet 5.5 c5167262b9 Remove the unused content choice and the plain-text hold method
Build and deploy / build (push) Successful in 1m34s
Build and deploy / deploy (push) Successful in 20s
The link labyrinth held every catch that mattered, text-drip was never
used. Flypaper__Drip__Content now only triggers the removed-settings warning.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 14:21:54 +01:00
TomandClaude Sonnet 5.5 4b946453fb Answer first visits to / and favicon with an instant WordPress lure
Build and deploy / build (push) Successful in 1m33s
Build and deploy / deploy (push) Successful in 20s
Unknown IPs get a small WordPress-looking page or icon and are not held;
later requests are trapped as before. Switch: Flypaper__Drip__Lure.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 12:57:29 +01:00
TomandClaude Opus 5.5 2437880013 Add explanation rules for catches, editable over MCP
Build and deploy / build (push) Successful in 1m29s
Build and deploy / deploy (push) Successful in 21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:46:22 +01:00
TomandClaude Opus 5.5 4086fa3da3 Drop the strategy details from the expanded catch row
Build and deploy / build (push) Successful in 1m30s
Build and deploy / deploy (push) Successful in 19s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:24:47 +01:00
TomandClaude Opus 5.5 1979fd91e9 Prepare changelog for 0.6.0
Build and deploy / build (push) Successful in 1m49s
Release / image (push) Successful in 2m0s
Build and deploy / deploy (push) Successful in 29s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:05:05 +01:00
TomandClaude Opus 5.5 119dafa505 Remove the research page, its MCP write tools and token write permission
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 11:05:05 +01:00
TomandClaude Opus 5.5 7f8a3ae882 Prepare changelog for 0.5.2
Build and deploy / build (push) Successful in 1m41s
Release / image (push) Successful in 2m1s
Build and deploy / deploy (push) Successful in 23s
Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:29:53 +01:00
TomandClaude Opus 5.5 cbd9830143 Group strategies by base type and rank them by median hold time
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:29:53 +01:00
TomandClaude Opus 5.5 d2cbab5d4b Prepare changelog for 0.5.1
Build and deploy / build (push) Successful in 1m41s
Release / image (push) Successful in 2m7s
Build and deploy / deploy (push) Successful in 22s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:52:11 +01:00
TomandClaude Opus 5.5 0655af2699 Show plain German strategy names with explanations in the dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:52:11 +01:00
TomandClaude Opus 5.5 e250a120ea Prepare changelog for 0.5.0
Release / image (push) Successful in 1m58s
Release / release (push) Successful in 8s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:30:17 +01:00
TomandClaude Opus 5.5 e88dc415f9 Add research page with MCP write tools, longer hold for repeat offenders and svn/hg decoys
Build and deploy / build (push) Successful in 1m50s
Build and deploy / deploy (push) Successful in 21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 18:27:35 +01:00
TomandClaude Opus 5.5 a25072e6fb Add link labyrinth, static robots.txt and robots bait paths
Build and deploy / build (push) Successful in 1m28s
Build and deploy / deploy (push) Successful in 20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 23:57:52 +01:00
TomandClaude Sonnet 5.5 b7027e2a72 Show the strategy of each catch in the dashboard
Build and deploy / build (push) Successful in 1m31s
Build and deploy / deploy (push) Successful in 30s
Add a Strategie column to the catch list (searchable, filterable) and a
Strategien tab to the Top 10 card. The MCP top tool accepts strategies.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:34:10 +01:00
TomandClaude Sonnet 5.5 7d3e6f8842 Add map markers for tiny countries that have a polygon
Build and deploy / build (push) Successful in 1m32s
Build and deploy / deploy (push) Successful in 20s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:10:05 +01:00
TomandClaude Sonnet 5.5 aeafaa71a8 Add Hikvision and WordPress login decoy profiles
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:06:19 +01:00
TomandClaude Sonnet 5.5 13468bbdf9 Pick tarpit content by request path
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 23:00:26 +01:00
TomandClaude Sonnet 5.5 e48b6bb832 Send a head start of the response immediately before dripping
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 22:54:03 +01:00
TomandClaude Opus 5.5 13a78f4268 Prepare changelog for 0.4.0
Release / image (push) Successful in 1m50s
Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:47:57 +01:00
TomandClaude Opus 5.5 9f07d41cb0 Add filters to the dashboard catch list and filter by clicking top 10 rows
Build and deploy / build (push) Successful in 1m30s
Build and deploy / deploy (push) Successful in 30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 23:40:52 +01:00
TomandClaude Opus 5.5 8eeb7894a3 Polish dashboard layout and use German number formats
Build and deploy / build (push) Successful in 1m27s
Build and deploy / deploy (push) Successful in 20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:09:52 +01:00
TomandClaude Opus 5.5 e86518cab1 Fix MCP schema mismatches and argument errors, highlight rejected connections and show average hold time
Build and deploy / build (push) Successful in 1m32s
Build and deploy / deploy (push) Successful in 30s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:56:50 +01:00
TomandClaude Opus 5.5 570ac20a5c Prepare changelog for 0.3.1
Build and deploy / build (push) Successful in 1m29s
Release / image (push) Successful in 1m51s
Build and deploy / deploy (push) Successful in 20s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:25:03 +01:00
TomandClaude Opus 5.5 393ebcdf0c Combine dashboard top 10 lists into one tabbed card
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:24:02 +01:00
TomandClaude Opus 5.5 f5bcc55a29 Prepare changelog for 0.3.0
Build and deploy / build (push) Successful in 1m28s
Release / image (push) Successful in 1m56s
Build and deploy / deploy (push) Successful in 21s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 20:01:33 +01:00
TomandClaude Opus 5.5 31bb8b21c2 Redesign dashboard with weighted metrics, compact map, share bars and empty-state onboarding
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:29:11 +01:00
TomandClaude Opus 5.5 de22f035dc Redesign settings page with sectioned layout, side navigation and choice cards
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:21:41 +01:00
TomandClaude Opus 5.5 6b9bf3cd5f Make the hold method configurable in the dashboard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 19:05:21 +01:00
TomandClaude Opus 5.5 9a56fc5b48 Remove trap paths and known hosts: catch everything on the trap port
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:56:35 +01:00
TomandClaude Opus 5.5 b9f2b0443c Prepare changelog for 0.2.0
Release / image (push) Successful in 1m48s
Release / release (push) Successful in 6s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 18:37:47 +01:00
TomandClaude Opus 5.5 49a8fa1154 Add read-only MCP server with token access
Build and deploy / build (push) Successful in 1m31s
Build and deploy / deploy (push) Successful in 20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:34:16 +01:00
176 changed files with 12083 additions and 846 deletions

No files matched your search

+255 -1
View File
@@ -6,6 +6,247 @@ All notable changes to Flypaper are documented in this file. The format follows
## [Unreleased] ## [Unreleased]
## [0.11.0] - 2026-11-27
### Added
- Command detection: path, headers and body of every catch are checked for injected commands (download or
connect with `wget`, `curl`, `tftp`, `nc` and a target, shell pipes, `chmod`, PHP code, PowerShell,
`base64 -d`, `rm -rf`), also URL-encoded. The command and the target server are stored with the catch
(migration `AddDetectedCommands`); stored catches are checked once at startup, bodies only where still
recorded. Pattern based, so it can miss commands or raise false alarms.
- Dashboard: card „Eingeschleuste Befehle“, badge „⚠ Befehl“ and details in the catch list and a filter
„Befehl: Nur mit Befehl“. Commands and servers are shown defanged as plain text.
- MCP: read-only tool `list_commands`.
## [0.10.0] - 2026-11-26
### Added
- Request recording: headers and the first 8 KB of the body of every trapped request are stored in a new table
(migration `AddTrapRequests`). The body is read alongside the response (at most 5 s, at most 1 s after the
catch ends), so the trap answers as before. Nothing is masked, including `Authorization`, `Cookie` and
passwords. Deleted after `Flypaper__Retention__RequestDays` (default 30) or together with the catch.
Rejected connections are not recorded. Switch: `Flypaper__CaptureRequests` (default `true`).
- Dashboard: expanded rows of the catch list show „Gesendete Anfrage“ with headers and body as plain text,
loaded only when a row is opened (signed-in only).
- MCP: read-only tool `get_request` returns the recorded headers and body of one catch, marked as untrusted.
## [0.9.0] - 2026-11-26
### Added
- Signposts in fake files: `.env` (`BACKUP_URL`, `ADMIN_URL`, `CONFIG_URL`), JSON and YAML (`backup_url`,
`api_base`), SQL dumps (comment naming the previous dump) and the Git config (remote URL) point back into the
trap. They sit in the first, undelayed chunk and carry the marker of the serving catch, so a later request
shows which catch the address came from, even from another IP. Switch: `Flypaper__Drip__Signposts`
(default `true`), no dashboard setting. No database change.
- MCP: every catch has a `marker`, and `list_catches` accepts `marker` to find the catch that handed out a
signpost.
## [0.8.0] - 2026-11-22
### Added
- Dashboard: the overview lists the bots held in the trap right now („Gerade in der Falle“) with IP (links to its
catches), origin, target, strategy, user agent, time held and bytes sent. The list is kept in memory only and
refreshes with the page (every 30 s).
- MCP: read-only tool `list_active` returns the same list (with provider, city and ASN); empty after a restart.
## [0.7.0] - 2026-11-21
### Added
- Lure for first visits: a GET on `/` or `/favicon.ico` from an IP without any stored catch is answered at once
with a small WordPress-looking page (`lure-page`, with `X-Powered-By: PHP/8.1.27`, a `wp-json` link header and
links to `/wp-login.php`, `/wp-admin/`, `/wp-content/uploads/backup/`, `/wp-config.php.bak`) or a favicon
(`lure-icon`) and is not held. Every later request of that IP is trapped as before. Switch:
`Flypaper__Drip__Lure` (default `true`), no dashboard setting.
- Explanations for catches: rules in the database (kind `Target`, `ClientInfo` or `Outcome`, regular expression,
German plain text, priority, on/off, note, creator) explain what a bot wanted, with which tool and how it ended.
Rules are matched when a catch is displayed, so new rules also apply to old catches; per kind the rule with
the highest priority wins. Patterns run with `NonBacktracking` and a timeout, are validated and length-limited
when saved, and compiled rules are cached until a rule changes. No rules are shipped.
- Dashboard: expanded rows of the catch list show „Was ist passiert?“ (or a muted „Unbekanntes Ziel“), the catch
filter has „Erklärung: Ohne Erklärung“, and the new page „Erklärungen“ lists the rules with pattern, text,
number of matches, on/off switch and delete.
- MCP: read-only tools `list_explanation_rules`, `list_unexplained` and `test_explanation_rule`; tools
`create_explanation_rule`, `update_explanation_rule`, `set_explanation_rule_enabled` and
`delete_explanation_rule` for tokens with write permission.
- MCP tokens: write permission is back (switch on the settings page, database column `CanWrite`, new migration).
Tokens without it neither see nor can call the write tools. The server description mentions the new tools.
### Changed
- Dashboard: the expanded row of the catch list no longer repeats the strategy name, explanation and
technical details; they stay in the tooltip of the „Strategie“ column and in the „Strategien“ tab.
### Removed
- Hold method „Inhalt“ (HTML filler text, random text, alternating) with `text-drip`, `TextDripStrategy`, the
setting `Flypaper__Drip__Content` and its radio buttons. The link labyrinth is always used; a leftover
`Flypaper__Drip__Content` is ignored and logged as a removed setting.
## [0.6.0] - 2026-11-21
### Removed
- Page „Erkenntnisse“ (`/erkenntnisse`) with lab notebook and idea table, including its navigation entry and
all stored entries and ideas (tables `LabEntries` and `Ideas` are dropped by a migration, without backup).
- MCP: tools `list_entries`, `list_ideas`, `create_entry`, `update_entry`, `create_idea`, `update_idea` and
`set_idea_status`. All MCP tools are read-only again.
- MCP tokens: write permission (switch on the settings page, column „Zugriff“, database column `CanWrite`).
- Markdown rendering (Markdig).
## [0.5.2] - 2026-11-17
### Changed
- Dashboard, Top 10 „Strategien“: strategies are grouped by base type, so `html-drip` with any drip speed
is one row „Endlose Webseite“; the old name `drip` counts as the same. Only `head`, `link` and `repeat` stay
separate rows and show small badges („Schnellstart“, „Links“, „Wiederholer“). The drip parameters moved to the
tooltip and the expanded row.
- Columns are now catches, **median hold time per catch** and total. The bar and the default sort use the median
(rows with fewer than 5 catches are greyed out, marked „wenige Daten“ and listed last).
- Clicking a row filters the catch list on all variants of the group. The catch list, filter chip and
expanded row show name plus badges. Old `?strategie=` links still work.
## [0.5.1] - 2026-11-17
### Changed
- Dashboard: strategies are shown with a plain German name (e.g. „Link-Labyrinth“, „Gefälschte Zugangsdaten
(.env)“) instead of the technical abbreviation. Tooltip and expanded row (also on touch devices) explain what
the bot gets, spell out the suffixes (`50-500ms 1-1024B`, `head`, `link`, `repeat`) and show the technical name.
Used in the catch list, the Top 10 „Strategien“ tab, filter chips and the page „Erkenntnisse“. The search also
finds the German names. Unknown names are shown unchanged. Stored values and MCP results stay technical.
## [0.5.0] - 2026-11-17
### Fixed
- Narrow or tiny countries that are drawn as a polygon but barely visible (Israel, Lebanon,
Palestine, Kuwait, Qatar, Netherlands, Belgium, Switzerland and others) now also get a
marker on the world map once they have catches.
### Added
- Version-control file profiles: `git-drip` now answers every `.git` variant (`/.git`, `/.git/…`, `.gitconfig`,
`.git-credentials`, `.gitignore` …), new `svn-drip` (`/.svn/…`: `format`, `entries`, `wc.db`) and `hg-drip`
(`/.hg/…`: `requires`, `store/requires`) serve plausible, endless files that start like the real ones.
- Repeat offenders: an IP that was already held until the limit (outcome `Timeout`) within the last
`Flypaper__RepeatWindowDays` days (default 7, `0` = off) is held for `Flypaper__RepeatHoldDuration`
(default 1 day) instead of the maximum hold duration. The catch's strategy gets the suffix `repeat`, so
it can be compared in the dashboard. Both values are adjustable under „Haltemethode“ on the settings page.
- Page „Erkenntnisse“ (`/erkenntnisse`, in the navigation): a lab notebook (date, title, kind experiment /
observation / hypothesis / measurement method, Markdown text, optional commit and strategy names; newest
first, filterable by kind) and an idea table (effort, efficiency, rationale, status open / in progress /
done / dropped, implementation date and commit; sorted by effort, done and dropped ones can be shown).
Markdown is rendered with Markdig without raw HTML and with only http, https and mailto links.
- MCP: new read tools `list_entries` and `list_ideas` and write tools `create_entry`, `update_entry`,
`create_idea`, `update_idea`, `set_idea_status`. Writing needs a token with write permission, set when
creating the token or later on the settings page (new „Zugriff“ column). Existing tokens and the token from
`Flypaper__Mcp__Token` stay read-only, and read-only tokens do not even see the write tools.
- Link labyrinth: the HTML page (strategy `maze-drip`, with `link <n>B` suffix) carries about ten links
already in the head start and then a new link every `LinkSpacing` bytes (default 160, `0` = old
`html-drip`). Links match the requested path and host (`/wiki/…`, `/docs/v2/…`, `/blog/2025/03/…`,
`/backup/2025/03/`), mix relative and absolute URLs and always lead to another labyrinth page.
Paths ending in `/` get an Apache-style „Index of /…“ listing (`index-drip`). `/robots.txt` is
served at once and complete (`User-agent: *`, `Disallow: /`, strategy `robots-static`), so well-behaved
crawlers stay out and only bots ignoring it get lost. Link spacing is adjustable on the settings page.
- Robots bait: below `Disallow: /` the robots.txt lists a few unlinked, plausible paths (default
`/backup-2024/`, `/admin-old/`, `/internal/db-export/`, `/old-site/`; `Flypaper__Drip__BaitPaths`,
editable on the settings page, empty = off). Requests to them and everything below get the labyrinth
as strategy `robots-bait` and are held for at least 24 hours, so catches show who read the
robots.txt and ignored it. The labyrinth never links to these paths.
- Dashboard: the catch list has a new „Strategie“ column (hidden on narrower screens, shown in
the expanded row) and the search covers it. A new „Strategien“ tab in the Top 10 card shows
catches and hold time per strategy and filters the list on click. The MCP `top` tool accepts
`strategies` as a dimension.
- Content matches the requested path: `.env`, `*.json`, `*.xml` (sitemaps), `*.yml`, `*.sql`,
`/.git/…`, Hikvision `/SDK/…` and `/ISAPI/…` (XML) and `wp-login.php`
(WordPress login page) get an endless, matching file with the right `Content-Type`
instead of an HTML page (strategy names `env-drip`, `json-drip`, …). Switchable on the
settings page (`Flypaper__Drip__MatchPath`).
- Head start: the first bytes of the page (at least `HeadStartSize`, default 1024) are sent
immediately after the `200` headers, with a `Server` header, so scanners see a real response
before the drip begins. Adjustable on the settings page; the stored strategy name gets a
`head <n>B` suffix (none when off).
## [0.4.0] - 2026-11-15
### Fixed
- MCP results now include fields whose value is `null` (e.g. `since` of `get_stats` with
`period=all`, a missing label in `top`) instead of leaving them out, so they match the
tools' output schemas.
- MCP tools answer unknown or missing parameters with a readable error instead of
"An error occurred invoking …" or silently ignoring them, e.g. `unknown parameter 'by';
expected 'dimension' (ips|countries|providers|targets|user_agents)`. `top` lists the allowed
values of `dimension` in its input schema. Invalid arguments are logged as warnings.
### Changed
- Rejected connections stand out on the dashboard: the "Abgelehnt" metric shows the last
24 hours, and the catch list marks them with an "Abgelehnt" badge. Outcomes are shown in
German. Top lists and hold times still count only real catches.
- The "Haltezeit gesamt" metric shows the average hold time per catch below it.
- The catch list on the dashboard has filters for period, outcome, country and a free-text
search over IP, provider, target and user agent. A click on a top 10 row filters the list by
that country, provider, IP or target (a second click removes it). Active filters show as
chips with the number of matches, live in the URL (`?land=HK&ausgang=abgelehnt&q=…`) and
survive the auto-refresh; "Weitere laden" shows up to 500 entries. Metrics and top 10 stay
unfiltered.
- The outcome "Abgebrochen" is now called "Aufgegeben".
- Dashboard polish: equal metric tiles with a one-line note each (unique IPs show the last
24 hours), map and top 10 card of equal height with a larger legend and visible
small-country markers, country and provider names in the regular font with a separate share
column, and German number formats throughout (e.g. `1.675` bytes, `15.11. 20:01:50`).
## [0.3.1] - 2026-11-15
### Changed
- The dashboard's top 10 lists share one card with tabs (Länder, Provider, IPs, Ziele); the
selected tab survives the auto-refresh.
## [0.3.0] - 2026-11-15
### Added
- Settings section "Haltemethode": content (HTML filler text, random plain text or alternating
per catch), pause and chunk size ranges and the maximum hold time, with an estimate of the
bandwidth per trapped connection and its own reset button. Changes apply to the next catch
without a restart.
- Plain-text drip strategy (`text-drip`), served as `text/plain`.
- Each catch stores its strategy with the parameters in use, e.g. `text-drip 50-1000ms 1-64B`;
MCP results include it as `strategy`.
### Changed
- The maximum hold time moved from the general settings to "Haltemethode".
- Saving one settings section no longer resets the values saved in another.
- Redesigned settings page with sections, side navigation and choice cards.
- Redesigned dashboard with weighted metrics, a more compact world map, share bars in the top
tables and a short guide while no catches exist yet.
### Removed
- Trap paths and known hosts, with their settings, the `Flypaper__Http__KnownHosts` and
`Flypaper__Http__TrapPaths` variables and the matching logic: every request on the trap port
is caught, only `/health` from private addresses is answered. Saved overrides are deleted on
start; the old variables are ignored with a warning in the log.
## [0.2.0] - 2026-11-15
### Added
- MCP server at `/mcp` on the dashboard port (Streamable HTTP) with read-only tools
`get_stats`, `list_catches`, `top`, `longest_catches` and `lookup_ip`, returning structured
JSON.
- Bearer tokens for MCP, created, listed and revoked on the settings page and stored only as
SHA-256 hashes; optional fixed token via `Flypaper__Mcp__Token`.
## [0.1.1] - 2026-11-15 ## [0.1.1] - 2026-11-15
### Fixed ### Fixed
@@ -48,6 +289,19 @@ First release.
- Unraid Docker template; when started as root, the container hands `/data` to its app user - Unraid Docker template; when started as root, the container hands `/data` to its app user
and drops privileges. and drops privileges.
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.1.1...main [Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.11.0...main
[0.11.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.11.0
[0.10.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.10.0
[0.9.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.9.0
[0.8.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.8.0
[0.7.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.7.0
[0.6.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.6.0
[0.5.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.2
[0.5.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.1
[0.5.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.5.0
[0.4.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.4.0
[0.3.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.3.1
[0.3.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.3.0
[0.2.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.2.0
[0.1.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.1 [0.1.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.1
[0.1.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.0 [0.1.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.0
+1
View File
@@ -11,6 +11,7 @@
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" /> <PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.15" />
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" /> <PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" />
<PackageVersion Include="MaxMind.GeoIP2" Version="6.1.0" /> <PackageVersion Include="MaxMind.GeoIP2" Version="6.1.0" />
<PackageVersion Include="ModelContextProtocol.AspNetCore" Version="2.4.0" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" /> <PackageVersion Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.15" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" /> <PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
</ItemGroup> </ItemGroup>
+4 -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
@@ -23,6 +23,7 @@ flowchart LR
within limits per IP, overall and per catch. within limits per IP, overall and per catch.
- Each catch is logged and stored with its origin (DB-IP GeoIP); the dashboard on port `8081` - Each catch is logged and stored with its origin (DB-IP GeoIP); the dashboard on port `8081`
shows maps and tables. shows maps and tables.
- AI assistants such as Claude can query the catches over MCP: [docs/mcp.md](docs/mcp.md).
More: [how it works and all features](docs/overview.md). More: [how it works and all features](docs/overview.md).
@@ -86,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
@@ -97,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 Hold method, 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
+15 -5
View File
@@ -15,13 +15,21 @@ 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__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` |
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` | | `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__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__MinDelay` / `MaxDelay` | Pause between chunks | `00:00:00.05` / `00:00:01` |
| `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` | | `Flypaper__Drip__MinChunkSize` / `MaxChunkSize` | Bytes per chunk | `1` / `64` |
| `Flypaper__Drip__HeadStartSize` | Bytes sent immediately before dripping starts (`0` = off) | `1024` |
| `Flypaper__Drip__LinkSpacing` | Link labyrinth: bytes of text between two links in the HTML page (`0` = off, plain `html-drip`) | `160` |
| `Flypaper__Drip__BaitPaths` | Comma-separated decoy paths listed in `robots.txt` (max. 8, empty = off); requests to them get `robots-bait` and are held for at least 24 h | `/backup-2024/,/admin-old/,/internal/db-export/,/old-site/` |
| `Flypaper__CaptureRequests` | Record all request headers (without the proxy's `X-Real-IP`, `X-Forwarded-*`) and the first 8 KB of the body of every trapped request. Nothing is masked: `Authorization`, `Cookie` and passwords in bodies are stored as sent, also those of your own devices that reach the trap by mistake | `true` |
| `Flypaper__Retention__RequestDays` | Days after which recorded headers and bodies are deleted (`0` = keep as long as the catch) | `30` |
| `Flypaper__Drip__Signposts` | Fake `.env`, JSON, YAML, SQL and Git files carry signpost URLs back into the trap (on the requested host, relative if the host is unusable); each URL holds the marker of the catch that served it (first 12 hex characters of its session id) | `true` |
| `Flypaper__Drip__Lure` | First visit of an unknown IP to `/` or `/favicon.ico` gets an instant WordPress-looking page or icon (`lure-page`, `lure-icon`) and is not held; every later request is trapped as usual | `true` |
| `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` |
| `TZ` | Time zone for the dashboard | UTC | | `TZ` | Time zone for the dashboard | UTC |
The defaults of the runtime settings below can also be set this way, e.g. The defaults of the runtime settings below can also be set this way, e.g.
@@ -30,13 +38,15 @@ The defaults of the runtime settings below can also be set this way, e.g.
## Runtime settings ## Runtime settings
Changed on the dashboard's settings page, stored in the database, effective immediately. The Changed on the dashboard's settings page, stored in the database, effective immediately. The
reset button removes all saved values. general reset button removes all saved values; the hold method section has its own reset.
| 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/*` | | Hold method: pause between chunks, min and max (10 ms to 30 s) | 50 ms / 1000 ms |
| Extra known hosts (merged with `KnownHosts`) | none | | Hold method: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes |
| Maximum hold time per catch | `01:00:00` | | Hold method: head start, sent without delay before the drip (0 to 65536 bytes) | 1024 bytes |
| Hold method: content matching the request path (e.g. `/.env`, `/config.json`) | on |
| Hold method: 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` |
| Keep catches (days, `0` = forever) | `90` | | Keep catches (days, `0` = forever) | `90` |
+74
View File
@@ -0,0 +1,74 @@
# MCP access for AI assistants
Flypaper includes a [Model Context Protocol](https://modelcontextprotocol.io) server, so AI
assistants such as Claude can query your catches: "Which countries hit the trap most this week?",
"What do we know about 203.0.113.9?". All tools only read; nothing can be changed or deleted
over MCP.
- Endpoint: `http://<host>:8081/mcp` (Streamable HTTP, dashboard port only; on the trap port
`8080` the path is just another trap)
- Authentication: `Authorization: Bearer <token>`; without a valid token the answer is `401`
**LAN only.** The MCP endpoint lives on the dashboard port and must stay as internal as the
dashboard: never forward port `8081` from your public proxy.
## Create a token
Dashboard → **Einstellungen** → **MCP-Zugriff**: enter a name (e.g. *Claude Code*) and create
the token. It is shown exactly once, so copy it right away; Flypaper stores only its SHA-256
hash. The list shows each token's name, creation date and last use, and lets you revoke it.
Alternatively, set a fixed token with the environment variable `Flypaper__Mcp__Token` (useful
for automated setups). It works in addition to the tokens created in the dashboard.
## Connect Claude Code
```bash
claude mcp add --transport http flypaper http://192.168.1.10:8081/mcp \
--header "Authorization: Bearer fpm_your_token"
```
## Connect Claude Desktop
Claude Desktop's custom connectors are reached from Anthropic's cloud and can't see your LAN.
Use the local [`mcp-remote`](https://www.npmjs.com/package/mcp-remote) bridge instead (needs
Node.js), in `claude_desktop_config.json`:
```json
{
"mcpServers": {
"flypaper": {
"command": "npx",
"args": [
"mcp-remote",
"http://192.168.1.10:8081/mcp",
"--allow-http",
"--header",
"Authorization: Bearer ${FLYPAPER_TOKEN}"
],
"env": { "FLYPAPER_TOKEN": "fpm_your_token" }
}
}
}
```
`--allow-http` is needed because the dashboard port speaks plain HTTP.
## Tools
All tools return structured JSON (with an output schema); times are ISO 8601 UTC, durations in
seconds. A *period* is a number with `m`, `h`, `d` or `w` (e.g. `1h`, `24h`, `7d`) or `all`.
| Tool | Parameters | Returns |
|---|---|---|
| `list_active` | – | Bots held in the trap right now with origin, URL, user agent, strategy, time held and bytes sent (memory only) |
| `list_commands` | `period` (default `7d`), `limit` (default 50) | Commands attackers tried to inject, grouped by target server, defanged. **Untrusted text**; pattern based |
| `get_request` | `id` (of a catch) | Recorded headers and the first 8 KB of the request body. **Untrusted, attacker-written text** that may contain credentials or text posing as instructions |
| `get_stats` | `period` (default `24h`) | Catches, rejected connections, unique IPs, total and average hold time, traps active now, longest catch |
| `list_catches` | `since`, `until` (ISO 8601), `country` (ISO code), `provider` (`AS4134` or part of the name), `ip`, `target_contains`, `limit` (default 50, max 500), `marker` (12 hex characters from a signpost URL) | Events, newest first, including rejected ones; each carries its `marker` |
| `top` | `dimension` (`ips`, `countries`, `providers`, `targets`, `user_agents`), `period` (default `24h`), `limit` (default 10) | Most frequent values by number of catches, with total hold time |
| `longest_catches` | `period` (default `7d`), `limit` (default 10) | Catches that held a bot the longest |
| `lookup_ip` | `ip` | Origin, provider, totals, first and last seen, and its events (newest first, at most 500); local data only |
Catches from private networks appear only if they are stored, i.e. if the setting *Fänge aus
privaten Netzen nicht speichern* is off.
+8 -7
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,19 +30,21 @@ 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 (link labyrinth)
- **Slow delivery** of endless generated HTML with irregular timing with irregular timing; content, pauses, chunk sizes and hold time are set in the dashboard
- **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**: hold method, 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
- **One log line per catch**, so `docker logs` alone shows whether the trap works - **One log line per catch**, so `docker logs` alone shows whether the trap works
- **MCP server** on the dashboard port, so AI assistants can query the catches read-only
([docs/mcp.md](mcp.md))
- **Health endpoint** `/health` for container health checks (on the trap port it answers only - **Health endpoint** `/health` for container health checks (on the trap port it answers only
to private addresses) to private addresses)
- **No configuration needed to start**: one volume, two ports, the admin password is set on - **No configuration needed to start**: one volume, two ports, the admin password is set on
+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"
``` ```
@@ -0,0 +1,15 @@
using Flypaper.Core.Models;
namespace Flypaper.Core.Abstractions;
public interface IActiveTraps
{
IActiveTrapHandle Begin(TrapContext context, string strategy);
IReadOnlyList<ActiveTrap> Snapshot();
}
public interface IActiveTrapHandle : IDisposable
{
void Attach(Func<long> bytesSent);
}
@@ -0,0 +1,6 @@
namespace Flypaper.Core.Abstractions;
public interface IHoldExtension
{
TimeSpan MinimumHold { get; }
}
@@ -0,0 +1,8 @@
using System.Net;
namespace Flypaper.Core.Abstractions;
public interface IKnownIpLookup
{
ValueTask<bool> HasSeenAsync(IPAddress address, CancellationToken ct);
}
@@ -0,0 +1,8 @@
using System.Net;
namespace Flypaper.Core.Abstractions;
public interface IRepeatOffenderLookup
{
ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct);
}
@@ -0,0 +1,8 @@
using Flypaper.Core.Models;
namespace Flypaper.Core.Abstractions;
public interface IRequestCapture
{
ValueTask<RequestDetails?> CompleteAsync();
}
@@ -0,0 +1,6 @@
namespace Flypaper.Core.Abstractions;
public interface IResponseHeaders
{
IReadOnlyDictionary<string, string> Headers { get; }
}
@@ -0,0 +1,8 @@
namespace Flypaper.Core.Abstractions;
public interface IStrategyDetails
{
string MediaType { get; }
string Describe();
}
@@ -6,5 +6,9 @@ public interface ITrapChannel
{ {
TrapSession Session { get; } TrapSession Session { get; }
string? Path => null;
string? Host => null;
ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct); ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct);
} }
@@ -0,0 +1,116 @@
using System.Text.RegularExpressions;
using Flypaper.Core.Models;
namespace Flypaper.Core.Analysis;
public sealed record DetectedCommand(string Command, string? Server);
public static class CommandDetector
{
public const int Version = 1;
public const int MaxCommandLength = 500;
public const int MaxServerLength = 256;
private const int LeadingContext = 80;
private static readonly TimeSpan Timeout = TimeSpan.FromMilliseconds(200);
private static readonly Regex Fetch = Create(
@"\b(?:wget|curl|tftp|ftpget|nc|ncat|netcat)(?:\s|\$\{IFS\}|\$IFS)[^\n;|&`]{0,80}?(?:(?:https?|ftp|tftp)://(?<url>[^\s/;|&`'""<>()?#]+)[^\s;|&`'""<>()]*|\b(?<ip>(?:\d{1,3}\.){3}\d{1,3})(?:[ :](?<port>\d{1,5})\b)?)");
private static readonly Regex Execute = Create(
@"\|\s*(?:/bin/)?(?:ba)?sh\b|/bin/(?:ba)?sh\b|\bchmod\s+(?:\+x|[0-7]{3,4})\s|<\?php|\bpowershell(?:\.exe)?\s+-|\bbase64\s+(?:-d|--decode)\b|\brm\s+-rf\s");
public static DetectedCommand? Detect(string? target, RequestDetails? request) => Detect(target, request?.Headers, request?.Body);
public static DetectedCommand? Detect(string? target, string? headers, string? body)
{
DetectedCommand? first = null;
foreach (var part in Parts(target, headers, body))
{
var fetch = Match(Fetch, part);
if (fetch is not null)
{
return new DetectedCommand(Snippet(part, fetch.Index), Server(fetch));
}
if (first is null && Match(Execute, part) is { } execute)
{
first = new DetectedCommand(Snippet(part, execute.Index), null);
}
}
return first;
}
private static IEnumerable<string> Parts(string? target, string? headers, string? body)
{
var slash = target?.IndexOf('/') ?? -1;
if (slash >= 0)
{
var path = target![slash..];
var question = path.IndexOf('?');
yield return Uri.UnescapeDataString(question < 0 ? path : path[..question]);
if (question >= 0)
{
foreach (var parameter in path[(question + 1)..].Split('&'))
{
yield return Decode(parameter);
}
}
}
if (body is not null)
{
var isForm = !body.Contains('\n') && !body.StartsWith('{') && !body.StartsWith('<') && body.Contains('=');
if (isForm)
{
foreach (var parameter in body.Split('&'))
{
yield return Decode(parameter);
}
}
else
{
yield return body;
}
}
foreach (var line in (headers ?? "").Split('\n', StringSplitOptions.RemoveEmptyEntries))
{
yield return line;
}
}
private static string Decode(string value) => Uri.UnescapeDataString(value.Replace('+', ' '));
private static Match? Match(Regex regex, string text)
{
try
{
var match = regex.Match(text);
return match.Success ? match : null;
}
catch (RegexMatchTimeoutException)
{
return null;
}
}
private static string? Server(Match fetch)
{
var server = fetch.Groups["url"].Success
? fetch.Groups["url"].Value
: fetch.Groups["port"].Success ? $"{fetch.Groups["ip"].Value}:{fetch.Groups["port"].Value}" : fetch.Groups["ip"].Value;
return server.Length > MaxServerLength ? server[..MaxServerLength] : server;
}
private static string Snippet(string part, int index)
{
var start = part.Length <= MaxCommandLength ? 0 : Math.Max(0, index - LeadingContext);
var snippet = part.Substring(start, Math.Min(MaxCommandLength, part.Length - start));
return string.Concat(snippet.Select(c => char.IsControl(c) ? ' ' : c)).Trim();
}
private static Regex Create(string pattern) =>
new(pattern, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.NonBacktracking, Timeout);
}
+16
View File
@@ -0,0 +1,16 @@
using System.Text.RegularExpressions;
namespace Flypaper.Core.Analysis;
public static partial class Defang
{
public static string Text(string value) => Host().Replace(Scheme().Replace(value, "hxx$1://"), match => match.Value.Replace(".", "[.]"));
public static string Server(string value) => value.Replace(".", "[.]");
[GeneratedRegex(@"\bhtt(ps?)://", RegexOptions.IgnoreCase)]
private static partial Regex Scheme();
[GeneratedRegex(@"(?<=://)[^\s/;|&'""]+|\b(?:\d{1,3}\.){3}\d{1,3}\b")]
private static partial Regex Host();
}
+26 -1
View File
@@ -5,6 +5,7 @@ using Flypaper.Core.Strategies;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace Flypaper.Core; namespace Flypaper.Core;
@@ -17,11 +18,35 @@ public static class FlypaperCoreExtensions
services.TryAddSingleton(TimeProvider.System); services.TryAddSingleton(TimeProvider.System);
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>(); services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
services.TryAddSingleton<IActiveTraps, ActiveTrapRegistry>();
services.TryAddSingleton<IRandomSource, SystemRandomSource>(); services.TryAddSingleton<IRandomSource, SystemRandomSource>();
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>()); services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
services.TryAddSingleton<ITrapStrategySelector, ProtocolStrategySelector>(); services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, RobotsStaticStrategy>());
services.AddSingleton<ITarpitStrategy>(_ => LureStrategy.Page());
services.AddSingleton<ITarpitStrategy>(_ => LureStrategy.Icon());
foreach (var kind in Enum.GetValues<MazeKind>())
{
services.AddSingleton<ITarpitStrategy>(provider => new MazeDripStrategy(
kind,
provider.GetRequiredService<IOptionsMonitor<DripOptions>>(),
provider.GetRequiredService<IRandomSource>(),
provider.GetRequiredService<TimeProvider>()));
}
foreach (var profile in FileContent.Profiles)
{
services.AddSingleton<ITarpitStrategy>(provider => new FileDripStrategy(
profile,
provider.GetRequiredService<IOptionsMonitor<DripOptions>>(),
provider.GetRequiredService<IRandomSource>(),
provider.GetRequiredService<TimeProvider>()));
}
services.TryAddSingleton<ITrapStrategySelector, ConfiguredStrategySelector>();
services.TryAddSingleton<TrapRunner>(); services.TryAddSingleton<TrapRunner>();
services.TryAddSingleton<IIpEnricher, NullIpEnricher>(); services.TryAddSingleton<IIpEnricher, NullIpEnricher>();
services.TryAddSingleton<IRepeatOffenderLookup, NullRepeatOffenderLookup>();
services.TryAddSingleton<IKnownIpLookup, NullKnownIpLookup>();
return services; return services;
} }
+6
View File
@@ -10,5 +10,11 @@ public sealed class FlypaperOptions
public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1); public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1);
public int RepeatWindowDays { get; set; } = 7;
public TimeSpan RepeatHoldDuration { get; set; } = TimeSpan.FromHours(24);
public bool CaptureRequests { get; set; } = true;
public bool IgnorePrivateNetworks { get; set; } = true; public bool IgnorePrivateNetworks { get; set; } = true;
} }
+5
View File
@@ -0,0 +1,5 @@
using System.Net;
namespace Flypaper.Core.Models;
public sealed record ActiveTrap(Guid Id, IPAddress Ip, string? Target, string? ClientInfo, string Strategy, DateTimeOffset StartedAt, long BytesSent);
@@ -0,0 +1,3 @@
namespace Flypaper.Core.Models;
public sealed record RequestDetails(string Headers, string? Body, long? ContentLength, bool Truncated);
+3 -1
View File
@@ -1,3 +1,5 @@
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Models; namespace Flypaper.Core.Models;
public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null); public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null, string? Path = null, bool IsNewIp = false, IRequestCapture? Capture = null);
+2 -1
View File
@@ -12,7 +12,8 @@ public sealed record TrapEvent(
long BytesSent, long BytesSent,
TrapOutcome Outcome, TrapOutcome Outcome,
string? Target = null, string? Target = null,
string? ClientInfo = null) string? ClientInfo = null,
RequestDetails? Request = null)
{ {
public TimeSpan Duration => EndedAt - StartedAt; public TimeSpan Duration => EndedAt - StartedAt;
} }
@@ -0,0 +1,9 @@
using System.Net;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Networking;
internal sealed class NullKnownIpLookup : IKnownIpLookup
{
public ValueTask<bool> HasSeenAsync(IPAddress address, CancellationToken ct) => ValueTask.FromResult(true);
}
@@ -0,0 +1,9 @@
using System.Net;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Networking;
internal sealed class NullRepeatOffenderLookup : IRepeatOffenderLookup
{
public ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct) => ValueTask.FromResult(false);
}
@@ -0,0 +1,38 @@
using System.Collections.Concurrent;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
namespace Flypaper.Core.Runtime;
public sealed class ActiveTrapRegistry(TimeProvider timeProvider) : IActiveTraps
{
private readonly ConcurrentDictionary<Guid, Entry> _entries = new();
public IActiveTrapHandle Begin(TrapContext context, string strategy)
{
var entry = new Entry(this, context, strategy, timeProvider.GetUtcNow());
_entries[context.Session.Id] = entry;
return entry;
}
public IReadOnlyList<ActiveTrap> Snapshot() =>
_entries.Values.Select(entry => entry.ToActiveTrap()).OrderBy(trap => trap.StartedAt).ToList();
private sealed class Entry(ActiveTrapRegistry owner, TrapContext context, string strategy, DateTimeOffset startedAt) : IActiveTrapHandle
{
private Func<long>? _bytesSent;
public void Attach(Func<long> bytesSent) => _bytesSent = bytesSent;
public ActiveTrap ToActiveTrap() => new(
context.Session.Id,
context.Session.RemoteIp,
context.Target,
context.ClientInfo,
strategy,
startedAt,
_bytesSent?.Invoke() ?? 0);
public void Dispose() => owner._entries.TryRemove(context.Session.Id, out _);
}
}
@@ -0,0 +1,53 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Flypaper.Core.Strategies;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Runtime;
public sealed class ConfiguredStrategySelector(
IEnumerable<ITarpitStrategy> strategies,
IOptionsMonitor<DripOptions> options,
IRandomSource random) : ITrapStrategySelector
{
public ITarpitStrategy? Select(TrapContext context)
{
var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList();
if (string.Equals(context.Path, RobotsStaticStrategy.Path, StringComparison.OrdinalIgnoreCase)
&& candidates.FirstOrDefault(strategy => strategy.Name == RobotsStaticStrategy.StrategyName) is { } robots)
{
return robots;
}
if (context.IsNewIp && options.CurrentValue.Lure && LureContent.Handles(context.Path)
&& candidates.FirstOrDefault(strategy => strategy.Name == (context.Path == LureContent.PagePath ? LureStrategy.PageName : LureStrategy.IconName)) is { } lure)
{
return lure;
}
if (BaitPaths.Matches(BaitPaths.Parse(options.CurrentValue.BaitPaths), context.Path)
&& candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.BaitName) is { } bait)
{
return bait;
}
if (options.CurrentValue.MatchPath && FileContent.Match(context.Path) is { } profile
&& candidates.FirstOrDefault(strategy => strategy.Name == profile.Name) is { } fileStrategy)
{
return fileStrategy;
}
var maze = options.CurrentValue.LinkSpacing > 0
&& candidates.Any(strategy => strategy.Name == MazeDripStrategy.PageName);
var page = maze ? MazeDripStrategy.PageName : HtmlDripStrategy.StrategyName;
var matching = candidates.Where(strategy => strategy.Name == page).ToList();
var chosen = matching.Count == 0
? candidates.FirstOrDefault()
: matching[random.Next(0, matching.Count)];
return chosen?.Name == MazeDripStrategy.PageName && MazeContent.IsDirectory(context.Path)
&& candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.ListingName) is { } listing
? listing
: chosen;
}
}
@@ -9,6 +9,10 @@ internal sealed class CountingTrapChannel(ITrapChannel inner) : ITrapChannel
public TrapSession Session => inner.Session; public TrapSession Session => inner.Session;
public string? Path => inner.Path;
public string? Host => inner.Host;
public long BytesSent => Interlocked.Read(ref _bytesSent); public long BytesSent => Interlocked.Read(ref _bytesSent);
public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct) public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
@@ -1,10 +0,0 @@
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));
}
+31 -8
View File
@@ -11,13 +11,15 @@ public sealed partial class TrapRunner(
IConnectionGovernor governor, IConnectionGovernor governor,
ITrapStrategySelector strategies, ITrapStrategySelector strategies,
ITrapEventSink sink, ITrapEventSink sink,
IActiveTraps activeTraps,
IRepeatOffenderLookup repeatOffenders,
IOptionsMonitor<FlypaperOptions> options, IOptionsMonitor<FlypaperOptions> options,
TimeProvider timeProvider, TimeProvider timeProvider,
ILogger<TrapRunner> logger) ILogger<TrapRunner> logger)
{ {
public async Task<TrapOutcome> RunAsync( public async Task<TrapOutcome> RunAsync(
TrapContext context, TrapContext context,
Func<CancellationToken, ValueTask<ITrapChannel>> openChannel, Func<ITarpitStrategy, CancellationToken, ValueTask<ITrapChannel>> openChannel,
CancellationToken ct) CancellationToken ct)
{ {
var session = context.Session; var session = context.Session;
@@ -25,19 +27,37 @@ public sealed partial class TrapRunner(
if (strategy is null || !governor.TryAcquire(session, out var lease)) if (strategy is null || !governor.TryAcquire(session, out var lease))
{ {
Publish(context, strategy?.Name ?? "none", 0, TrapOutcome.Rejected); Publish(context, strategy?.Name ?? "none", 0, TrapOutcome.Rejected, timeProvider.GetUtcNow(), null);
return TrapOutcome.Rejected; return TrapOutcome.Rejected;
} }
using var _ = lease; using var _ = lease;
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider); var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name;
var holdDuration = options.CurrentValue.MaxHoldDuration;
if (strategy is IHoldExtension extension && extension.MinimumHold > holdDuration)
{
holdDuration = extension.MinimumHold;
}
if (options.CurrentValue is { RepeatWindowDays: > 0 } current
&& current.RepeatHoldDuration > holdDuration
&& await repeatOffenders.HasTimedOutSinceAsync(session.RemoteIp, timeProvider.GetUtcNow().UtcDateTime.AddDays(-current.RepeatWindowDays), ct))
{
holdDuration = current.RepeatHoldDuration;
description += " repeat";
}
using var active = activeTraps.Begin(context, description);
using var hold = new CancellationTokenSource(holdDuration, timeProvider);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token); using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token);
CountingTrapChannel? channel = null; CountingTrapChannel? channel = null;
var outcome = TrapOutcome.Completed; var outcome = TrapOutcome.Completed;
try try
{ {
channel = new CountingTrapChannel(await openChannel(linked.Token)); channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
var counting = channel;
active.Attach(() => counting.BytesSent);
await strategy.RunAsync(channel, linked.Token); await strategy.RunAsync(channel, linked.Token);
} }
catch (OperationCanceledException) when (linked.IsCancellationRequested) catch (OperationCanceledException) when (linked.IsCancellationRequested)
@@ -51,11 +71,13 @@ public sealed partial class TrapRunner(
outcome = TrapOutcome.ClientAborted; outcome = TrapOutcome.ClientAborted;
} }
Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome); var endedAt = timeProvider.GetUtcNow();
var request = context.Capture is null ? null : await context.Capture.CompleteAsync();
Publish(context, description, channel?.BytesSent ?? 0, outcome, endedAt, request);
return outcome; return outcome;
} }
private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome) private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome, DateTimeOffset endedAt, RequestDetails? request)
{ {
var session = context.Session; var session = context.Session;
var trapEvent = new TrapEvent( var trapEvent = new TrapEvent(
@@ -64,11 +86,12 @@ public sealed partial class TrapRunner(
session.RemoteIp, session.RemoteIp,
strategy, strategy,
session.StartedAt, session.StartedAt,
timeProvider.GetUtcNow(), endedAt,
bytesSent, bytesSent,
outcome, outcome,
context.Target, context.Target,
context.ClientInfo); context.ClientInfo,
request);
var store = !(options.CurrentValue.IgnorePrivateNetworks && PrivateNetworks.Contains(trapEvent.RemoteIp)); var store = !(options.CurrentValue.IgnorePrivateNetworks && PrivateNetworks.Contains(trapEvent.RemoteIp));
var storageNote = store ? "" : " (not stored)"; var storageNote = store ? "" : " (not stored)";
@@ -0,0 +1,56 @@
using System.Globalization;
using Flypaper.Core.Strategies;
namespace Flypaper.Core.Settings;
public sealed record HoldMethodSettings(
TimeSpan MinDelay,
TimeSpan MaxDelay,
int MinChunkSize,
int MaxChunkSize,
int HeadStartSize,
bool MatchPath,
int LinkSpacing,
string BaitPaths,
TimeSpan MaxHoldDuration,
int RepeatWindowDays,
TimeSpan RepeatHoldDuration)
{
public double BytesPerSecond => AverageBytesPerSecond(MinDelay, MaxDelay, MinChunkSize, MaxChunkSize);
public IReadOnlyDictionary<string, string> ToConfiguration() => new Dictionary<string, string>
{
[SettingKeys.DripMinDelay] = MinDelay.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.DripMaxDelay] = MaxDelay.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.DripMinChunkSize] = MinChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripMaxChunkSize] = MaxChunkSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripHeadStartSize] = HeadStartSize.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripMatchPath] = MatchPath ? "true" : "false",
[SettingKeys.DripLinkSpacing] = LinkSpacing.ToString(CultureInfo.InvariantCulture),
[SettingKeys.DripBaitPaths] = BaitPaths,
[SettingKeys.MaxHoldDuration] = MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
[SettingKeys.RepeatWindowDays] = RepeatWindowDays.ToString(CultureInfo.InvariantCulture),
[SettingKeys.RepeatHoldDuration] = RepeatHoldDuration.ToString("c", CultureInfo.InvariantCulture)
};
public static double AverageBytesPerSecond(TimeSpan minDelay, TimeSpan maxDelay, int minChunkSize, int maxChunkSize)
{
var averageDelay = (minDelay + maxDelay).TotalSeconds / 2;
return averageDelay <= 0 ? 0 : (minChunkSize + maxChunkSize) / 2d / averageDelay;
}
}
public sealed record HoldMethodInput(
string? MinDelayMs,
string? MaxDelayMs,
string? MinChunkSize,
string? MaxChunkSize,
string? HeadStartSize,
bool MatchPath,
string? LinkSpacing,
string? BaitPaths,
string? MaxHoldDuration,
string? RepeatWindowDays,
string? RepeatHoldDuration);
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
@@ -3,21 +3,15 @@ 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,
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.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,7 @@
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? ExtraKnownHosts,
string? RetentionDays, string? RetentionDays,
bool IgnorePrivateNetworks); bool IgnorePrivateNetworks);
@@ -1,29 +1,26 @@
using System.Globalization; using System.Globalization;
using System.Text.RegularExpressions; using Flypaper.Core.Strategies;
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);
private const int MinDelayMs = 10;
[GeneratedRegex(@"^(\*\.)?[A-Za-z0-9]([A-Za-z0-9.\-]*[A-Za-z0-9])?$")] private const int MaxDelayMs = 30_000;
private static partial Regex HostPattern(); private const int MaxChunkSize = 4096;
private const int MaxHeadStartSize = 65_536;
private const int MaxLinkSpacing = 4096;
private const int MaxRepeatWindowDays = 365;
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 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);
var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors); var retention = ParseInt(input.RetentionDays, nameof(input.RetentionDays), 0, MaxRetentionDays, errors);
@@ -40,78 +37,77 @@ public static partial class RuntimeSettingsParser
} }
var settings = new RuntimeSettings( var settings = new RuntimeSettings(
paths!,
maxConnections!.Value, maxConnections!.Value,
perIp!.Value, perIp!.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( public static HoldMethodParseResult ParseHoldMethod(HoldMethodInput input)
string? raw,
string field,
Func<string, string?> validate,
Dictionary<string, string> errors)
{ {
var lines = (raw ?? string.Empty) var errors = new Dictionary<string, string>();
.Split(['\r', '\n'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
if (lines.Length > MaxListEntries) var minDelay = ParseInt(input.MinDelayMs, nameof(input.MinDelayMs), MinDelayMs, MaxDelayMs, errors);
var maxDelay = ParseInt(input.MaxDelayMs, nameof(input.MaxDelayMs), MinDelayMs, MaxDelayMs, errors);
var minChunk = ParseInt(input.MinChunkSize, nameof(input.MinChunkSize), 1, MaxChunkSize, errors);
var maxChunk = ParseInt(input.MaxChunkSize, nameof(input.MaxChunkSize), 1, MaxChunkSize, errors);
var headStart = ParseInt(input.HeadStartSize, nameof(input.HeadStartSize), 0, MaxHeadStartSize, errors);
var linkSpacing = ParseInt(input.LinkSpacing, nameof(input.LinkSpacing), 0, MaxLinkSpacing, errors);
var baits = ParseBaitPaths(input.BaitPaths, nameof(input.BaitPaths), errors);
var hold = ParseTimeSpan(input.MaxHoldDuration, nameof(input.MaxHoldDuration), MinHold, MaxHold, errors);
var repeatWindow = ParseInt(input.RepeatWindowDays, nameof(input.RepeatWindowDays), 0, MaxRepeatWindowDays, errors);
var repeatHold = ParseTimeSpan(input.RepeatHoldDuration, nameof(input.RepeatHoldDuration), MinHold, MaxHold, errors);
if (minDelay > maxDelay)
{ {
errors[field] = $"Höchstens {MaxListEntries} Einträge."; errors[nameof(input.MaxDelayMs)] = "Darf nicht kleiner sein als das Minimum.";
}
if (minChunk > maxChunk)
{
errors[nameof(input.MaxChunkSize)] = "Darf nicht kleiner sein als das Minimum.";
}
if (errors.Count > 0)
{
return new HoldMethodParseResult(null, errors);
}
return new HoldMethodParseResult(
new HoldMethodSettings(
TimeSpan.FromMilliseconds(minDelay!.Value),
TimeSpan.FromMilliseconds(maxDelay!.Value),
minChunk!.Value,
maxChunk!.Value,
headStart!.Value,
input.MatchPath,
linkSpacing!.Value,
baits!,
hold!.Value,
repeatWindow!.Value,
repeatHold!.Value),
errors);
}
private static string? ParseBaitPaths(string? raw, string field, Dictionary<string, string> errors)
{
var entries = BaitPaths.Split(raw);
var normalized = entries.Select(BaitPaths.Normalize).ToList();
if (normalized.Any(entry => entry is null))
{
errors[field] = "Pfade wie /backup-2024/, ohne Leerzeichen; nicht /robots.txt und nicht unter den Labyrinth-Ordnern (wiki, docs, blog, backup …).";
return null; return null;
} }
var problems = new List<string>(); var distinct = normalized.OfType<string>().Distinct().ToList();
for (var i = 0; i < lines.Length; i++) if (distinct.Count > BaitPaths.MaxCount)
{ {
if (validate(lines[i]) is { } problem) errors[field] = $"Höchstens {BaitPaths.MaxCount} Pfade.";
{
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 null;
} }
return lines.Distinct(StringComparer.Ordinal).ToArray(); return string.Join(',', distinct);
}
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(
@@ -130,7 +126,7 @@ public static partial class RuntimeSettingsParser
if (!text.Contains(':') || !TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var value)) if (!text.Contains(':') || !TimeSpan.TryParse(text, CultureInfo.InvariantCulture, out var value))
{ {
errors[field] = "Format hh:mm:ss, zum Beispiel 00:00:10."; errors[field] = "Format hh:mm:ss (ab einem Tag d.hh:mm:ss), zum Beispiel 00:00:10.";
return null; return null;
} }
+18 -12
View File
@@ -5,19 +5,25 @@ 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 RepeatWindowDays = "Flypaper:RepeatWindowDays";
public const string ExtraKnownHosts = "Flypaper:Http:ExtraKnownHosts"; public const string RepeatHoldDuration = "Flypaper:RepeatHoldDuration";
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";
public const string DripMinDelay = "Flypaper:Drip:MinDelay";
public const string DripMaxDelay = "Flypaper:Drip:MaxDelay";
public const string DripMinChunkSize = "Flypaper:Drip:MinChunkSize";
public const string DripMaxChunkSize = "Flypaper:Drip:MaxChunkSize";
public const string DripHeadStartSize = "Flypaper:Drip:HeadStartSize";
public const string DripMatchPath = "Flypaper:Drip:MatchPath";
public const string DripBaitPaths = "Flypaper:Drip:BaitPaths";
public const string DripLinkSpacing = "Flypaper:Drip:LinkSpacing";
public static readonly IReadOnlySet<string> All = new HashSet<string>(StringComparer.OrdinalIgnoreCase) public static readonly IReadOnlyList<string> General =
{ [MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
MaxConnections,
MaxConnectionsPerIp, public static readonly IReadOnlyList<string> HoldMethod =
MaxHoldDuration, [DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration, RepeatWindowDays, RepeatHoldDuration];
TrapPaths,
ExtraKnownHosts, public static readonly IReadOnlySet<string> All =
IgnorePrivateNetworks, new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
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);
}
+52
View File
@@ -0,0 +1,52 @@
using System.Text.RegularExpressions;
namespace Flypaper.Core.Strategies;
public static partial class BaitPaths
{
public const int MaxCount = 8;
public const string Default = "/backup-2024/,/admin-old/,/internal/db-export/,/old-site/";
[GeneratedRegex("^/[A-Za-z0-9._~-]+(/[A-Za-z0-9._~-]+)*/?$")]
private static partial Regex Valid();
public static IReadOnlyList<string> Split(string? raw) =>
(raw ?? "").Split([',', ';', ' ', '\n', '\r', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
public static string? Normalize(string entry)
{
if (!Valid().IsMatch(entry) || entry.Length > 100)
{
return null;
}
var normalized = entry.ToLowerInvariant();
if (!normalized.EndsWith('/'))
{
normalized += "/";
}
var first = normalized.Split('/', StringSplitOptions.RemoveEmptyEntries)[0];
return normalized == RobotsStaticStrategy.Path + "/" || Array.IndexOf(MazeContent.Roots, first) >= 0 ? null : normalized;
}
public static IReadOnlyList<string> Parse(string? raw) =>
Split(raw).Select(Normalize).OfType<string>().Distinct().Take(MaxCount).ToList();
public static bool Matches(IReadOnlyList<string> baits, string? path)
{
if (string.IsNullOrEmpty(path) || baits.Count == 0)
{
return false;
}
var normalized = path.ToLowerInvariant();
if (!normalized.EndsWith('/'))
{
normalized += "/";
}
return baits.Any(bait => normalized.StartsWith(bait, StringComparison.Ordinal));
}
}
@@ -11,4 +11,16 @@ public sealed class DripOptions
public int MinChunkSize { get; set; } = 1; public int MinChunkSize { get; set; } = 1;
public int MaxChunkSize { get; set; } = 64; public int MaxChunkSize { get; set; } = 64;
public int HeadStartSize { get; set; } = 1024;
public bool MatchPath { get; set; } = true;
public int LinkSpacing { get; set; } = 160;
public bool Signposts { get; set; } = true;
public bool Lure { get; set; } = true;
public string BaitPaths { get; set; } = Strategies.BaitPaths.Default;
} }
@@ -5,6 +5,25 @@ namespace Flypaper.Core.Strategies;
public static class DripSchedule public static class DripSchedule
{ {
public static ReadOnlyMemory<byte> TakeHead(IEnumerator<string> fragments, int minBytes)
{
var head = new List<byte>();
while (head.Count < minBytes && fragments.MoveNext())
{
head.AddRange(Encoding.UTF8.GetBytes(fragments.Current));
}
return head.ToArray();
}
public static IEnumerable<string> Remaining(IEnumerator<string> fragments)
{
while (fragments.MoveNext())
{
yield return fragments.Current;
}
}
public static IEnumerable<DripStep> Create(IEnumerable<string> content, IRandomSource random, DripOptions options) public static IEnumerable<DripStep> Create(IEnumerable<string> content, IRandomSource random, DripOptions options)
{ {
var minChunk = Math.Max(1, options.MinChunkSize); var minChunk = Math.Max(1, options.MinChunkSize);
@@ -0,0 +1,50 @@
using System.Globalization;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public abstract class DripStrategy(
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : ITarpitStrategy, IStrategyDetails
{
public abstract string Name { get; }
public abstract string MediaType { get; }
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public string Describe()
{
var current = options.CurrentValue;
var head = current.HeadStartSize > 0 ? $" head {current.HeadStartSize}B" : "";
return string.Create(
CultureInfo.InvariantCulture,
$"{Name} {current.MinDelay.TotalMilliseconds:0}-{current.MaxDelay.TotalMilliseconds:0}ms {current.MinChunkSize}-{current.MaxChunkSize}B{head}{Extra(current)}");
}
public async Task RunAsync(ITrapChannel channel, CancellationToken ct)
{
var current = options.CurrentValue;
using var fragments = Content(random, channel, current).GetEnumerator();
var head = DripSchedule.TakeHead(fragments, current.HeadStartSize);
if (head.Length > 0)
{
await channel.WriteAsync(head, ct);
}
foreach (var step in DripSchedule.Create(DripSchedule.Remaining(fragments), random, current))
{
ct.ThrowIfCancellationRequested();
await channel.WriteAsync(step.Chunk, ct);
await Task.Delay(step.Delay, timeProvider, ct);
}
}
protected virtual string Extra(DripOptions options) => "";
protected abstract IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options);
}
+219
View File
@@ -0,0 +1,219 @@
using System.Globalization;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public sealed record FileProfile(
string Name,
string MediaType,
Func<string, bool> Matches,
Func<IRandomSource, SignpostLinks?, IEnumerable<string>> Generate);
public static class FileContent
{
public static readonly IReadOnlyList<FileProfile> Profiles =
[
new("git-drip", "text/plain; charset=utf-8", IsGit, GitConfig),
new("svn-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.svn"), (random, _) => Svn(random)),
new("hg-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.hg"), (random, _) => Mercurial(random)),
new("wordpress-drip", "text/html; charset=UTF-8", path => LastSegment(path) == "wp-login.php", (random, _) => WordPressLogin(random)),
new("hikvision-drip", "application/xml", path => path.StartsWith("/sdk/", StringComparison.Ordinal) || path.StartsWith("/isapi/", StringComparison.Ordinal), (random, _) => Hikvision(random)),
new("env-drip", "text/plain; charset=utf-8", path => IsEnv(LastSegment(path)), Env),
new("json-drip", "application/json", path => path.EndsWith(".json", StringComparison.Ordinal), Json),
new("xml-drip", "application/xml", path => path.EndsWith(".xml", StringComparison.Ordinal), (random, _) => Xml(random)),
new("yaml-drip", "text/plain; charset=utf-8", path => path.EndsWith(".yml", StringComparison.Ordinal) || path.EndsWith(".yaml", StringComparison.Ordinal), Yaml),
new("sql-drip", "text/plain; charset=utf-8", path => path.EndsWith(".sql", StringComparison.Ordinal), Sql)
];
public static FileProfile? Match(string? path)
{
if (string.IsNullOrEmpty(path))
{
return null;
}
var normalized = path.ToLowerInvariant();
return Profiles.FirstOrDefault(profile => profile.Matches(normalized));
}
private static bool IsInside(string path, string directory) =>
path.Contains(directory + "/", StringComparison.Ordinal) || path.EndsWith(directory, StringComparison.Ordinal);
private static bool IsGit(string path) => IsInside(path, "/.git") || LastSegment(path).StartsWith(".git", StringComparison.Ordinal);
private static string LastSegment(string path) => path[(path.LastIndexOf('/') + 1)..];
private static bool IsEnv(string name) =>
name.StartsWith(".env", StringComparison.Ordinal) || name.EndsWith(".env", StringComparison.Ordinal) || name == "env";
private static IEnumerable<string> Env(IRandomSource random, SignpostLinks? links)
{
var appUrl = links is { BaseUrl.Length: > 0 } ? links.BaseUrl : "https://example.com";
var signposts = links is null ? "" : $"BACKUP_URL={links.Backup}\nADMIN_URL={links.Admin}\nCONFIG_URL={links.Settings}\n\n";
yield return $"APP_NAME=Portal\nAPP_ENV=production\nAPP_DEBUG=false\nAPP_URL={appUrl}\nAPP_KEY=base64:{Hex(random, 32)}\n\n"
+ $"DB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=app\nDB_USERNAME=app\nDB_PASSWORD={Hex(random, 16)}\n\n"
+ signposts;
while (true)
{
var key = $"{Upper(random)}_{Upper(random)}";
yield return random.Next(0, 4) switch
{
0 => $"{key}=true\n",
1 => $"{key}={random.Next(1, 65536)}\n",
2 => $"{key}=https://{LoremText.Word(random)}.internal/\n",
_ => $"{key}={Hex(random, 24)}\n"
};
}
}
private static IEnumerable<string> WordPressLogin(IRandomSource random)
{
yield return """
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Log In &lsaquo; Portal &#8212; WordPress</title>
<meta name='robots' content='max-image-preview:large, noindex, noarchive' />
<link rel='stylesheet' id='login-css' href='/wp-admin/css/login.min.css?ver=6.4.3' media='all' />
<meta name='viewport' content='width=device-width' />
</head>
<body class="login no-js login-action-login wp-core-ui locale-en-us">
<div id="login">
<h1><a href="https://wordpress.org/">Powered by WordPress</a></h1>
<form name="loginform" id="loginform" action="/wp-login.php" method="post">
<p>
<label for="user_login">Username or Email Address</label>
<input type="text" name="log" id="user_login" class="input" value="" size="20" autocapitalize="off" autocomplete="username" required="required" />
</p>
<div class="user-pass-wrap">
<label for="user_pass">Password</label>
<input type="password" name="pwd" id="user_pass" class="input password-input" value="" size="20" autocomplete="current-password" required="required" />
</div>
<p class="submit">
<input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" />
<input type="hidden" name="redirect_to" value="/wp-admin/" />
<input type="hidden" name="testcookie" value="1" />
</p>
</form>
<p id="nav"><a href="/wp-login.php?action=lostpassword">Lost your password?</a></p>
<p id="backtoblog"><a href="/">&larr; Go to Portal</a></p>
</div>
""";
while (true)
{
yield return $"<!-- {Hex(random, 32)} -->\n";
}
}
private static IEnumerable<string> Hikvision(IRandomSource random)
{
yield return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<LanguageList version=\"2.0\" xmlns=\"http://www.hikvision.com/ver20/XMLSchema\">\n";
var id = 1;
while (true)
{
yield return $" <Language>\n <id>{id++}</id>\n <name>{LoremText.Word(random)}</name>\n <enabled>{(random.Next(0, 2) == 0 ? "true" : "false")}</enabled>\n </Language>\n";
}
}
private static IEnumerable<string> Json(IRandomSource random, SignpostLinks? links)
{
var signposts = links is null ? "" : $" \"backup_url\": \"{links.Backup}\",\n \"api_base\": \"{links.Settings}\",\n";
yield return "{\n \"name\": \"portal\",\n \"version\": \"1.4.2\",\n \"private\": true,\n" + signposts + " \"entries\": [\n";
var id = 1;
while (true)
{
yield return $" {{\"id\": {id++}, \"name\": \"{LoremText.Word(random)}\", \"token\": \"{Hex(random, 16)}\", \"enabled\": {(random.Next(0, 2) == 0 ? "true" : "false")}}},\n";
}
}
private static IEnumerable<string> Xml(IRandomSource random)
{
yield return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n";
while (true)
{
var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}");
yield return $" <url>\n <loc>https://example.com/{Pick(random, MazeContent.Roots)}/{LoremText.Phrase(random, 2).Replace(' ', '-')}</loc>\n <lastmod>{date}</lastmod>\n </url>\n";
}
}
private static IEnumerable<string> Yaml(IRandomSource random, SignpostLinks? links)
{
var signposts = links is null ? "" : $"x-backup:\n backup_url: {links.Backup}\n api_base: {links.Settings}\n";
yield return "version: \"3.8\"\n" + signposts + "services:\n";
while (true)
{
yield return $" {LoremText.Word(random)}:\n image: {LoremText.Word(random)}:{random.Next(1, 10)}.{random.Next(0, 20)}\n restart: unless-stopped\n environment:\n - SECRET={Hex(random, 12)}\n";
}
}
private static IEnumerable<string> Sql(IRandomSource random, SignpostLinks? links)
{
var signpost = links is null ? "" : $"-- Previous full dump: {links.Backup}\n";
yield return "-- MySQL dump 10.13 Distrib 8.0.36, for Linux (x86_64)\n--\n-- Host: localhost Database: app\n" + signpost + "-- ------------------------------------------------------\n\n"
+ "DROP TABLE IF EXISTS `users`;\nCREATE TABLE `users` (\n `id` int NOT NULL AUTO_INCREMENT,\n `name` varchar(64) NOT NULL,\n `token` varchar(64) NOT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n\n"
+ "LOCK TABLES `users` WRITE;\n";
var id = 1;
while (true)
{
yield return $"INSERT INTO `users` VALUES ({id++},'{LoremText.Word(random)}','{Hex(random, 32)}');\n";
}
}
private static IEnumerable<string> GitConfig(IRandomSource random, SignpostLinks? links)
{
var remote = links?.Repository ?? "https://example.com/portal.git";
yield return "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n"
+ $"[remote \"origin\"]\n\turl = {remote}\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n";
while (true)
{
var branch = $"{LoremText.Word(random)}-{LoremText.Word(random)}";
yield return $"[branch \"{branch}\"]\n\tremote = origin\n\tmerge = refs/heads/{branch}\n";
}
}
private static IEnumerable<string> Svn(IRandomSource random)
{
yield return "12\n\ndir\n4821\nhttps://svn.example.com/repos/portal/trunk\nhttps://svn.example.com/repos/portal\n2026-03-14T09:21:07.512340Z\n4821\ndeploy\n\n\n\n\n\n\n\n";
while (true)
{
var date = string.Create(CultureInfo.InvariantCulture, $"2026-{random.Next(1, 13):00}-{random.Next(1, 29):00}T{random.Next(0, 24):00}:{random.Next(0, 60):00}:{random.Next(0, 60):00}.{random.Next(0, 1_000_000):000000}Z");
yield return $"{LoremText.Word(random)}-{LoremText.Word(random)}.php\nfile\n\n\n{date}\n{Hex(random, 32)}\n{date}\ndeploy\n{random.Next(200, 90_000)}\n\n\n\n\n";
}
}
private static IEnumerable<string> Mercurial(IRandomSource random)
{
yield return "dotencode\nfncache\ngeneraldelta\nrevlogv1\nsparserevlog\nstore\n";
while (true)
{
yield return $"data/{Pick(random, MazeContent.Roots)}/{LoremText.Word(random)}-{LoremText.Word(random)}.php.i\n";
}
}
private static string Hex(IRandomSource random, int length)
{
var chars = new char[length];
for (var i = 0; i < length; i++)
{
chars[i] = "0123456789abcdef"[random.Next(0, 16)];
}
return new string(chars);
}
private static string Upper(IRandomSource random) => LoremText.Word(random).ToUpperInvariant();
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
}
@@ -0,0 +1,18 @@
using Flypaper.Core.Abstractions;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class FileDripStrategy(
FileProfile profile,
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
{
public override string Name => profile.Name;
public override string MediaType => profile.MediaType;
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) =>
profile.Generate(random, options.Signposts ? SignpostLinks.For(channel) : null);
}
+5 -27
View File
@@ -14,24 +14,6 @@ public static class HtmlContent
a { color: #0b5cad; } 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 = private static readonly string[] Sections =
["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"]; ["docs", "blog", "wiki", "support", "products", "archive", "news", "help", "files", "guides", "kb", "releases"];
@@ -78,7 +60,7 @@ public static class HtmlContent
var count = random.Next(3, 7); var count = random.Next(3, 7);
for (var i = 0; i < count; i++) for (var i = 0; i < count; i++)
{ {
builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{Capitalize(Pick(random, Vocabulary))}</a>\n"); builder.Append($"<a href=\"/{Pick(random, Sections)}/\">{LoremText.Capitalize(LoremText.Word(random))}</a>\n");
} }
return builder.Append("</nav>\n").ToString(); return builder.Append("</nav>\n").ToString();
@@ -145,8 +127,8 @@ public static class HtmlContent
continue; continue;
} }
var word = Pick(random, Vocabulary); var word = LoremText.Word(random);
builder.Append(i == 0 ? Capitalize(word) : word); builder.Append(i == 0 ? LoremText.Capitalize(word) : word);
} }
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString(); return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
@@ -154,17 +136,13 @@ public static class HtmlContent
private static string Link(IRandomSource random, int words) private static string Link(IRandomSource random, int words)
{ {
var text = Phrase(random, words); var text = LoremText.Phrase(random, words);
var slug = text.Replace(' ', '-'); var slug = text.Replace(' ', '-');
return $"<a href=\"/{Pick(random, Sections)}/{slug}\">{text}</a>"; 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 Title(IRandomSource random, int min, int max) => LoremText.Capitalize(LoremText.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 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..];
} }
@@ -1,5 +1,4 @@
using Flypaper.Core.Abstractions; using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies; namespace Flypaper.Core.Strategies;
@@ -7,19 +6,13 @@ namespace Flypaper.Core.Strategies;
public sealed class HtmlDripStrategy( public sealed class HtmlDripStrategy(
IOptionsMonitor<DripOptions> options, IOptionsMonitor<DripOptions> options,
IRandomSource random, IRandomSource random,
TimeProvider timeProvider) : ITarpitStrategy TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
{ {
public string Name => "html-drip"; public const string StrategyName = "html-drip";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http; public override string Name => StrategyName;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct) public override string MediaType => "text/html; charset=utf-8";
{
foreach (var step in DripSchedule.Create(HtmlContent.Generate(random), random, options.CurrentValue)) protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => HtmlContent.Generate(random);
{
ct.ThrowIfCancellationRequested();
await channel.WriteAsync(step.Chunk, ct);
await Task.Delay(step.Delay, timeProvider, ct);
}
}
} }
+50
View File
@@ -0,0 +1,50 @@
using System.Text;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
internal static class LoremText
{
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"
];
public static string Word(IRandomSource random) => Vocabulary[random.Next(0, Vocabulary.Length)];
public static string Phrase(IRandomSource random, int count) =>
string.Join(' ', Enumerable.Range(0, count).Select(_ => Word(random)));
public static string Sentence(IRandomSource random)
{
var builder = new StringBuilder();
var words = random.Next(4, 21);
for (var i = 0; i < words; i++)
{
if (i > 0)
{
builder.Append(i > 2 && random.Next(0, 9) == 0 ? ", " : " ");
}
var word = Word(random);
builder.Append(i == 0 ? Capitalize(word) : word);
}
return builder.Append(random.Next(0, 10) == 0 ? '?' : '.').ToString();
}
public static string Capitalize(string value) => value.Length == 0 ? value : char.ToUpperInvariant(value[0]) + value[1..];
}
@@ -0,0 +1,90 @@
using System.Text;
namespace Flypaper.Core.Strategies;
public static class LureContent
{
public const string PagePath = "/";
public const string IconPath = "/favicon.ico";
public static readonly IReadOnlyDictionary<string, string> Headers = new Dictionary<string, string>
{
["X-Powered-By"] = "PHP/8.1.27",
["Link"] = "</wp-json/>; rel=\"https://api.w.org/\""
};
public static bool Handles(string? path) =>
string.Equals(path, PagePath, StringComparison.Ordinal) || string.Equals(path, IconPath, StringComparison.OrdinalIgnoreCase);
public static byte[] Page() => Encoding.UTF8.GetBytes("""
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="WordPress 6.4.3">
<title>Intranet &#8211; Just another WordPress site</title>
<link rel="icon" href="/favicon.ico">
<link rel="stylesheet" href="/wp-content/themes/twentytwentyfour/style.css?ver=1.0">
<link rel="alternate" type="application/rss+xml" title="Intranet &raquo; Feed" href="/feed/">
<link rel="https://api.w.org/" href="/wp-json/">
<link rel="EditURI" type="application/rsd+xml" title="RSD" href="/xmlrpc.php?rsd">
</head>
<body class="home blog">
<header><h1>Intranet</h1><p>Just another WordPress site</p></header>
<nav>
<a href="/wp-login.php">Log in</a>
<a href="/wp-admin/">Dashboard</a>
<a href="/wp-content/uploads/backup/">Backups</a>
<a href="/wp-config.php.bak">Config</a>
</nav>
<main><article><h2>Hello world!</h2><p>Welcome to WordPress. This is your first post. Edit or delete it, then start writing!</p></article></main>
<footer><p>Proudly powered by <a href="https://wordpress.org/">WordPress</a></p></footer>
</body>
</html>
""");
public static byte[] Icon()
{
const int size = 16;
using var stream = new MemoryStream();
using var writer = new BinaryWriter(stream);
writer.Write((ushort)0);
writer.Write((ushort)1);
writer.Write((ushort)1);
writer.Write((byte)size);
writer.Write((byte)size);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((ushort)1);
writer.Write((ushort)32);
var imageSize = 40 + size * size * 4 + size * 4;
writer.Write(imageSize);
writer.Write(22);
writer.Write(40);
writer.Write(size);
writer.Write(size * 2);
writer.Write((ushort)1);
writer.Write((ushort)32);
writer.Write(0);
writer.Write(size * size * 4);
writer.Write(0);
writer.Write(0);
writer.Write(0);
writer.Write(0);
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
{
var dx = x - 7.5;
var dy = y - 7.5;
var inside = dx * dx + dy * dy <= 56;
writer.Write(inside ? 0xFF8A5A21u : 0u);
}
}
writer.Write(new byte[size * 4]);
return stream.ToArray();
}
}
@@ -0,0 +1,27 @@
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
namespace Flypaper.Core.Strategies;
public sealed class LureStrategy(string name, string mediaType, byte[] body) : ITarpitStrategy, IStrategyDetails, IResponseHeaders
{
public const string PageName = "lure-page";
public const string IconName = "lure-icon";
public static LureStrategy Page() => new(PageName, "text/html; charset=utf-8", LureContent.Page());
public static LureStrategy Icon() => new(IconName, "image/x-icon", LureContent.Icon());
public string Name => name;
public string MediaType => mediaType;
public IReadOnlyDictionary<string, string> Headers => LureContent.Headers;
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public string Describe() => Name;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct) => await channel.WriteAsync(body, ct);
}
+231
View File
@@ -0,0 +1,231 @@
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public static partial class MazeContent
{
public static readonly string[] Roots =
["wiki", "docs", "blog", "backup", "archive", "files", "kb", "guides", "releases", "news", "help", "support", "products"];
private const int MaxDepth = 6;
public static bool IsDirectory(string? path) => path is { Length: > 1 } && path[^1] == '/';
public static IEnumerable<string> Page(IRandomSource random, string? path, string? host, int spacing)
{
var site = new Site(path, host);
var siteName = site.Host ?? "Portal";
var title = $"{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 4)))} · {siteName}";
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>body{margin:0 auto;max-width:52rem;padding:1.5rem;font:16px/1.6 system-ui,sans-serif}nav a{margin-right:1rem}</style>
</head>
<body>
<header>
<h1>{{title}}</h1>
""";
yield return Navigation(random, site);
yield return "</header>\n<main>\n<h2>Related pages</h2>\n" + List(random, site, random.Next(7, 11));
yield return "<p>";
var minFiller = Math.Max(1, spacing / 2);
var maxFiller = Math.Max(minFiller, spacing * 3 / 2);
while (true)
{
var words = Math.Max(2, random.Next(minFiller, maxFiller + 1) / 7);
yield return $"{LoremText.Capitalize(LoremText.Phrase(random, words))}. {Anchor(random, site)} ";
switch (random.Next(0, 8))
{
case 0:
yield return $"</p>\n{List(random, site, random.Next(3, 6))}<p>";
break;
case 1:
yield return $"</p>\n<h3>{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 6)))}</h3>\n<p>";
break;
}
}
}
public static IEnumerable<string> Listing(IRandomSource random, string? path, string? host)
{
var site = new Site(path, host);
var shown = WebUtility.HtmlEncode(site.DisplayPath);
var wide = site.Section is "backup" or "files" or "archive";
yield return $$"""
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of {{shown}}</title>
</head>
<body>
<h1>Index of {{shown}}</h1>
<pre>Name{{new string(' ', 46)}}Last modified Size
<hr><a href="../">Parent Directory</a> -
""";
while (true)
{
yield return Entry(random, site, wide);
}
}
private static string Entry(IRandomSource random, Site site, bool wide)
{
var slug = Slug(random, site);
var directory = random.Next(0, 3) == 0;
var name = directory
? slug + "/"
: wide
? $"{slug}-{Date(random)[..10]}{Pick(random, [".tar.gz", ".zip", ".bak", ".gz"])}"
: $"{slug}{Pick(random, [".html", ".html", ".htm", ".txt"])}";
var size = directory
? "-"
: random.Next(0, 4) == 0
? string.Create(CultureInfo.InvariantCulture, $"{random.Next(1, 900)}.{random.Next(0, 10)}M")
: string.Create(CultureInfo.InvariantCulture, $"{random.Next(1, 900)}K");
var href = random.Next(0, 5) == 0 ? Absolute(random, site) : name;
var padding = new string(' ', Math.Max(1, 50 - name.Length));
return $"<a href=\"{href}\">{name}</a>{padding}{Date(random)} {size}\n";
}
private static string Date(IRandomSource random) =>
string.Create(CultureInfo.InvariantCulture, $"{random.Next(2022, 2027)}-{random.Next(1, 13):00}-{random.Next(1, 29):00} {random.Next(0, 24):00}:{random.Next(0, 60):00}");
private static string Navigation(IRandomSource random, Site site)
{
var builder = new StringBuilder("<nav>\n");
var count = random.Next(8, 12);
for (var i = 0; i < count; i++)
{
builder.Append($"<a href=\"{Href(random, site, rootOnly: i % 2 == 0)}\">{LoremText.Capitalize(LoremText.Word(random))}</a>\n");
}
return builder.Append("</nav>\n").ToString();
}
private static string List(IRandomSource random, Site site, int items)
{
var builder = new StringBuilder("<ul>\n");
for (var i = 0; i < items; i++)
{
builder.Append($"<li>{Anchor(random, site)}</li>\n");
}
return builder.Append("</ul>\n").ToString();
}
private static string Anchor(IRandomSource random, Site site) =>
$"<a href=\"{Href(random, site)}\">{LoremText.Capitalize(LoremText.Phrase(random, random.Next(2, 5)))}</a>";
private static string Href(IRandomSource random, Site site, bool rootOnly = false)
{
if (rootOnly)
{
return $"/{Pick(random, Roots)}/";
}
var kind = random.Next(0, 10);
if (site.Section is null)
{
kind = 5 + kind % 5;
}
else if (site.Depth >= MaxDepth && kind is 0 or 3)
{
kind = 4;
}
return kind switch
{
0 => $"{Slug(random, site)}/",
1 or 2 => Slug(random, site),
3 => $"{LoremText.Word(random)}/{Slug(random, site)}",
4 => random.Next(0, 2) == 0 ? "../" : $"../{Slug(random, site)}",
< 8 => Absolute(random, site),
_ => site.Host is { } host ? $"http://{host}{Absolute(random, site)}" : Absolute(random, site)
};
}
private static string Absolute(IRandomSource random, Site site)
{
var root = site.Section is { } section && random.Next(0, 10) < 7 ? section : Pick(random, Roots);
var slug = Slug(random, site);
return root switch
{
"docs" => $"/docs/v{random.Next(1, 5)}/{slug}",
"blog" => string.Create(CultureInfo.InvariantCulture, $"/blog/{random.Next(2022, 2027)}/{random.Next(1, 13):00}/{slug}"),
"backup" => string.Create(CultureInfo.InvariantCulture, $"/backup/{random.Next(2022, 2027)}/{random.Next(1, 13):00}/"),
_ => random.Next(0, 3) == 0 ? $"/{root}/{slug}/" : $"/{root}/{slug}"
};
}
private static string Slug(IRandomSource random, Site site)
{
var words = new List<string>();
var count = random.Next(1, 4);
for (var i = 0; i < count; i++)
{
words.Add(LoremText.Word(random));
}
if (site.Topic is { } topic && random.Next(0, 4) == 0)
{
words[0] = topic;
}
return string.Join('-', words);
}
private static string Pick(IRandomSource random, string[] values) => values[random.Next(0, values.Length)];
[GeneratedRegex("^[A-Za-z0-9.-]{1,253}$")]
private static partial Regex HostPattern();
[GeneratedRegex("^[a-z]{3,}$")]
private static partial Regex TopicPattern();
private sealed class Site
{
public Site(string? path, string? host)
{
var normalized = (path ?? "/").ToLowerInvariant();
var segments = normalized.Split('/', StringSplitOptions.RemoveEmptyEntries);
var endsWithSlash = normalized.EndsWith('/');
Section = segments.Length > 0 && Array.IndexOf(Roots, segments[0]) >= 0 ? segments[0] : null;
Depth = endsWithSlash ? segments.Length : Math.Max(0, segments.Length - 1);
Host = host is not null && HostPattern().IsMatch(host) ? host : null;
DisplayPath = normalized.Length > 200 ? normalized[..200] : normalized;
if (!endsWithSlash && segments.Length > 0)
{
var word = segments[^1].Split('-', '.', '_')[0];
Topic = TopicPattern().IsMatch(word) ? word : null;
}
}
public string? Section { get; }
public int Depth { get; }
public string? Host { get; }
public string? Topic { get; }
public string DisplayPath { get; }
}
}
@@ -0,0 +1,44 @@
using System.Globalization;
using Flypaper.Core.Abstractions;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public enum MazeKind
{
Page,
Listing,
Bait
}
public sealed class MazeDripStrategy(
MazeKind kind,
IOptionsMonitor<DripOptions> options,
IRandomSource random,
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider), IHoldExtension
{
public const string PageName = "maze-drip";
public const string ListingName = "index-drip";
public const string BaitName = "robots-bait";
public override string Name => kind switch
{
MazeKind.Listing => ListingName,
MazeKind.Bait => BaitName,
_ => PageName
};
public override string MediaType => "text/html; charset=utf-8";
public TimeSpan MinimumHold => kind == MazeKind.Bait ? TimeSpan.FromHours(24) : TimeSpan.Zero;
protected override string Extra(DripOptions options) =>
string.Create(CultureInfo.InvariantCulture, $" link {options.LinkSpacing}B");
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) =>
kind == MazeKind.Listing || kind == MazeKind.Bait && MazeContent.IsDirectory(channel.Path)
? MazeContent.Listing(random, channel.Path, channel.Host)
: MazeContent.Page(random, channel.Path, channel.Host, options.LinkSpacing);
}
@@ -0,0 +1,27 @@
using System.Text;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.Extensions.Options;
namespace Flypaper.Core.Strategies;
public sealed class RobotsStaticStrategy(IOptionsMonitor<DripOptions> options) : ITarpitStrategy, IStrategyDetails
{
public const string StrategyName = "robots-static";
public const string Path = "/robots.txt";
public string Name => StrategyName;
public string MediaType => "text/plain; charset=utf-8";
public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http;
public string Describe() => Name;
public async Task RunAsync(ITrapChannel channel, CancellationToken ct) =>
await channel.WriteAsync(Encoding.UTF8.GetBytes(Body()), ct);
public string Body() =>
"User-agent: *\nDisallow: /\n" + string.Concat(BaitPaths.Parse(options.CurrentValue.BaitPaths).Select(bait => $"Disallow: {bait}\n"));
}
@@ -0,0 +1,28 @@
using System.Text.RegularExpressions;
using Flypaper.Core.Abstractions;
namespace Flypaper.Core.Strategies;
public sealed partial record SignpostLinks(string BaseUrl, string Marker)
{
public const int MarkerLength = 12;
public string Backup => $"{BaseUrl}/backup/db-{Marker}.sql";
public string Admin => $"{BaseUrl}/admin-{Marker}/";
public string Settings => $"{BaseUrl}/storage/settings-{Marker}.json";
public string Repository => $"{BaseUrl}/git-{Marker}/portal.git";
public static string MarkerOf(Guid sessionId) => sessionId.ToString("N")[..MarkerLength];
public static SignpostLinks For(ITrapChannel channel)
{
var baseUrl = channel.Host is { } host && HostPattern().IsMatch(host) ? $"http://{host}" : "";
return new SignpostLinks(baseUrl, MarkerOf(channel.Session.Id));
}
[GeneratedRegex(@"^[A-Za-z0-9.-]{1,253}\z")]
private static partial Regex HostPattern();
}
+20 -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,19 @@ 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",
"Flypaper:Drip:Content"
];
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 +52,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;
} }
+4
View File
@@ -8,6 +8,10 @@ internal sealed class HttpTrapChannel(TrapSession session, HttpResponse response
{ {
public TrapSession Session => session; public TrapSession Session => session;
public string? Path => response.HttpContext.Request.Path.Value;
public string? Host => response.HttpContext.Request.Host.Host;
public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct) public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
{ {
await response.Body.WriteAsync(data, ct); await response.Body.WriteAsync(data, ct);
-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;
}
}
@@ -1,9 +1,10 @@
using System.Net; using System.Net;
using Flypaper.Core;
using Flypaper.Core.Abstractions; 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 Flypaper.Core.Strategies;
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,9 +14,11 @@ 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,
IKnownIpLookup knownIps,
IOptionsMonitor<DripOptions> drip,
IOptionsMonitor<FlypaperOptions> options,
TimeProvider timeProvider) TimeProvider timeProvider)
{ {
public async Task InvokeAsync(HttpContext context) public async Task InvokeAsync(HttpContext context)
@@ -27,11 +30,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(),
@@ -39,14 +37,29 @@ internal sealed class FlypaperMiddleware(
context.Connection.RemoteIpAddress ?? IPAddress.None, context.Connection.RemoteIpAddress ?? IPAddress.None,
timeProvider.GetUtcNow()); timeProvider.GetUtcNow());
var isNewIp = drip.CurrentValue.Lure
&& HttpMethods.IsGet(request.Method)
&& LureContent.Handles(request.Path.Value)
&& !await knownIps.HasSeenAsync(session.RemoteIp, context.RequestAborted);
var capture = options.CurrentValue.CaptureRequests ? new RequestCapture(context) : null;
var trapContext = new TrapContext( var trapContext = new TrapContext(
session, session,
$"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}", $"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}",
request.Headers.UserAgent.ToString()); request.Headers.UserAgent.ToString(),
request.Path.Value,
isNewIp,
capture);
var outcome = await runner.RunAsync( var outcome = await runner.RunAsync(
trapContext, trapContext,
ct => OpenChannelAsync(context, session, ct), async (strategy, ct) =>
{
var channel = await OpenChannelAsync(context, session, strategy, ct);
capture?.Start();
return channel;
},
context.RequestAborted); context.RequestAborted);
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted) if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
@@ -66,6 +79,7 @@ internal sealed class FlypaperMiddleware(
private static async ValueTask<ITrapChannel> OpenChannelAsync( private static async ValueTask<ITrapChannel> OpenChannelAsync(
HttpContext context, HttpContext context,
TrapSession session, TrapSession session,
ITarpitStrategy strategy,
CancellationToken ct) CancellationToken ct)
{ {
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>(); var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
@@ -78,9 +92,18 @@ internal sealed class FlypaperMiddleware(
var response = context.Response; var response = context.Response;
response.StatusCode = StatusCodes.Status200OK; response.StatusCode = StatusCodes.Status200OK;
response.ContentType = "text/html; charset=utf-8"; response.ContentType = strategy is IStrategyDetails details ? details.MediaType : "text/html; charset=utf-8";
response.Headers.Server = "nginx";
response.Headers.CacheControl = "no-store"; response.Headers.CacheControl = "no-store";
response.Headers["X-Accel-Buffering"] = "no"; response.Headers["X-Accel-Buffering"] = "no";
if (strategy is IResponseHeaders extra)
{
foreach (var (name, value) in extra.Headers)
{
response.Headers[name] = value;
}
}
await response.StartAsync(ct); await response.StartAsync(ct);
return new HttpTrapChannel(session, response); return new HttpTrapChannel(session, response);
+172
View File
@@ -0,0 +1,172 @@
using System.Globalization;
using System.Text;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
namespace Flypaper.Http;
internal sealed class RequestCapture(HttpContext context) : IRequestCapture
{
public const int MaxBodyBytes = 8 * 1024;
private const int MaxHeaders = 64;
private const int MaxHeaderValueLength = 1024;
private const int MaxHeadersLength = 8 * 1024;
private static readonly TimeSpan ReadTimeout = TimeSpan.FromSeconds(5);
private static readonly TimeSpan CompletionGrace = TimeSpan.FromSeconds(1);
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
private readonly byte[] _buffer = new byte[MaxBodyBytes + 1];
private readonly CancellationTokenSource _stop = new();
private int _length;
private string? _headers;
private long? _contentLength;
private Task? _reading;
public void Start()
{
var request = context.Request;
_headers = FormatHeaders(request.Headers);
_contentLength = request.ContentLength;
if (request.ContentLength is not > 0 && request.Headers.TransferEncoding.Count == 0)
{
return;
}
if (context.Features.Get<IHttpMinRequestBodyDataRateFeature>() is { } rate)
{
rate.MinDataRate = null;
}
if (context.Features.Get<IHttpMaxRequestBodySizeFeature>() is { IsReadOnly: false } size)
{
size.MaxRequestBodySize = null;
}
_reading = ReadAsync(request.Body, context.RequestAborted);
}
public async ValueTask<RequestDetails?> CompleteAsync()
{
if (_headers is null)
{
return null;
}
if (_reading is { IsCompleted: false } pending)
{
await Task.WhenAny(pending, Task.Delay(CompletionGrace));
await _stop.CancelAsync();
}
if (_reading is not null)
{
await _reading;
}
var length = Volatile.Read(ref _length);
var kept = Math.Min(length, MaxBodyBytes);
return new RequestDetails(
_headers,
kept == 0 ? null : Printable(_buffer.AsSpan(0, kept)),
_contentLength,
length > MaxBodyBytes || _contentLength > kept);
}
private async Task ReadAsync(Stream body, CancellationToken aborted)
{
using var timeout = new CancellationTokenSource(ReadTimeout);
using var linked = CancellationTokenSource.CreateLinkedTokenSource(aborted, timeout.Token, _stop.Token);
try
{
while (_length < _buffer.Length)
{
var read = await body.ReadAsync(_buffer.AsMemory(_length), linked.Token);
if (read == 0)
{
break;
}
Volatile.Write(ref _length, _length + read);
}
}
catch (Exception ex) when (ex is OperationCanceledException or IOException or InvalidOperationException)
{
}
}
private static string FormatHeaders(IHeaderDictionary headers)
{
var text = new StringBuilder();
var count = 0;
foreach (var (name, values) in headers)
{
if (IsAddedByProxy(name))
{
continue;
}
foreach (var value in values)
{
if (++count > MaxHeaders || text.Length >= MaxHeadersLength)
{
return Limit(text.ToString(), MaxHeadersLength);
}
text.Append(Escape(name)).Append(": ").Append(Escape(Limit(value ?? "", MaxHeaderValueLength))).Append('\n');
}
}
return Limit(text.ToString(), MaxHeadersLength);
}
private static bool IsAddedByProxy(string name) =>
name.Equals("X-Real-IP", StringComparison.OrdinalIgnoreCase)
|| name.StartsWith("X-Forwarded-", StringComparison.OrdinalIgnoreCase)
|| name.StartsWith("X-Original-", StringComparison.OrdinalIgnoreCase);
private static string Limit(string value, int length) => value.Length > length ? value[..length] : value;
private static string Printable(ReadOnlySpan<byte> data)
{
try
{
return Escape(StrictUtf8.GetString(data));
}
catch (DecoderFallbackException)
{
var text = new StringBuilder(data.Length);
foreach (var value in data)
{
Append(text, (char)value, value > 0x7E);
}
return text.ToString();
}
}
private static string Escape(string value)
{
var text = new StringBuilder(value.Length);
foreach (var character in value)
{
Append(text, character, false);
}
return text.ToString();
}
private static void Append(StringBuilder text, char character, bool escape)
{
if (escape || (char.IsControl(character) && character is not ('\n' or '\r' or '\t')))
{
text.Append(CultureInfo.InvariantCulture, $"\\x{(int)character:X2}");
}
else
{
text.Append(character);
}
}
}
@@ -1,18 +1,20 @@
using Flypaper.Storage.Entities;
namespace Flypaper.Storage.Dashboard; namespace Flypaper.Storage.Dashboard;
public sealed record DashboardData( public sealed record DashboardData(
int TotalCatches, int TotalCatches,
int CatchesLast24Hours, int CatchesLast24Hours,
int Rejected, int Rejected,
int RejectedLast24Hours,
int UniqueIps, int UniqueIps,
int UniqueIpsLast24Hours,
TimeSpan TotalHoldTime, TimeSpan TotalHoldTime,
IReadOnlyList<TrapEventEntity> Recent,
IReadOnlyList<TopEntry> TopIps, IReadOnlyList<TopEntry> TopIps,
IReadOnlyList<TopEntry> TopTargets, IReadOnlyList<TopEntry> TopTargets,
IReadOnlyList<StrategySample> StrategyCatches,
IReadOnlyList<TopEntry> TopCountries, IReadOnlyList<TopEntry> TopCountries,
IReadOnlyList<TopEntry> TopProviders, IReadOnlyList<TopEntry> TopProviders,
IReadOnlyDictionary<string, int> CatchesByCountry); IReadOnlyDictionary<string, int> CatchesByCountry);
public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime, string? Label = null); public sealed record TopEntry(string Key, int Count, TimeSpan HoldTime, string? Label = null, TimeSpan? MedianHold = null);
public sealed record StrategySample(string Strategy, long DurationMs);
@@ -1,12 +1,12 @@
using Flypaper.Core.Models; using Flypaper.Core.Models;
using Flypaper.Storage.Entities; using Flypaper.Storage.Entities;
using Flypaper.Storage.Explanations;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Dashboard; namespace Flypaper.Storage.Dashboard;
public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider) public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider, ExplanationRuleStore explanations)
{ {
private const int RecentCount = 50;
private const int TopCount = 10; private const int TopCount = 10;
public async Task<DashboardData> GetAsync(CancellationToken ct = default) public async Task<DashboardData> GetAsync(CancellationToken ct = default)
@@ -37,11 +37,13 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
await catches.CountAsync(ct), await catches.CountAsync(ct),
await catches.CountAsync(e => e.StartedAt >= since, ct), await catches.CountAsync(e => e.StartedAt >= since, ct),
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct), await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected && e.StartedAt >= since, ct),
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct), await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
await events.Where(e => e.StartedAt >= since).Select(e => e.RemoteIp).Distinct().CountAsync(ct),
TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)), TimeSpan.FromMilliseconds(await catches.SumAsync(e => e.DurationMs, ct)),
await events.OrderByDescending(e => e.Id).Take(RecentCount).ToListAsync(ct),
await TopAsync(catches.GroupBy(e => e.RemoteIp), ct), await TopAsync(catches.GroupBy(e => e.RemoteIp), ct),
await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct), await TopAsync(catches.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
await catches.Select(e => new StrategySample(e.Strategy, e.DurationMs)).ToListAsync(ct),
countries countries
.Take(TopCount) .Take(TopCount)
.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name)) .Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
@@ -52,6 +54,116 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase)); countries.ToDictionary(x => x.Key, x => x.Count, StringComparer.OrdinalIgnoreCase));
} }
public async Task<RecentCatches> GetRecentAsync(RecentFilter filter, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = Apply(db.TrapEvents.AsNoTracking(), filter);
var countries = await db.TrapEvents
.Where(e => e.CountryCode != null)
.GroupBy(e => e.CountryCode!)
.Select(g => new CountryOption(g.Key, g.Max(e => e.Country)))
.ToListAsync(ct);
var ordered = events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id);
var take = Math.Clamp(filter.Limit, 1, RecentFilter.MaxLimit);
if (filter.Unexplained)
{
var rules = await explanations.GetRuleSetAsync(ct);
var candidates = await ordered.Where(e => e.Target != null).Select(e => new { e.Id, e.Target }).ToListAsync(ct);
var ids = candidates
.Where(c => rules.Winner(ExplanationKind.Target, ExplanationText.Path(c.Target)!) is null)
.Select(c => c.Id)
.ToList();
var page = ids.Take(take).ToList();
var items = (await db.TrapEvents.AsNoTracking().Where(e => page.Contains(e.Id)).ToListAsync(ct))
.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).ToList();
return new RecentCatches(items, ids.Count, countries, await WithRequestAsync(db, items, ct));
}
var recent = await ordered.Take(take).ToListAsync(ct);
return new RecentCatches(recent, await events.CountAsync(ct), countries, await WithRequestAsync(db, recent, ct));
}
private static async Task<IReadOnlySet<long>> WithRequestAsync(FlypaperDbContext db, IReadOnlyList<TrapEventEntity> events, CancellationToken ct)
{
var ids = events.Select(e => e.Id).ToList();
var recorded = await db.TrapRequests.Where(r => ids.Contains(r.TrapEventId)).Select(r => r.TrapEventId).ToListAsync(ct);
return recorded.ToHashSet();
}
private IQueryable<TrapEventEntity> Apply(IQueryable<TrapEventEntity> events, RecentFilter filter)
{
if (filter.Window is { } window)
{
var since = timeProvider.GetUtcNow().UtcDateTime - window;
events = events.Where(e => e.StartedAt >= since);
}
if (filter.WithCommand)
{
events = events.Where(e => e.Command != null);
}
if (filter.Outcome is { } outcome)
{
events = events.Where(e => e.Outcome == outcome);
}
if (filter.CountryCode is { } country)
{
events = events.Where(e => e.CountryCode == country);
}
if (filter.Asn is { } asn)
{
events = events.Where(e => e.Asn == asn);
}
if (filter.Ip is { } ip)
{
events = events.Where(e => e.RemoteIp == ip);
}
if (filter.Target is { } target)
{
events = events.Where(e => e.Target == target);
}
if (filter.Strategy is { } strategy)
{
var bases = strategy.Bases;
events = events.Where(e => bases.Any(name => e.Strategy == name || EF.Functions.Like(e.Strategy, name + " %", "\\")));
foreach (var flag in strategy.With)
{
var pattern = $"% {flag} %";
events = events.Where(e => EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
}
foreach (var flag in strategy.Without)
{
var pattern = $"% {flag} %";
events = events.Where(e => !EF.Functions.Like(" " + e.Strategy + " ", pattern, "\\"));
}
}
if (!string.IsNullOrWhiteSpace(filter.Search))
{
var pattern = $"%{filter.Search.Trim().Replace("\\", "\\\\").Replace("%", "\\%").Replace("_", "\\_")}%";
var strategyNames = filter.SearchStrategies ?? [];
events = events.Where(e =>
EF.Functions.Like(e.RemoteIp, pattern, "\\")
|| strategyNames.Any(name => e.Strategy == name || EF.Functions.Like(e.Strategy, name + " %", "\\"))
|| EF.Functions.Like(e.Provider!, pattern, "\\")
|| EF.Functions.Like(e.Target!, pattern, "\\")
|| EF.Functions.Like(e.Strategy, pattern, "\\")
|| EF.Functions.Like(e.ClientInfo!, pattern, "\\"));
}
return events;
}
private static async Task<IReadOnlyList<TopEntry>> TopAsync( private static async Task<IReadOnlyList<TopEntry>> TopAsync(
IQueryable<IGrouping<string, TrapEventEntity>> groups, IQueryable<IGrouping<string, TrapEventEntity>> groups,
CancellationToken ct) CancellationToken ct)
@@ -0,0 +1,28 @@
using Flypaper.Core.Models;
using Flypaper.Storage.Entities;
namespace Flypaper.Storage.Dashboard;
public sealed record RecentFilter(
TimeSpan? Window = null,
TrapOutcome? Outcome = null,
string? CountryCode = null,
long? Asn = null,
string? Ip = null,
string? Target = null,
StrategyMatch? Strategy = null,
string? Search = null,
int Limit = RecentFilter.DefaultLimit,
IReadOnlyList<string>? SearchStrategies = null,
bool Unexplained = false,
bool WithCommand = false)
{
public const int DefaultLimit = 50;
public const int MaxLimit = 500;
}
public sealed record RecentCatches(IReadOnlyList<TrapEventEntity> Items, int Total, IReadOnlyList<CountryOption> Countries, IReadOnlySet<long> WithRequest);
public sealed record CountryOption(string Code, string? Name);
public sealed record StrategyMatch(IReadOnlyList<string> Bases, IReadOnlyList<string> With, IReadOnlyList<string> Without);
@@ -0,0 +1,31 @@
namespace Flypaper.Storage.Entities;
public enum ExplanationKind
{
Target,
ClientInfo,
Outcome
}
public sealed class ExplanationRuleEntity
{
public int Id { get; set; }
public ExplanationKind Kind { get; set; }
public required string Pattern { get; set; }
public required string Text { get; set; }
public int Priority { get; set; }
public bool Enabled { get; set; } = true;
public string? Note { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public required string CreatedBy { get; set; }
}
@@ -0,0 +1,16 @@
namespace Flypaper.Storage.Entities;
public sealed class McpTokenEntity
{
public int Id { get; set; }
public required string Name { get; set; }
public required string TokenHash { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? LastUsedAt { get; set; }
public bool CanWrite { get; set; }
}
@@ -1,3 +1,4 @@
using Flypaper.Core.Analysis;
using Flypaper.Core.Models; using Flypaper.Core.Models;
namespace Flypaper.Storage.Entities; namespace Flypaper.Storage.Entities;
@@ -38,8 +39,34 @@ public sealed class TrapEventEntity
public string? Provider { get; set; } public string? Provider { get; set; }
public static TrapEventEntity From(TrapEvent trapEvent) => new() public TrapRequestEntity? Request { get; set; }
public string? Command { get; set; }
public string? CommandServer { get; set; }
public int CommandScan { get; set; }
public static TrapEventEntity From(TrapEvent trapEvent)
{ {
var entity = Map(trapEvent);
if (CommandDetector.Detect(trapEvent.Target, trapEvent.Request) is { } command)
{
entity.ApplyCommand(command);
}
return entity;
}
public void ApplyCommand(DetectedCommand command)
{
Command = command.Command;
CommandServer = command.Server;
}
private static TrapEventEntity Map(TrapEvent trapEvent) => new()
{
CommandScan = CommandDetector.Version,
SessionId = trapEvent.SessionId, SessionId = trapEvent.SessionId,
Protocol = trapEvent.Protocol, Protocol = trapEvent.Protocol,
RemoteIp = trapEvent.RemoteIp.ToString(), RemoteIp = trapEvent.RemoteIp.ToString(),
@@ -50,7 +77,8 @@ public sealed class TrapEventEntity
BytesSent = trapEvent.BytesSent, BytesSent = trapEvent.BytesSent,
Outcome = trapEvent.Outcome, Outcome = trapEvent.Outcome,
Target = Truncate(trapEvent.Target, FlypaperDbContext.MaxTextLength), Target = Truncate(trapEvent.Target, FlypaperDbContext.MaxTextLength),
ClientInfo = Truncate(trapEvent.ClientInfo, FlypaperDbContext.MaxTextLength) ClientInfo = Truncate(trapEvent.ClientInfo, FlypaperDbContext.MaxTextLength),
Request = trapEvent.Request is null ? null : TrapRequestEntity.From(trapEvent.Request)
}; };
public void ApplyOrigin(IpOrigin? origin) public void ApplyOrigin(IpOrigin? origin)
@@ -0,0 +1,26 @@
using Flypaper.Core.Models;
namespace Flypaper.Storage.Entities;
public sealed class TrapRequestEntity
{
public long Id { get; set; }
public long TrapEventId { get; set; }
public required string Headers { get; set; }
public string? Body { get; set; }
public long? ContentLength { get; set; }
public bool Truncated { get; set; }
public static TrapRequestEntity From(RequestDetails details) => new()
{
Headers = details.Headers,
Body = details.Body,
ContentLength = details.ContentLength,
Truncated = details.Truncated
};
}
@@ -0,0 +1,69 @@
using Flypaper.Core.Analysis;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace Flypaper.Storage.Events;
internal sealed partial class CommandBackfill(
IDbContextFactory<FlypaperDbContext> dbContextFactory,
ILogger<CommandBackfill> logger) : BackgroundService
{
private const int BatchSize = 500;
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
var found = await BackfillAsync(stoppingToken);
if (found > 0)
{
LogBackfilled(found);
}
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogBackfillFailed(ex);
}
}
internal async Task<int> BackfillAsync(CancellationToken ct)
{
var found = 0;
while (true)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var batch = await db.TrapEvents
.Include(e => e.Request)
.Where(e => e.CommandScan < CommandDetector.Version)
.OrderBy(e => e.Id)
.Take(BatchSize)
.ToListAsync(ct);
if (batch.Count == 0)
{
return found;
}
foreach (var trapEvent in batch)
{
if (CommandDetector.Detect(trapEvent.Target, trapEvent.Request?.Headers, trapEvent.Request?.Body) is { } command)
{
trapEvent.ApplyCommand(command);
found++;
}
trapEvent.CommandScan = CommandDetector.Version;
}
await db.SaveChangesAsync(ct);
}
}
[LoggerMessage(Level = LogLevel.Information, Message = "Found commands in {Count} stored trap events")]
private partial void LogBackfilled(int count);
[LoggerMessage(Level = LogLevel.Warning, Message = "Command backfill failed")]
private partial void LogBackfillFailed(Exception exception);
}
@@ -0,0 +1,11 @@
namespace Flypaper.Storage.Explanations;
public static class ExplanationLimits
{
public const int MaxPatternLength = 500;
public const int MaxTextLength = 600;
public const int MaxNoteLength = 500;
public const int MaxCreatedByLength = 100;
public const int MaxPriority = 1000;
public const int MaxRules = 2000;
}
@@ -0,0 +1,186 @@
using Flypaper.Storage.Entities;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Explanations;
public enum UnexplainedGrouping
{
Path,
Pattern
}
public sealed record ObservedValue(string Value, int Catches, DateTime FirstSeen, DateTime LastSeen, string? ExampleTarget, string? ExampleUserAgent);
public sealed record UnexplainedGroup(string Key, int Catches, IReadOnlyList<string> ExamplePaths, string? ExampleUserAgent, DateTime FirstSeen, DateTime LastSeen);
public sealed record UnexplainedResult(int Catches, int DistinctPaths, IReadOnlyList<UnexplainedGroup> Groups, int GroupsOmitted);
public sealed record RuleTakeover(ExplanationRuleEntity Rule, int Catches, IReadOnlyList<string> Examples);
public sealed record RuleTestResult(
int Catches,
int DistinctValues,
IReadOnlyList<(string Value, int Catches)> Examples,
int NewlyExplained,
IReadOnlyList<RuleTakeover> TakesOver,
int Lost,
IReadOnlyList<string> LostExamples);
public sealed class ExplanationQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory, ExplanationRuleStore store)
{
public const int ExampleCount = 10;
public const int MaxGroups = 500;
public async Task<IReadOnlyList<ObservedValue>> GetValuesAsync(ExplanationKind kind, DateTime? since, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = db.TrapEvents.AsNoTracking();
if (since is { } start)
{
events = events.Where(e => e.StartedAt >= start);
}
IEnumerable<ObservedValue> values;
switch (kind)
{
case ExplanationKind.Target:
var targets = await events.Where(e => e.Target != null).GroupBy(e => e.Target!)
.Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Agent = g.Max(e => e.ClientInfo) })
.ToListAsync(ct);
values = targets.Select(t => new ObservedValue(ExplanationText.Path(t.Key)!, t.Count, t.First, t.Last, t.Key, t.Agent));
break;
case ExplanationKind.ClientInfo:
var agents = await events.GroupBy(e => e.ClientInfo ?? "")
.Select(g => new { g.Key, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target) })
.ToListAsync(ct);
values = agents.Select(a => new ObservedValue(a.Key, a.Count, a.First, a.Last, a.Target, a.Key.Length == 0 ? null : a.Key));
break;
default:
var outcomes = await events.GroupBy(e => new { e.Outcome, Seconds = e.DurationMs / 1000 })
.Select(g => new { g.Key.Outcome, g.Key.Seconds, Count = g.Count(), First = g.Min(e => e.StartedAt), Last = g.Max(e => e.StartedAt), Target = g.Max(e => e.Target), Agent = g.Max(e => e.ClientInfo) })
.ToListAsync(ct);
values = outcomes.Select(o => new ObservedValue(ExplanationText.Outcome(o.Outcome, o.Seconds * 1000), o.Count, o.First, o.Last, o.Target, o.Agent));
break;
}
return values
.GroupBy(v => v.Value)
.Select(g => new ObservedValue(
g.Key,
g.Sum(v => v.Catches),
g.Min(v => v.FirstSeen),
g.Max(v => v.LastSeen),
g.OrderByDescending(v => v.Catches).First().ExampleTarget,
g.Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null)))
.ToList();
}
public async Task<UnexplainedResult> FindUnexplainedAsync(DateTime? since, UnexplainedGrouping grouping, int limit, CancellationToken ct = default)
{
var rules = await store.GetRuleSetAsync(ct);
var unexplained = (await GetValuesAsync(ExplanationKind.Target, since, ct))
.Where(v => rules.Winner(ExplanationKind.Target, v.Value) is null)
.ToList();
var groups = unexplained
.GroupBy(v => grouping == UnexplainedGrouping.Path ? v.Value : ExplanationText.PathShape(v.Value))
.Select(g => new UnexplainedGroup(
g.Key,
g.Sum(v => v.Catches),
g.OrderByDescending(v => v.Catches).Take(3).Select(v => v.Value).ToList(),
g.OrderByDescending(v => v.Catches).Select(v => v.ExampleUserAgent).FirstOrDefault(a => a is not null),
g.Min(v => v.FirstSeen),
g.Max(v => v.LastSeen)))
.OrderByDescending(g => g.Catches)
.ThenBy(g => g.Key, StringComparer.Ordinal)
.ToList();
var take = Math.Clamp(limit, 1, MaxGroups);
return new UnexplainedResult(unexplained.Sum(v => v.Catches), unexplained.Count, groups.Take(take).ToList(), Math.Max(0, groups.Count - take));
}
public async Task<RuleTestResult> TestAsync(ExplanationKind kind, string pattern, int priority, int? replacesRuleId, DateTime? since, CancellationToken ct = default)
{
var validPattern = ExplanationValidator.Pattern(pattern);
ExplanationValidator.Priority(priority);
var existing = (await store.ListAsync(ct)).Where(r => r.Enabled).ToList();
var candidateId = replacesRuleId ?? int.MaxValue;
var candidate = new ExplanationRuleEntity { Id = candidateId, Kind = kind, Pattern = validPattern, Text = "-", Priority = priority, CreatedBy = "test" };
var before = new RuleSet(existing);
var after = new RuleSet(existing.Where(r => r.Id != replacesRuleId).Append(candidate));
var candidateOnly = new RuleSet([candidate]);
var byId = existing.ToDictionary(r => r.Id);
var matched = new List<ObservedValue>();
var newly = 0;
var lost = 0;
var lostExamples = new List<string>();
var takeovers = new Dictionary<int, (int Catches, List<string> Examples)>();
foreach (var value in (await GetValuesAsync(kind, since, ct)).OrderByDescending(v => v.Catches))
{
var wasWinner = before.Winner(kind, value.Value);
var nowWinner = after.Winner(kind, value.Value);
var hit = candidateOnly.Winner(kind, value.Value) is not null;
if (hit)
{
matched.Add(value);
}
if (nowWinner?.Id == candidateId)
{
if (wasWinner is null)
{
newly += value.Catches;
}
else if (wasWinner.Id != candidateId)
{
var (catches, examples) = takeovers.GetValueOrDefault(wasWinner.Id, (0, []));
if (examples.Count < ExampleCount)
{
examples.Add(value.Value);
}
takeovers[wasWinner.Id] = (catches + value.Catches, examples);
}
}
else if (wasWinner?.Id == candidateId && nowWinner is null)
{
lost += value.Catches;
if (lostExamples.Count < ExampleCount)
{
lostExamples.Add(value.Value);
}
}
}
return new RuleTestResult(
matched.Sum(v => v.Catches),
matched.Count,
matched.Take(ExampleCount).Select(v => (v.Value, v.Catches)).ToList(),
newly,
takeovers.OrderByDescending(t => t.Value.Catches).Select(t => new RuleTakeover(byId[t.Key], t.Value.Catches, t.Value.Examples)).ToList(),
lost,
lostExamples);
}
public async Task<IReadOnlyDictionary<int, int>> CountHitsAsync(CancellationToken ct = default)
{
var rules = await store.ListAsync(ct);
var hits = rules.ToDictionary(r => r.Id, _ => 0);
foreach (var group in rules.GroupBy(r => r.Kind))
{
var set = new RuleSet(group);
foreach (var value in await GetValuesAsync(group.Key, null, ct))
{
foreach (var rule in set.Matching(group.Key, value.Value))
{
hits[rule.Id] += value.Catches;
}
}
}
return hits;
}
}
@@ -0,0 +1,156 @@
using Flypaper.Storage.Entities;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Explanations;
public sealed record ExplanationRuleInput(
ExplanationKind? Kind = null,
string? Pattern = null,
string? Text = null,
int? Priority = null,
string? Note = null);
public sealed class ExplanationRuleStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
{
public const string DashboardActor = "Dashboard";
private readonly object _gate = new();
private RuleSet? _cached;
private int _version;
public async Task<RuleSet> GetRuleSetAsync(CancellationToken ct = default)
{
int version;
lock (_gate)
{
if (_cached is { } cached)
{
return cached;
}
version = _version;
}
var rules = new RuleSet((await ListAsync(ct)).Where(r => r.Enabled));
lock (_gate)
{
if (version == _version)
{
_cached = rules;
}
}
return rules;
}
public async Task<IReadOnlyList<ExplanationRuleEntity>> ListAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.ExplanationRules.AsNoTracking().OrderBy(r => r.Kind).ThenByDescending(r => r.Priority).ThenBy(r => r.Id).ToListAsync(ct);
}
public async Task<ExplanationRuleEntity?> GetAsync(int id, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.ExplanationRules.AsNoTracking().FirstOrDefaultAsync(r => r.Id == id, ct);
}
public async Task<ExplanationRuleEntity> CreateAsync(ExplanationRuleInput input, string createdBy, CancellationToken ct = default)
{
var rule = new ExplanationRuleEntity
{
Kind = input.Kind ?? throw new ArgumentException("The kind is required."),
Pattern = ExplanationValidator.Pattern(input.Pattern),
Text = ExplanationValidator.Text(input.Text),
Priority = ExplanationValidator.Priority(input.Priority ?? 0),
Note = ExplanationValidator.Note(input.Note),
CreatedBy = createdBy.Length > ExplanationLimits.MaxCreatedByLength ? createdBy[..ExplanationLimits.MaxCreatedByLength] : createdBy,
CreatedAt = timeProvider.GetUtcNow().UtcDateTime
};
rule.UpdatedAt = rule.CreatedAt;
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
if (await db.ExplanationRules.CountAsync(ct) >= ExplanationLimits.MaxRules)
{
throw new ArgumentException($"There are already {ExplanationLimits.MaxRules} rules; delete unused ones first.");
}
db.ExplanationRules.Add(rule);
await db.SaveChangesAsync(ct);
Invalidate();
return rule;
}
public async Task<ExplanationRuleEntity?> UpdateAsync(int id, ExplanationRuleInput input, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var rule = await db.ExplanationRules.FirstOrDefaultAsync(r => r.Id == id, ct);
if (rule is null)
{
return null;
}
if (input.Kind is { } kind)
{
rule.Kind = kind;
}
if (input.Pattern is not null)
{
rule.Pattern = ExplanationValidator.Pattern(input.Pattern);
}
if (input.Text is not null)
{
rule.Text = ExplanationValidator.Text(input.Text);
}
if (input.Priority is { } priority)
{
rule.Priority = ExplanationValidator.Priority(priority);
}
if (input.Note is not null)
{
rule.Note = ExplanationValidator.Note(input.Note);
}
rule.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
await db.SaveChangesAsync(ct);
Invalidate();
return rule;
}
public async Task<ExplanationRuleEntity?> SetEnabledAsync(int id, bool enabled, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var rule = await db.ExplanationRules.FirstOrDefaultAsync(r => r.Id == id, ct);
if (rule is null)
{
return null;
}
rule.Enabled = enabled;
rule.UpdatedAt = timeProvider.GetUtcNow().UtcDateTime;
await db.SaveChangesAsync(ct);
Invalidate();
return rule;
}
public async Task<bool> DeleteAsync(int id, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var deleted = await db.ExplanationRules.Where(r => r.Id == id).ExecuteDeleteAsync(ct) > 0;
Invalidate();
return deleted;
}
private void Invalidate()
{
lock (_gate)
{
_version++;
_cached = null;
}
}
}
@@ -0,0 +1,54 @@
using System.Text.RegularExpressions;
using Flypaper.Core.Models;
using Flypaper.Storage.Entities;
namespace Flypaper.Storage.Explanations;
public static partial class ExplanationText
{
[GeneratedRegex("[0-9a-fA-F]{8,}")]
private static partial Regex LongHex();
[GeneratedRegex("[0-9]+")]
private static partial Regex Digits();
public static string? Path(string? target)
{
if (target is null)
{
return null;
}
var space = target.IndexOf(' ');
if (space < 0)
{
return target;
}
var hostAndPath = target[(space + 1)..];
if (hostAndPath.StartsWith('/'))
{
return hostAndPath;
}
var slash = hostAndPath.IndexOf('/');
return slash < 0 ? "/" : hostAndPath[slash..];
}
public static string Outcome(TrapOutcome outcome, long durationMs) =>
outcome == TrapOutcome.Rejected ? outcome.ToString() : $"{outcome} {durationMs / 1000}s";
public static string Value(ExplanationKind kind, TrapEventEntity trapEvent) => kind switch
{
ExplanationKind.Target => Path(trapEvent.Target) ?? "",
ExplanationKind.ClientInfo => trapEvent.ClientInfo ?? "",
_ => Outcome(trapEvent.Outcome, trapEvent.DurationMs)
};
public static string PathShape(string path)
{
var query = path.IndexOf('?');
var bare = query < 0 ? path : path[..query];
return Digits().Replace(LongHex().Replace(bare, "{hex}"), "{n}");
}
}
@@ -0,0 +1,82 @@
using System.Text.RegularExpressions;
namespace Flypaper.Storage.Explanations;
public static class ExplanationValidator
{
public static readonly TimeSpan MatchTimeout = TimeSpan.FromMilliseconds(250);
public static Regex Compile(string pattern) =>
new(pattern, RegexOptions.NonBacktracking | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, MatchTimeout);
public static string Pattern(string? pattern)
{
var value = pattern?.Trim();
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("The pattern must not be empty.");
}
if (value.Length > ExplanationLimits.MaxPatternLength)
{
throw new ArgumentException($"The pattern must have at most {ExplanationLimits.MaxPatternLength} characters.");
}
try
{
Compile(value);
}
catch (ArgumentException exception)
{
throw new ArgumentException($"The pattern is not a valid regular expression: {exception.Message}");
}
catch (NotSupportedException exception)
{
throw new ArgumentException($"The pattern uses a feature that is not supported (no lookarounds, backreferences or atomic groups): {exception.Message}");
}
return value;
}
public static string Text(string? text)
{
var value = text?.Trim();
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException("The text must not be empty.");
}
if (value.Length > ExplanationLimits.MaxTextLength)
{
throw new ArgumentException($"The text must have at most {ExplanationLimits.MaxTextLength} characters.");
}
if (value.Any(char.IsControl))
{
throw new ArgumentException("The text must be plain text without line breaks or control characters.");
}
return value;
}
public static string? Note(string? note)
{
var value = note?.Trim();
if (string.IsNullOrEmpty(value))
{
return null;
}
if (value.Length > ExplanationLimits.MaxNoteLength)
{
throw new ArgumentException($"The note must have at most {ExplanationLimits.MaxNoteLength} characters.");
}
return value.Any(char.IsControl) ? throw new ArgumentException("The note must be plain text without control characters.") : value;
}
public static int Priority(int priority) =>
Math.Abs(priority) <= ExplanationLimits.MaxPriority
? priority
: throw new ArgumentException($"The priority must be between -{ExplanationLimits.MaxPriority} and {ExplanationLimits.MaxPriority}.");
}
@@ -0,0 +1,77 @@
using System.Text.RegularExpressions;
using Flypaper.Storage.Entities;
namespace Flypaper.Storage.Explanations;
public sealed record Explanation(ExplanationRuleEntity? Target, ExplanationRuleEntity? Client, ExplanationRuleEntity? Outcome)
{
public bool HasTarget => Target is not null;
}
public sealed class RuleSet
{
public static readonly RuleSet Empty = new([]);
private readonly IReadOnlyDictionary<ExplanationKind, IReadOnlyList<(ExplanationRuleEntity Rule, Regex Regex)>> _byKind;
public RuleSet(IEnumerable<ExplanationRuleEntity> rules)
{
var compiled = new Dictionary<ExplanationKind, List<(ExplanationRuleEntity, Regex)>>();
foreach (var rule in rules.OrderByDescending(r => r.Priority).ThenBy(r => r.Id))
{
Regex regex;
try
{
regex = ExplanationValidator.Compile(rule.Pattern);
}
catch (Exception exception) when (exception is ArgumentException or NotSupportedException)
{
continue;
}
if (!compiled.TryGetValue(rule.Kind, out var list))
{
compiled[rule.Kind] = list = [];
}
list.Add((rule, regex));
}
_byKind = compiled.ToDictionary(p => p.Key, p => (IReadOnlyList<(ExplanationRuleEntity, Regex)>)p.Value);
}
public ExplanationRuleEntity? Winner(ExplanationKind kind, string value) => Matching(kind, value).FirstOrDefault();
public IEnumerable<ExplanationRuleEntity> Matching(ExplanationKind kind, string value)
{
if (!_byKind.TryGetValue(kind, out var rules))
{
yield break;
}
foreach (var (rule, regex) in rules)
{
if (IsMatch(regex, value))
{
yield return rule;
}
}
}
public Explanation Explain(TrapEventEntity trapEvent) => new(
trapEvent.Target is null ? null : Winner(ExplanationKind.Target, ExplanationText.Value(ExplanationKind.Target, trapEvent)),
Winner(ExplanationKind.ClientInfo, ExplanationText.Value(ExplanationKind.ClientInfo, trapEvent)),
Winner(ExplanationKind.Outcome, ExplanationText.Value(ExplanationKind.Outcome, trapEvent)));
private static bool IsMatch(Regex regex, string value)
{
try
{
return regex.IsMatch(value);
}
catch (RegexMatchTimeoutException)
{
return false;
}
}
}
+28
View File
@@ -1,4 +1,6 @@
using Flypaper.Core.Analysis;
using Flypaper.Storage.Entities; using Flypaper.Storage.Entities;
using Flypaper.Storage.Explanations;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage; namespace Flypaper.Storage;
@@ -10,8 +12,14 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
public DbSet<TrapEventEntity> TrapEvents => Set<TrapEventEntity>(); public DbSet<TrapEventEntity> TrapEvents => Set<TrapEventEntity>();
public DbSet<TrapRequestEntity> TrapRequests => Set<TrapRequestEntity>();
public DbSet<SettingEntity> Settings => Set<SettingEntity>(); public DbSet<SettingEntity> Settings => Set<SettingEntity>();
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
public DbSet<ExplanationRuleEntity> ExplanationRules => Set<ExplanationRuleEntity>();
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) => protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>(); configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
@@ -32,9 +40,29 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
trapEvent.HasIndex(e => e.RemoteIp); trapEvent.HasIndex(e => e.RemoteIp);
trapEvent.HasIndex(e => e.CountryCode); trapEvent.HasIndex(e => e.CountryCode);
trapEvent.HasIndex(e => e.Asn); trapEvent.HasIndex(e => e.Asn);
trapEvent.Property(e => e.Command).HasMaxLength(CommandDetector.MaxCommandLength);
trapEvent.Property(e => e.CommandServer).HasMaxLength(CommandDetector.MaxServerLength);
trapEvent.HasIndex(e => e.CommandScan);
trapEvent.HasIndex(e => e.StartedAt, "IX_TrapEvents_Commands").HasFilter("\"Command\" IS NOT NULL");
trapEvent.HasOne(e => e.Request)
.WithOne()
.HasForeignKey<TrapRequestEntity>(e => e.TrapEventId)
.OnDelete(DeleteBehavior.Cascade);
var setting = modelBuilder.Entity<SettingEntity>(); var setting = modelBuilder.Entity<SettingEntity>();
setting.HasKey(e => e.Key); setting.HasKey(e => e.Key);
setting.Property(e => e.Key).HasMaxLength(128); setting.Property(e => e.Key).HasMaxLength(128);
var mcpToken = modelBuilder.Entity<McpTokenEntity>();
mcpToken.Property(e => e.Name).HasMaxLength(100);
mcpToken.Property(e => e.TokenHash).HasMaxLength(64);
mcpToken.HasIndex(e => e.TokenHash).IsUnique();
var explanationRule = modelBuilder.Entity<ExplanationRuleEntity>();
explanationRule.Property(e => e.Kind).HasConversion<string>().HasMaxLength(16);
explanationRule.Property(e => e.Pattern).HasMaxLength(ExplanationLimits.MaxPatternLength);
explanationRule.Property(e => e.Text).HasMaxLength(ExplanationLimits.MaxTextLength);
explanationRule.Property(e => e.Note).HasMaxLength(ExplanationLimits.MaxNoteLength);
explanationRule.Property(e => e.CreatedBy).HasMaxLength(ExplanationLimits.MaxCreatedByLength);
} }
} }
@@ -1,7 +1,9 @@
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.Explanations;
using Flypaper.Storage.Maintenance; using Flypaper.Storage.Maintenance;
using Flypaper.Storage.Queries;
using Flypaper.Storage.Settings; using Flypaper.Storage.Settings;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
@@ -21,6 +23,7 @@ public static class FlypaperStorageExtensions
builder.Services.AddSingleton(source); builder.Services.AddSingleton(source);
builder.Services.AddSingleton<RuntimeSettingsStore>(); builder.Services.AddSingleton<RuntimeSettingsStore>();
builder.Services.AddSingleton<AdminCredentialStore>(); builder.Services.AddSingleton<AdminCredentialStore>();
builder.Services.AddSingleton<McpTokenStore>();
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName)); builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
builder.Services.AddFlypaperStorage(connectionString); builder.Services.AddFlypaperStorage(connectionString);
@@ -34,7 +37,14 @@ public static class FlypaperStorageExtensions
services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>()); services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
services.AddHostedService<TrapEventWriter>(); services.AddHostedService<TrapEventWriter>();
services.AddHostedService<OriginBackfill>(); services.AddHostedService<OriginBackfill>();
services.AddHostedService<CommandBackfill>();
services.AddSingleton<ExplanationRuleStore>();
services.AddSingleton<ExplanationQueries>();
services.AddSingleton<DashboardQueries>(); services.AddSingleton<DashboardQueries>();
services.AddSingleton<CatchQueries>();
services.AddSingleton<CommandQueries>();
services.AddSingleton<IRepeatOffenderLookup, RepeatOffenderLookup>();
services.AddSingleton<IKnownIpLookup, KnownIpLookup>();
services.AddSingleton<TrapDataMaintenance>(); services.AddSingleton<TrapDataMaintenance>();
services.AddHostedService<RetentionCleanup>(); services.AddHostedService<RetentionCleanup>();
return services; return services;
@@ -32,6 +32,12 @@ internal sealed partial class RetentionCleanup(
internal async Task<int> CleanupAsync(CancellationToken ct) internal async Task<int> CleanupAsync(CancellationToken ct)
{ {
var requestDays = options.CurrentValue.RequestDays;
if (requestDays > 0)
{
await maintenance.DeleteRequestsOlderThanAsync(timeProvider.GetUtcNow().UtcDateTime.AddDays(-requestDays), ct);
}
var days = options.CurrentValue.Days; var days = options.CurrentValue.Days;
if (days <= 0) if (days <= 0)
{ {
@@ -5,4 +5,6 @@ public sealed class RetentionOptions
public const string SectionName = "Flypaper:Retention"; public const string SectionName = "Flypaper:Retention";
public int Days { get; set; } = 90; public int Days { get; set; } = 90;
public int RequestDays { get; set; } = 30;
} }
@@ -22,6 +22,14 @@ public sealed class TrapDataMaintenance(IDbContextFactory<FlypaperDbContext> dbC
return await db.TrapEvents.Where(e => e.StartedAt < cutoffUtc).ExecuteDeleteAsync(ct); return await db.TrapEvents.Where(e => e.StartedAt < cutoffUtc).ExecuteDeleteAsync(ct);
} }
public async Task<int> DeleteRequestsOlderThanAsync(DateTime cutoffUtc, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapRequests
.Where(r => db.TrapEvents.Any(e => e.Id == r.TrapEventId && e.StartedAt < cutoffUtc))
.ExecuteDeleteAsync(ct);
}
public async Task<int> DeletePrivateAsync(CancellationToken ct = default) public async Task<int> DeletePrivateAsync(CancellationToken ct = default)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var db = await dbContextFactory.CreateDbContextAsync(ct);
@@ -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("20261115122552_AddMcpTokens")]
partial class AddMcpTokens
{
/// <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,44 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class AddMcpTokens : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "McpTokens",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false),
TokenHash = table.Column<string>(type: "TEXT", maxLength: 64, nullable: false),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
LastUsedAt = table.Column<DateTime>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_McpTokens", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_McpTokens_TokenHash",
table: "McpTokens",
column: "TokenHash",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "McpTokens");
}
}
}
@@ -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)
{
}
}
}
@@ -0,0 +1,248 @@
// <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("20261117165523_AddResearch")]
partial class AddResearch
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.IdeaEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Commit")
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("Efficiency")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Effort")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<DateTime?>("ImplementedOn")
.HasColumnType("TEXT");
b.Property<string>("Rationale")
.IsRequired()
.HasMaxLength(20000)
.HasColumnType("TEXT");
b.Property<string>("Status")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Ideas");
});
modelBuilder.Entity("Flypaper.Storage.Entities.LabEntryEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Commit")
.HasMaxLength(64)
.HasColumnType("TEXT");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<DateTime>("Date")
.HasColumnType("TEXT");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Strategies")
.HasMaxLength(512)
.HasColumnType("TEXT");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(20000)
.HasColumnType("TEXT");
b.Property<string>("Title")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("Date");
b.ToTable("LabEntries");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.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,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class AddResearch : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanWrite",
table: "McpTokens",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "Ideas",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
Effort = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Efficiency = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Rationale = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Status = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
ImplementedOn = table.Column<DateTime>(type: "TEXT", nullable: true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ideas", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LabEntries",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Date = table.Column<DateTime>(type: "TEXT", nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Text = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
Strategies = table.Column<string>(type: "TEXT", maxLength: 512, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LabEntries", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_LabEntries_Date",
table: "LabEntries",
column: "Date");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Ideas");
migrationBuilder.DropTable(
name: "LabEntries");
migrationBuilder.DropColumn(
name: "CanWrite",
table: "McpTokens");
}
}
}
@@ -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("20261121100100_RemoveResearch")]
partial class RemoveResearch
{
/// <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,82 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class RemoveResearch : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Ideas");
migrationBuilder.DropTable(
name: "LabEntries");
migrationBuilder.DropColumn(
name: "CanWrite",
table: "McpTokens");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanWrite",
table: "McpTokens",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "Ideas",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Efficiency = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Effort = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
ImplementedOn = table.Column<DateTime>(type: "TEXT", nullable: true),
Rationale = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Status = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Ideas", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LabEntries",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Commit = table.Column<string>(type: "TEXT", maxLength: 64, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
Date = table.Column<DateTime>(type: "TEXT", nullable: false),
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Strategies = table.Column<string>(type: "TEXT", maxLength: 512, nullable: true),
Text = table.Column<string>(type: "TEXT", maxLength: 20000, nullable: false),
Title = table.Column<string>(type: "TEXT", maxLength: 200, nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LabEntries", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_LabEntries_Date",
table: "LabEntries",
column: "Date");
}
}
}
@@ -0,0 +1,201 @@
// <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("20261121103849_AddExplanationRulesAndTokenWrite")]
partial class AddExplanationRulesAndTokenWrite
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Pattern")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("ExplanationRules");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.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,54 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class AddExplanationRulesAndTokenWrite : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<bool>(
name: "CanWrite",
table: "McpTokens",
type: "INTEGER",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "ExplanationRules",
columns: table => new
{
Id = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Kind = table.Column<string>(type: "TEXT", maxLength: 16, nullable: false),
Pattern = table.Column<string>(type: "TEXT", maxLength: 500, nullable: false),
Text = table.Column<string>(type: "TEXT", maxLength: 600, nullable: false),
Priority = table.Column<int>(type: "INTEGER", nullable: false),
Enabled = table.Column<bool>(type: "INTEGER", nullable: false),
Note = table.Column<string>(type: "TEXT", maxLength: 500, nullable: true),
CreatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
UpdatedAt = table.Column<DateTime>(type: "TEXT", nullable: false),
CreatedBy = table.Column<string>(type: "TEXT", maxLength: 100, nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ExplanationRules", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ExplanationRules");
migrationBuilder.DropColumn(
name: "CanWrite",
table: "McpTokens");
}
}
}
@@ -0,0 +1,245 @@
// <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("20261126204205_AddTrapRequests")]
partial class AddTrapRequests
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Pattern")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("ExplanationRules");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.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");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapRequestEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Body")
.HasColumnType("TEXT");
b.Property<long?>("ContentLength")
.HasColumnType("INTEGER");
b.Property<string>("Headers")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("TrapEventId")
.HasColumnType("INTEGER");
b.Property<bool>("Truncated")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TrapEventId")
.IsUnique();
b.ToTable("TrapRequests");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapRequestEntity", b =>
{
b.HasOne("Flypaper.Storage.Entities.TrapEventEntity", null)
.WithOne("Request")
.HasForeignKey("Flypaper.Storage.Entities.TrapRequestEntity", "TrapEventId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Navigation("Request");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,50 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class AddTrapRequests : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "TrapRequests",
columns: table => new
{
Id = table.Column<long>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
TrapEventId = table.Column<long>(type: "INTEGER", nullable: false),
Headers = table.Column<string>(type: "TEXT", nullable: false),
Body = table.Column<string>(type: "TEXT", nullable: true),
ContentLength = table.Column<long>(type: "INTEGER", nullable: true),
Truncated = table.Column<bool>(type: "INTEGER", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_TrapRequests", x => x.Id);
table.ForeignKey(
name: "FK_TrapRequests_TrapEvents_TrapEventId",
column: x => x.TrapEventId,
principalTable: "TrapEvents",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_TrapRequests_TrapEventId",
table: "TrapRequests",
column: "TrapEventId",
unique: true);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "TrapRequests");
}
}
}
@@ -0,0 +1,261 @@
// <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("20261127200648_AddDetectedCommands")]
partial class AddDetectedCommands
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Pattern")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("ExplanationRules");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.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>("Command")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("CommandScan")
.HasColumnType("INTEGER");
b.Property<string>("CommandServer")
.HasMaxLength(256)
.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("CommandScan");
b.HasIndex("CountryCode");
b.HasIndex("RemoteIp");
b.HasIndex("StartedAt");
b.HasIndex(new[] { "StartedAt" }, "IX_TrapEvents_Commands")
.HasFilter("\"Command\" IS NOT NULL");
b.ToTable("TrapEvents");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapRequestEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Body")
.HasColumnType("TEXT");
b.Property<long?>("ContentLength")
.HasColumnType("INTEGER");
b.Property<string>("Headers")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("TrapEventId")
.HasColumnType("INTEGER");
b.Property<bool>("Truncated")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TrapEventId")
.IsUnique();
b.ToTable("TrapRequests");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapRequestEntity", b =>
{
b.HasOne("Flypaper.Storage.Entities.TrapEventEntity", null)
.WithOne("Request")
.HasForeignKey("Flypaper.Storage.Entities.TrapRequestEntity", "TrapEventId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Navigation("Request");
});
#pragma warning restore 612, 618
}
}
}
@@ -0,0 +1,70 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Flypaper.Storage.Migrations
{
/// <inheritdoc />
public partial class AddDetectedCommands : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "Command",
table: "TrapEvents",
type: "TEXT",
maxLength: 500,
nullable: true);
migrationBuilder.AddColumn<int>(
name: "CommandScan",
table: "TrapEvents",
type: "INTEGER",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<string>(
name: "CommandServer",
table: "TrapEvents",
type: "TEXT",
maxLength: 256,
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_TrapEvents_Commands",
table: "TrapEvents",
column: "StartedAt",
filter: "\"Command\" IS NOT NULL");
migrationBuilder.CreateIndex(
name: "IX_TrapEvents_CommandScan",
table: "TrapEvents",
column: "CommandScan");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropIndex(
name: "IX_TrapEvents_Commands",
table: "TrapEvents");
migrationBuilder.DropIndex(
name: "IX_TrapEvents_CommandScan",
table: "TrapEvents");
migrationBuilder.DropColumn(
name: "Command",
table: "TrapEvents");
migrationBuilder.DropColumn(
name: "CommandScan",
table: "TrapEvents");
migrationBuilder.DropColumn(
name: "CommandServer",
table: "TrapEvents");
}
}
}
@@ -17,6 +17,86 @@ namespace Flypaper.Storage.Migrations
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); modelBuilder.HasAnnotation("ProductVersion", "10.0.15");
modelBuilder.Entity("Flypaper.Storage.Entities.ExplanationRuleEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<DateTime>("CreatedAt")
.HasColumnType("TEXT");
b.Property<string>("CreatedBy")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("TEXT");
b.Property<bool>("Enabled")
.HasColumnType("INTEGER");
b.Property<string>("Kind")
.IsRequired()
.HasMaxLength(16)
.HasColumnType("TEXT");
b.Property<string>("Note")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<string>("Pattern")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("Priority")
.HasColumnType("INTEGER");
b.Property<string>("Text")
.IsRequired()
.HasMaxLength(600)
.HasColumnType("TEXT");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("ExplanationRules");
});
modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<bool>("CanWrite")
.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 => modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b =>
{ {
b.Property<string>("Key") b.Property<string>("Key")
@@ -52,6 +132,17 @@ namespace Flypaper.Storage.Migrations
.HasMaxLength(2048) .HasMaxLength(2048)
.HasColumnType("TEXT"); .HasColumnType("TEXT");
b.Property<string>("Command")
.HasMaxLength(500)
.HasColumnType("TEXT");
b.Property<int>("CommandScan")
.HasColumnType("INTEGER");
b.Property<string>("CommandServer")
.HasMaxLength(256)
.HasColumnType("TEXT");
b.Property<string>("Country") b.Property<string>("Country")
.HasMaxLength(256) .HasMaxLength(256)
.HasColumnType("TEXT"); .HasColumnType("TEXT");
@@ -104,14 +195,63 @@ namespace Flypaper.Storage.Migrations
b.HasIndex("Asn"); b.HasIndex("Asn");
b.HasIndex("CommandScan");
b.HasIndex("CountryCode"); b.HasIndex("CountryCode");
b.HasIndex("RemoteIp"); b.HasIndex("RemoteIp");
b.HasIndex("StartedAt"); b.HasIndex("StartedAt");
b.HasIndex(new[] { "StartedAt" }, "IX_TrapEvents_Commands")
.HasFilter("\"Command\" IS NOT NULL");
b.ToTable("TrapEvents"); b.ToTable("TrapEvents");
}); });
modelBuilder.Entity("Flypaper.Storage.Entities.TrapRequestEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("Body")
.HasColumnType("TEXT");
b.Property<long?>("ContentLength")
.HasColumnType("INTEGER");
b.Property<string>("Headers")
.IsRequired()
.HasColumnType("TEXT");
b.Property<long>("TrapEventId")
.HasColumnType("INTEGER");
b.Property<bool>("Truncated")
.HasColumnType("INTEGER");
b.HasKey("Id");
b.HasIndex("TrapEventId")
.IsUnique();
b.ToTable("TrapRequests");
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapRequestEntity", b =>
{
b.HasOne("Flypaper.Storage.Entities.TrapEventEntity", null)
.WithOne("Request")
.HasForeignKey("Flypaper.Storage.Entities.TrapRequestEntity", "TrapEventId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b =>
{
b.Navigation("Request");
});
#pragma warning restore 612, 618 #pragma warning restore 612, 618
} }
} }
@@ -0,0 +1,211 @@
using System.Globalization;
using Flypaper.Core.Models;
using Flypaper.Core.Strategies;
using Flypaper.Storage.Entities;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Queries;
public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory)
{
public const int MaxLimit = 500;
public async Task<CatchStats> GetStatsAsync(DateTime? since, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = InPeriod(db, since);
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
var count = await catches.CountAsync(ct);
var totalMs = count == 0 ? 0 : await catches.SumAsync(e => e.DurationMs, ct);
var longest = await catches.OrderByDescending(e => e.DurationMs).ThenByDescending(e => e.Id).FirstOrDefaultAsync(ct);
return new CatchStats(
count,
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
await events.Select(e => e.RemoteIp).Distinct().CountAsync(ct),
totalMs / 1000d,
count == 0 ? 0 : totalMs / 1000d / count,
longest is null ? null : ToRecord(longest));
}
public async Task<IReadOnlyList<CatchRecord>> ListAsync(CatchFilter filter, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = InPeriod(db, filter.Since);
if (filter.Until is { } until)
{
events = events.Where(e => e.StartedAt < until);
}
if (!string.IsNullOrWhiteSpace(filter.Country))
{
var country = filter.Country.Trim().ToUpperInvariant();
events = events.Where(e => e.CountryCode == country);
}
if (!string.IsNullOrWhiteSpace(filter.Provider))
{
events = ByProvider(events, filter.Provider.Trim());
}
if (!string.IsNullOrWhiteSpace(filter.Ip))
{
var ip = filter.Ip.Trim();
events = events.Where(e => e.RemoteIp == ip);
}
if (!string.IsNullOrWhiteSpace(filter.TargetContains))
{
var text = filter.TargetContains.Trim().ToLowerInvariant();
events = events.Where(e => e.Target != null && e.Target.ToLower().Contains(text));
}
if (!string.IsNullOrWhiteSpace(filter.Marker))
{
var marker = filter.Marker.Trim();
var prefix = $"{marker[..8]}-{marker[8..]}%";
events = events.Where(e => EF.Functions.Like(e.SessionId.ToString(), prefix));
}
var rows = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(Clamp(filter.Limit)).ToListAsync(ct);
return rows.Select(ToRecord).ToList();
}
public async Task<IReadOnlyList<CatchRecord>> LongestAsync(DateTime? since, int limit, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var rows = await InPeriod(db, since)
.Where(e => e.Outcome != TrapOutcome.Rejected)
.OrderByDescending(e => e.DurationMs)
.ThenByDescending(e => e.Id)
.Take(Clamp(limit))
.ToListAsync(ct);
return rows.Select(ToRecord).ToList();
}
public async Task<IReadOnlyList<TopItem>> TopAsync(TopDimension dimension, DateTime? since, int limit, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var catches = InPeriod(db, since).Where(e => e.Outcome != TrapOutcome.Rejected);
var take = Clamp(limit);
IQueryable<TopRow> rows = dimension switch
{
TopDimension.Ips => catches.GroupBy(e => e.RemoteIp)
.Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.CountryCode), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.Countries => catches.Where(e => e.CountryCode != null).GroupBy(e => e.CountryCode!)
.Select(g => new TopRow { Key = g.Key, Label = g.Max(e => e.Country), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.Providers => catches.Where(e => e.Asn != null).GroupBy(e => e.Asn!.Value)
.Select(g => new TopRow { Key = "AS" + g.Key.ToString(), Label = g.Max(e => e.Provider), Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.Targets => catches.Where(e => e.Target != null).GroupBy(e => e.Target!)
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.Strategies => catches.GroupBy(e => e.Strategy)
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
TopDimension.UserAgents => catches.Where(e => e.ClientInfo != null).GroupBy(e => e.ClientInfo!)
.Select(g => new TopRow { Key = g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) }),
_ => throw new ArgumentOutOfRangeException(nameof(dimension))
};
var top = await rows
.OrderByDescending(x => x.Count)
.ThenByDescending(x => x.DurationMs)
.Take(take)
.ToListAsync(ct);
return top.Select(x => new TopItem(x.Key, x.Label, x.Count, x.DurationMs / 1000d)).ToList();
}
public async Task<(bool Found, TrapRequestEntity? Request)> GetRequestAsync(long catchId, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
if (!await db.TrapEvents.AnyAsync(e => e.Id == catchId, ct))
{
return (false, null);
}
return (true, await db.TrapRequests.AsNoTracking().FirstOrDefaultAsync(r => r.TrapEventId == catchId, ct));
}
public async Task<IpProfile?> LookupIpAsync(string ip, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = db.TrapEvents.AsNoTracking().Where(e => e.RemoteIp == ip);
var total = await events.CountAsync(ct);
if (total == 0)
{
return null;
}
var catches = events.Where(e => e.Outcome != TrapOutcome.Rejected);
var origin = await events.Where(e => e.CountryCode != null || e.Asn != null).OrderByDescending(e => e.Id).FirstOrDefaultAsync(ct);
var recent = await events.OrderByDescending(e => e.StartedAt).ThenByDescending(e => e.Id).Take(MaxLimit).ToListAsync(ct);
return new IpProfile(
ip,
origin?.CountryCode,
origin?.Country,
origin?.City,
origin?.Asn,
origin?.Provider,
await catches.CountAsync(ct),
await events.CountAsync(e => e.Outcome == TrapOutcome.Rejected, ct),
await catches.SumAsync(e => e.DurationMs, ct) / 1000d,
await events.SumAsync(e => e.BytesSent, ct),
await events.MinAsync(e => e.StartedAt, ct),
await events.MaxAsync(e => e.EndedAt, ct),
recent.Select(ToRecord).ToList(),
Math.Max(0, total - recent.Count));
}
private static IQueryable<TrapEventEntity> InPeriod(FlypaperDbContext db, DateTime? since)
{
var events = db.TrapEvents.AsNoTracking();
return since is { } start ? events.Where(e => e.StartedAt >= start) : events;
}
private static IQueryable<TrapEventEntity> ByProvider(IQueryable<TrapEventEntity> events, string provider)
{
var number = provider.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? provider[2..] : provider;
if (long.TryParse(number, NumberStyles.None, CultureInfo.InvariantCulture, out var asn))
{
return events.Where(e => e.Asn == asn);
}
var text = provider.ToLowerInvariant();
return events.Where(e => e.Provider != null && e.Provider.ToLower().Contains(text));
}
private static int Clamp(int limit) => Math.Clamp(limit, 1, MaxLimit);
private static CatchRecord ToRecord(TrapEventEntity e) => new(
e.Id,
e.StartedAt,
e.EndedAt,
e.DurationMs / 1000d,
e.BytesSent,
e.Outcome,
e.Strategy,
e.RemoteIp,
e.CountryCode,
e.Country,
e.City,
e.Asn,
e.Provider,
e.Target,
e.ClientInfo,
SignpostLinks.MarkerOf(e.SessionId));
private sealed class TopRow
{
public required string Key { get; init; }
public string? Label { get; init; }
public int Count { get; init; }
public long DurationMs { get; init; }
}
}
@@ -0,0 +1,67 @@
using Flypaper.Core.Models;
namespace Flypaper.Storage.Queries;
public sealed record CatchRecord(
long Id,
DateTime StartedAt,
DateTime EndedAt,
double DurationSeconds,
long BytesSent,
TrapOutcome Outcome,
string Strategy,
string Ip,
string? CountryCode,
string? Country,
string? City,
long? Asn,
string? Provider,
string? Target,
string? UserAgent,
string Marker);
public sealed record CatchFilter(
DateTime? Since = null,
DateTime? Until = null,
string? Country = null,
string? Provider = null,
string? Ip = null,
string? TargetContains = null,
int Limit = 50,
string? Marker = null);
public sealed record CatchStats(
int Catches,
int Rejected,
int UniqueIps,
double TotalHoldSeconds,
double AverageHoldSeconds,
CatchRecord? Longest);
public enum TopDimension
{
Ips,
Countries,
Providers,
Targets,
Strategies,
UserAgents
}
public sealed record TopItem(string Key, string? Label, int Catches, double TotalHoldSeconds);
public sealed record IpProfile(
string Ip,
string? CountryCode,
string? Country,
string? City,
long? Asn,
string? Provider,
int Catches,
int Rejected,
double TotalHoldSeconds,
long TotalBytesSent,
DateTime? FirstSeen,
DateTime? LastSeen,
IReadOnlyList<CatchRecord> Events,
int EventsOmitted);
@@ -0,0 +1,49 @@
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Queries;
public sealed record CommandGroup(
string Command,
string? Server,
int Catches,
int Ips,
DateTime FirstSeen,
DateTime LastSeen,
long LastCatchId,
string LastIp);
public sealed class CommandQueries(IDbContextFactory<FlypaperDbContext> dbContextFactory)
{
private const int MaxRows = 5_000;
public async Task<IReadOnlyList<CommandGroup>> GetGroupsAsync(DateTime? since, int limit, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var events = db.TrapEvents.AsNoTracking().Where(e => e.Command != null);
if (since is { } start)
{
events = events.Where(e => e.StartedAt >= start);
}
var rows = await events
.OrderByDescending(e => e.StartedAt)
.ThenByDescending(e => e.Id)
.Take(MaxRows)
.Select(e => new { e.Id, e.StartedAt, e.RemoteIp, Command = e.Command!, e.CommandServer })
.ToListAsync(ct);
return rows
.GroupBy(r => r.CommandServer ?? r.Command, StringComparer.OrdinalIgnoreCase)
.Select(g => new CommandGroup(
g.First().Command,
g.First().CommandServer,
g.Count(),
g.Select(r => r.RemoteIp).Distinct().Count(),
g.Min(r => r.StartedAt),
g.First().StartedAt,
g.First().Id,
g.First().RemoteIp))
.Take(Math.Clamp(limit, 1, CatchQueries.MaxLimit))
.ToList();
}
}
@@ -0,0 +1,15 @@
using System.Net;
using Flypaper.Core.Abstractions;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Queries;
public sealed class KnownIpLookup(IDbContextFactory<FlypaperDbContext> dbContextFactory) : IKnownIpLookup
{
public async ValueTask<bool> HasSeenAsync(IPAddress address, CancellationToken ct)
{
var ip = address.ToString();
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapEvents.AnyAsync(e => e.RemoteIp == ip, ct);
}
}
@@ -0,0 +1,36 @@
using System.Globalization;
using System.Text.RegularExpressions;
namespace Flypaper.Storage.Queries;
public static partial class QueryPeriod
{
[GeneratedRegex(@"^(\d{1,5})([mhdw])$", RegexOptions.IgnoreCase)]
private static partial Regex Pattern();
public static bool TryParse(string? value, out TimeSpan? span)
{
span = null;
var text = value?.Trim();
if (string.IsNullOrEmpty(text) || text.Equals("all", StringComparison.OrdinalIgnoreCase))
{
return true;
}
var match = Pattern().Match(text);
if (!match.Success)
{
return false;
}
var amount = int.Parse(match.Groups[1].Value, CultureInfo.InvariantCulture);
span = char.ToLowerInvariant(match.Groups[2].Value[0]) switch
{
'm' => TimeSpan.FromMinutes(amount),
'h' => TimeSpan.FromHours(amount),
'd' => TimeSpan.FromDays(amount),
_ => TimeSpan.FromDays(amount * 7)
};
return amount > 0;
}
}
@@ -0,0 +1,16 @@
using System.Net;
using Flypaper.Core.Abstractions;
using Flypaper.Core.Models;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Queries;
public sealed class RepeatOffenderLookup(IDbContextFactory<FlypaperDbContext> dbContextFactory) : IRepeatOffenderLookup
{
public async ValueTask<bool> HasTimedOutSinceAsync(IPAddress address, DateTime since, CancellationToken ct)
{
var ip = address.ToString();
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.TrapEvents.AnyAsync(e => e.RemoteIp == ip && e.Outcome == TrapOutcome.Timeout && e.StartedAt >= since, ct);
}
}
@@ -0,0 +1,55 @@
using Flypaper.Storage.Entities;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Settings;
public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContextFactory, TimeProvider timeProvider)
{
private static readonly TimeSpan LastUsedResolution = TimeSpan.FromMinutes(1);
public async Task<IReadOnlyList<McpTokenEntity>> ListAsync(CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
}
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, bool canWrite = false, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CanWrite = canWrite, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
db.McpTokens.Add(token);
await db.SaveChangesAsync(ct);
return token;
}
public async Task<bool> RevokeAsync(int id, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.McpTokens.Where(t => t.Id == id).ExecuteDeleteAsync(ct) > 0;
}
public async Task<bool> SetCanWriteAsync(int id, bool canWrite, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.McpTokens.Where(t => t.Id == id).ExecuteUpdateAsync(set => set.SetProperty(t => t.CanWrite, canWrite), ct) > 0;
}
public async Task<McpTokenEntity?> UseAsync(string tokenHash, CancellationToken ct = default)
{
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
var token = await db.McpTokens.SingleOrDefaultAsync(t => t.TokenHash == tokenHash, ct);
if (token is null)
{
return null;
}
var now = timeProvider.GetUtcNow().UtcDateTime;
if (token.LastUsedAt is null || now - token.LastUsedAt >= LastUsedResolution)
{
token.LastUsedAt = now;
await db.SaveChangesAsync(ct);
}
return token;
}
}
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more