Add Flypaper solution skeleton with HTTP tarpit, SQLite event log and tests

This commit is contained in:
Tom committed 2026-11-14 13:15:57 +01:00
1 parent 20314268c6
commit f9161f48e7
55 files changed
+1331

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Flypaper.Core\Flypaper.Core.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,44 @@
using System.Net;
using System.Net.Sockets;
using Flypaper.Core;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
namespace Flypaper.Http;
public static class FlypaperHttpExtensions
{
public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName));
services.TryAddSingleton<TrapMatcher>();
services.AddOptions<ForwardedHeadersOptions>()
.Configure<IOptions<HttpTrapOptions>>((forwarded, trap) =>
{
forwarded.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
forwarded.ForwardLimit = 1;
foreach (var proxy in trap.Value.TrustedProxies)
{
forwarded.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(proxy.Contains('/') ? proxy : $"{proxy}/{HostBits(proxy)}"));
}
});
return services;
}
public static IApplicationBuilder UseFlypaper(this IApplicationBuilder app)
{
app.UseForwardedHeaders();
app.UseMiddleware<RealIpMiddleware>();
app.UseMiddleware<FlypaperMiddleware>();
return app;
}
private static int HostBits(string address) =>
IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32;
}
+68
View File
@@ -0,0 +1,68 @@
using System.Net;
using Flypaper.Core;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
namespace Flypaper.Http;
internal sealed class FlypaperMiddleware(
RequestDelegate next,
TrapMatcher matcher,
TrapRunner runner,
TimeProvider timeProvider)
{
public async Task InvokeAsync(HttpContext context)
{
var request = context.Request;
if (matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None)
{
await next(context);
return;
}
var session = new TrapSession(
Guid.NewGuid(),
TrapProtocol.Http,
context.Connection.RemoteIpAddress ?? IPAddress.None,
timeProvider.GetUtcNow());
var trapContext = new TrapContext(
session,
$"{request.Method} {request.Host}{request.Path}{request.QueryString}",
request.Headers.UserAgent.ToString());
var outcome = await runner.RunAsync(
trapContext,
ct => OpenChannelAsync(context, session, ct),
context.RequestAborted);
if (outcome == TrapOutcome.Rejected && !context.Response.HasStarted)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
}
}
private static async ValueTask<ITrapChannel> OpenChannelAsync(
HttpContext context,
TrapSession session,
CancellationToken ct)
{
var minDataRate = context.Features.Get<IHttpMinResponseDataRateFeature>();
if (minDataRate is not null)
{
minDataRate.MinDataRate = null;
}
context.Features.Get<IHttpResponseBodyFeature>()?.DisableBuffering();
var response = context.Response;
response.StatusCode = StatusCodes.Status200OK;
response.ContentType = "text/html; charset=utf-8";
response.Headers.CacheControl = "no-store";
response.Headers["X-Accel-Buffering"] = "no";
await response.StartAsync(ct);
return new HttpTrapChannel(session, response);
}
}
+15
View File
@@ -0,0 +1,15 @@
using Flypaper.Core;
using Microsoft.AspNetCore.Http;
namespace Flypaper.Http;
internal sealed class HttpTrapChannel(TrapSession session, HttpResponse response) : ITrapChannel
{
public TrapSession Session => session;
public async ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
{
await response.Body.WriteAsync(data, ct);
await response.Body.FlushAsync(ct);
}
}
+12
View File
@@ -0,0 +1,12 @@
namespace Flypaper.Http;
public sealed class HttpTrapOptions
{
public const string SectionName = "Flypaper:Http";
public string[] KnownHosts { get; set; } = [];
public string[] TrapPaths { get; set; } = [];
public string[] TrustedProxies { get; set; } = [];
}
+39
View File
@@ -0,0 +1,39 @@
using System.Net;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
namespace Flypaper.Http;
internal sealed class RealIpMiddleware(RequestDelegate next, IOptions<ForwardedHeadersOptions> options)
{
private const string RealIpHeader = "X-Real-IP";
private const string OriginalForHeader = "X-Original-For";
public Task InvokeAsync(HttpContext context)
{
var headers = context.Request.Headers;
var remoteIp = context.Connection.RemoteIpAddress;
if (!headers.ContainsKey(OriginalForHeader)
&& remoteIp is not null
&& IsTrustedProxy(remoteIp)
&& IPAddress.TryParse(headers[RealIpHeader].ToString(), out var realIp))
{
context.Connection.RemoteIpAddress = realIp;
}
return next(context);
}
private bool IsTrustedProxy(IPAddress ip)
{
if (ip.IsIPv4MappedToIPv6)
{
ip = ip.MapToIPv4();
}
var value = options.Value;
return value.KnownProxies.Contains(ip) || value.KnownIPNetworks.Any(network => network.Contains(ip));
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace Flypaper.Http;
public enum TrapMatch
{
None,
UnknownHost,
TrapPath
}
+59
View File
@@ -0,0 +1,59 @@
using Microsoft.Extensions.Options;
namespace Flypaper.Http;
public sealed class TrapMatcher
{
private readonly HashSet<string> _hosts = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _hostSuffixes = [];
private readonly HashSet<string> _paths = new(StringComparer.OrdinalIgnoreCase);
private readonly List<string> _pathPrefixes = [];
public TrapMatcher(IOptions<HttpTrapOptions> options)
{
foreach (var host in options.Value.KnownHosts)
{
if (host.StartsWith("*.", StringComparison.Ordinal))
{
_hostSuffixes.Add(host[1..]);
}
else
{
_hosts.Add(host);
}
}
foreach (var path in options.Value.TrapPaths)
{
if (path.EndsWith('*'))
{
_pathPrefixes.Add(path[..^1]);
}
else
{
_paths.Add(TrimTrailingSlash(path));
}
}
}
public TrapMatch Match(string? host, string? path)
{
if (!IsKnownHost(host))
{
return TrapMatch.UnknownHost;
}
return IsTrapPath(path ?? "/") ? TrapMatch.TrapPath : TrapMatch.None;
}
private bool IsKnownHost(string? host) =>
!string.IsNullOrEmpty(host)
&& (_hosts.Contains(host)
|| _hostSuffixes.Any(suffix => host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase)));
private bool IsTrapPath(string path) =>
_paths.Contains(TrimTrailingSlash(path))
|| _pathPrefixes.Any(prefix => path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
private static string TrimTrailingSlash(string path) => path.Length > 1 ? path.TrimEnd('/') : path;
}