diff --git a/CHANGELOG.md b/CHANGELOG.md index e6fdca8..d7177f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,19 @@ All notable changes to Flypaper are documented in this file. The format follows ## [Unreleased] +## [0.11.0] - 2026-11-27 + +### Added + +- Command detection: path, headers and body of every catch are checked for injected commands (download or + connect with `wget`, `curl`, `tftp`, `nc` and a target, shell pipes, `chmod`, PHP code, PowerShell, + `base64 -d`, `rm -rf`), also URL-encoded. The command and the target server are stored with the catch + (migration `AddDetectedCommands`); stored catches are checked once at startup, bodies only where still + recorded. Pattern based, so it can miss commands or raise false alarms. +- Dashboard: card „Eingeschleuste Befehle“, badge „⚠ Befehl“ and details in the catch list and a filter + „Befehl: Nur mit Befehl“. Commands and servers are shown defanged as plain text. +- MCP: read-only tool `list_commands`. + ## [0.10.0] - 2026-11-26 ### Added @@ -276,7 +289,8 @@ 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.10.0...main +[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.11.0...main +[0.11.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.11.0 [0.10.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.10.0 [0.9.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.9.0 [0.8.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.8.0 diff --git a/docs/mcp.md b/docs/mcp.md index b1f4f1a..1876a33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -62,6 +62,7 @@ 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), `marker` (12 hex characters from a signpost URL) | Events, newest first, including rejected ones; each carries its `marker` | diff --git a/src/Flypaper.Core/Analysis/CommandDetector.cs b/src/Flypaper.Core/Analysis/CommandDetector.cs new file mode 100644 index 0000000..cca88a3 --- /dev/null +++ b/src/Flypaper.Core/Analysis/CommandDetector.cs @@ -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)://(?[^\s/;|&`'""<>()?#]+)[^\s;|&`'""<>()]*|\b(?(?:\d{1,3}\.){3}\d{1,3})(?:[ :](?\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 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); +} diff --git a/src/Flypaper.Core/Analysis/Defang.cs b/src/Flypaper.Core/Analysis/Defang.cs new file mode 100644 index 0000000..0c2a40b --- /dev/null +++ b/src/Flypaper.Core/Analysis/Defang.cs @@ -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(); +} diff --git a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs index f5dfb36..9b61de7 100644 --- a/src/Flypaper.Storage/Dashboard/DashboardQueries.cs +++ b/src/Flypaper.Storage/Dashboard/DashboardQueries.cs @@ -101,6 +101,11 @@ public sealed class DashboardQueries(IDbContextFactory dbCont 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); diff --git a/src/Flypaper.Storage/Dashboard/RecentFilter.cs b/src/Flypaper.Storage/Dashboard/RecentFilter.cs index 9e5c128..4888fa4 100644 --- a/src/Flypaper.Storage/Dashboard/RecentFilter.cs +++ b/src/Flypaper.Storage/Dashboard/RecentFilter.cs @@ -14,7 +14,8 @@ public sealed record RecentFilter( string? Search = null, int Limit = RecentFilter.DefaultLimit, IReadOnlyList? SearchStrategies = null, - bool Unexplained = false) + bool Unexplained = false, + bool WithCommand = false) { public const int DefaultLimit = 50; public const int MaxLimit = 500; diff --git a/src/Flypaper.Storage/Entities/TrapEventEntity.cs b/src/Flypaper.Storage/Entities/TrapEventEntity.cs index a14efdd..a6287d8 100644 --- a/src/Flypaper.Storage/Entities/TrapEventEntity.cs +++ b/src/Flypaper.Storage/Entities/TrapEventEntity.cs @@ -1,3 +1,4 @@ +using Flypaper.Core.Analysis; using Flypaper.Core.Models; namespace Flypaper.Storage.Entities; @@ -40,8 +41,32 @@ public sealed class TrapEventEntity public TrapRequestEntity? Request { get; set; } - public static TrapEventEntity From(TrapEvent trapEvent) => new() + 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(), diff --git a/src/Flypaper.Storage/Events/CommandBackfill.cs b/src/Flypaper.Storage/Events/CommandBackfill.cs new file mode 100644 index 0000000..8eebec1 --- /dev/null +++ b/src/Flypaper.Storage/Events/CommandBackfill.cs @@ -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 dbContextFactory, + ILogger 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 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); +} diff --git a/src/Flypaper.Storage/FlypaperDbContext.cs b/src/Flypaper.Storage/FlypaperDbContext.cs index f0b52fc..477aa99 100644 --- a/src/Flypaper.Storage/FlypaperDbContext.cs +++ b/src/Flypaper.Storage/FlypaperDbContext.cs @@ -1,3 +1,4 @@ +using Flypaper.Core.Analysis; using Flypaper.Storage.Entities; using Flypaper.Storage.Explanations; using Microsoft.EntityFrameworkCore; @@ -39,6 +40,10 @@ public sealed class FlypaperDbContext(DbContextOptions 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(e => e.TrapEventId) diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs index 4dfcf66..46ff415 100644 --- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -37,10 +37,12 @@ public static class FlypaperStorageExtensions services.AddSingleton(sp => sp.GetRequiredService()); services.AddHostedService(); services.AddHostedService(); + services.AddHostedService(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/Flypaper.Storage/Migrations/20261127200648_AddDetectedCommands.Designer.cs b/src/Flypaper.Storage/Migrations/20261127200648_AddDetectedCommands.Designer.cs new file mode 100644 index 0000000..6d98d94 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261127200648_AddDetectedCommands.Designer.cs @@ -0,0 +1,261 @@ +// +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 + { + /// + 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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("Enabled") + .HasColumnType("INTEGER"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Note") + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("Pattern") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("Priority") + .HasColumnType("INTEGER"); + + b.Property("Text") + .IsRequired() + .HasMaxLength(600) + .HasColumnType("TEXT"); + + b.Property("UpdatedAt") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("ExplanationRules"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.McpTokenEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("CanWrite") + .HasColumnType("INTEGER"); + + b.Property("CreatedAt") + .HasColumnType("TEXT"); + + b.Property("LastUsedAt") + .HasColumnType("TEXT"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("TEXT"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("McpTokens"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b => + { + b.Property("Key") + .HasMaxLength(128) + .HasColumnType("TEXT"); + + b.Property("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Key"); + + b.ToTable("Settings"); + }); + + modelBuilder.Entity("Flypaper.Storage.Entities.TrapEventEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Asn") + .HasColumnType("INTEGER"); + + b.Property("BytesSent") + .HasColumnType("INTEGER"); + + b.Property("City") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("ClientInfo") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.Property("Command") + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("CommandScan") + .HasColumnType("INTEGER"); + + b.Property("CommandServer") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("Country") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("CountryCode") + .HasMaxLength(2) + .HasColumnType("TEXT"); + + b.Property("DurationMs") + .HasColumnType("INTEGER"); + + b.Property("EndedAt") + .HasColumnType("TEXT"); + + b.Property("Outcome") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Protocol") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("TEXT"); + + b.Property("Provider") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property("RemoteIp") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("SessionId") + .HasColumnType("TEXT"); + + b.Property("StartedAt") + .HasColumnType("TEXT"); + + b.Property("Strategy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property("Target") + .HasMaxLength(2048) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Asn"); + + b.HasIndex("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("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Body") + .HasColumnType("TEXT"); + + b.Property("ContentLength") + .HasColumnType("INTEGER"); + + b.Property("Headers") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("TrapEventId") + .HasColumnType("INTEGER"); + + b.Property("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 + } + } +} diff --git a/src/Flypaper.Storage/Migrations/20261127200648_AddDetectedCommands.cs b/src/Flypaper.Storage/Migrations/20261127200648_AddDetectedCommands.cs new file mode 100644 index 0000000..60901e2 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261127200648_AddDetectedCommands.cs @@ -0,0 +1,70 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + /// + public partial class AddDetectedCommands : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Command", + table: "TrapEvents", + type: "TEXT", + maxLength: 500, + nullable: true); + + migrationBuilder.AddColumn( + name: "CommandScan", + table: "TrapEvents", + type: "INTEGER", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + 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"); + } + + /// + 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"); + } + } +} diff --git a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs index 7ecdb14..95b431e 100644 --- a/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs +++ b/src/Flypaper.Storage/Migrations/FlypaperDbContextModelSnapshot.cs @@ -132,6 +132,17 @@ namespace Flypaper.Storage.Migrations .HasMaxLength(2048) .HasColumnType("TEXT"); + b.Property("Command") + .HasMaxLength(500) + .HasColumnType("TEXT"); + + b.Property("CommandScan") + .HasColumnType("INTEGER"); + + b.Property("CommandServer") + .HasMaxLength(256) + .HasColumnType("TEXT"); + b.Property("Country") .HasMaxLength(256) .HasColumnType("TEXT"); @@ -184,12 +195,17 @@ 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"); }); diff --git a/src/Flypaper.Storage/Queries/CommandQueries.cs b/src/Flypaper.Storage/Queries/CommandQueries.cs new file mode 100644 index 0000000..9a9433a --- /dev/null +++ b/src/Flypaper.Storage/Queries/CommandQueries.cs @@ -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 dbContextFactory) +{ + private const int MaxRows = 5_000; + + public async Task> 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(); + } +} diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs index 63279ab..c55bd76 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs +++ b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardFilter.cs @@ -16,7 +16,8 @@ public sealed record DashboardFilter( string? Strategie = null, string? Q = null, int Limit = RecentFilter.DefaultLimit, - string? Erklaerung = null) + string? Erklaerung = null, + string? Befehl = null) { public const string Anchor = "faenge"; @@ -27,6 +28,8 @@ public sealed record DashboardFilter( 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( @@ -39,7 +42,8 @@ public sealed record DashboardFilter( string? strategie, string? q, string? limit, - string? erklaerung = null) + string? erklaerung = null, + string? befehl = null) { var parsedLimit = int.TryParse(limit, NumberStyles.None, CultureInfo.InvariantCulture, out var value) ? Math.Clamp(value, 1, RecentFilter.MaxLimit) @@ -55,7 +59,8 @@ public sealed record DashboardFilter( Clean(strategie) is { } strategy ? StrategyNames.GroupKey(strategy) : null, Clean(q), parsedLimit, - Known(Explanations, erklaerung)); + Known(Explanations, erklaerung), + Known(Commands, befehl)); } public RecentFilter ToRecentFilter() => new( @@ -79,7 +84,8 @@ public sealed record DashboardFilter( StrategyNames.Group(Strategie), Q, Limit, - Unexplained: Erklaerung == "ohne"); + Unexplained: Erklaerung == "ohne", + WithCommand: Befehl == "ja"); public int NextLimit => Math.Min(Limit * 2, RecentFilter.MaxLimit); @@ -95,6 +101,7 @@ public sealed record DashboardFilter( 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)); diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor index 4563ff3..b07604f 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor +++ b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor @@ -3,10 +3,13 @@ @using Flypaper.Core.Models @using Flypaper.Http @using Microsoft.Extensions.Options +@using Flypaper.Core.Analysis @using Flypaper.Storage.Dashboard +@using Flypaper.Storage.Queries @using Flypaper.Storage.Entities @using Flypaper.Storage.Explanations @inject DashboardQueries Queries +@inject CommandQueries CommandQueries @inject ExplanationRuleStore Explanations @inject IConnectionGovernor Governor @inject IActiveTraps ActiveTraps @@ -107,6 +110,44 @@ } + @if (_commands.Count > 0) + { +
+
+

⚠ Eingeschleuste Befehle

+ Alle Fänge mit Befehl +
+
+ + + + + + + + + + + + + @foreach (var command in _commands) + { + var last = command.LastSeen.ToLocalTime(); + + + + + + + + + } + +
ZuletztZielserverBefehl (entschärft)Letzte Angreifer-IPFängeIPs
@last.ToString("dd.MM. HH:mm")@(command.Server is { } server ? Defang.Server(server) : "–")@Defang.Text(command.Command)@command.LastIp@Formatting.Number(command.Catches)@Formatting.Number(command.Ips)
+
+
+ } + @if (data.TotalCatches == 0) {
@@ -190,6 +231,15 @@ } +