diff --git a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs index b46afdf..fd4da5d 100644 --- a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs +++ b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs @@ -41,7 +41,7 @@ internal sealed class FlypaperMiddleware( var trapContext = new TrapContext( session, - $"{request.Method} {request.Host}{request.Path}{request.QueryString}", + $"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}", request.Headers.UserAgent.ToString()); var outcome = await runner.RunAsync( @@ -55,6 +55,9 @@ internal sealed class FlypaperMiddleware( } } + private static string StoredHost(HostString host) => + string.IsNullOrEmpty(host.Host) || host.Host == "_" ? "" : host.Value!; + private static bool IsInternalHealthProbe(HttpContext context) => context.Request.Path.Equals(HttpTrapOptions.HealthPath, StringComparison.OrdinalIgnoreCase) && context.Connection.RemoteIpAddress is { } remoteIp diff --git a/src/Flypaper.Storage/Migrations/20261115114013_NormalizeMissingHost.Designer.cs b/src/Flypaper.Storage/Migrations/20261115114013_NormalizeMissingHost.Designer.cs new file mode 100644 index 0000000..8ef3135 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261115114013_NormalizeMissingHost.Designer.cs @@ -0,0 +1,121 @@ +// +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("20261115114013_NormalizeMissingHost")] + partial class NormalizeMissingHost + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.15"); + + modelBuilder.Entity("Flypaper.Storage.Entities.SettingEntity", b => + { + b.Property("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("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("CountryCode"); + + b.HasIndex("RemoteIp"); + + b.HasIndex("StartedAt"); + + b.ToTable("TrapEvents"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Flypaper.Storage/Migrations/20261115114013_NormalizeMissingHost.cs b/src/Flypaper.Storage/Migrations/20261115114013_NormalizeMissingHost.cs new file mode 100644 index 0000000..33db180 --- /dev/null +++ b/src/Flypaper.Storage/Migrations/20261115114013_NormalizeMissingHost.cs @@ -0,0 +1,26 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Flypaper.Storage.Migrations +{ + /// + public partial class NormalizeMissingHost : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(""" + UPDATE "TrapEvents" + SET "Target" = substr("Target", 1, instr("Target", ' _/')) || substr("Target", instr("Target", ' _/') + 2) + WHERE instr("Target", ' _/') > 0; + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + + } + } +} diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor index 0ab33cf..893217f 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor +++ b/src/Flypaper.Web/Components/Pages/Dashboard/DashboardPage.razor @@ -32,7 +32,7 @@ - +
@@ -47,40 +47,51 @@ - - - - - - - - - + + + + + + + + + @foreach (var trapEvent in data.Recent) { + 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"); - - - + + - - - - - - + + + + + + } diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor b/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor index e94fedc..dd7fb74 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor +++ b/src/Flypaper.Web/Components/Pages/Dashboard/TopTable.razor @@ -43,5 +43,11 @@ [Parameter] public bool ShowFlags { get; set; } - private static string Display(TopEntry entry) => entry.Label is null ? entry.Key : $"{entry.Key} · {entry.Label}"; + [Parameter] public Func? KeyFormatter { get; set; } + + private string Display(TopEntry entry) + { + var key = KeyFormatter?.Invoke(entry.Key) ?? entry.Key; + return entry.Label is null ? key : $"{key} · {entry.Label}"; + } } diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/WorldMap.razor b/src/Flypaper.Web/Components/Pages/Dashboard/WorldMap.razor index ed2fc11..896309c 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/WorldMap.razor +++ b/src/Flypaper.Web/Components/Pages/Dashboard/WorldMap.razor @@ -6,7 +6,15 @@ @foreach (var country in Map.Countries) { var count = Count(country.Code); - @country.Name: @count.ToString("N0") @(count == 1 ? "Fang" : "Fänge") + @Title(country.Name, count) + } + @foreach (var marker in Map.Markers) + { + var count = Count(marker.Code); + if (count > 0) + { + @Title(marker.Name, count) + } }
@@ -31,6 +39,8 @@ private int Count(string? code) => code is not null && CatchesByCountry.TryGetValue(code, out var count) ? count : 0; + private static string Title(string name, int count) => $"{name}: {count:N0} {(count == 1 ? "Fang" : "Fänge")}"; + private int Level(int count) => count == 0 || _max == 0 ? 0 : Math.Max(1, (int)Math.Ceiling(Math.Log(count + 1) / Math.Log(_max + 1) * Levels)); } diff --git a/src/Flypaper.Web/Components/Pages/Dashboard/WorldMapData.cs b/src/Flypaper.Web/Components/Pages/Dashboard/WorldMapData.cs index f6d5e86..4bf0957 100644 --- a/src/Flypaper.Web/Components/Pages/Dashboard/WorldMapData.cs +++ b/src/Flypaper.Web/Components/Pages/Dashboard/WorldMapData.cs @@ -2,7 +2,11 @@ using System.Text.Json; namespace Flypaper.Web.Components.Pages.Dashboard; -internal sealed record WorldMapData(double Width, double Height, IReadOnlyList Countries) +internal sealed record WorldMapData( + double Width, + double Height, + IReadOnlyList Countries, + IReadOnlyList Markers) { private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); @@ -18,3 +22,5 @@ internal sealed record WorldMapData(double Width, double Height, IReadOnlyList $"{bytes} B" }; + public static string? Target(string? target) + { + var space = target?.IndexOf(' ') ?? -1; + if (space < 0) + { + return target; + } + + var hostAndPath = target![(space + 1)..]; + if (hostAndPath.StartsWith('/')) + { + return $"{target[..space]} (ohne Host){hostAndPath}"; + } + + return hostAndPath == "_" || hostAndPath.StartsWith("_/", StringComparison.Ordinal) + ? $"{target[..space]} (ohne Host){hostAndPath[1..]}" + : target; + } + public static string? Provider(long? asn, string? provider) => asn is null ? provider : $"AS{asn} {provider}".TrimEnd(); } diff --git a/src/Flypaper.Web/Flypaper.Web.csproj b/src/Flypaper.Web/Flypaper.Web.csproj index d08af5a..80c0e5c 100644 --- a/src/Flypaper.Web/Flypaper.Web.csproj +++ b/src/Flypaper.Web/Flypaper.Web.csproj @@ -15,4 +15,8 @@ + + + + diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css index 3e43dd4..ac36959 100644 --- a/src/Flypaper.Web/wwwroot/app.css +++ b/src/Flypaper.Web/wwwroot/app.css @@ -127,8 +127,104 @@ h2 { max-width: none; } -.recent-table .clip { - max-width: 200px; +.recent-table { + table-layout: fixed; +} + +.recent-table td { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.recent-table tr.open td { + white-space: normal; + overflow-wrap: anywhere; +} + +.recent-table tr.open td.num, +.recent-table tr.open td.c-time, +.recent-table tr.open td.c-origin, +.recent-table tr.open td.c-outcome { + white-space: nowrap; +} + +.recent-table tr.open .extra-all { + display: block; +} + +.recent-table .c-time { + width: 116px; +} + +.recent-table .c-ip { + width: 132px; +} + +.recent-table .c-origin { + width: 76px; +} + +.recent-table .c-duration { + width: 92px; +} + +.recent-table .c-bytes { + width: 104px; +} + +.recent-table .c-outcome { + width: 116px; +} + +.recent-table .extra { + display: none; + margin-top: 4px; + color: var(--muted); + font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + font-size: 12px; +} + +@media (max-width: 1199px) { + .recent-table .c-provider, + .recent-table .c-agent { + display: none; + } + + .recent-table tr.open .extra-md { + display: block; + } +} + +@media (max-width: 899px) { + .recent-table .c-origin, + .recent-table .c-duration, + .recent-table .c-bytes { + display: none; + } + + .recent-table tr.open .extra-sm { + display: block; + } +} + +@media (max-width: 599px) { + .recent-table .c-outcome, + .recent-table .c-date { + display: none; + } + + .recent-table .c-time { + width: 76px; + } + + .recent-table .c-ip { + width: 120px; + } + + .recent-table tr.open .extra-xs { + display: block; + } } .scroll { @@ -401,6 +497,15 @@ tbody th { stroke-width: 0.5; } +.world-map .marker { + stroke: var(--surface); + stroke-width: 1.5; +} + +.world-map .marker:hover { + stroke: var(--text); +} + .world-map path:hover { stroke: var(--text); stroke-width: 1; diff --git a/test/Flypaper.Tests/Http/TargetNormalizationTests.cs b/test/Flypaper.Tests/Http/TargetNormalizationTests.cs new file mode 100644 index 0000000..b53008d --- /dev/null +++ b/test/Flypaper.Tests/Http/TargetNormalizationTests.cs @@ -0,0 +1,50 @@ +using System.Net; +using Flypaper.Core; +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; +using Flypaper.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Shouldly; + +namespace Flypaper.Tests.Http; + +public sealed class TargetNormalizationTests +{ + [Theory] + [InlineData("_", "GET /boaform/admin/formLogin")] + [InlineData("", "GET /boaform/admin/formLogin")] + [InlineData("example.com", "GET example.com/boaform/admin/formLogin")] + [InlineData("203.0.113.7:8080", "GET 203.0.113.7:8080/boaform/admin/formLogin")] + public async Task Stores_missing_or_placeholder_host_as_empty(string host, string expectedTarget) + { + var sink = Substitute.For(); + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary { ["Flypaper:MaxConnections"] = "0" }) + .Build(); + var services = new ServiceCollection() + .AddLogging() + .AddSingleton(sink) + .AddFlypaperCore(configuration) + .AddFlypaperHttp(configuration) + .BuildServiceProvider(); + + var app = new ApplicationBuilder(services); + app.UseFlypaper(); + app.Run(_ => Task.CompletedTask); + + var context = new DefaultHttpContext { RequestServices = services }; + context.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9"); + context.Connection.LocalPort = 8080; + context.Request.Method = "GET"; + context.Request.Host = new HostString(host); + context.Request.Path = "/boaform/admin/formLogin"; + + await app.Build()(context); + + sink.Received(1).Publish(Arg.Is(e => e.Target == expectedTarget)); + } +} diff --git a/test/Flypaper.Tests/Storage/MigrationTests.cs b/test/Flypaper.Tests/Storage/MigrationTests.cs index e5f02b0..86104f1 100644 --- a/test/Flypaper.Tests/Storage/MigrationTests.cs +++ b/test/Flypaper.Tests/Storage/MigrationTests.cs @@ -25,6 +25,24 @@ public sealed class MigrationTests : IDisposable (await db.Settings.Select(s => s.Key).ToListAsync()).ShouldBe(["Flypaper:MaxConnections"]); } + [Fact] + public async Task Rewrites_placeholder_host_of_existing_trap_events() + { + await using var db = new FlypaperDbContext(new DbContextOptionsBuilder().UseSqlite($"Data Source={_dbPath}").Options); + await db.GetService().MigrateAsync("RemoveDripIntervalSetting"); + await db.Database.ExecuteSqlRawAsync( + """ + INSERT INTO "TrapEvents" ("SessionId", "Protocol", "RemoteIp", "Strategy", "StartedAt", "EndedAt", "DurationMs", "BytesSent", "Outcome", "Target") + VALUES ('A', 'Http', '203.0.113.9', 'html-drip', '2026-11-14 10:00:00', '2026-11-14 10:00:05', 5000, 50, 'ClientAborted', 'GET _/boaform/admin/formLogin'), + ('B', 'Http', '203.0.113.9', 'html-drip', '2026-11-14 10:00:00', '2026-11-14 10:00:05', 5000, 50, 'ClientAborted', 'GET example.com/.env') + """); + + await db.Database.MigrateAsync(); + + (await db.TrapEvents.OrderBy(e => e.SessionId).Select(e => e.Target).ToListAsync()) + .ShouldBe(["GET /boaform/admin/formLogin", "GET example.com/.env"]); + } + public void Dispose() { SqliteConnection.ClearAllPools(); diff --git a/test/Flypaper.Tests/Web/FormattingTests.cs b/test/Flypaper.Tests/Web/FormattingTests.cs new file mode 100644 index 0000000..b64922c --- /dev/null +++ b/test/Flypaper.Tests/Web/FormattingTests.cs @@ -0,0 +1,17 @@ +using Flypaper.Web.Components.Shared; +using Shouldly; + +namespace Flypaper.Tests.Web; + +public sealed class FormattingTests +{ + [Theory] + [InlineData("GET /boaform/admin/formLogin", "GET (ohne Host)/boaform/admin/formLogin")] + [InlineData("GET _/boaform/admin/formLogin", "GET (ohne Host)/boaform/admin/formLogin")] + [InlineData("GET _", "GET (ohne Host)")] + [InlineData("GET example.com/.env", "GET example.com/.env")] + [InlineData("GET _example.com/.env", "GET _example.com/.env")] + [InlineData(null, null)] + public void Shows_missing_host_explicitly(string? target, string? expected) => + Formatting.Target(target).ShouldBe(expected); +} diff --git a/test/Flypaper.Tests/Web/WorldMapDataTests.cs b/test/Flypaper.Tests/Web/WorldMapDataTests.cs new file mode 100644 index 0000000..767d45a --- /dev/null +++ b/test/Flypaper.Tests/Web/WorldMapDataTests.cs @@ -0,0 +1,52 @@ +using Flypaper.Web.Components.Pages.Dashboard; +using Shouldly; + +namespace Flypaper.Tests.Web; + +public sealed class WorldMapDataTests +{ + private static readonly string[] Iso3166Alpha2 = + """ + AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ + CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR + GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO + JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME MF MG MH MK ML MM MN MO MP MQ MR + MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO + RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV + TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW + """.Split((char[])[' ', '\n', '\r'], StringSplitOptions.RemoveEmptyEntries); + + private readonly WorldMapData _map = WorldMapData.Instance; + + [Fact] + public void Lists_all_249_iso_codes() => Iso3166Alpha2.Distinct().Count().ShouldBe(249); + + [Fact] + public void Every_iso_country_has_a_polygon_or_a_marker() + { + var drawn = _map.Countries.Select(c => c.Code).OfType().Concat(_map.Markers.Select(m => m.Code)).ToHashSet(); + + Iso3166Alpha2.Where(code => !drawn.Contains(code)).ShouldBeEmpty(); + } + + [Theory] + [InlineData("HK")] + [InlineData("SG")] + [InlineData("MO")] + [InlineData("BH")] + [InlineData("MT")] + public void Small_bot_heavy_countries_have_markers(string code) => + _map.Markers.ShouldContain(m => m.Code == code); + + [Fact] + public void No_country_has_both_a_polygon_and_a_marker() + { + var polygons = _map.Countries.Select(c => c.Code).OfType().ToHashSet(); + + _map.Markers.Where(m => polygons.Contains(m.Code)).ShouldBeEmpty(); + } + + [Fact] + public void Markers_lie_inside_the_map() => + _map.Markers.ShouldAllBe(m => m.X >= 0 && m.X <= _map.Width && m.Y >= 0 && m.Y <= _map.Height); +}
ZeitIPHerkunftProviderZielUser-AgentDauerBytesAusgangZeitIPHerkunftProviderZielUser-AgentDauerBytesAusgang