Record request headers and bodies and show them per catch
Headers and the first 8 KB of the body are stored unmasked for 30 days, read alongside the response so the trap answers as before. MCP get_request and the expanded catch row show them. Changelog prepared for 0.10.0. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a46727bab3
commit
b559f83550
35 files changed
+1012
-18
No files matched your search
@@ -0,0 +1,120 @@
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Flypaper.Core;
|
||||
using Flypaper.Core.Abstractions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Http;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using NSubstitute;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Http;
|
||||
|
||||
public sealed class RequestCaptureTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Records_headers_and_body_without_masking_and_without_proxy_headers()
|
||||
{
|
||||
var (trapEvent, _) = await SendAsync(
|
||||
"POST /wp-login.php HTTP/1.1\r\nHost: trap.example\r\nAuthorization: Basic YWRtaW46YWRtaW4=\r\nCookie: session=abc\r\n"
|
||||
+ "X-Real-IP: 203.0.113.9\r\nX-Forwarded-For: 203.0.113.9\r\nContent-Length: 17\r\n\r\nlog=admin&pwd=123");
|
||||
|
||||
var request = trapEvent.Request.ShouldNotBeNull();
|
||||
request.Body.ShouldBe("log=admin&pwd=123");
|
||||
request.ContentLength.ShouldBe(17);
|
||||
request.Truncated.ShouldBeFalse();
|
||||
request.Headers.ShouldContain("Authorization: Basic YWRtaW46YWRtaW4=");
|
||||
request.Headers.ShouldContain("Cookie: session=abc");
|
||||
request.Headers.ShouldNotContain("X-Real-IP");
|
||||
request.Headers.ShouldNotContain("X-Forwarded-For");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Cuts_large_bodies_and_escapes_binary_data()
|
||||
{
|
||||
var body = "\0\u0001A" + new string('x', 20_000);
|
||||
|
||||
var (trapEvent, _) = await SendAsync($"POST / HTTP/1.1\r\nHost: trap.example\r\nContent-Length: {body.Length}\r\n\r\n{body}");
|
||||
|
||||
var request = trapEvent.Request.ShouldNotBeNull();
|
||||
request.Body.ShouldNotBeNull().ShouldStartWith("\\x00\\x01Axxx");
|
||||
request.Body.Length.ShouldBe(8192 + 6);
|
||||
request.ContentLength.ShouldBe(body.Length);
|
||||
request.Truncated.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_body_that_never_arrives_neither_delays_nor_ends_the_drip()
|
||||
{
|
||||
var (trapEvent, firstByte) = await SendAsync(
|
||||
"POST /.env HTTP/1.1\r\nHost: trap.example\r\nContent-Length: 500\r\n\r\npartial",
|
||||
holdFor: TimeSpan.FromSeconds(8));
|
||||
|
||||
firstByte.ShouldBeLessThan(TimeSpan.FromSeconds(2));
|
||||
trapEvent.Outcome.ShouldBe(TrapOutcome.Timeout);
|
||||
trapEvent.Duration.ShouldBeGreaterThan(TimeSpan.FromSeconds(7));
|
||||
trapEvent.Request.ShouldNotBeNull().Body.ShouldBe("partial");
|
||||
trapEvent.Request!.Truncated.ShouldBeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Records_nothing_when_switched_off()
|
||||
{
|
||||
var (trapEvent, _) = await SendAsync("GET /.env HTTP/1.1\r\nHost: trap.example\r\n\r\n", capture: false);
|
||||
|
||||
trapEvent.Request.ShouldBeNull();
|
||||
}
|
||||
|
||||
private static async Task<(TrapEvent Event, TimeSpan FirstByte)> SendAsync(string rawRequest, TimeSpan? holdFor = null, bool capture = true)
|
||||
{
|
||||
var published = new TaskCompletionSource<TrapEvent>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var sink = Substitute.For<ITrapEventSink>();
|
||||
sink.When(s => s.Publish(Arg.Any<TrapEvent>())).Do(call => published.TrySetResult(call.Arg<TrapEvent>()));
|
||||
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
builder.WebHost.UseUrls("http://127.0.0.1:0");
|
||||
builder.Configuration["Flypaper:MaxHoldDuration"] = (holdFor ?? TimeSpan.FromMilliseconds(500)).ToString("c");
|
||||
builder.Configuration["Flypaper:IgnorePrivateNetworks"] = "false";
|
||||
builder.Configuration["Flypaper:CaptureRequests"] = capture ? "true" : "false";
|
||||
builder.Services.AddSingleton(sink);
|
||||
builder.Services.AddFlypaperCore(builder.Configuration);
|
||||
builder.Services.AddFlypaperHttp(builder.Configuration);
|
||||
await using var app = builder.Build();
|
||||
app.UseFlypaper();
|
||||
await app.StartAsync();
|
||||
var address = new Uri(app.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>()!.Addresses.First());
|
||||
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(address.Host, address.Port);
|
||||
var stream = client.GetStream();
|
||||
var started = System.Diagnostics.Stopwatch.StartNew();
|
||||
await stream.WriteAsync(Encoding.Latin1.GetBytes(rawRequest));
|
||||
var buffer = new byte[4096];
|
||||
await stream.ReadAsync(buffer).AsTask().WaitAsync(TimeSpan.FromSeconds(10));
|
||||
var firstByte = started.Elapsed;
|
||||
_ = DrainAsync(stream, buffer);
|
||||
|
||||
var trapEvent = await published.Task.WaitAsync(TimeSpan.FromSeconds(20));
|
||||
client.Close();
|
||||
await app.StopAsync();
|
||||
return (trapEvent, firstByte);
|
||||
}
|
||||
|
||||
private static async Task DrainAsync(Stream stream, byte[] buffer)
|
||||
{
|
||||
try
|
||||
{
|
||||
while (await stream.ReadAsync(buffer) > 0)
|
||||
{
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or ObjectDisposedException)
|
||||
{
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,7 +24,7 @@ public sealed class McpEndpointTests : IDisposable
|
||||
}
|
||||
|
||||
private static readonly string[] ReadTools =
|
||||
["get_stats", "list_active", "list_catches", "longest_catches", "lookup_ip", "top", "list_explanation_rules", "list_unexplained", "test_explanation_rule"];
|
||||
["get_stats", "get_request", "list_active", "list_catches", "longest_catches", "lookup_ip", "top", "list_explanation_rules", "list_unexplained", "test_explanation_rule"];
|
||||
|
||||
[Fact]
|
||||
public async Task Rejects_requests_without_token()
|
||||
@@ -81,6 +81,7 @@ public sealed class McpEndpointTests : IDisposable
|
||||
{ "get_stats", """{"period":"all"}""" },
|
||||
{ "get_stats", """{"period":"24h"}""" },
|
||||
{ "list_active", """{}""" },
|
||||
{ "get_request", """{"id":1}""" },
|
||||
{ "list_catches", """{}""" },
|
||||
{ "list_catches", """{"country":"CN","limit":1}""" },
|
||||
{ "top", """{"dimension":"ips","period":"all"}""" },
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
using System.Net;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Flypaper.Storage.Maintenance;
|
||||
using Flypaper.Storage.Queries;
|
||||
using Flypaper.Tests.Mcp;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Storage;
|
||||
|
||||
public sealed class TrapRequestStorageTests : IDisposable
|
||||
{
|
||||
private readonly McpTestData _data = new();
|
||||
|
||||
[Fact]
|
||||
public async Task Request_details_are_returned_expire_early_and_go_with_their_catch()
|
||||
{
|
||||
long oldId, newId;
|
||||
using (var db = _data.Factory.CreateDbContext())
|
||||
{
|
||||
var old = Entity(daysAgo: 40);
|
||||
var recent = Entity(daysAgo: 1);
|
||||
db.TrapEvents.AddRange(old, recent);
|
||||
db.SaveChanges();
|
||||
(oldId, newId) = (old.Id, recent.Id);
|
||||
}
|
||||
|
||||
var queries = new CatchQueries(_data.Factory);
|
||||
var maintenance = new TrapDataMaintenance(_data.Factory);
|
||||
(await queries.GetRequestAsync(newId)).Request.ShouldNotBeNull().Body.ShouldBe("pwd=1");
|
||||
|
||||
(await maintenance.DeleteRequestsOlderThanAsync(McpTestData.Now.UtcDateTime.AddDays(-30))).ShouldBe(1);
|
||||
|
||||
var expired = await queries.GetRequestAsync(oldId);
|
||||
expired.Found.ShouldBeTrue();
|
||||
expired.Request.ShouldBeNull();
|
||||
(await queries.GetRequestAsync(999_999)).Found.ShouldBeFalse();
|
||||
|
||||
await maintenance.DeleteAllAsync();
|
||||
using var check = _data.Factory.CreateDbContext();
|
||||
(await check.TrapRequests.CountAsync()).ShouldBe(0);
|
||||
}
|
||||
|
||||
private static TrapEventEntity Entity(int daysAgo)
|
||||
{
|
||||
var started = McpTestData.Now.AddDays(-daysAgo);
|
||||
return TrapEventEntity.From(new TrapEvent(
|
||||
Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.60"), "maze-drip", started, started.AddSeconds(5), 10,
|
||||
TrapOutcome.ClientAborted, "POST /", null, new RequestDetails("Host: x\n", "pwd=1", 5, false)));
|
||||
}
|
||||
|
||||
public void Dispose() => _data.Dispose();
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Flypaper.Core.Models;
|
||||
using Flypaper.Storage;
|
||||
using Flypaper.Storage.Entities;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
|
||||
namespace Flypaper.Tests.Web;
|
||||
|
||||
public sealed partial class RequestViewTests : IDisposable
|
||||
{
|
||||
private const string Password = "test-only-password";
|
||||
private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-request-{Guid.NewGuid():N}.db");
|
||||
private readonly WebApplicationFactory<Program> _factory;
|
||||
|
||||
public RequestViewTests() =>
|
||||
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
|
||||
{
|
||||
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
|
||||
builder.UseSetting("Flypaper:Ports:Dashboard", "0");
|
||||
builder.UseSetting("Flypaper:Admin:Password", Password);
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public async Task Signed_in_users_get_the_request_and_attacker_markup_stays_out_of_the_page()
|
||||
{
|
||||
using var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
|
||||
var (withRequest, without) = await SeedAsync();
|
||||
|
||||
(await client.GetAsync($"/catches/{withRequest}/request")).StatusCode.ShouldBe(HttpStatusCode.Redirect);
|
||||
|
||||
var token = TokenPattern().Match(await client.GetStringAsync("/login")).Groups[1].Value;
|
||||
await client.PostAsync("/auth/login", new FormUrlEncodedContent(
|
||||
[KeyValuePair.Create("password", Password), KeyValuePair.Create("__RequestVerificationToken", token)]));
|
||||
|
||||
var response = await client.GetAsync($"/catches/{withRequest}/request");
|
||||
response.Headers.CacheControl!.NoStore.ShouldBeTrue();
|
||||
using var json = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
|
||||
json.RootElement.GetProperty("body").GetString().ShouldBe("<script>alert(1)</script>");
|
||||
json.RootElement.GetProperty("headers").GetString().ShouldNotBeNull().ShouldContain("Host: x");
|
||||
|
||||
var page = await client.GetStringAsync("/");
|
||||
page.ShouldContain($"data-request=\"catches/{withRequest}/request\"");
|
||||
page.ShouldNotContain($"data-request=\"catches/{without}/request\"");
|
||||
page.ShouldNotContain("<script>alert(1)</script>");
|
||||
}
|
||||
|
||||
private async Task<(long WithRequest, long Without)> SeedAsync()
|
||||
{
|
||||
await using var db = await _factory.Services.GetRequiredService<IDbContextFactory<FlypaperDbContext>>().CreateDbContextAsync();
|
||||
var first = Entity(new RequestDetails("Host: x\n", "<script>alert(1)</script>", 25, false));
|
||||
var second = Entity(null);
|
||||
db.TrapEvents.AddRange(first, second);
|
||||
await db.SaveChangesAsync();
|
||||
return (first.Id, second.Id);
|
||||
}
|
||||
|
||||
private static TrapEventEntity Entity(RequestDetails? request)
|
||||
{
|
||||
var started = DateTimeOffset.UtcNow.AddMinutes(-1);
|
||||
return TrapEventEntity.From(new TrapEvent(
|
||||
Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.70"), "maze-drip", started, started.AddSeconds(5), 10,
|
||||
TrapOutcome.ClientAborted, "POST /", null, request));
|
||||
}
|
||||
|
||||
[GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"")]
|
||||
private static partial Regex TokenPattern();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_factory.Dispose();
|
||||
SqliteConnection.ClearAllPools();
|
||||
foreach (var suffix in new[] { "", "-wal", "-shm" })
|
||||
{
|
||||
File.Delete(_dbPath + suffix);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user