Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3b6e8c327c | ||
|
|
3ce8d11c72 | ||
|
|
b168d1124d | ||
|
|
46f70c9065 | ||
|
|
c2ecb14b4a | ||
|
|
b559f83550 | ||
|
|
a46727bab3 | ||
|
|
302b40c172 | ||
|
|
7c11bf211e | ||
|
|
35aba56255 | ||
|
|
c5167262b9 | ||
|
|
4b946453fb | ||
|
|
2437880013 | ||
|
|
4086fa3da3 | ||
|
|
1979fd91e9 | ||
|
|
119dafa505 | ||
|
|
7f8a3ae882 | ||
|
|
cbd9830143 | ||
|
|
d2cbab5d4b | ||
|
|
0655af2699 | ||
|
|
e250a120ea | ||
|
|
e88dc415f9 | ||
|
|
a25072e6fb | ||
|
|
b7027e2a72 | ||
|
|
7d3e6f8842 | ||
|
|
aeafaa71a8 | ||
|
|
13468bbdf9 | ||
|
|
e48b6bb832 | ||
|
|
13a78f4268 | ||
|
|
9f07d41cb0 | ||
|
|
8eeb7894a3 | ||
|
|
e86518cab1 | ||
|
|
570ac20a5c | ||
|
|
393ebcdf0c |
No files matched your search
+252
-1
@@ -6,6 +6,243 @@ All notable changes to Flypaper are documented in this file. The format follows
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.12.0] - 2026-12-03
|
||||
|
||||
### Removed
|
||||
|
||||
- Signposts in the fake `.env`, JSON, YAML, SQL and Git files, together with the setting
|
||||
`Flypaper__Drip__Signposts` and the MCP `marker` (filter and field of `list_catches`). In a week none of about
|
||||
400 handed-out signposts was followed. The fake files are plain again.
|
||||
|
||||
## [0.11.2] - 2026-11-27
|
||||
|
||||
### Changed
|
||||
|
||||
- Dashboard: the column „Ziel“ is now „Aufgerufen“, in the catch list and the list of held bots: `/` reads
|
||||
„Startseite“, `GET` is not shown, other methods are named in plain words (`POST` „schickt Daten“, `HEAD`
|
||||
„prüft nur, ob es das gibt“, `OPTIONS` „fragt, was erlaubt ist“). The top-10 tab „Aufrufe“ counts the same
|
||||
call across all requested hosts, and its filter matches all of them.
|
||||
|
||||
### Removed
|
||||
|
||||
- Dashboard: the card „Eingeschleuste Befehle“ above the world map. Commands are found with the catch filter
|
||||
„Befehl: Nur mit Befehl“ and the ⚠ mark.
|
||||
|
||||
## [0.11.1] - 2026-11-27
|
||||
|
||||
### Changed
|
||||
|
||||
- Dashboard catch list: opened rows show a full-width detail area: the explanation in plain language first, for
|
||||
commands the facts „Angreifer“, „Fremder Server“ and „Befehl“, then collapsed „Technische Details“ (full
|
||||
request URL, origin, user agent, recorded headers and body). The list shows only method and path (without
|
||||
the requested host); commands are marked with „⚠“. Commands and servers are no longer defanged in the
|
||||
dashboard (still plain text, never links); MCP `list_commands` stays defanged.
|
||||
- The filter bar of the catch list fits the filter „Befehl“ into one row.
|
||||
|
||||
## [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
|
||||
@@ -85,7 +322,21 @@ First release.
|
||||
- Unraid Docker template; when started as root, the container hands `/data` to its app user
|
||||
and drops privileges.
|
||||
|
||||
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.3.0...main
|
||||
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.12.0...main
|
||||
[0.12.0]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.11.2...v0.12.0
|
||||
[0.11.2]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.11.2
|
||||
[0.11.1]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.11.1
|
||||
[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
|
||||
|
||||
@@ -20,9 +20,15 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...).
|
||||
| `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
|
||||
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` |
|
||||
| `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` |
|
||||
| `Flypaper__Drip__Content` | Hold method: `Html`, `Text` or `Alternating` | `Html` |
|
||||
| `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__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__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 |
|
||||
|
||||
The defaults of the runtime settings below can also be set this way, e.g.
|
||||
@@ -35,9 +41,10 @@ general reset button removes all saved values; the hold method section has its o
|
||||
|
||||
| Setting | Default |
|
||||
|---|---|
|
||||
| Hold method: content (HTML filler text, random plain text, or alternating per catch) | HTML filler text |
|
||||
| Hold method: pause between chunks, min and max (10 ms to 30 s) | 50 ms / 1000 ms |
|
||||
| Hold method: chunk size, min and max (1 to 4096 bytes) | 1 / 64 bytes |
|
||||
| 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 per IP | `10` |
|
||||
|
||||
@@ -61,6 +61,9 @@ seconds. A *period* is a number with `m`, `h`, `d` or `w` (e.g. `1h`, `24h`, `7d
|
||||
|
||||
| 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) | Events, newest first, including rejected ones |
|
||||
| `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 |
|
||||
|
||||
+1
-1
@@ -31,7 +31,7 @@ flowchart LR
|
||||
## Features
|
||||
|
||||
- **Trap** for everything that reaches the trap port: whatever host or path a bot asks for
|
||||
- **Slow delivery** of endless generated HTML or plain text (or both, alternating per catch)
|
||||
- **Slow delivery** of endless generated HTML (link labyrinth)
|
||||
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
|
||||
- **Dashboard**: totals, a world map, top countries, providers, IPs and paths, the latest
|
||||
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -6,5 +6,9 @@ public interface ITrapChannel
|
||||
{
|
||||
TrapSession Session { get; }
|
||||
|
||||
string? Path => null;
|
||||
|
||||
string? Host => null;
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -5,6 +5,7 @@ using Flypaper.Core.Strategies;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core;
|
||||
|
||||
@@ -17,12 +18,35 @@ public static class FlypaperCoreExtensions
|
||||
|
||||
services.TryAddSingleton(TimeProvider.System);
|
||||
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||
services.TryAddSingleton<IActiveTraps, ActiveTrapRegistry>();
|
||||
services.TryAddSingleton<IRandomSource, SystemRandomSource>();
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, HtmlDripStrategy>());
|
||||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, TextDripStrategy>());
|
||||
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<IIpEnricher, NullIpEnricher>();
|
||||
services.TryAddSingleton<IRepeatOffenderLookup, NullRepeatOffenderLookup>();
|
||||
services.TryAddSingleton<IKnownIpLookup, NullKnownIpLookup>();
|
||||
|
||||
return services;
|
||||
}
|
||||
|
||||
@@ -10,5 +10,11 @@ public sealed class FlypaperOptions
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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);
|
||||
@@ -1,3 +1,5 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
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);
|
||||
@@ -12,7 +12,8 @@ public sealed record TrapEvent(
|
||||
long BytesSent,
|
||||
TrapOutcome Outcome,
|
||||
string? Target = null,
|
||||
string? ClientInfo = null)
|
||||
string? ClientInfo = null,
|
||||
RequestDetails? Request = null)
|
||||
{
|
||||
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 _);
|
||||
}
|
||||
}
|
||||
@@ -13,16 +13,41 @@ public sealed class ConfiguredStrategySelector(
|
||||
public ITarpitStrategy? Select(TrapContext context)
|
||||
{
|
||||
var candidates = strategies.Where(strategy => strategy.Supports(context.Session.Protocol)).ToList();
|
||||
string[] wanted = options.CurrentValue.Content switch
|
||||
if (string.Equals(context.Path, RobotsStaticStrategy.Path, StringComparison.OrdinalIgnoreCase)
|
||||
&& candidates.FirstOrDefault(strategy => strategy.Name == RobotsStaticStrategy.StrategyName) is { } robots)
|
||||
{
|
||||
DripContent.Text => [TextDripStrategy.StrategyName],
|
||||
DripContent.Alternating => [HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName],
|
||||
_ => [HtmlDripStrategy.StrategyName]
|
||||
};
|
||||
return robots;
|
||||
}
|
||||
|
||||
var matching = candidates.Where(strategy => wanted.Contains(strategy.Name)).ToList();
|
||||
return matching.Count == 0
|
||||
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 string? Path => inner.Path;
|
||||
|
||||
public string? Host => inner.Host;
|
||||
|
||||
public long BytesSent => Interlocked.Read(ref _bytesSent);
|
||||
|
||||
public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
|
||||
|
||||
@@ -11,6 +11,8 @@ public sealed partial class TrapRunner(
|
||||
IConnectionGovernor governor,
|
||||
ITrapStrategySelector strategies,
|
||||
ITrapEventSink sink,
|
||||
IActiveTraps activeTraps,
|
||||
IRepeatOffenderLookup repeatOffenders,
|
||||
IOptionsMonitor<FlypaperOptions> options,
|
||||
TimeProvider timeProvider,
|
||||
ILogger<TrapRunner> logger)
|
||||
@@ -25,13 +27,28 @@ public sealed partial class TrapRunner(
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
using var _ = lease;
|
||||
var description = strategy is IStrategyDetails details ? details.Describe() : strategy.Name;
|
||||
using var hold = new CancellationTokenSource(options.CurrentValue.MaxHoldDuration, timeProvider);
|
||||
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);
|
||||
|
||||
CountingTrapChannel? channel = null;
|
||||
@@ -39,6 +56,8 @@ public sealed partial class TrapRunner(
|
||||
try
|
||||
{
|
||||
channel = new CountingTrapChannel(await openChannel(strategy, linked.Token));
|
||||
var counting = channel;
|
||||
active.Attach(() => counting.BytesSent);
|
||||
await strategy.RunAsync(channel, linked.Token);
|
||||
}
|
||||
catch (OperationCanceledException) when (linked.IsCancellationRequested)
|
||||
@@ -52,11 +71,13 @@ public sealed partial class TrapRunner(
|
||||
outcome = TrapOutcome.ClientAborted;
|
||||
}
|
||||
|
||||
Publish(context, description, 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;
|
||||
}
|
||||
|
||||
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 trapEvent = new TrapEvent(
|
||||
@@ -65,11 +86,12 @@ public sealed partial class TrapRunner(
|
||||
session.RemoteIp,
|
||||
strategy,
|
||||
session.StartedAt,
|
||||
timeProvider.GetUtcNow(),
|
||||
endedAt,
|
||||
bytesSent,
|
||||
outcome,
|
||||
context.Target,
|
||||
context.ClientInfo);
|
||||
context.ClientInfo,
|
||||
request);
|
||||
|
||||
var store = !(options.CurrentValue.IgnorePrivateNetworks && PrivateNetworks.Contains(trapEvent.RemoteIp));
|
||||
var storageNote = store ? "" : " (not stored)";
|
||||
|
||||
@@ -4,23 +4,33 @@ using Flypaper.Core.Strategies;
|
||||
namespace Flypaper.Core.Settings;
|
||||
|
||||
public sealed record HoldMethodSettings(
|
||||
DripContent Content,
|
||||
TimeSpan MinDelay,
|
||||
TimeSpan MaxDelay,
|
||||
int MinChunkSize,
|
||||
int MaxChunkSize,
|
||||
TimeSpan MaxHoldDuration)
|
||||
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.DripContent] = Content.ToString(),
|
||||
[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.MaxHoldDuration] = MaxHoldDuration.ToString("c", 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)
|
||||
@@ -31,11 +41,16 @@ public sealed record HoldMethodSettings(
|
||||
}
|
||||
|
||||
public sealed record HoldMethodInput(
|
||||
string? Content,
|
||||
string? MinDelayMs,
|
||||
string? MaxDelayMs,
|
||||
string? MinChunkSize,
|
||||
string? MaxChunkSize,
|
||||
string? MaxHoldDuration);
|
||||
string? HeadStartSize,
|
||||
bool MatchPath,
|
||||
string? LinkSpacing,
|
||||
string? BaitPaths,
|
||||
string? MaxHoldDuration,
|
||||
string? RepeatWindowDays,
|
||||
string? RepeatHoldDuration);
|
||||
|
||||
public sealed record HoldMethodParseResult(HoldMethodSettings? Settings, IReadOnlyDictionary<string, string> Errors);
|
||||
@@ -13,6 +13,9 @@ public static class RuntimeSettingsParser
|
||||
private const int MinDelayMs = 10;
|
||||
private const int MaxDelayMs = 30_000;
|
||||
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)
|
||||
{
|
||||
@@ -45,19 +48,16 @@ public static class RuntimeSettingsParser
|
||||
{
|
||||
var errors = new Dictionary<string, string>();
|
||||
|
||||
DripContent? content = Enum.TryParse<DripContent>(input.Content, ignoreCase: true, out var parsed) && Enum.IsDefined(parsed)
|
||||
? parsed
|
||||
: null;
|
||||
if (content is null)
|
||||
{
|
||||
errors[nameof(input.Content)] = "Bitte eine Methode wählen.";
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
@@ -76,15 +76,40 @@ public static class RuntimeSettingsParser
|
||||
|
||||
return new HoldMethodParseResult(
|
||||
new HoldMethodSettings(
|
||||
content!.Value,
|
||||
TimeSpan.FromMilliseconds(minDelay!.Value),
|
||||
TimeSpan.FromMilliseconds(maxDelay!.Value),
|
||||
minChunk!.Value,
|
||||
maxChunk!.Value,
|
||||
hold!.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;
|
||||
}
|
||||
|
||||
var distinct = normalized.OfType<string>().Distinct().ToList();
|
||||
if (distinct.Count > BaitPaths.MaxCount)
|
||||
{
|
||||
errors[field] = $"Höchstens {BaitPaths.MaxCount} Pfade.";
|
||||
return null;
|
||||
}
|
||||
|
||||
return string.Join(',', distinct);
|
||||
}
|
||||
|
||||
private static TimeSpan? ParseTimeSpan(
|
||||
string? raw,
|
||||
string field,
|
||||
@@ -101,7 +126,7 @@ public static class RuntimeSettingsParser
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,19 +5,24 @@ public static class SettingKeys
|
||||
public const string MaxConnections = "Flypaper:MaxConnections";
|
||||
public const string MaxConnectionsPerIp = "Flypaper:MaxConnectionsPerIp";
|
||||
public const string MaxHoldDuration = "Flypaper:MaxHoldDuration";
|
||||
public const string RepeatWindowDays = "Flypaper:RepeatWindowDays";
|
||||
public const string RepeatHoldDuration = "Flypaper:RepeatHoldDuration";
|
||||
public const string IgnorePrivateNetworks = "Flypaper:IgnorePrivateNetworks";
|
||||
public const string RetentionDays = "Flypaper:Retention:Days";
|
||||
public const string DripContent = "Flypaper:Drip:Content";
|
||||
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 IReadOnlyList<string> General =
|
||||
[MaxConnections, MaxConnectionsPerIp, IgnorePrivateNetworks, RetentionDays];
|
||||
|
||||
public static readonly IReadOnlyList<string> HoldMethod =
|
||||
[DripContent, DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, MaxHoldDuration];
|
||||
[DripMinDelay, DripMaxDelay, DripMinChunkSize, DripMaxChunkSize, DripHeadStartSize, DripMatchPath, DripLinkSpacing, DripBaitPaths, MaxHoldDuration, RepeatWindowDays, RepeatHoldDuration];
|
||||
|
||||
public static readonly IReadOnlySet<string> All =
|
||||
new HashSet<string>(General.Concat(HoldMethod), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public enum DripContent
|
||||
{
|
||||
Html,
|
||||
Text,
|
||||
Alternating
|
||||
}
|
||||
@@ -4,8 +4,6 @@ public sealed class DripOptions
|
||||
{
|
||||
public const string SectionName = "Flypaper:Drip";
|
||||
|
||||
public DripContent Content { get; set; } = DripContent.Html;
|
||||
|
||||
public TimeSpan MinDelay { get; set; } = TimeSpan.FromMilliseconds(50);
|
||||
|
||||
public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(1);
|
||||
@@ -13,4 +11,14 @@ public sealed class DripOptions
|
||||
public int MinChunkSize { get; set; } = 1;
|
||||
|
||||
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 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 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)
|
||||
{
|
||||
var minChunk = Math.Max(1, options.MinChunkSize);
|
||||
|
||||
@@ -19,14 +19,24 @@ public abstract class DripStrategy(
|
||||
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");
|
||||
$"{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)
|
||||
{
|
||||
foreach (var step in DripSchedule.Create(Content(random), random, options.CurrentValue))
|
||||
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);
|
||||
@@ -34,5 +44,7 @@ public abstract class DripStrategy(
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract IEnumerable<string> Content(IRandomSource random);
|
||||
protected virtual string Extra(DripOptions options) => "";
|
||||
|
||||
protected abstract IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options);
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
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, 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"), Svn),
|
||||
new("hg-drip", "text/plain; charset=utf-8", path => IsInside(path, "/.hg"), Mercurial),
|
||||
new("wordpress-drip", "text/html; charset=UTF-8", path => LastSegment(path) == "wp-login.php", WordPressLogin),
|
||||
new("hikvision-drip", "application/xml", path => path.StartsWith("/sdk/", StringComparison.Ordinal) || path.StartsWith("/isapi/", StringComparison.Ordinal), Hikvision),
|
||||
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), Xml),
|
||||
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)
|
||||
{
|
||||
yield return $"APP_NAME=Portal\nAPP_ENV=production\nAPP_DEBUG=false\nAPP_URL=https://example.com\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";
|
||||
|
||||
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 ‹ Portal — 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="/">← 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)
|
||||
{
|
||||
yield return "{\n \"name\": \"portal\",\n \"version\": \"1.4.2\",\n \"private\": true,\n \"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)
|
||||
{
|
||||
yield return "version: \"3.8\"\nservices:\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)
|
||||
{
|
||||
yield return "-- MySQL dump 10.13 Distrib 8.0.36, for Linux (x86_64)\n--\n-- Host: localhost Database: app\n-- ------------------------------------------------------\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)
|
||||
{
|
||||
yield return "[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n\tlogallrefupdates = true\n"
|
||||
+ "[remote \"origin\"]\n\turl = https://example.com/portal.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n";
|
||||
|
||||
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)];
|
||||
}
|
||||
+5
-6
@@ -3,16 +3,15 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public sealed class TextDripStrategy(
|
||||
public sealed class FileDripStrategy(
|
||||
FileProfile profile,
|
||||
IOptionsMonitor<DripOptions> options,
|
||||
IRandomSource random,
|
||||
TimeProvider timeProvider) : DripStrategy(options, random, timeProvider)
|
||||
{
|
||||
public const string StrategyName = "text-drip";
|
||||
public override string Name => profile.Name;
|
||||
|
||||
public override string Name => StrategyName;
|
||||
public override string MediaType => profile.MediaType;
|
||||
|
||||
public override string MediaType => "text/plain; charset=utf-8";
|
||||
|
||||
protected override IEnumerable<string> Content(IRandomSource random) => TextContent.Generate(random);
|
||||
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => profile.Generate(random);
|
||||
}
|
||||
@@ -14,5 +14,5 @@ public sealed class HtmlDripStrategy(
|
||||
|
||||
public override string MediaType => "text/html; charset=utf-8";
|
||||
|
||||
protected override IEnumerable<string> Content(IRandomSource random) => HtmlContent.Generate(random);
|
||||
protected override IEnumerable<string> Content(IRandomSource random, ITrapChannel channel, DripOptions options) => HtmlContent.Generate(random);
|
||||
}
|
||||
@@ -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 – 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 » 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);
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
using System.Text;
|
||||
using Flypaper.Core.Abstractions;
|
||||
|
||||
namespace Flypaper.Core.Strategies;
|
||||
|
||||
public static class TextContent
|
||||
{
|
||||
public static IEnumerable<string> Generate(IRandomSource random)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
var builder = new StringBuilder();
|
||||
var sentences = random.Next(1, 7);
|
||||
for (var i = 0; i < sentences; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
{
|
||||
builder.Append(' ');
|
||||
}
|
||||
|
||||
builder.Append(LoremText.Sentence(random));
|
||||
}
|
||||
|
||||
yield return builder.Append(random.Next(0, 4) == 0 ? "\n\n" : "\n").ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,8 @@ public static class FlypaperHttpExtensions
|
||||
"Flypaper:Http:KnownHosts",
|
||||
"Flypaper:Http:TrapPaths",
|
||||
"Flypaper:Http:ExtraKnownHosts",
|
||||
"Flypaper:Http:TrapPathsOverride"
|
||||
"Flypaper:Http:TrapPathsOverride",
|
||||
"Flypaper:Drip:Content"
|
||||
];
|
||||
|
||||
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
|
||||
|
||||
@@ -8,6 +8,10 @@ internal sealed class HttpTrapChannel(TrapSession session, HttpResponse response
|
||||
{
|
||||
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)
|
||||
{
|
||||
await response.Body.WriteAsync(data, ct);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Core.Networking;
|
||||
using Flypaper.Core.Runtime;
|
||||
using Flypaper.Core.Strategies;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.Features;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
|
||||
@@ -14,6 +16,9 @@ internal sealed class FlypaperMiddleware(
|
||||
RequestDelegate next,
|
||||
TrapRunner runner,
|
||||
IOptions<PortOptions> ports,
|
||||
IKnownIpLookup knownIps,
|
||||
IOptionsMonitor<DripOptions> drip,
|
||||
IOptionsMonitor<FlypaperOptions> options,
|
||||
TimeProvider timeProvider)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
@@ -32,14 +37,29 @@ internal sealed class FlypaperMiddleware(
|
||||
context.Connection.RemoteIpAddress ?? IPAddress.None,
|
||||
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(
|
||||
session,
|
||||
$"{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(
|
||||
trapContext,
|
||||
(strategy, ct) => OpenChannelAsync(context, session, strategy, ct),
|
||||
async (strategy, ct) =>
|
||||
{
|
||||
var channel = await OpenChannelAsync(context, session, strategy, ct);
|
||||
capture?.Start();
|
||||
return channel;
|
||||
},
|
||||
context.RequestAborted);
|
||||
|
||||
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
|
||||
@@ -73,8 +93,17 @@ internal sealed class FlypaperMiddleware(
|
||||
var response = context.Response;
|
||||
response.StatusCode = StatusCodes.Status200OK;
|
||||
response.ContentType = strategy is IStrategyDetails details ? details.MediaType : "text/html; charset=utf-8";
|
||||
response.Headers.Server = "nginx";
|
||||
response.Headers.CacheControl = "no-store";
|
||||
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);
|
||||
|
||||
return new HttpTrapChannel(session, response);
|
||||
|
||||
@@ -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;
|
||||
|
||||
public sealed record DashboardData(
|
||||
int TotalCatches,
|
||||
int CatchesLast24Hours,
|
||||
int Rejected,
|
||||
int RejectedLast24Hours,
|
||||
int UniqueIps,
|
||||
int UniqueIpsLast24Hours,
|
||||
TimeSpan TotalHoldTime,
|
||||
IReadOnlyList<TrapEventEntity> Recent,
|
||||
IReadOnlyList<TopEntry> TopIps,
|
||||
IReadOnlyList<TopEntry> TopTargets,
|
||||
IReadOnlyList<StrategySample> StrategyCatches,
|
||||
IReadOnlyList<TopEntry> TopCountries,
|
||||
IReadOnlyList<TopEntry> TopProviders,
|
||||
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.Storage.Entities;
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
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;
|
||||
|
||||
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(e => e.StartedAt >= since, 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.Where(e => e.StartedAt >= since).Select(e => e.RemoteIp).Distinct().CountAsync(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.Where(e => e.Target != null).GroupBy(e => e.Target!), ct),
|
||||
await TopRequestsAsync(catches, ct),
|
||||
await catches.Select(e => new StrategySample(e.Strategy, e.DurationMs)).ToListAsync(ct),
|
||||
countries
|
||||
.Take(TopCount)
|
||||
.Select(x => new TopEntry(x.Key, x.Count, TimeSpan.FromMilliseconds(x.DurationMs), x.Name))
|
||||
@@ -52,6 +54,143 @@ public sealed class DashboardQueries(IDbContextFactory<FlypaperDbContext> dbCont
|
||||
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)
|
||||
{
|
||||
var space = target.IndexOf(' ');
|
||||
if (space >= 0 && target.AsSpan(space + 1).StartsWith("/"))
|
||||
{
|
||||
var method = target[..(space + 1)];
|
||||
var path = target[(space + 1)..];
|
||||
events = events.Where(e => e.Target!.StartsWith(method) && e.Target.Substring(e.Target.IndexOf("/")) == path);
|
||||
}
|
||||
else
|
||||
{
|
||||
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>> TopRequestsAsync(IQueryable<TrapEventEntity> catches, CancellationToken ct)
|
||||
{
|
||||
var rows = await catches
|
||||
.Where(e => e.Target != null)
|
||||
.GroupBy(e => e.Target!)
|
||||
.Select(g => new { g.Key, Count = g.Count(), DurationMs = g.Sum(e => e.DurationMs) })
|
||||
.ToListAsync(ct);
|
||||
|
||||
return rows
|
||||
.GroupBy(r => RequestKey.Of(r.Key), StringComparer.Ordinal)
|
||||
.Select(g => new TopEntry(g.Key, g.Sum(r => r.Count), TimeSpan.FromMilliseconds(g.Sum(r => r.DurationMs))))
|
||||
.OrderByDescending(x => x.Count)
|
||||
.ThenByDescending(x => x.HoldTime)
|
||||
.Take(TopCount)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
private static async Task<IReadOnlyList<TopEntry>> TopAsync(
|
||||
IQueryable<IGrouping<string, TrapEventEntity>> groups,
|
||||
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,13 @@
|
||||
namespace Flypaper.Storage.Dashboard;
|
||||
|
||||
public static class RequestKey
|
||||
{
|
||||
public static (string Method, string Path)? Split(string? target)
|
||||
{
|
||||
var space = target?.IndexOf(' ') ?? -1;
|
||||
var slash = space < 0 ? -1 : target!.IndexOf('/', space);
|
||||
return slash < 0 ? null : (target![..space], target[slash..]);
|
||||
}
|
||||
|
||||
public static string Of(string target) => Split(target) is var (method, path) ? $"{method} {path}" : target;
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -11,4 +11,6 @@ public sealed class McpTokenEntity
|
||||
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;
|
||||
|
||||
namespace Flypaper.Storage.Entities;
|
||||
@@ -38,8 +39,34 @@ public sealed class TrapEventEntity
|
||||
|
||||
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,
|
||||
Protocol = trapEvent.Protocol,
|
||||
RemoteIp = trapEvent.RemoteIp.ToString(),
|
||||
@@ -50,7 +77,8 @@ public sealed class TrapEventEntity
|
||||
BytesSent = trapEvent.BytesSent,
|
||||
Outcome = trapEvent.Outcome,
|
||||
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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using Flypaper.Core.Analysis;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Flypaper.Storage;
|
||||
@@ -10,10 +12,14 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
|
||||
public DbSet<TrapEventEntity> TrapEvents => Set<TrapEventEntity>();
|
||||
|
||||
public DbSet<TrapRequestEntity> TrapRequests => Set<TrapRequestEntity>();
|
||||
|
||||
public DbSet<SettingEntity> Settings => Set<SettingEntity>();
|
||||
|
||||
public DbSet<McpTokenEntity> McpTokens => Set<McpTokenEntity>();
|
||||
|
||||
public DbSet<ExplanationRuleEntity> ExplanationRules => Set<ExplanationRuleEntity>();
|
||||
|
||||
protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) =>
|
||||
configurationBuilder.Properties<DateTime>().HaveConversion<UtcDateTimeConverter>();
|
||||
|
||||
@@ -34,6 +40,14 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
trapEvent.HasIndex(e => e.RemoteIp);
|
||||
trapEvent.HasIndex(e => e.CountryCode);
|
||||
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>();
|
||||
setting.HasKey(e => e.Key);
|
||||
@@ -43,5 +57,12 @@ public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> option
|
||||
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,6 +1,7 @@
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Storage.Dashboard;
|
||||
using Flypaper.Storage.Events;
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Flypaper.Storage.Maintenance;
|
||||
using Flypaper.Storage.Queries;
|
||||
using Flypaper.Storage.Settings;
|
||||
@@ -36,8 +37,14 @@ public static class FlypaperStorageExtensions
|
||||
services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
|
||||
services.AddHostedService<TrapEventWriter>();
|
||||
services.AddHostedService<OriginBackfill>();
|
||||
services.AddHostedService<CommandBackfill>();
|
||||
services.AddSingleton<ExplanationRuleStore>();
|
||||
services.AddSingleton<ExplanationQueries>();
|
||||
services.AddSingleton<DashboardQueries>();
|
||||
services.AddSingleton<CatchQueries>();
|
||||
services.AddSingleton<CommandQueries>();
|
||||
services.AddSingleton<IRepeatOffenderLookup, RepeatOffenderLookup>();
|
||||
services.AddSingleton<IKnownIpLookup, KnownIpLookup>();
|
||||
services.AddSingleton<TrapDataMaintenance>();
|
||||
services.AddHostedService<RetentionCleanup>();
|
||||
return services;
|
||||
|
||||
@@ -32,6 +32,12 @@ internal sealed partial class RetentionCleanup(
|
||||
|
||||
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;
|
||||
if (days <= 0)
|
||||
{
|
||||
|
||||
@@ -5,4 +5,6 @@ public sealed class RetentionOptions
|
||||
public const string SectionName = "Flypaper:Retention";
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
await using var db = await dbContextFactory.CreateDbContextAsync(ct);
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+201
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
+261
@@ -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,12 +17,62 @@ namespace Flypaper.Storage.Migrations
|
||||
#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");
|
||||
|
||||
@@ -82,6 +132,17 @@ namespace Flypaper.Storage.Migrations
|
||||
.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");
|
||||
@@ -134,14 +195,63 @@ namespace Flypaper.Storage.Migrations
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +93,8 @@ public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextF
|
||||
.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))
|
||||
@@ -107,6 +109,17 @@ public sealed class CatchQueries(IDbContextFactory<FlypaperDbContext> dbContextF
|
||||
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);
|
||||
|
||||
@@ -42,6 +42,7 @@ public enum TopDimension
|
||||
Countries,
|
||||
Providers,
|
||||
Targets,
|
||||
Strategies,
|
||||
UserAgents
|
||||
}
|
||||
|
||||
|
||||
@@ -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,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);
|
||||
}
|
||||
}
|
||||
@@ -13,10 +13,10 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
|
||||
return await db.McpTokens.AsNoTracking().OrderBy(t => t.Id).ToListAsync(ct);
|
||||
}
|
||||
|
||||
public async Task<McpTokenEntity> CreateAsync(string name, string tokenHash, CancellationToken ct = default)
|
||||
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, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
||||
var token = new McpTokenEntity { Name = name, TokenHash = tokenHash, CanWrite = canWrite, CreatedAt = timeProvider.GetUtcNow().UtcDateTime };
|
||||
db.McpTokens.Add(token);
|
||||
await db.SaveChangesAsync(ct);
|
||||
return token;
|
||||
@@ -28,6 +28,12 @@ public sealed class McpTokenStore(IDbContextFactory<FlypaperDbContext> dbContext
|
||||
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);
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
<nav class="nav">
|
||||
<a href="/" class="brand"><span class="brand-mark" aria-hidden="true"></span>Flypaper</a>
|
||||
<NavLink href="/" Match="NavLinkMatch.All">Dashboard</NavLink>
|
||||
<NavLink href="/erklaerungen">Erklärungen</NavLink>
|
||||
<NavLink href="/settings">Einstellungen</NavLink>
|
||||
<form method="post" action="/auth/logout" class="logout">
|
||||
<AntiforgeryToken />
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
@{
|
||||
var (text, note, method) = Formatting.Called(Target);
|
||||
}
|
||||
@text@if (note is not null)
|
||||
{
|
||||
<span class="method-note" title="@method"> · @note</span>
|
||||
}
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public string? Target { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage.Dashboard;
|
||||
using Flypaper.Web.Components.Shared;
|
||||
|
||||
namespace Flypaper.Web.Components.Pages.Dashboard;
|
||||
|
||||
public sealed record DashboardFilter(
|
||||
string? Zeit = null,
|
||||
string? Ausgang = null,
|
||||
string? Land = null,
|
||||
string? Provider = null,
|
||||
string? Ip = null,
|
||||
string? Ziel = null,
|
||||
string? Strategie = null,
|
||||
string? Q = null,
|
||||
int Limit = RecentFilter.DefaultLimit,
|
||||
string? Erklaerung = null,
|
||||
string? Befehl = null)
|
||||
{
|
||||
public const string Anchor = "faenge";
|
||||
|
||||
public static readonly IReadOnlyList<(string Value, string Label)> Periods = [("", "Alles"), ("24h", "24 h"), ("7d", "7 Tage")];
|
||||
|
||||
public static readonly IReadOnlyList<(string Value, string Label)> Outcomes =
|
||||
[("", "Alle"), ("aufgegeben", "Aufgegeben"), ("zeitlimit", "Zeitlimit"), ("abgelehnt", "Abgelehnt")];
|
||||
|
||||
public static readonly IReadOnlyList<(string Value, string Label)> Explanations = [("", "Alle"), ("ohne", "Ohne Erklärung")];
|
||||
|
||||
public static readonly IReadOnlyList<(string Value, string Label)> Commands = [("", "Alle"), ("ja", "Nur mit Befehl")];
|
||||
|
||||
public bool IsEmpty => this with { Limit = RecentFilter.DefaultLimit } == new DashboardFilter();
|
||||
|
||||
public static DashboardFilter Parse(
|
||||
string? zeit,
|
||||
string? ausgang,
|
||||
string? land,
|
||||
string? provider,
|
||||
string? ip,
|
||||
string? ziel,
|
||||
string? strategie,
|
||||
string? q,
|
||||
string? limit,
|
||||
string? erklaerung = null,
|
||||
string? befehl = null)
|
||||
{
|
||||
var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value)
|
||||
? Math.Clamp(value, 1, RecentFilter.MaxLimit)
|
||||
: RecentFilter.DefaultLimit;
|
||||
|
||||
return new DashboardFilter(
|
||||
Known(Periods, zeit),
|
||||
Known(Outcomes, ausgang),
|
||||
Clean(land) is { Length: 2 } country && country.All(char.IsAsciiLetter) ? country.ToUpperInvariant() : null,
|
||||
Asn(provider) is { } asn ? $"AS{asn.ToString(CultureInfo.InvariantCulture)}" : null,
|
||||
IPAddress.TryParse(Clean(ip), out var address) ? address.ToString() : null,
|
||||
Clean(ziel),
|
||||
Clean(strategie) is { } strategy ? StrategyNames.GroupKey(strategy) : null,
|
||||
Clean(q),
|
||||
parsedLimit,
|
||||
Known(Explanations, erklaerung),
|
||||
Known(Commands, befehl));
|
||||
}
|
||||
|
||||
public RecentFilter ToRecentFilter() => new(
|
||||
Zeit switch
|
||||
{
|
||||
"24h" => TimeSpan.FromHours(24),
|
||||
"7d" => TimeSpan.FromDays(7),
|
||||
_ => null
|
||||
},
|
||||
Ausgang switch
|
||||
{
|
||||
"aufgegeben" => TrapOutcome.ClientAborted,
|
||||
"zeitlimit" => TrapOutcome.Timeout,
|
||||
"abgelehnt" => TrapOutcome.Rejected,
|
||||
_ => null
|
||||
},
|
||||
Land,
|
||||
Asn(Provider),
|
||||
Ip,
|
||||
Ziel,
|
||||
StrategyNames.Group(Strategie),
|
||||
Q,
|
||||
Limit,
|
||||
Unexplained: Erklaerung == "ohne",
|
||||
WithCommand: Befehl == "ja");
|
||||
|
||||
public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit);
|
||||
|
||||
public string Href(string anchor = Anchor)
|
||||
{
|
||||
var parts = new List<string>();
|
||||
Add(parts, "zeit", Zeit);
|
||||
Add(parts, "ausgang", Ausgang);
|
||||
Add(parts, "land", Land);
|
||||
Add(parts, "provider", Provider);
|
||||
Add(parts, "ip", Ip);
|
||||
Add(parts, "ziel", Ziel);
|
||||
Add(parts, "strategie", Strategie);
|
||||
Add(parts, "q", Q);
|
||||
Add(parts, "erklaerung", Erklaerung);
|
||||
Add(parts, "befehl", Befehl);
|
||||
if (Limit != RecentFilter.DefaultLimit)
|
||||
{
|
||||
Add(parts, "limit", Limit.ToString(CultureInfo.InvariantCulture));
|
||||
}
|
||||
|
||||
return parts.Count == 0 ? $"/#{anchor}" : $"/?{string.Join("&", parts)}#{anchor}";
|
||||
}
|
||||
|
||||
private static void Add(List<string> parts, string name, string? value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
{
|
||||
parts.Add($"{name}={Uri.EscapeDataString(value)}");
|
||||
}
|
||||
}
|
||||
|
||||
private static string? Known(IReadOnlyList<(string Value, string Label)> options, string? value)
|
||||
{
|
||||
var clean = Clean(value)?.ToLowerInvariant();
|
||||
return clean is not null && options.Any(o => o.Value == clean) ? clean : null;
|
||||
}
|
||||
|
||||
private static long? Asn(string? value)
|
||||
{
|
||||
var clean = Clean(value);
|
||||
if (clean is null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var digits = clean.StartsWith("AS", StringComparison.OrdinalIgnoreCase) ? clean[2..] : clean;
|
||||
return long.TryParse(digits, NumberStyles.None, CultureInfo.InvariantCulture, out var asn) ? asn : null;
|
||||
}
|
||||
|
||||
private static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
}
|
||||
@@ -1,11 +1,16 @@
|
||||
@page "/"
|
||||
@using Flypaper.Core.Abstractions
|
||||
@using Flypaper.Core.Models
|
||||
@using Flypaper.Http
|
||||
@using Microsoft.Extensions.Options
|
||||
@using Flypaper.Storage.Dashboard
|
||||
@using Flypaper.Storage.Entities
|
||||
@using Flypaper.Storage.Explanations
|
||||
@inject DashboardQueries Queries
|
||||
@inject ExplanationRuleStore Explanations
|
||||
@inject IConnectionGovernor Governor
|
||||
@inject IActiveTraps ActiveTraps
|
||||
@inject IIpEnricher Enricher
|
||||
@inject IOptions<PortOptions> Ports
|
||||
|
||||
<PageTitle>Flypaper</PageTitle>
|
||||
@@ -21,32 +26,86 @@
|
||||
@if (_data is { } data)
|
||||
{
|
||||
var active = Governor.ActiveConnections;
|
||||
var tabs = TopTabs(data);
|
||||
<section class="metrics">
|
||||
<div class="metric metric-hero @(active > 0 ? "live" : null)">
|
||||
<div class="metric @(active > 0 ? "live" : null)">
|
||||
<span class="label">Gerade in der Falle</span>
|
||||
<span class="value">@active.ToString("N0")</span>
|
||||
<span class="sub">@(active == 1 ? "Bot wird festgehalten" : "Bots werden festgehalten")</span>
|
||||
<span class="value">@Formatting.Number(active)</span>
|
||||
<span class="sub">@(active == 1 ? "Bot festgehalten" : "Bots festgehalten")</span>
|
||||
</div>
|
||||
<div class="metric metric-hero">
|
||||
<div class="metric">
|
||||
<span class="label">Fänge gesamt</span>
|
||||
<span class="value">@data.TotalCatches.ToString("N0")</span>
|
||||
<span class="sub">+@data.CatchesLast24Hours.ToString("N0") in den letzten 24 h</span>
|
||||
<span class="value">@Formatting.Number(data.TotalCatches)</span>
|
||||
<span class="sub">+@Formatting.Number(data.CatchesLast24Hours) in 24 h</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Eindeutige IPs</span>
|
||||
<span class="value">@data.UniqueIps.ToString("N0")</span>
|
||||
<span class="value">@Formatting.Number(data.UniqueIps)</span>
|
||||
<span class="sub">@Formatting.Number(data.UniqueIpsLast24Hours) in 24 h aktiv</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Haltezeit gesamt</span>
|
||||
<span class="value">@Formatting.Duration(data.TotalHoldTime)</span>
|
||||
<span class="sub">Ø @(data.TotalCatches == 0 ? "–" : Formatting.Duration(data.TotalHoldTime / data.TotalCatches)) pro Fang</span>
|
||||
</div>
|
||||
<div class="metric">
|
||||
<span class="label">Abgelehnt</span>
|
||||
<span class="value">@data.Rejected.ToString("N0")</span>
|
||||
<span class="sub">wegen Verbindungslimits</span>
|
||||
<span class="value">@Formatting.Number(data.Rejected)</span>
|
||||
<span class="sub">+@Formatting.Number(data.RejectedLast24Hours) in 24 h · Limit erreicht</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@if (_active.Count > 0)
|
||||
{
|
||||
<section class="card recent-card active-card">
|
||||
<div class="card-head">
|
||||
<h2>Gerade in der Falle <span class="count">· @Formatting.Number(_active.Count)</span></h2>
|
||||
<span class="hint">Seit dem Laden der Seite weiter festgehalten</span>
|
||||
</div>
|
||||
<div class="scroll">
|
||||
<table class="recent-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="c-ip">IP</th>
|
||||
<th class="c-origin">Herkunft</th>
|
||||
<th class="c-target">Aufgerufen</th>
|
||||
<th class="c-strategy">Strategie</th>
|
||||
<th class="c-agent">User-Agent</th>
|
||||
<th class="c-duration num">Seit</th>
|
||||
<th class="c-bytes num">Bytes</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var trap in _active)
|
||||
{
|
||||
var origin = Enricher.Lookup(trap.Ip);
|
||||
var strategy = StrategyNames.Describe(trap.Strategy);
|
||||
var ip = trap.Ip.ToString();
|
||||
<tr>
|
||||
<td class="c-ip mono"><a href="@(new DashboardFilter { Ip = ip }.Href(DashboardFilter.Anchor))" title="Fänge dieser IP anzeigen">@ip</a></td>
|
||||
<td class="c-origin" title="@origin?.Provider">
|
||||
@if (origin?.CountryCode is { } countryCode)
|
||||
{
|
||||
@($"{Formatting.Flag(countryCode)} {countryCode}")
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="muted">–</span>
|
||||
}
|
||||
</td>
|
||||
<td class="c-target mono" title="@Formatting.CalledText(trap.Target)"><CalledCell Target="@trap.Target" /></td>
|
||||
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName</td>
|
||||
<td class="c-agent" title="@trap.ClientInfo">@trap.ClientInfo</td>
|
||||
<td class="c-duration num">@Formatting.Duration(_loadedAtUtc - trap.StartedAt)</td>
|
||||
<td class="c-bytes num">@Formatting.Number(trap.BytesSent)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (data.TotalCatches == 0)
|
||||
{
|
||||
<section class="card onboarding">
|
||||
@@ -62,22 +121,112 @@
|
||||
|
||||
<section class="origin">
|
||||
<WorldMap CatchesByCountry="data.CatchesByCountry" />
|
||||
<TopTable Title="Top 10 Länder" KeyLabel="Land" Entries="data.TopCountries" ShowFlags="true" LabelFormatter="CountryNames.Display" />
|
||||
</section>
|
||||
|
||||
@if (data.TotalCatches > 0)
|
||||
{
|
||||
<section class="tops">
|
||||
<TopTable Title="Top 10 Provider" KeyLabel="Provider" Entries="data.TopProviders" />
|
||||
<TopTable Title="Top 10 IPs" KeyLabel="IP" Entries="data.TopIps" />
|
||||
<TopTable Title="Top 10 Ziele" KeyLabel="Ziel" Entries="data.TopTargets" KeyFormatter="Formatting.Target" />
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<section class="card tops-card">
|
||||
<div class="card-head">
|
||||
<h2>Letzte 50 Fänge</h2>
|
||||
<span class="hint">Zeile anklicken zum Aufklappen</span>
|
||||
<h2 id="tops-title">Top 10</h2>
|
||||
<span class="hint">Klick filtert die Fänge</span>
|
||||
</div>
|
||||
<div class="tabs" role="tablist" aria-labelledby="tops-title">
|
||||
@foreach (var tab in tabs)
|
||||
{
|
||||
var first = tab == tabs[0];
|
||||
<button type="button" role="tab" id="tab-@tab.Id" aria-controls="panel-@tab.Id" aria-selected="@(first ? "true" : "false")" tabindex="@(first ? 0 : -1)">@tab.Label</button>
|
||||
}
|
||||
</div>
|
||||
@foreach (var tab in tabs)
|
||||
{
|
||||
<div role="tabpanel" id="panel-@tab.Id" aria-labelledby="tab-@tab.Id" tabindex="0" hidden="@(tab != tabs[0])">
|
||||
<TopTable KeyLabel="@tab.KeyLabel" Entries="tab.Entries" ShowFlags="tab.ShowFlags" KeyFormatter="tab.KeyFormatter" LabelFormatter="tab.LabelFormatter" TitleFormatter="tab.TitleFormatter" BadgesFormatter="tab.BadgesFormatter"
|
||||
Href="entry => TopFilter(tab, entry).Href()" IsActive="entry => tab.Current(_filter) == entry.Key" />
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
</section>
|
||||
|
||||
@if (data.TotalCatches > 0 || data.Rejected > 0)
|
||||
{
|
||||
var recent = _recent!;
|
||||
<section class="card recent-card" id="@DashboardFilter.Anchor">
|
||||
<div class="card-head">
|
||||
<h2>Fänge <span class="count">· @Formatting.Number(recent.Total) Treffer</span></h2>
|
||||
<span class="hint">Filter gelten nur für diese Liste</span>
|
||||
</div>
|
||||
<form class="filters" method="get" action="/#@DashboardFilter.Anchor">
|
||||
<label>
|
||||
<span>Zeitraum</span>
|
||||
<select name="zeit" data-autosubmit>
|
||||
@foreach (var (value, label) in DashboardFilter.Periods)
|
||||
{
|
||||
<option value="@value" selected="@(value == (_filter.Zeit ?? ""))">@label</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Ausgang</span>
|
||||
<select name="ausgang" data-autosubmit>
|
||||
@foreach (var (value, label) in DashboardFilter.Outcomes)
|
||||
{
|
||||
<option value="@value" selected="@(value == (_filter.Ausgang ?? ""))">@label</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Land</span>
|
||||
<select name="land" data-autosubmit>
|
||||
<option value="" selected="@(_filter.Land is null)">Alle</option>
|
||||
@foreach (var country in recent.Countries.OrderBy(c => CountryNames.Display(c.Code, c.Name), StringComparer.CurrentCulture))
|
||||
{
|
||||
<option value="@country.Code" selected="@(country.Code == _filter.Land)">@Formatting.Flag(country.Code) @CountryNames.Display(country.Code, country.Name)</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Erklärung</span>
|
||||
<select name="erklaerung" data-autosubmit>
|
||||
@foreach (var (value, label) in DashboardFilter.Explanations)
|
||||
{
|
||||
<option value="@value" selected="@(value == (_filter.Erklaerung ?? ""))">@label</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label>
|
||||
<span>Befehl</span>
|
||||
<select name="befehl" data-autosubmit>
|
||||
@foreach (var (value, label) in DashboardFilter.Commands)
|
||||
{
|
||||
<option value="@value" selected="@(value == (_filter.Befehl ?? ""))">@label</option>
|
||||
}
|
||||
</select>
|
||||
</label>
|
||||
<label class="filter-search">
|
||||
<span>Suche</span>
|
||||
<input type="search" name="q" value="@_filter.Q" placeholder="IP, Provider, Adresse, Strategie, User-Agent" />
|
||||
</label>
|
||||
@foreach (var (name, value) in new[] { ("provider", _filter.Provider), ("ip", _filter.Ip), ("ziel", _filter.Ziel), ("strategie", _filter.Strategie) })
|
||||
{
|
||||
if (value is not null)
|
||||
{
|
||||
<input type="hidden" name="@name" value="@value" />
|
||||
}
|
||||
}
|
||||
<button type="submit">Filtern</button>
|
||||
</form>
|
||||
@if (!_filter.IsEmpty)
|
||||
{
|
||||
<div class="chips">
|
||||
@foreach (var (label, without) in Chips())
|
||||
{
|
||||
<a class="chip" href="@without.Href()" title="Filter entfernen">@label <span aria-hidden="true">✕</span></a>
|
||||
}
|
||||
<a class="chip-reset" href="@(new DashboardFilter().Href())">Alle Filter zurücksetzen</a>
|
||||
</div>
|
||||
}
|
||||
@if (recent.Items.Count == 0)
|
||||
{
|
||||
<p class="empty">Keine Fänge für diese Filter. <a href="@(new DashboardFilter().Href())">Filter zurücksetzen</a></p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="scroll">
|
||||
<table class="recent-table">
|
||||
<thead>
|
||||
@@ -86,7 +235,8 @@
|
||||
<th class="c-ip">IP</th>
|
||||
<th class="c-origin">Herkunft</th>
|
||||
<th class="c-provider">Provider</th>
|
||||
<th class="c-target">Ziel</th>
|
||||
<th class="c-target">Aufgerufen</th>
|
||||
<th class="c-strategy">Strategie</th>
|
||||
<th class="c-agent">User-Agent</th>
|
||||
<th class="c-duration num">Dauer</th>
|
||||
<th class="c-bytes num">Bytes</th>
|
||||
@@ -94,15 +244,17 @@
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var trapEvent in data.Recent)
|
||||
@foreach (var (trapEvent, index) in recent.Items.Select((trapEvent, index) => (trapEvent, index)))
|
||||
{
|
||||
var started = trapEvent.StartedAt.ToLocalTime();
|
||||
var provider = Formatting.Provider(trapEvent.Asn, trapEvent.Provider);
|
||||
var target = Formatting.Target(trapEvent.Target);
|
||||
var duration = Formatting.Duration(TimeSpan.FromMilliseconds(trapEvent.DurationMs));
|
||||
var bytes = trapEvent.BytesSent.ToString("N0");
|
||||
<tr data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false">
|
||||
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.") </span>@started.ToString("HH:mm:ss")</td>
|
||||
var bytes = Formatting.Number(trapEvent.BytesSent);
|
||||
var strategy = StrategyNames.Describe(trapEvent.Strategy);
|
||||
var explanation = _rules.Explain(trapEvent);
|
||||
<tr id="f@(index)" data-expand="event:@trapEvent.Id" tabindex="0" aria-expanded="false" class="@(trapEvent.Outcome == TrapOutcome.Rejected ? "rejected" : null)">
|
||||
<td class="c-time"><span class="c-date">@started.ToString("dd.MM.") </span>@started.ToString("HH:mm:ss")</td>
|
||||
<td class="c-ip mono" title="@trapEvent.RemoteIp">@trapEvent.RemoteIp</td>
|
||||
<td class="c-origin" title="@Origin(trapEvent)">
|
||||
@if (trapEvent.CountryCode is { } countryCode)
|
||||
@@ -115,23 +267,109 @@
|
||||
}
|
||||
</td>
|
||||
<td class="c-provider" title="@provider">@provider</td>
|
||||
<td class="c-target mono" title="@target">
|
||||
@target
|
||||
<div class="extra extra-md">Provider: @(provider ?? "–")</div>
|
||||
<div class="extra extra-md">User-Agent: @(trapEvent.ClientInfo ?? "–")</div>
|
||||
<div class="extra extra-all">Herkunft: @(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {code} · {Origin(trapEvent)}" : "–")</div>
|
||||
<div class="extra extra-sm">Dauer: @duration · Bytes: @bytes</div>
|
||||
<div class="extra extra-xs">Datum: @started.ToString("dd.MM.yyyy") · Ausgang: @trapEvent.Outcome</div>
|
||||
<td class="c-target mono" title="@Formatting.CalledText(trapEvent.Target)">
|
||||
@if (trapEvent.Command is not null)
|
||||
{
|
||||
<span class="command-mark" title="Angriff mit Befehl" role="img" aria-label="Angriff mit Befehl">⚠</span>
|
||||
}
|
||||
<CalledCell Target="@trapEvent.Target" />
|
||||
</td>
|
||||
<td class="c-strategy" title="@strategy.Tooltip">@strategy.DisplayName@foreach (var badge in strategy.Badges){<span class="badge">@badge</span>}</td>
|
||||
<td class="c-agent" title="@trapEvent.ClientInfo">@trapEvent.ClientInfo</td>
|
||||
<td class="c-duration num">@duration</td>
|
||||
<td class="c-bytes num">@bytes</td>
|
||||
<td class="c-outcome"><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@trapEvent.Outcome</span></td>
|
||||
<td class="c-outcome"><span class="outcome @trapEvent.Outcome.ToString().ToLowerInvariant()">@OutcomeLabel(trapEvent.Outcome)</span></td>
|
||||
</tr>
|
||||
<tr class="detail-row" hidden>
|
||||
<td colspan="10">
|
||||
<div class="catch-detail">
|
||||
<h3 class="@(trapEvent.Command is null ? null : "alert")">@(trapEvent.Command is null ? "Was ist passiert?" : "⚠ Angriff mit Befehl")</h3>
|
||||
@if (explanation.Target is { } targetRule)
|
||||
{
|
||||
<p>@targetRule.Text</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="muted">Unbekanntes Ziel</p>
|
||||
}
|
||||
@if (explanation.Client is { } clientRule)
|
||||
{
|
||||
<p>@clientRule.Text</p>
|
||||
}
|
||||
@if (explanation.Outcome is { } outcomeRule)
|
||||
{
|
||||
<p>@outcomeRule.Text</p>
|
||||
}
|
||||
@if (trapEvent.Command is { } command)
|
||||
{
|
||||
var (field, text) = Formatting.CommandParts(command);
|
||||
<dl class="facts">
|
||||
<dt>Angreifer</dt>
|
||||
<dd><span class="mono">@trapEvent.RemoteIp</span>@(provider is null ? "" : $" · {provider}")@(trapEvent.CountryCode is null ? "" : $" · {Origin(trapEvent)}")</dd>
|
||||
@if (trapEvent.CommandServer is { } server)
|
||||
{
|
||||
<dt>Fremder Server</dt>
|
||||
<dd class="mono">@Formatting.Server(server)</dd>
|
||||
}
|
||||
<dt>Befehl</dt>
|
||||
<dd>
|
||||
<code>@text</code>
|
||||
@if (field is not null)
|
||||
{
|
||||
<span class="muted">eingeschleust über das Feld „@field“</span>
|
||||
}
|
||||
</dd>
|
||||
</dl>
|
||||
}
|
||||
<details data-remember="details:@trapEvent.Id">
|
||||
<summary>Technische Details</summary>
|
||||
<dl class="facts">
|
||||
<dt>Anfrage</dt>
|
||||
<dd class="mono">@target</dd>
|
||||
<dt>Zeit</dt>
|
||||
<dd>@started.ToString("dd.MM.yyyy HH:mm:ss")</dd>
|
||||
<dt>Herkunft</dt>
|
||||
<dd>@(trapEvent.CountryCode is { } code ? $"{Formatting.Flag(code)} {Origin(trapEvent)}" : "–")</dd>
|
||||
<dt>Provider</dt>
|
||||
<dd>@(provider ?? "–")</dd>
|
||||
<dt>User-Agent</dt>
|
||||
<dd>@(trapEvent.ClientInfo ?? "–")</dd>
|
||||
<dt>Strategie</dt>
|
||||
<dd>@strategy.DisplayName</dd>
|
||||
<dt>Verlauf</dt>
|
||||
<dd>@duration · @bytes Byte · @OutcomeLabel(trapEvent.Outcome)</dd>
|
||||
</dl>
|
||||
@if (recent.WithRequest.Contains(trapEvent.Id))
|
||||
{
|
||||
<div class="request" data-request="catches/@trapEvent.Id/request">
|
||||
<strong>Gesendete Anfrage</strong>
|
||||
<span class="muted">· vom Angreifer geschrieben</span>
|
||||
<div class="request-content"><span class="muted">Wird geladen …</span></div>
|
||||
</div>
|
||||
}
|
||||
</details>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
@if (recent.Total > recent.Items.Count)
|
||||
{
|
||||
<div class="more">
|
||||
<span class="muted">@Formatting.Number(recent.Items.Count) von @Formatting.Number(recent.Total)</span>
|
||||
@if (_filter.Limit < RecentFilter.MaxLimit)
|
||||
{
|
||||
<a class="button ghost" href="@((_filter with { Limit = _filter.NextLimit }).Href($"f{recent.Items.Count}"))">Weitere laden</a>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="muted">· Für ältere Fänge die Filter eingrenzen</span>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
}
|
||||
}
|
||||
@@ -140,14 +378,138 @@
|
||||
|
||||
@code {
|
||||
private DashboardData? _data;
|
||||
private RecentCatches? _recent;
|
||||
private DashboardFilter _filter = new();
|
||||
private RuleSet _rules = RuleSet.Empty;
|
||||
private DateTime _loadedAt;
|
||||
private DateTimeOffset _loadedAtUtc;
|
||||
private IReadOnlyList<ActiveTrap> _active = [];
|
||||
|
||||
[SupplyParameterFromQuery(Name = "zeit")] public string? Zeit { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "ausgang")] public string? Ausgang { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "land")] public string? Land { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "provider")] public string? Provider { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "ip")] public string? Ip { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "ziel")] public string? Ziel { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "strategie")] public string? Strategie { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "q")] public string? Q { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "limit")] public string? Limit { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "erklaerung")] public string? Erklaerung { get; set; }
|
||||
|
||||
[SupplyParameterFromQuery(Name = "befehl")] public string? Befehl { get; set; }
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_filter = DashboardFilter.Parse(Zeit, Ausgang, Land, Provider, Ip, Ziel, Strategie, Q, Limit, Erklaerung, Befehl);
|
||||
_rules = await Explanations.GetRuleSetAsync();
|
||||
_data = await Queries.GetAsync();
|
||||
_recent = await Queries.GetRecentAsync(_filter.ToRecentFilter() with { SearchStrategies = StrategyNames.Matching(_filter.Q) });
|
||||
_active = ActiveTraps.Snapshot();
|
||||
_loadedAtUtc = DateTimeOffset.UtcNow;
|
||||
_loadedAt = DateTime.Now;
|
||||
}
|
||||
|
||||
private static IReadOnlyList<TopTab> TopTabs(DashboardData data) =>
|
||||
[
|
||||
new("countries", "Länder", "Land", data.TopCountries, f => f.Land, (f, key) => f with { Land = key }, ShowFlags: true, LabelFormatter: CountryNames.Display),
|
||||
new("providers", "Provider", "Provider", data.TopProviders, f => f.Provider, (f, key) => f with { Provider = key }),
|
||||
new("ips", "IPs", "IP", data.TopIps, f => f.Ip, (f, key) => f with { Ip = key }),
|
||||
new("targets", "Aufrufe", "Aufgerufen", data.TopTargets, f => f.Ziel, (f, key) => f with { Ziel = key }, KeyFormatter: Formatting.CalledText, TitleFormatter: key => key),
|
||||
new("strategies", "Strategien", "Strategie", StrategyNames.Rank(data.StrategyCatches, 10), f => f.Strategie, (f, key) => f with { Strategie = key }, KeyFormatter: _ => "", LabelFormatter: (key, _) => StrategyNames.Display(key), TitleFormatter: key => StrategyNames.Describe(key).Tooltip, BadgesFormatter: key => StrategyNames.Describe(key).Badges)
|
||||
];
|
||||
|
||||
private DashboardFilter TopFilter(TopTab tab, TopEntry entry) =>
|
||||
tab.Set(_filter with { Limit = RecentFilter.DefaultLimit }, tab.Current(_filter) == entry.Key ? null : entry.Key);
|
||||
|
||||
private IEnumerable<(string Label, DashboardFilter Without)> Chips()
|
||||
{
|
||||
var reset = _filter with { Limit = RecentFilter.DefaultLimit };
|
||||
if (_filter.Befehl is not null)
|
||||
{
|
||||
yield return ("Nur mit Befehl", reset with { Befehl = null });
|
||||
}
|
||||
|
||||
if (_filter.Zeit is { } zeit)
|
||||
{
|
||||
yield return ($"Zeitraum: {DashboardFilter.Periods.First(p => p.Value == zeit).Label}", reset with { Zeit = null });
|
||||
}
|
||||
|
||||
if (_filter.Ausgang is { } ausgang)
|
||||
{
|
||||
yield return ($"Ausgang: {DashboardFilter.Outcomes.First(o => o.Value == ausgang).Label}", reset with { Ausgang = null });
|
||||
}
|
||||
|
||||
if (_filter.Land is { } land)
|
||||
{
|
||||
var name = _recent?.Countries.FirstOrDefault(c => c.Code == land)?.Name;
|
||||
yield return ($"Land: {CountryNames.Display(land, name)}", reset with { Land = null });
|
||||
}
|
||||
|
||||
if (_filter.Provider is { } provider)
|
||||
{
|
||||
var name = _data?.TopProviders.FirstOrDefault(p => p.Key == provider)?.Label
|
||||
?? _recent?.Items.FirstOrDefault()?.Provider;
|
||||
yield return ($"Provider: {(name is null ? provider : $"{name} ({provider})")}", reset with { Provider = null });
|
||||
}
|
||||
|
||||
if (_filter.Ip is { } ip)
|
||||
{
|
||||
yield return ($"IP: {ip}", reset with { Ip = null });
|
||||
}
|
||||
|
||||
if (_filter.Ziel is { } ziel)
|
||||
{
|
||||
yield return ($"Aufgerufen: {Formatting.CalledText(ziel)}", reset with { Ziel = null });
|
||||
}
|
||||
|
||||
if (_filter.Strategie is { } strategie)
|
||||
{
|
||||
var badges = StrategyNames.Describe(strategie).Badges;
|
||||
yield return ($"Strategie: {StrategyNames.Display(strategie)}{(badges.Count == 0 ? "" : $" ({string.Join(", ", badges)})")}", reset with { Strategie = null });
|
||||
}
|
||||
|
||||
if (_filter.Erklaerung is { } erklaerung)
|
||||
{
|
||||
yield return ($"Erklärung: {DashboardFilter.Explanations.First(e => e.Value == erklaerung).Label}", reset with { Erklaerung = null });
|
||||
}
|
||||
|
||||
if (_filter.Q is { } q)
|
||||
{
|
||||
yield return ($"Suche: „{q}“", reset with { Q = null });
|
||||
}
|
||||
}
|
||||
|
||||
private static string OutcomeLabel(TrapOutcome outcome) => outcome switch
|
||||
{
|
||||
TrapOutcome.Timeout => "Zeitlimit",
|
||||
TrapOutcome.ClientAborted => "Aufgegeben",
|
||||
TrapOutcome.Rejected => "Abgelehnt",
|
||||
TrapOutcome.Completed => "Beendet",
|
||||
_ => outcome.ToString()
|
||||
};
|
||||
|
||||
private static string Origin(TrapEventEntity trapEvent) =>
|
||||
string.Join(", ", new[] { trapEvent.City, CountryNames.Display(trapEvent.CountryCode, trapEvent.Country) }.Where(part => !string.IsNullOrEmpty(part)));
|
||||
|
||||
private sealed record TopTab(
|
||||
string Id,
|
||||
string Label,
|
||||
string KeyLabel,
|
||||
IReadOnlyList<TopEntry> Entries,
|
||||
Func<DashboardFilter, string?> Current,
|
||||
Func<DashboardFilter, string?, DashboardFilter> Set,
|
||||
bool ShowFlags = false,
|
||||
Func<string?, string?>? KeyFormatter = null,
|
||||
Func<string?, string?, string?>? LabelFormatter = null,
|
||||
Func<string?, string?>? TitleFormatter = null,
|
||||
Func<string?, IReadOnlyList<string>>? BadgesFormatter = null);
|
||||
}
|
||||
@@ -1,44 +1,105 @@
|
||||
@using System.Globalization
|
||||
@using Flypaper.Storage.Dashboard
|
||||
<section class="card">
|
||||
<h2>@Title</h2>
|
||||
@using Flypaper.Web.Components.Shared
|
||||
|
||||
@{
|
||||
var byMedian = Entries.Any(entry => entry.MedianHold is not null);
|
||||
var barMax = byMedian
|
||||
? Entries.Where(entry => entry.Count >= StrategyNames.MinCatches).Select(entry => entry.MedianHold!.Value.TotalMilliseconds).DefaultIfEmpty(0).Max()
|
||||
: Entries.Count == 0 ? 0 : Entries[0].Count;
|
||||
}
|
||||
@if (Entries.Count == 0)
|
||||
{
|
||||
<p class="empty">Noch keine Einträge.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<table class="top-table">
|
||||
<table class="top-table @(byMedian ? "by-median" : null)">
|
||||
<colgroup>
|
||||
<col />
|
||||
<col class="share" />
|
||||
<col class="count" />
|
||||
@if (byMedian)
|
||||
{
|
||||
<col class="hold" />
|
||||
}
|
||||
<col class="hold sum" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>@KeyLabel</th>
|
||||
<th><span class="sr-only">Anteil</span></th>
|
||||
<th class="num">Fänge</th>
|
||||
<th class="num">Haltezeit</th>
|
||||
@if (byMedian)
|
||||
{
|
||||
<th class="num" title="Mittlere Haltezeit pro Fang (Median): Einzelne Dauerhalter verfälschen sie nicht">Median</th>
|
||||
}
|
||||
<th class="num sum">@(byMedian ? "Summe" : "Haltezeit")</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var entry in Entries)
|
||||
{
|
||||
var share = (entry.Count * 100.0 / Entries[0].Count).ToString("0.#", CultureInfo.InvariantCulture);
|
||||
<tr data-expand="@($"{KeyLabel}:{entry.Key}")" tabindex="0" aria-expanded="false" style="--share: @(share)%">
|
||||
<td class="mono clip bar" title="@Display(entry)">@(ShowFlags ? $"{Formatting.Flag(entry.Key)} " : "")@Display(entry)</td>
|
||||
<td class="num">@entry.Count.ToString("N0")</td>
|
||||
<td class="num">@Formatting.Duration(entry.HoldTime)</td>
|
||||
var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key;
|
||||
var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label);
|
||||
var value = byMedian ? entry.MedianHold!.Value.TotalMilliseconds : entry.Count;
|
||||
var share = (barMax == 0 ? 0 : Math.Min(100, value * 100.0 / barMax)).ToString("0.#", CultureInfo.InvariantCulture);
|
||||
var sparse = byMedian && entry.Count < StrategyNames.MinCatches;
|
||||
var badges = BadgesFormatter?.Invoke(entry.Key) ?? [];
|
||||
var active = IsActive(entry);
|
||||
var title = TitleFormatter?.Invoke(entry.Key) ?? (label is null ? key : $"{label} · {key}");
|
||||
if (sparse)
|
||||
{
|
||||
title += $"\nNur {entry.Count} {(entry.Count == 1 ? "Fang" : "Fänge")}: wenig aussagekräftig";
|
||||
}
|
||||
|
||||
<tr data-href="@Href(entry)" class="@(active ? "active" : null) @(sparse ? "sparse" : null)">
|
||||
<td class="clip" title="@title">
|
||||
<a href="@Href(entry)" aria-current="@(active ? "true" : null)" title="@(active ? $"Filter {title} entfernen" : $"Fänge filtern: {title}")">
|
||||
@if (ShowFlags)
|
||||
{
|
||||
<span class="flag">@Formatting.Flag(entry.Key)</span>
|
||||
}
|
||||
@if (label is not null)
|
||||
{
|
||||
<span class="top-label">@label</span>
|
||||
@foreach (var badge in badges)
|
||||
{
|
||||
<span class="badge">@badge</span>
|
||||
}
|
||||
@if (sparse)
|
||||
{
|
||||
<span class="badge sparse-note">wenige Daten</span>
|
||||
}
|
||||
@if (key.Length > 0)
|
||||
{
|
||||
<span class="top-key mono">@key</span>
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="mono">@key</span>
|
||||
}
|
||||
</a>
|
||||
</td>
|
||||
<td><span class="share-bar" style="--share: @(share)%"></span></td>
|
||||
<td class="num">@Formatting.Number(entry.Count)</td>
|
||||
@if (byMedian)
|
||||
{
|
||||
<td class="num">@Formatting.Duration(entry.MedianHold!.Value)</td>
|
||||
}
|
||||
<td class="num sum">@Formatting.Duration(entry.HoldTime)</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
@if (byMedian)
|
||||
{
|
||||
<p class="top-note">Balken = Median Haltezeit pro Fang. Unter @StrategyNames.MinCatches Fängen wenig aussagekräftig, diese Zeilen stehen am Ende.</p>
|
||||
}
|
||||
}
|
||||
</section>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public required string Title { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required string KeyLabel { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required IReadOnlyList<TopEntry> Entries { get; set; }
|
||||
@@ -49,10 +110,11 @@
|
||||
|
||||
[Parameter] public Func<string?, string?, string?>? LabelFormatter { get; set; }
|
||||
|
||||
private string Display(TopEntry entry)
|
||||
{
|
||||
var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key;
|
||||
var label = LabelFormatter is null ? entry.Label : LabelFormatter(entry.Key, entry.Label);
|
||||
return label is null ? key : $"{key} · {label}";
|
||||
}
|
||||
[Parameter] public Func<string?, string?>? TitleFormatter { get; set; }
|
||||
|
||||
[Parameter] public Func<string?, IReadOnlyList<string>>? BadgesFormatter { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required Func<TopEntry, string> Href { get; set; }
|
||||
|
||||
[Parameter, EditorRequired] public required Func<TopEntry, bool> IsActive { get; set; }
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
{
|
||||
<span class="swatch @($"level-{level}")"></span>
|
||||
}
|
||||
<span>@_max.ToString("N0")</span>
|
||||
<span>@Formatting.Number(_max)</span>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"width":1000.0,"height":439.1,"countries":[{"code":"AF","name":"Afghanistan","path":"M669.6,108.7L671,108.7L673.1,109.4L674,109.9L675.5,108.8L676.6,109.4L677,107.9L678.5,108L678.7,107.5L678.6,106.1L679.3,104.9L680.9,105.7L681,106.7L681.8,106.9L682.4,109.7L683.8,110.8L684.5,110.1L685.5,109.8L686.6,108.3L688.4,108.5L691.1,108.5L691.8,109.5L690.5,109.9L689.4,110.5L686.6,110.9L684,111.6L683,113.1L684,114.5L684.8,116.2L683.9,117.6L684.4,119L684.1,120.2L681.6,120.1L683.2,122.4L681.8,123.3L681.2,125.4L681.9,127.5L681.1,128.4L680.1,128.1L678.2,128.6L678.1,129.5L676.2,129.5L675.2,131.5L675.8,134.5L672.6,136L670.7,135.7L670.4,136.5L668.7,136L666.1,136.5L661.3,134.7L663,131.5L662.3,129.3L660.2,128.7L659.5,126.5L658,123.7L658.7,121.8L657.4,121.3L657.6,118.8L657.5,114.5L660.5,115.8L662.3,115.4L662.5,113.8L664.4,113.3L665.5,112.3L665.3,109.6L667.2,108.9L667.3,107.7L668.8,108.6L669.6,108.7Z"},{"code":"AL","name":"Albanien","path":"M552.5,97.2L552.5,98L551.7,98.5L551.7,99.6L550.7,101.2L550.2,100.9L550.1,100.2L548.6,99.1L548.2,97.5L548.2,95.3L548.5,94.3L548,93.8L547.8,92.8L548.7,91.2L548.9,91.8L549.5,91.5L550.1,92.4L550.8,92.7L551,93.9L550.8,95L551.3,96.4L552.5,97.2Z"},{"code":"DZ","name":"Algerien","path":"M476.7,143.4L476.8,142.7L476.8,142.5L476.9,138.2L481.3,135.6L483.9,135.1L486.1,134.1L487.2,132.4L490.3,131L490.4,128.4L491.9,128.1L493.1,126.8L496.6,126.2L497.1,124.8L496.4,124.1L495.5,120.4L495.4,118.4L494.4,116.2L496.9,114.3L499.7,113.7L501.3,112.3L503.8,111.3L508.1,110.7L512.3,110.4L513.6,110.9L516,109.6L518.7,109.5L519.8,110.3L521.5,110.1L521.1,111.9L521.6,115.1L521.1,117.9L519.5,119.8L519.8,122.4L522,124.5L522.1,125.3L523.7,126.7L525.1,133L526,136.2L526.2,137.8L525.9,140.7L526.1,142.3L525.8,144.3L526.1,146.6L525.1,148.1L526.8,150.7L526.9,152.2L527.9,154.3L529.2,153.6L531.4,155.3L532.6,157.6L523.5,164.5L515.6,171.8L511.8,173.4L508.7,173.8L508.7,171.4L507.4,170.8L505.7,169.8L505,168L495.8,160L486.7,152.1L476.7,143.4Z"},{"code":"AO","name":"Angola","path":"M536.7,264L535.7,264.8L535.2,265.8L535.1,267.4L534.4,267.8L533.7,265L534.8,263.3L535.7,262.7L536.7,264ZM534.8,269L536,268.5L536.8,268.6L537.8,268.1L546.1,268.1L546.8,271L547.5,273.3L548.2,274.5L549.2,276.5L551.1,276.2L552,275.6L553.6,276.2L554,275.2L554.8,273L556.5,272.9L556.7,272.2L558.1,272.2L557.8,273.6L561.3,273.5L561.3,275.9L561.8,277.4L561.4,279.7L561.5,282L562.4,283.4L562.2,287.9L562.9,287.5L564.1,287.6L565.8,287.1L567.1,287.3L567.4,288.5L567,290.3L567.4,292.1L567,293.5L567.2,294.8L561.3,294.7L560.8,306.7L562.5,309.7L564.3,312L559.1,313.5L552.4,313L550.6,311.2L539.3,311.4L538.9,311.7L537.3,310L535.5,309.9L533.8,310.5L532.5,311.2L532.3,308.9L532.7,305.6L533.8,302.2L533.9,300.6L534.9,297.2L535.6,295.6L537.3,293.2L538.2,291.5L538.5,288.7L538.4,286.6L537.6,285.2L536.9,282.9L536.2,280.6L536.4,279.8L537.3,278.3L536.5,274.7L535.9,272.1L534.5,269.7L534.8,269Z"},{"code":"AR","name":"Argentinien","path":"M343.2,430.7L344.7,432L346.9,434.2L350.6,435.8L354.1,436.5L353.8,437.9L351.7,438.1L350.1,437.1L348.7,437L346.3,437L343.2,430.7ZM347.6,358.1L347.5,361L347.5,364.6L348.3,368L347.9,368.8L348.2,371L348.5,372.8L352.4,375.8L352.6,378.1L354.6,379.6L354.9,381.2L353.5,385.5L350.2,387.3L345.3,388L342.5,387.7L343.6,389.7L343.8,392.1L344.7,393.8L343.6,395L341.2,395.4L338.4,394.2L337.7,395.1L339.1,398.3L341.1,399.3L342.1,398.3L343.4,399.9L341.5,400.9L340.2,402.9L340.9,406.1L341,407.8L338.7,407.8L337.4,409.4L337.6,411.8L340.8,414L343.4,414.6L343.6,417.4L341.5,419.1L341.5,422.6L339.9,423.8L339.5,425.2L341.7,428.2L344,429.9L342.9,429.7L340.6,429.3L334.9,428.9L333.1,427.2L332.1,425L330.6,425.2L329.3,424.1L327.6,421L328.8,419.6L328.7,417.7L327.8,416.2L327.9,413.6L327.1,409.5L326.1,407.6L326.9,407L326.2,405.8L324.8,405.2L325.1,403.9L323.6,402.6L321.6,398.9L322.4,398.3L320.5,394.3L319.9,390.9L319.6,388L320.7,386.8L318.9,383.5L318,380.4L319.2,378.2L318.4,375.4L318.9,372L318,368.8L317.2,368.2L314.4,362.2L315.2,358.6L314.1,355.1L314.3,351.9L315.3,348.6L316.7,346.3L315.7,344.9L316,343.8L314.7,337.7L317.3,336L317.6,332.2L317.1,331.3L318.9,328L322.6,328.8L324.6,331.5L325.2,328.5L328.3,328.7L328.9,329.5L334.8,335.4L337.2,336L340.9,338.7L343.9,340.1L344.6,341.7L342.9,347.1L345.7,348.1L348.8,348.7L350.9,348.1L352.8,345.3L352.8,342.2L354,341.5L355.7,343.6L356.1,346.4L354.1,348.4L352.6,349.9L350.2,353.3L347.6,358.1Z"},{"code":"AM","name":"Armenien","path":"M617.6,104L616.7,104.1L615.2,102.2L615.1,101.7L614,101.7L613.1,100.8L612.6,100.9L611.4,99.9L609.4,99.1L609.3,97.5L608.6,96.3L611.9,95.8L612.6,96.7L613.7,97.3L613.4,98.1L615,99.2L614.5,100.3L615.8,101.2L617,101.7L617.6,104Z"},{"code":"AZ","name":"Aserbaidschan","path":"M615,93.8L615.8,94L617.9,95.9L619.1,96.2L619.3,95.3L620.5,94L622.2,95.7L624,98L625.2,98.2L626.2,99.1L624.2,99.3L624.4,101.9L624.2,103.1L623.5,103.9L623.9,105.5L623.3,105.7L621.4,103.9L621.9,102.3L620.9,101.3L620,101.6L617.6,104L617,101.7L615.8,101.2L614.5,100.3L615,99.2L613.4,98.1L613.7,97.3L612.6,96.7L611.9,95.8L612.4,95.3L614.5,96.2L615.9,96.4L616.1,96.1L614.5,94.3L615,93.8ZM616.7Line truncated
|
||||
{"width":1000.0,"height":439.1,"countries":[{"code":"AF","name":"Afghanistan","path":"M669.6,108.7L671,108.7L673.1,109.4L674,109.9L675.5,108.8L676.6,109.4L677,107.9L678.5,108L678.7,107.5L678.6,106.1L679.3,104.9L680.9,105.7L681,106.7L681.8,106.9L682.4,109.7L683.8,110.8L684.5,110.1L685.5,109.8L686.6,108.3L688.4,108.5L691.1,108.5L691.8,109.5L690.5,109.9L689.4,110.5L686.6,110.9L684,111.6L683,113.1L684,114.5L684.8,116.2L683.9,117.6L684.4,119L684.1,120.2L681.6,120.1L683.2,122.4L681.8,123.3L681.2,125.4L681.9,127.5L681.1,128.4L680.1,128.1L678.2,128.6L678.1,129.5L676.2,129.5L675.2,131.5L675.8,134.5L672.6,136L670.7,135.7L670.4,136.5L668.7,136L666.1,136.5L661.3,134.7L663,131.5L662.3,129.3L660.2,128.7L659.5,126.5L658,123.7L658.7,121.8L657.4,121.3L657.6,118.8L657.5,114.5L660.5,115.8L662.3,115.4L662.5,113.8L664.4,113.3L665.5,112.3L665.3,109.6L667.2,108.9L667.3,107.7L668.8,108.6L669.6,108.7Z"},{"code":"AL","name":"Albanien","path":"M552.5,97.2L552.5,98L551.7,98.5L551.7,99.6L550.7,101.2L550.2,100.9L550.1,100.2L548.6,99.1L548.2,97.5L548.2,95.3L548.5,94.3L548,93.8L547.8,92.8L548.7,91.2L548.9,91.8L549.5,91.5L550.1,92.4L550.8,92.7L551,93.9L550.8,95L551.3,96.4L552.5,97.2Z"},{"code":"DZ","name":"Algerien","path":"M476.7,143.4L476.8,142.7L476.8,142.5L476.9,138.2L481.3,135.6L483.9,135.1L486.1,134.1L487.2,132.4L490.3,131L490.4,128.4L491.9,128.1L493.1,126.8L496.6,126.2L497.1,124.8L496.4,124.1L495.5,120.4L495.4,118.4L494.4,116.2L496.9,114.3L499.7,113.7L501.3,112.3L503.8,111.3L508.1,110.7L512.3,110.4L513.6,110.9L516,109.6L518.7,109.5L519.8,110.3L521.5,110.1L521.1,111.9L521.6,115.1L521.1,117.9L519.5,119.8L519.8,122.4L522,124.5L522.1,125.3L523.7,126.7L525.1,133L526,136.2L526.2,137.8L525.9,140.7L526.1,142.3L525.8,144.3L526.1,146.6L525.1,148.1L526.8,150.7L526.9,152.2L527.9,154.3L529.2,153.6L531.4,155.3L532.6,157.6L523.5,164.5L515.6,171.8L511.8,173.4L508.7,173.8L508.7,171.4L507.4,170.8L505.7,169.8L505,168L495.8,160L486.7,152.1L476.7,143.4Z"},{"code":"AO","name":"Angola","path":"M536.7,264L535.7,264.8L535.2,265.8L535.1,267.4L534.4,267.8L533.7,265L534.8,263.3L535.7,262.7L536.7,264ZM534.8,269L536,268.5L536.8,268.6L537.8,268.1L546.1,268.1L546.8,271L547.5,273.3L548.2,274.5L549.2,276.5L551.1,276.2L552,275.6L553.6,276.2L554,275.2L554.8,273L556.5,272.9L556.7,272.2L558.1,272.2L557.8,273.6L561.3,273.5L561.3,275.9L561.8,277.4L561.4,279.7L561.5,282L562.4,283.4L562.2,287.9L562.9,287.5L564.1,287.6L565.8,287.1L567.1,287.3L567.4,288.5L567,290.3L567.4,292.1L567,293.5L567.2,294.8L561.3,294.7L560.8,306.7L562.5,309.7L564.3,312L559.1,313.5L552.4,313L550.6,311.2L539.3,311.4L538.9,311.7L537.3,310L535.5,309.9L533.8,310.5L532.5,311.2L532.3,308.9L532.7,305.6L533.8,302.2L533.9,300.6L534.9,297.2L535.6,295.6L537.3,293.2L538.2,291.5L538.5,288.7L538.4,286.6L537.6,285.2L536.9,282.9L536.2,280.6L536.4,279.8L537.3,278.3L536.5,274.7L535.9,272.1L534.5,269.7L534.8,269Z"},{"code":"AR","name":"Argentinien","path":"M343.2,430.7L344.7,432L346.9,434.2L350.6,435.8L354.1,436.5L353.8,437.9L351.7,438.1L350.1,437.1L348.7,437L346.3,437L343.2,430.7ZM347.6,358.1L347.5,361L347.5,364.6L348.3,368L347.9,368.8L348.2,371L348.5,372.8L352.4,375.8L352.6,378.1L354.6,379.6L354.9,381.2L353.5,385.5L350.2,387.3L345.3,388L342.5,387.7L343.6,389.7L343.8,392.1L344.7,393.8L343.6,395L341.2,395.4L338.4,394.2L337.7,395.1L339.1,398.3L341.1,399.3L342.1,398.3L343.4,399.9L341.5,400.9L340.2,402.9L340.9,406.1L341,407.8L338.7,407.8L337.4,409.4L337.6,411.8L340.8,414L343.4,414.6L343.6,417.4L341.5,419.1L341.5,422.6L339.9,423.8L339.5,425.2L341.7,428.2L344,429.9L342.9,429.7L340.6,429.3L334.9,428.9L333.1,427.2L332.1,425L330.6,425.2L329.3,424.1L327.6,421L328.8,419.6L328.7,417.7L327.8,416.2L327.9,413.6L327.1,409.5L326.1,407.6L326.9,407L326.2,405.8L324.8,405.2L325.1,403.9L323.6,402.6L321.6,398.9L322.4,398.3L320.5,394.3L319.9,390.9L319.6,388L320.7,386.8L318.9,383.5L318,380.4L319.2,378.2L318.4,375.4L318.9,372L318,368.8L317.2,368.2L314.4,362.2L315.2,358.6L314.1,355.1L314.3,351.9L315.3,348.6L316.7,346.3L315.7,344.9L316,343.8L314.7,337.7L317.3,336L317.6,332.2L317.1,331.3L318.9,328L322.6,328.8L324.6,331.5L325.2,328.5L328.3,328.7L328.9,329.5L334.8,335.4L337.2,336L340.9,338.7L343.9,340.1L344.6,341.7L342.9,347.1L345.7,348.1L348.8,348.7L350.9,348.1L352.8,345.3L352.8,342.2L354,341.5L355.7,343.6L356.1,346.4L354.1,348.4L352.6,349.9L350.2,353.3L347.6,358.1Z"},{"code":"AM","name":"Armenien","path":"M617.6,104L616.7,104.1L615.2,102.2L615.1,101.7L614,101.7L613.1,100.8L612.6,100.9L611.4,99.9L609.4,99.1L609.3,97.5L608.6,96.3L611.9,95.8L612.6,96.7L613.7,97.3L613.4,98.1L615,99.2L614.5,100.3L615.8,101.2L617,101.7L617.6,104Z"},{"code":"AZ","name":"Aserbaidschan","path":"M615,93.8L615.8,94L617.9,95.9L619.1,96.2L619.3,95.3L620.5,94L622.2,95.7L624,98L625.2,98.2L626.2,99.1L624.2,99.3L624.4,101.9L624.2,103.1L623.5,103.9L623.9,105.5L623.3,105.7L621.4,103.9L621.9,102.3L620.9,101.3L620,101.6L617.6,104L617,101.7L615.8,101.2L614.5,100.3L615,99.2L613.4,98.1L613.7,97.3L612.6,96.7L611.9,95.8L612.4,95.3L614.5,96.2L615.9,96.4L616.1,96.1L614.5,94.3L615,93.8ZM616.7Line truncated
|
||||
@@ -0,0 +1,89 @@
|
||||
@page "/erklaerungen"
|
||||
@using Flypaper.Storage.Entities
|
||||
@using Flypaper.Storage.Explanations
|
||||
@inject ExplanationRuleStore Store
|
||||
@inject ExplanationQueries Queries
|
||||
|
||||
<PageTitle>Flypaper · Erklärungen</PageTitle>
|
||||
|
||||
<header class="page-head">
|
||||
<h1>Erklärungen</h1>
|
||||
<p>Regeln, die in der Fang-Liste erklären, was ein Bot wollte. Neue Regeln legt eine KI per MCP an. Änderungen gelten sofort, auch für alte Fänge.</p>
|
||||
</header>
|
||||
|
||||
<section class="card">
|
||||
<div class="card-head">
|
||||
<h2>Regeln <span class="count">· @_rules.Count</span></h2>
|
||||
<span class="hint"><a href="/?erklaerung=ohne#faenge">Fänge ohne Erklärung anzeigen</a></span>
|
||||
</div>
|
||||
@if (_rules.Count == 0)
|
||||
{
|
||||
<p class="empty">Noch keine Regeln.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="scroll">
|
||||
<table class="s-table rule-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Art</th>
|
||||
<th>Muster</th>
|
||||
<th>Text</th>
|
||||
<th class="num">Priorität</th>
|
||||
<th class="num">Treffer</th>
|
||||
<th></th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@foreach (var rule in _rules)
|
||||
{
|
||||
<tr class="@(rule.Enabled ? null : "off")">
|
||||
<td class="nowrap">@KindLabel(rule.Kind)</td>
|
||||
<td class="mono">@rule.Pattern</td>
|
||||
<td>
|
||||
@rule.Text
|
||||
<div class="muted rule-meta">
|
||||
@(rule.Note is { } note ? note + " · " : "")von @rule.CreatedBy, @rule.UpdatedAt.ToLocalTime().ToString("dd.MM.yyyy")
|
||||
</div>
|
||||
</td>
|
||||
<td class="num">@rule.Priority</td>
|
||||
<td class="num">@Formatting.Number(_hits.GetValueOrDefault(rule.Id))</td>
|
||||
<td class="nowrap">
|
||||
<form method="post" action="/explanations/@rule.Id/enabled" class="inline-form">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="enabled" value="@(rule.Enabled ? "false" : "true")" />
|
||||
<button type="submit" class="ghost">@(rule.Enabled ? "Ausschalten" : "Einschalten")</button>
|
||||
</form>
|
||||
</td>
|
||||
<td class="nowrap">
|
||||
<form method="post" action="/explanations/@rule.Id/delete" class="inline-form" onsubmit="return confirm('Regel wirklich löschen?')">
|
||||
<AntiforgeryToken />
|
||||
<button type="submit" class="ghost danger-text">Löschen</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
}
|
||||
</section>
|
||||
|
||||
@code {
|
||||
private IReadOnlyList<ExplanationRuleEntity> _rules = [];
|
||||
private IReadOnlyDictionary<int, int> _hits = new Dictionary<int, int>();
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
_rules = await Store.ListAsync();
|
||||
_hits = await Queries.CountHitsAsync();
|
||||
}
|
||||
|
||||
private static string KindLabel(ExplanationKind kind) => kind switch
|
||||
{
|
||||
ExplanationKind.Target => "Ziel",
|
||||
ExplanationKind.ClientInfo => "User-Agent",
|
||||
_ => "Ausgang"
|
||||
};
|
||||
}
|
||||
@@ -2,8 +2,6 @@ namespace Flypaper.Web.Components.Pages.Settings;
|
||||
|
||||
public sealed class HoldMethodModel
|
||||
{
|
||||
public string? Content { get; set; }
|
||||
|
||||
public string? MinDelayMs { get; set; }
|
||||
|
||||
public string? MaxDelayMs { get; set; }
|
||||
@@ -12,5 +10,17 @@ public sealed class HoldMethodModel
|
||||
|
||||
public string? MaxChunkSize { get; set; }
|
||||
|
||||
public string? HeadStartSize { get; set; }
|
||||
|
||||
public bool MatchPath { get; set; }
|
||||
|
||||
public string? LinkSpacing { get; set; }
|
||||
|
||||
public string? BaitPaths { get; set; }
|
||||
|
||||
public string? MaxHoldDuration { get; set; }
|
||||
|
||||
public string? RepeatWindowDays { get; set; }
|
||||
|
||||
public string? RepeatHoldDuration { get; set; }
|
||||
}
|
||||
@@ -21,28 +21,6 @@
|
||||
|
||||
<EditForm Model="Model" FormName="hold-method" OnSubmit="SaveAsync" action="/settings#hold-method" id="hold-method-form">
|
||||
<div class="s-body">
|
||||
<fieldset class="choices">
|
||||
<legend>Inhalt</legend>
|
||||
<InputRadioGroup @bind-Value="Model!.Content">
|
||||
<div class="choice-grid">
|
||||
@foreach (var choice in Choices)
|
||||
{
|
||||
<label class="choice">
|
||||
<InputRadio Value="@choice.Value" />
|
||||
<span class="choice-body">
|
||||
<strong>@choice.Title</strong>
|
||||
<span>@choice.Text</span>
|
||||
</span>
|
||||
</label>
|
||||
}
|
||||
</div>
|
||||
</InputRadioGroup>
|
||||
@if (_errors.TryGetValue(nameof(HoldMethodModel.Content), out var contentError))
|
||||
{
|
||||
<p class="field-error">@contentError</p>
|
||||
}
|
||||
</fieldset>
|
||||
|
||||
<div class="fields">
|
||||
<SettingsField Label="Pause min." For="drip-min-delay" Unit="ms" Hint="10 bis 30000" Errors="_errors" Key="@nameof(HoldMethodModel.MinDelayMs)">
|
||||
<InputText id="drip-min-delay" @bind-Value="Model!.MinDelayMs" inputmode="numeric" data-bandwidth-input />
|
||||
@@ -56,11 +34,37 @@
|
||||
<SettingsField Label="Paket max." For="drip-max-chunk" Unit="Bytes" Hint="Zufällig zwischen min. und max." Errors="_errors" Key="@nameof(HoldMethodModel.MaxChunkSize)">
|
||||
<InputText id="drip-max-chunk" @bind-Value="Model!.MaxChunkSize" inputmode="numeric" data-bandwidth-input />
|
||||
</SettingsField>
|
||||
<SettingsField Label="Schneller Start" For="drip-head-start" Unit="Bytes" Hint="0 bis 65536, sofort ohne Pause gesendet" Errors="_errors" Key="@nameof(HoldMethodModel.HeadStartSize)">
|
||||
<InputText id="drip-head-start" @bind-Value="Model!.HeadStartSize" inputmode="numeric" />
|
||||
</SettingsField>
|
||||
<SettingsField Label="Link-Abstand" For="drip-link-spacing" Unit="Bytes" Hint="0 bis 4096, Text zwischen zwei Links, 0 = Labyrinth aus" Errors="_errors" Key="@nameof(HoldMethodModel.LinkSpacing)">
|
||||
<InputText id="drip-link-spacing" @bind-Value="Model!.LinkSpacing" inputmode="numeric" />
|
||||
</SettingsField>
|
||||
<SettingsField Label="Maximale Haltedauer" For="hold" Hint="hh:mm:ss, höchstens 7 Tage" Errors="_errors" Key="@nameof(HoldMethodModel.MaxHoldDuration)">
|
||||
<InputText id="hold" @bind-Value="Model!.MaxHoldDuration" />
|
||||
</SettingsField>
|
||||
<SettingsField Label="Wiederholer erkennen" For="repeat-window" Unit="Tage" Hint="0 bis 365, 0 = aus. IPs mit einem Timeout in diesem Zeitraum gelten als Wiederholer" Errors="_errors" Key="@nameof(HoldMethodModel.RepeatWindowDays)">
|
||||
<InputText id="repeat-window" @bind-Value="Model!.RepeatWindowDays" inputmode="numeric" />
|
||||
</SettingsField>
|
||||
<SettingsField Label="Haltedauer für Wiederholer" For="repeat-hold" Hint="d.hh:mm:ss, höchstens 7 Tage. Strategie bekommt den Zusatz repeat („Wiederholer“)" Errors="_errors" Key="@nameof(HoldMethodModel.RepeatHoldDuration)">
|
||||
<InputText id="repeat-hold" @bind-Value="Model!.RepeatHoldDuration" />
|
||||
</SettingsField>
|
||||
</div>
|
||||
|
||||
<div class="fields">
|
||||
<SettingsField Label="Köder-Pfade in der robots.txt" For="drip-bait-paths" Wide="true" Hint="Kommagetrennt, höchstens 8, leer = keine. Nirgends verlinkt; Anfragen darauf heißen robots-bait und werden 24 Stunden gehalten." Errors="_errors" Key="@nameof(HoldMethodModel.BaitPaths)">
|
||||
<InputText id="drip-bait-paths" @bind-Value="Model!.BaitPaths" />
|
||||
</SettingsField>
|
||||
</div>
|
||||
|
||||
<label class="switch-row">
|
||||
<InputCheckbox class="switch" @bind-Value="Model!.MatchPath" />
|
||||
<span>
|
||||
<strong>Inhalt zum Pfad passend wählen</strong>
|
||||
<span class="muted">Anfragen wie /.env, /config.json, /sitemap.xml oder /backup.sql bekommen passend aussehenden Inhalt statt einer Webseite.</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div class="estimate">
|
||||
<span class="estimate-value">Ø <strong id="drip-bandwidth">@Bandwidth</strong> Bytes/s</span>
|
||||
<span class="muted">pro gefangener Verbindung, berechnet aus Pausen und Paketgrößen</span>
|
||||
@@ -79,13 +83,6 @@
|
||||
<script src="@Assets["settings.js"]" defer></script>
|
||||
|
||||
@code {
|
||||
private static readonly (string Value, string Title, string Text)[] Choices =
|
||||
[
|
||||
(nameof(DripContent.Html), "HTML-Fülltext", "Eine endlose Webseite mit Überschriften, Absätzen und Links. Wirkt auf Crawler am echtesten."),
|
||||
(nameof(DripContent.Text), "Zufallstext", "Schlichter Text ohne Markup, ausgeliefert als text/plain."),
|
||||
(nameof(DripContent.Alternating), "Wechselnd", "Pro Fang zufällig eine der beiden. Gut, um zu vergleichen, was Bots länger hält.")
|
||||
];
|
||||
|
||||
private readonly object _resetModel = new();
|
||||
private IReadOnlyDictionary<string, string> _errors = new Dictionary<string, string>();
|
||||
private bool _hasOverrides;
|
||||
@@ -107,7 +104,7 @@
|
||||
|
||||
var bytesPerSecond = HoldMethodSettings.AverageBytesPerSecond(
|
||||
TimeSpan.FromMilliseconds(minDelay), TimeSpan.FromMilliseconds(maxDelay), minChunk, maxChunk);
|
||||
return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", CultureInfo.GetCultureInfo("de-DE"));
|
||||
return bytesPerSecond.ToString(bytesPerSecond < 10 ? "0.0" : "N0", Formatting.German);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,12 +117,17 @@
|
||||
private async Task SaveAsync()
|
||||
{
|
||||
var result = RuntimeSettingsParser.ParseHoldMethod(new HoldMethodInput(
|
||||
Model!.Content,
|
||||
Model.MinDelayMs,
|
||||
Model!.MinDelayMs,
|
||||
Model.MaxDelayMs,
|
||||
Model.MinChunkSize,
|
||||
Model.MaxChunkSize,
|
||||
Model.MaxHoldDuration));
|
||||
Model.HeadStartSize,
|
||||
Model.MatchPath,
|
||||
Model.LinkSpacing,
|
||||
Model.BaitPaths,
|
||||
Model.MaxHoldDuration,
|
||||
Model.RepeatWindowDays,
|
||||
Model.RepeatHoldDuration));
|
||||
|
||||
if (result.Settings is null)
|
||||
{
|
||||
@@ -148,12 +150,17 @@
|
||||
var drip = Drip.CurrentValue;
|
||||
return new HoldMethodModel
|
||||
{
|
||||
Content = drip.Content.ToString(),
|
||||
MinDelayMs = ((int)drip.MinDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||
MaxDelayMs = ((int)drip.MaxDelay.TotalMilliseconds).ToString(CultureInfo.InvariantCulture),
|
||||
MinChunkSize = drip.MinChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||
MaxChunkSize = drip.MaxChunkSize.ToString(CultureInfo.InvariantCulture),
|
||||
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
HeadStartSize = drip.HeadStartSize.ToString(CultureInfo.InvariantCulture),
|
||||
MatchPath = drip.MatchPath,
|
||||
LinkSpacing = drip.LinkSpacing.ToString(CultureInfo.InvariantCulture),
|
||||
BaitPaths = drip.BaitPaths,
|
||||
MaxHoldDuration = Core.CurrentValue.MaxHoldDuration.ToString("c", CultureInfo.InvariantCulture),
|
||||
RepeatWindowDays = Core.CurrentValue.RepeatWindowDays.ToString(CultureInfo.InvariantCulture),
|
||||
RepeatHoldDuration = Core.CurrentValue.RepeatHoldDuration.ToString("c", CultureInfo.InvariantCulture)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -5,11 +5,19 @@
|
||||
@inject McpTokenStore Store
|
||||
@inject NavigationManager Navigation
|
||||
|
||||
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol. Nur lesend und nur im LAN.">
|
||||
<SettingsSection Id="mcp" Title="MCP-Zugriff" Description="KI-Assistenten wie Claude lesen die Fänge über das Model Context Protocol und pflegen die Erklärungsregeln. Regeln ändern dürfen nur Tokens mit Schreibrecht. Nur im LAN.">
|
||||
@if (Revoked == "revoked")
|
||||
{
|
||||
<Notice>Token widerrufen.</Notice>
|
||||
}
|
||||
else if (Revoked == "write-on")
|
||||
{
|
||||
<Notice>Schreibrecht erteilt.</Notice>
|
||||
}
|
||||
else if (Revoked == "write-off")
|
||||
{
|
||||
<Notice>Schreibrecht entzogen.</Notice>
|
||||
}
|
||||
|
||||
@if (_newToken is not null)
|
||||
{
|
||||
@@ -37,6 +45,7 @@
|
||||
<th>Name</th>
|
||||
<th>Erstellt</th>
|
||||
<th>Zuletzt genutzt</th>
|
||||
<th>Zugriff</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -47,6 +56,14 @@
|
||||
<td>@token.Name</td>
|
||||
<td class="nowrap">@token.CreatedAt.ToLocalTime().ToString("dd.MM.yyyy HH:mm")</td>
|
||||
<td class="nowrap">@(token.LastUsedAt?.ToLocalTime().ToString("dd.MM.yyyy HH:mm") ?? "nie")</td>
|
||||
<td class="nowrap">
|
||||
<form method="post" action="/mcp-tokens/@token.Id/write" class="inline-form">
|
||||
<AntiforgeryToken />
|
||||
<input type="hidden" name="enabled" value="@(token.CanWrite ? "false" : "true")" />
|
||||
<span>@(token.CanWrite ? "Lesen und schreiben" : "Nur lesen")</span>
|
||||
<button type="submit" class="ghost">@(token.CanWrite ? "Schreibrecht entziehen" : "Schreibrecht erteilen")</button>
|
||||
</form>
|
||||
</td>
|
||||
<td class="num">
|
||||
<form method="post" action="/mcp-tokens/@token.Id/revoke" onsubmit="return confirm('Token „@token.Name“ widerrufen?')">
|
||||
<AntiforgeryToken />
|
||||
@@ -72,6 +89,10 @@
|
||||
<span class="field-error">@nameError</span>
|
||||
}
|
||||
</div>
|
||||
<label class="inline-check">
|
||||
<InputCheckbox @bind-Value="Model!.CanWrite" />
|
||||
<span>Mit Schreibrecht</span>
|
||||
</label>
|
||||
<button type="submit">Token erzeugen</button>
|
||||
</EditForm>
|
||||
</SettingsSection>
|
||||
@@ -103,9 +124,10 @@
|
||||
return;
|
||||
}
|
||||
|
||||
_newToken = await Tokens.CreateAsync(name);
|
||||
_newToken = await Tokens.CreateAsync(name, Model.CanWrite);
|
||||
_newTokenName = name;
|
||||
Model.Name = null;
|
||||
Model.CanWrite = false;
|
||||
_tokens = await Store.ListAsync();
|
||||
}
|
||||
}
|
||||
@@ -3,4 +3,6 @@ namespace Flypaper.Web.Components.Pages.Settings;
|
||||
public sealed class McpTokenModel
|
||||
{
|
||||
public string? Name { get; set; }
|
||||
|
||||
public bool CanWrite { get; set; }
|
||||
}
|
||||
@@ -5,12 +5,12 @@
|
||||
<SettingsSection Id="data" Title="Daten" Description="Gespeicherte Fänge. Einstellungen und GeoIP-Dateien bleiben beim Löschen erhalten.">
|
||||
@if (Deleted is { } deleted)
|
||||
{
|
||||
<Notice>@deleted.ToString("N0") @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</Notice>
|
||||
<Notice>@Formatting.Number(deleted) @(deleted == 1 ? "Fang" : "Fänge") gelöscht.</Notice>
|
||||
}
|
||||
|
||||
<div class="s-body">
|
||||
<div class="stat-row">
|
||||
<div class="stat"><span class="stat-label">Fänge</span><span class="stat-value">@(_stats?.Count.ToString("N0") ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Fänge</span><span class="stat-value">@((_stats is null ? null : Formatting.Number(_stats.Count)) ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Ältester Fang</span><span class="stat-value">@(_stats?.Oldest?.ToLocalTime().ToString("dd.MM.yyyy") ?? "–")</span></div>
|
||||
<div class="stat"><span class="stat-label">Datenbank</span><span class="stat-value">@Formatting.Bytes(_stats?.DatabaseBytes)</span></div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Flypaper.Storage.Dashboard;
|
||||
|
||||
namespace Flypaper.Web.Components.Shared;
|
||||
|
||||
public static class Formatting
|
||||
public static partial class Formatting
|
||||
{
|
||||
public static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE");
|
||||
|
||||
public static string Number(long value) => value.ToString("N0", German);
|
||||
|
||||
public static string Duration(TimeSpan duration) => duration switch
|
||||
{
|
||||
{ TotalDays: >= 1 } => $"{(int)duration.TotalDays}\u00a0d {duration.Hours}\u00a0h",
|
||||
@@ -43,5 +51,46 @@ public static class Formatting
|
||||
: target;
|
||||
}
|
||||
|
||||
public static (string Text, string? Note, string? Method) Called(string? target)
|
||||
{
|
||||
if (RequestKey.Split(target) is not var (method, path))
|
||||
{
|
||||
return (target ?? "–", null, null);
|
||||
}
|
||||
|
||||
var note = method.ToUpperInvariant() switch
|
||||
{
|
||||
"GET" => null,
|
||||
"POST" => "schickt Daten",
|
||||
"HEAD" => "prüft nur, ob es das gibt",
|
||||
"OPTIONS" => "fragt, was erlaubt ist",
|
||||
_ => method
|
||||
};
|
||||
return (path == "/" ? "Startseite" : path, note, method);
|
||||
}
|
||||
|
||||
public static string CalledText(string? target)
|
||||
{
|
||||
var (text, note, _) = Called(target);
|
||||
return note is null ? text : $"{text} · {note}";
|
||||
}
|
||||
|
||||
public static string Server(string server)
|
||||
{
|
||||
var colon = server.LastIndexOf(':');
|
||||
return colon > 0 && server.AsSpan(colon + 1) is { Length: > 0 } port && !port.ContainsAnyExceptInRange('0', '9')
|
||||
? $"{server[..colon]}, Port {port}"
|
||||
: server;
|
||||
}
|
||||
|
||||
public static (string? Field, string Command) CommandParts(string command)
|
||||
{
|
||||
var match = FormField().Match(command);
|
||||
return match.Success ? (match.Groups[1].Value, command[match.Length..]) : (null, command);
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^([A-Za-z_][A-Za-z0-9_.-]{0,39})=(?!=)")]
|
||||
private static partial Regex FormField();
|
||||
|
||||
public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd();
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Flypaper.Storage.Dashboard;
|
||||
|
||||
namespace Flypaper.Web.Components.Shared;
|
||||
|
||||
public sealed record StrategyInfo(string Raw, string BaseName, string DisplayName, string? Explanation, IReadOnlyList<string> Details, IReadOnlyList<string> Flags)
|
||||
{
|
||||
public string GroupKey => string.Join(' ', [BaseName, .. Flags]);
|
||||
|
||||
public IReadOnlyList<string> Badges => Flags.Select(StrategyNames.BadgeLabel).ToList();
|
||||
|
||||
public string Tooltip
|
||||
{
|
||||
get
|
||||
{
|
||||
var lines = new List<string> { DisplayName };
|
||||
if (Explanation is not null)
|
||||
{
|
||||
lines.Add(Explanation);
|
||||
}
|
||||
|
||||
lines.AddRange(Details);
|
||||
lines.Add($"Technisch: {Raw}");
|
||||
return string.Join("\n", lines);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static partial class StrategyNames
|
||||
{
|
||||
private static readonly Dictionary<string, (string Name, string Explanation)> Known = new(StringComparer.Ordinal)
|
||||
{
|
||||
["maze-drip"] = ("Link-Labyrinth", "Eine Webseite voller Links, die immer zu neuen, erfundenen Seiten führen. Der Bot folgt ihnen und verirrt sich, während alles nur tröpfchenweise ankommt."),
|
||||
["index-drip"] = ("Gefälschtes Ordner-Listing", "Eine Dateiliste im Stil von „Index of /…“ mit erfundenen Ordnern und Dateien. Wer weiterklickt, landet im Link-Labyrinth."),
|
||||
["html-drip"] = ("Endlose Webseite", "Eine gewöhnlich aussehende Webseite, die nie aufhört und nur Stück für Stück geliefert wird. Der Bot wartet auf das Ende, das nie kommt."),
|
||||
["env-drip"] = ("Gefälschte Zugangsdaten (.env)", "Eine erfundene .env-Datei mit Passwörtern und Schlüsseln, die nie endet. Bots, die nach geleakten Zugangsdaten suchen, lesen sie bis zum Ende."),
|
||||
["git-drip"] = ("Gefälschtes Git-Projekt", "Eine erfundene Git-Konfiguration, die wie die echte beginnt und nie endet. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
|
||||
["svn-drip"] = ("Gefälschtes Subversion-Projekt", "Erfundene Dateien aus einem .svn-Ordner, die wie die echten beginnen und nie enden. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
|
||||
["hg-drip"] = ("Gefälschtes Mercurial-Projekt", "Erfundene Dateien aus einem .hg-Ordner, die wie die echten beginnen und nie enden. Bots, die Quellcode abgreifen wollen, bleiben daran hängen."),
|
||||
["json-drip"] = ("Gefälschte JSON-Datei", "Eine erfundene JSON-Datei, die nie endet. Bots, die Konfigurationen und Daten einsammeln, warten auf das Dateiende."),
|
||||
["xml-drip"] = ("Gefälschte XML-Datei", "Eine erfundene XML-Datei, die nie endet. Bots, die Konfigurationen und Daten einsammeln, warten auf das Dateiende."),
|
||||
["yaml-drip"] = ("Gefälschte YAML-Datei", "Eine erfundene YAML-Konfiguration, die nie endet. Bots, die Konfigurationen einsammeln, warten auf das Dateiende."),
|
||||
["sql-drip"] = ("Gefälschter Datenbank-Export (SQL)", "Ein erfundener SQL-Dump mit endlos vielen Einträgen. Bots, die nach Datenbank-Backups suchen, laden ihn herunter, solange es geht."),
|
||||
["hikvision-drip"] = ("Gefälschte Überwachungskamera (Hikvision)", "Die Antwort einer erfundenen Hikvision-Kamera, die nie endet. Bots, die nach angreifbaren Kameras suchen, warten auf die komplette Antwort."),
|
||||
["wordpress-drip"] = ("Gefälschte WordPress-Anmeldung", "Eine erfundene WordPress-Anmeldeseite, die nie fertig geladen wird. Bots, die Passwörter durchprobieren, kommen nie zum Formular."),
|
||||
["lure-page"] = ("Köder-Startseite (WordPress)", "Beim ersten Besuch einer unbekannten IP wird sofort eine kleine WordPress-Seite mit Links geliefert und niemand festgehalten. Wer danach gezielt weitersucht, kommt in die Falle."),
|
||||
["lure-icon"] = ("Köder-Favicon (WordPress)", "Beim ersten Besuch einer unbekannten IP wird sofort ein kleines Favicon geliefert und niemand festgehalten."),
|
||||
["robots-static"] = ("robots.txt (Hinweis an brave Crawler)", "Die robots.txt wird sofort und vollständig geliefert. Sie verbietet alles, brave Crawler bleiben draußen. Es wird bewusst niemand festgehalten."),
|
||||
["robots-bait"] = ("Köder aus der robots.txt", "Ein Pfad, der in der robots.txt als verboten steht, aber ins Link-Labyrinth führt. Wer dort landet, hat das Verbot gelesen und ignoriert. Er wird mindestens 24 Stunden festgehalten.")
|
||||
};
|
||||
|
||||
private static readonly Dictionary<string, string> Aliases = new(StringComparer.Ordinal)
|
||||
{
|
||||
["drip"] = "html-drip"
|
||||
};
|
||||
|
||||
private static readonly string[] VariantFlags = ["head", "link", "repeat"];
|
||||
|
||||
private static readonly HashSet<string> LinkedByDesign = new(StringComparer.Ordinal) { "maze-drip", "index-drip", "robots-bait" };
|
||||
|
||||
public const int MinCatches = 5;
|
||||
|
||||
public static string BadgeLabel(string flag) => flag switch
|
||||
{
|
||||
"head" => "Schnellstart",
|
||||
"link" => "Links",
|
||||
"repeat" => "Wiederholer",
|
||||
_ => flag
|
||||
};
|
||||
|
||||
public static StrategyInfo Describe(string? strategy)
|
||||
{
|
||||
var raw = strategy?.Trim() ?? "";
|
||||
var tokens = raw.Split(' ', StringSplitOptions.RemoveEmptyEntries);
|
||||
if (tokens.Length == 0)
|
||||
{
|
||||
return new StrategyInfo(raw, raw, raw, null, [], []);
|
||||
}
|
||||
|
||||
var baseName = Aliases.GetValueOrDefault(tokens[0], tokens[0]);
|
||||
var flags = VariantFlags
|
||||
.Where(flag => tokens.Skip(1).Contains(flag) && !(flag == "link" && LinkedByDesign.Contains(baseName)))
|
||||
.ToList();
|
||||
|
||||
var details = new List<string>();
|
||||
if (baseName != tokens[0])
|
||||
{
|
||||
details.Add($"früherer Name von {Known[baseName].Name}");
|
||||
}
|
||||
|
||||
for (var i = 1; i < tokens.Length; i++)
|
||||
{
|
||||
var token = tokens[i];
|
||||
if (DelayPattern().Match(token) is { Success: true } delay
|
||||
&& i + 1 < tokens.Length && SizePattern().Match(tokens[i + 1]) is { Success: true } chunk)
|
||||
{
|
||||
details.Add($"tröpfelt {Range(chunk.Groups[1].Value, chunk.Groups[2].Value)} Byte alle {Range(delay.Groups[1].Value, delay.Groups[2].Value)} ms");
|
||||
i++;
|
||||
}
|
||||
else if (token is "head" or "link" && i + 1 < tokens.Length && SingleSizePattern().Match(tokens[i + 1]) is { Success: true } size)
|
||||
{
|
||||
var bytes = Number(size.Groups[1].Value);
|
||||
details.Add(token == "head"
|
||||
? $"schneller Start: die ersten {bytes} Byte sofort"
|
||||
: $"alle {bytes} Byte ein Link");
|
||||
i++;
|
||||
}
|
||||
else if (token is "head" or "link")
|
||||
{
|
||||
details.Add(token == "head" ? "schneller Start: erste Bytes sofort" : "enthält Links");
|
||||
}
|
||||
else if (token == "repeat")
|
||||
{
|
||||
details.Add("Wiederholer: darf länger festgehalten werden");
|
||||
}
|
||||
else
|
||||
{
|
||||
details.Add(token);
|
||||
}
|
||||
}
|
||||
|
||||
return Known.TryGetValue(baseName, out var known)
|
||||
? new StrategyInfo(raw, baseName, known.Name, known.Explanation, details, flags)
|
||||
: new StrategyInfo(raw, baseName, baseName, null, details, flags);
|
||||
}
|
||||
|
||||
public static string Display(string? strategy) => Describe(strategy).DisplayName;
|
||||
|
||||
public static string GroupKey(string? strategy) => Describe(strategy).GroupKey;
|
||||
|
||||
public static StrategyMatch? Group(string? strategy)
|
||||
{
|
||||
var info = Describe(strategy);
|
||||
if (info.BaseName.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var bases = Aliases.Where(pair => pair.Value == info.BaseName).Select(pair => pair.Key).Prepend(info.BaseName).ToList();
|
||||
var variableFlags = VariantFlags.Where(flag => !(flag == "link" && LinkedByDesign.Contains(info.BaseName)));
|
||||
return new StrategyMatch(bases, info.Flags, variableFlags.Except(info.Flags).ToList());
|
||||
}
|
||||
|
||||
public static IReadOnlyList<TopEntry> Rank(IEnumerable<StrategySample> samples, int take)
|
||||
{
|
||||
var groups = samples
|
||||
.GroupBy(sample => GroupKey(sample.Strategy))
|
||||
.Select(group =>
|
||||
{
|
||||
var durations = group.Select(sample => sample.DurationMs).Order().ToList();
|
||||
var middle = durations.Count / 2;
|
||||
var median = durations.Count % 2 == 1 ? durations[middle] : (durations[middle - 1] + durations[middle]) / 2d;
|
||||
return new TopEntry(group.Key, durations.Count, TimeSpan.FromMilliseconds(durations.Sum()), MedianHold: TimeSpan.FromMilliseconds(median));
|
||||
});
|
||||
|
||||
return groups
|
||||
.OrderBy(entry => entry.Count < MinCatches)
|
||||
.ThenByDescending(entry => entry.MedianHold)
|
||||
.ThenByDescending(entry => entry.Count)
|
||||
.Take(take)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
public static IReadOnlyList<string> Matching(string? search)
|
||||
{
|
||||
var term = search?.Trim();
|
||||
if (string.IsNullOrEmpty(term))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var keys = Known.Where(pair => pair.Value.Name.Contains(term, StringComparison.CurrentCultureIgnoreCase)).Select(pair => pair.Key).ToList();
|
||||
return [.. keys, .. Aliases.Where(pair => keys.Contains(pair.Value)).Select(pair => pair.Key)];
|
||||
}
|
||||
|
||||
private static string Range(string min, string max) => min == max ? Number(min) : $"{Number(min)}–{Number(max)}";
|
||||
|
||||
private static string Number(string digits) => long.Parse(digits, CultureInfo.InvariantCulture).ToString("N0", Formatting.German);
|
||||
|
||||
[GeneratedRegex(@"^(\d+)-(\d+)ms$")]
|
||||
private static partial Regex DelayPattern();
|
||||
|
||||
[GeneratedRegex(@"^(\d+)-(\d+)B$")]
|
||||
private static partial Regex SizePattern();
|
||||
|
||||
[GeneratedRegex(@"^(\d+)B$")]
|
||||
private static partial Regex SingleSizePattern();
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Microsoft.AspNetCore.Antiforgery;
|
||||
|
||||
namespace Flypaper.Web.Explanations;
|
||||
|
||||
public static class ExplanationEndpoints
|
||||
{
|
||||
public static IEndpointRouteBuilder MapExplanationEndpoints(this IEndpointRouteBuilder app)
|
||||
{
|
||||
app.MapPost("/explanations/{id:int}/enabled", async (int id, HttpContext context, IAntiforgery antiforgery, ExplanationRuleStore store) =>
|
||||
{
|
||||
if (!await antiforgery.IsRequestValidAsync(context))
|
||||
{
|
||||
return Results.BadRequest();
|
||||
}
|
||||
|
||||
var enabled = (await context.Request.ReadFormAsync(context.RequestAborted))["enabled"] == "true";
|
||||
await store.SetEnabledAsync(id, enabled, context.RequestAborted);
|
||||
return Results.LocalRedirect("/erklaerungen");
|
||||
});
|
||||
|
||||
app.MapPost("/explanations/{id:int}/delete", async (int id, HttpContext context, IAntiforgery antiforgery, ExplanationRuleStore store) =>
|
||||
{
|
||||
if (!await antiforgery.IsRequestValidAsync(context))
|
||||
{
|
||||
return Results.BadRequest();
|
||||
}
|
||||
|
||||
await store.DeleteAsync(id, context.RequestAborted);
|
||||
return Results.LocalRedirect("/erklaerungen");
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
using System.ComponentModel;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Storage.Explanations;
|
||||
using Flypaper.Storage.Queries;
|
||||
using ModelContextProtocol;
|
||||
using ModelContextProtocol.Server;
|
||||
|
||||
namespace Flypaper.Web.Mcp;
|
||||
|
||||
[McpServerToolType]
|
||||
public sealed class ExplanationTools(ExplanationRuleStore store, ExplanationQueries queries, TimeProvider timeProvider, IHttpContextAccessor httpContext)
|
||||
{
|
||||
private const string PeriodDescription = "Time window ending now: a number with m (minutes), h (hours), d (days) or w (weeks), e.g. 24h, 7d; or all.";
|
||||
|
||||
private const string KindDescription =
|
||||
"What the pattern is matched against. " +
|
||||
"target: the requested path including the query string, without method and host, e.g. /.git/HEAD or /index.php?s=/x (the text explains what the bot was looking for). " +
|
||||
"client_info: the User-Agent header, an empty string if the bot sent none (the text explains which tool or kind of client it is). " +
|
||||
"outcome: the text '<Outcome> <whole seconds>s', e.g. 'ClientAborted 9s', 'Timeout 60s', 'Completed 3600s', or just 'Rejected' (the text explains how the catch ended; " +
|
||||
"ClientAborted = the bot gave up, Timeout = Flypaper ended it, Rejected = connection refused because the trap was full, Completed = finished normally).";
|
||||
|
||||
private const string PatternDescription =
|
||||
".NET regular expression, case-insensitive, matches anywhere in the text unless anchored with ^ and $. Lookarounds, backreferences and atomic groups are not supported. " +
|
||||
"Make it as narrow as possible and anchor it, e.g. ^/\\.env(\\.[a-z0-9_-]+)?$ instead of env. Test it with test_explanation_rule before saving. At most 500 characters.";
|
||||
|
||||
private const string TextDescription =
|
||||
"One or two short sentences in German, simple language for laypeople, plain text only (no Markdown, HTML or line breaks), at most 600 characters. " +
|
||||
"target: what the bot wanted, e.g. 'Sucht nach einer vergessenen Konfigurationsdatei, in der oft Passwörter stehen.' " +
|
||||
"client_info: which tool it is, e.g. 'Ein Programm, das das Internet automatisch nach offenen Servern absucht.' " +
|
||||
"outcome: how it ended, e.g. 'Der Bot hat nach 9 Sekunden aufgegeben.' Do not claim more than the data shows.";
|
||||
|
||||
private const string PriorityDescription = "Higher wins when several rules of the same kind match; ties go to the older rule. Use about 10 for narrow rules and 0 for broad fallbacks. Range -1000 to 1000.";
|
||||
|
||||
private const string NoteDescription = "Optional source or remark for maintainers, e.g. a CVE number or a link. At most 500 characters. An empty string removes it.";
|
||||
|
||||
[McpServerTool(Name = "list_explanation_rules", Title = "List explanation rules", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("All explanation rules with pattern, text, priority, enabled state and how many catches each one matches (counted over all stored catches, even when the rule is disabled). Look here before creating a rule to avoid duplicates.")]
|
||||
public async Task<RuleListResult> ListRules(
|
||||
[Description("Only this kind: target, client_info or outcome.")] string? kind = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var filter = kind is null ? (ExplanationKind?)null : ParseKind(kind);
|
||||
var hits = await queries.CountHitsAsync(ct);
|
||||
var rules = (await store.ListAsync(ct)).Where(r => filter is null || r.Kind == filter).Select(r => ToItem(r, hits.GetValueOrDefault(r.Id))).ToList();
|
||||
return new RuleListResult(rules.Count, rules);
|
||||
}
|
||||
|
||||
[McpServerTool(Name = "list_unexplained", Title = "List unexplained targets", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Catches whose requested path is not explained by any enabled target rule, grouped by path or by path pattern and sorted by number of catches. Start here to find what to write rules for: take the biggest groups first.")]
|
||||
public async Task<UnexplainedListResult> ListUnexplained(
|
||||
[Description(PeriodDescription)] string period = "all",
|
||||
[Description("path: one group per exact path including the query string. pattern: paths that differ only in numbers or long hex strings are merged (digits become {n}, hex strings {hex}) and the query string is dropped.")]
|
||||
[AllowedValues("path", "pattern")]
|
||||
string group_by = "pattern",
|
||||
[Description("Maximum number of groups, 1 to 500.")] int limit = 50,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var grouping = group_by.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"path" => UnexplainedGrouping.Path,
|
||||
"pattern" => UnexplainedGrouping.Pattern,
|
||||
_ => throw new McpException("group_by must be path or pattern.")
|
||||
};
|
||||
|
||||
var result = await queries.FindUnexplainedAsync(Since(period), grouping, limit, ct);
|
||||
return new UnexplainedListResult(
|
||||
Normalize(period),
|
||||
group_by.Trim().ToLowerInvariant(),
|
||||
result.Catches,
|
||||
result.DistinctPaths,
|
||||
result.Groups.Select(g => new UnexplainedItem(g.Key, g.Catches, g.ExamplePaths, g.ExampleUserAgent, g.FirstSeen, g.LastSeen)).ToList(),
|
||||
result.GroupsOmitted);
|
||||
}
|
||||
|
||||
[McpServerTool(Name = "test_explanation_rule", Title = "Test an explanation rule", ReadOnly = true, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Tries a pattern against the stored catches without saving anything: how many catches match, example values, how many were unexplained before, and which existing rules would lose catches to it (a higher priority takes over). Check the examples for false positives and tighten the pattern before create_explanation_rule. Pass rule_id to test a change to an existing rule.")]
|
||||
public async Task<RuleTestItem> TestRule(
|
||||
[Description(KindDescription)] [AllowedValues("target", "client_info", "outcome")] string kind,
|
||||
[Description(PatternDescription)] string pattern,
|
||||
[Description(PriorityDescription)] int priority = 0,
|
||||
[Description("Id of an existing rule that this pattern would replace; its current pattern is then ignored and catches it would no longer explain are reported.")] int? rule_id = null,
|
||||
[Description(PeriodDescription)] string period = "all",
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var parsed = ParseKind(kind);
|
||||
if (rule_id is { } id && await store.GetAsync(id, ct) is null)
|
||||
{
|
||||
throw NotFound(id);
|
||||
}
|
||||
|
||||
var result = await queries.TestAsync(parsed, pattern, priority, rule_id, Since(period), ct);
|
||||
return new RuleTestItem(
|
||||
KindName(parsed),
|
||||
pattern.Trim(),
|
||||
Normalize(period),
|
||||
result.Catches,
|
||||
result.DistinctValues,
|
||||
result.Examples.Select(e => new ValueCount(e.Value, e.Catches)).ToList(),
|
||||
result.NewlyExplained,
|
||||
result.TakesOver.Select(t => new TakeoverItem(t.Rule.Id, t.Rule.Pattern, t.Rule.Text, t.Rule.Priority, t.Catches, t.Examples)).ToList(),
|
||||
result.Lost,
|
||||
result.LostExamples);
|
||||
}
|
||||
|
||||
[McpServerTool(Name = "create_explanation_rule", Title = "Create explanation rule", ReadOnly = false, Destructive = false, Idempotent = false, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Creates an explanation rule. It is active immediately and shows up in the dashboard for all matching catches, old ones included. Test the pattern with test_explanation_rule first. Needs a token with write permission.")]
|
||||
public async Task<RuleItem> CreateRule(
|
||||
[Description(KindDescription)] [AllowedValues("target", "client_info", "outcome")] string kind,
|
||||
[Description(PatternDescription)] string pattern,
|
||||
[Description(TextDescription)] string text,
|
||||
[Description(PriorityDescription)] int priority = 0,
|
||||
[Description(NoteDescription)] string? note = null,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.CreateAsync(new ExplanationRuleInput(ParseKind(kind), pattern, text, priority, note), Actor(), ct), null);
|
||||
|
||||
[McpServerTool(Name = "update_explanation_rule", Title = "Update explanation rule", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Changes an explanation rule; only the given fields are changed. Test a new pattern with test_explanation_rule (rule_id) first. Needs a token with write permission.")]
|
||||
public async Task<RuleItem> UpdateRule(
|
||||
[Description("Id of the rule.")] int id,
|
||||
[Description("New kind. " + KindDescription)] string? kind = null,
|
||||
[Description("New pattern. " + PatternDescription)] string? pattern = null,
|
||||
[Description("New text. " + TextDescription)] string? text = null,
|
||||
[Description("New priority. " + PriorityDescription)] int? priority = null,
|
||||
[Description(NoteDescription)] string? note = null,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.UpdateAsync(id, new ExplanationRuleInput(kind is null ? null : ParseKind(kind), pattern, text, priority, note), ct) ?? throw NotFound(id), null);
|
||||
|
||||
[McpServerTool(Name = "set_explanation_rule_enabled", Title = "Enable or disable explanation rule", ReadOnly = false, Destructive = false, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Switches a rule on or off without deleting it. Needs a token with write permission.")]
|
||||
public async Task<RuleItem> SetEnabled(
|
||||
[Description("Id of the rule.")] int id,
|
||||
[Description("true to enable, false to disable.")] bool enabled,
|
||||
CancellationToken ct = default) =>
|
||||
ToItem(await store.SetEnabledAsync(id, enabled, ct) ?? throw NotFound(id), null);
|
||||
|
||||
[McpServerTool(Name = "delete_explanation_rule", Title = "Delete explanation rule", ReadOnly = false, Destructive = true, Idempotent = true, OpenWorld = false, UseStructuredContent = true)]
|
||||
[Description("Permanently deletes a rule. Prefer set_explanation_rule_enabled when unsure. Needs a token with write permission.")]
|
||||
public async Task<DeleteResult> DeleteRule(
|
||||
[Description("Id of the rule.")] int id,
|
||||
CancellationToken ct = default) =>
|
||||
new(id, await store.DeleteAsync(id, ct));
|
||||
|
||||
private string Actor() => httpContext.HttpContext?.User.Identity?.Name is { Length: > 0 } name ? name : "MCP";
|
||||
|
||||
private DateTime? Since(string? period)
|
||||
{
|
||||
if (!QueryPeriod.TryParse(period, out var span))
|
||||
{
|
||||
throw new McpException($"Invalid period '{period}'. {PeriodDescription}");
|
||||
}
|
||||
|
||||
return span is { } window ? timeProvider.GetUtcNow().UtcDateTime - window : null;
|
||||
}
|
||||
|
||||
private static string Normalize(string? period) => string.IsNullOrWhiteSpace(period) ? "all" : period.Trim().ToLowerInvariant();
|
||||
|
||||
private static ExplanationKind ParseKind(string kind) => kind.Trim().ToLowerInvariant() switch
|
||||
{
|
||||
"target" => ExplanationKind.Target,
|
||||
"client_info" => ExplanationKind.ClientInfo,
|
||||
"outcome" => ExplanationKind.Outcome,
|
||||
_ => throw new McpException("kind must be one of target, client_info, outcome.")
|
||||
};
|
||||
|
||||
private static string KindName(ExplanationKind kind) => kind switch
|
||||
{
|
||||
ExplanationKind.Target => "target",
|
||||
ExplanationKind.ClientInfo => "client_info",
|
||||
_ => "outcome"
|
||||
};
|
||||
|
||||
private static McpException NotFound(int id) => new($"There is no explanation rule with id {id}.");
|
||||
|
||||
private static RuleItem ToItem(ExplanationRuleEntity rule, int? catches) => new(
|
||||
rule.Id,
|
||||
KindName(rule.Kind),
|
||||
rule.Pattern,
|
||||
rule.Text,
|
||||
rule.Priority,
|
||||
rule.Enabled,
|
||||
rule.Note,
|
||||
rule.CreatedAt,
|
||||
rule.UpdatedAt,
|
||||
rule.CreatedBy,
|
||||
catches);
|
||||
}
|
||||
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user