From f9161f48e7830d2c4bd84573b83e15bf09c880ca Mon Sep 17 00:00:00 2001 From: Tom Date: Sat, 14 Nov 2026 13:15:57 +0100 Subject: [PATCH] Add Flypaper solution skeleton with HTTP tarpit, SQLite event log and tests --- .gitignore | 6 ++ Directory.Build.props | 8 ++ Directory.Packages.props | 20 +++++ Flypaper.slnx | 11 +++ src/Flypaper.Core/ConnectionGovernor.cs | 72 +++++++++++++++ src/Flypaper.Core/CountingTrapChannel.cs | 16 ++++ src/Flypaper.Core/Flypaper.Core.csproj | 12 +++ src/Flypaper.Core/FlypaperOptions.cs | 12 +++ src/Flypaper.Core/IConnectionGovernor.cs | 8 ++ src/Flypaper.Core/ITarpitStrategy.cs | 10 +++ src/Flypaper.Core/ITrapChannel.cs | 8 ++ src/Flypaper.Core/ITrapEventSink.cs | 6 ++ .../ServiceCollectionExtensions.cs | 22 +++++ src/Flypaper.Core/Strategies/DripOptions.cs | 8 ++ src/Flypaper.Core/Strategies/DripStrategy.cs | 24 +++++ src/Flypaper.Core/TrapContext.cs | 3 + src/Flypaper.Core/TrapEvent.cs | 18 ++++ src/Flypaper.Core/TrapOutcome.cs | 9 ++ src/Flypaper.Core/TrapProtocol.cs | 7 ++ src/Flypaper.Core/TrapRunner.cs | 67 ++++++++++++++ src/Flypaper.Core/TrapSession.cs | 5 ++ src/Flypaper.Http/Flypaper.Http.csproj | 11 +++ src/Flypaper.Http/FlypaperHttpExtensions.cs | 44 ++++++++++ src/Flypaper.Http/FlypaperMiddleware.cs | 68 ++++++++++++++ src/Flypaper.Http/HttpTrapChannel.cs | 15 ++++ src/Flypaper.Http/HttpTrapOptions.cs | 12 +++ src/Flypaper.Http/RealIpMiddleware.cs | 39 ++++++++ src/Flypaper.Http/TrapMatch.cs | 8 ++ src/Flypaper.Http/TrapMatcher.cs | 59 +++++++++++++ src/Flypaper.Storage/ChannelTrapEventSink.cs | 20 +++++ src/Flypaper.Storage/Flypaper.Storage.csproj | 12 +++ src/Flypaper.Storage/FlypaperDbContext.cs | 23 +++++ .../FlypaperStorageExtensions.cs | 17 ++++ src/Flypaper.Storage/TrapEventEntity.cs | 48 ++++++++++ src/Flypaper.Storage/TrapEventWriter.cs | 44 ++++++++++ src/Flypaper.Web/Components/App.razor | 20 +++++ .../Components/Layout/MainLayout.razor | 3 + .../Components/Layout/MainLayout.razor.css | 20 +++++ src/Flypaper.Web/Components/Pages/Error.razor | 36 ++++++++ src/Flypaper.Web/Components/Pages/Home.razor | 7 ++ .../Components/Pages/NotFound.razor | 5 ++ src/Flypaper.Web/Components/Routes.razor | 6 ++ src/Flypaper.Web/Components/_Imports.razor | 11 +++ src/Flypaper.Web/Flypaper.Web.csproj | 12 +++ src/Flypaper.Web/Program.cs | 30 +++++++ .../Properties/launchSettings.json | 23 +++++ src/Flypaper.Web/appsettings.Development.json | 16 ++++ src/Flypaper.Web/appsettings.json | 40 +++++++++ src/Flypaper.Web/wwwroot/app.css | 38 ++++++++ .../Flypaper.Tests/ConnectionGovernorTests.cs | 76 ++++++++++++++++ test/Flypaper.Tests/DripStrategyTests.cs | 43 +++++++++ test/Flypaper.Tests/FakeTrapChannel.cs | 19 ++++ test/Flypaper.Tests/Flypaper.Tests.csproj | 25 ++++++ test/Flypaper.Tests/TrapMatcherTests.cs | 41 +++++++++ test/Flypaper.Tests/TrapRunnerTests.cs | 88 +++++++++++++++++++ 55 files changed, 1331 insertions(+) create mode 100644 Directory.Build.props create mode 100644 Directory.Packages.props create mode 100644 Flypaper.slnx create mode 100644 src/Flypaper.Core/ConnectionGovernor.cs create mode 100644 src/Flypaper.Core/CountingTrapChannel.cs create mode 100644 src/Flypaper.Core/Flypaper.Core.csproj create mode 100644 src/Flypaper.Core/FlypaperOptions.cs create mode 100644 src/Flypaper.Core/IConnectionGovernor.cs create mode 100644 src/Flypaper.Core/ITarpitStrategy.cs create mode 100644 src/Flypaper.Core/ITrapChannel.cs create mode 100644 src/Flypaper.Core/ITrapEventSink.cs create mode 100644 src/Flypaper.Core/ServiceCollectionExtensions.cs create mode 100644 src/Flypaper.Core/Strategies/DripOptions.cs create mode 100644 src/Flypaper.Core/Strategies/DripStrategy.cs create mode 100644 src/Flypaper.Core/TrapContext.cs create mode 100644 src/Flypaper.Core/TrapEvent.cs create mode 100644 src/Flypaper.Core/TrapOutcome.cs create mode 100644 src/Flypaper.Core/TrapProtocol.cs create mode 100644 src/Flypaper.Core/TrapRunner.cs create mode 100644 src/Flypaper.Core/TrapSession.cs create mode 100644 src/Flypaper.Http/Flypaper.Http.csproj create mode 100644 src/Flypaper.Http/FlypaperHttpExtensions.cs create mode 100644 src/Flypaper.Http/FlypaperMiddleware.cs create mode 100644 src/Flypaper.Http/HttpTrapChannel.cs create mode 100644 src/Flypaper.Http/HttpTrapOptions.cs create mode 100644 src/Flypaper.Http/RealIpMiddleware.cs create mode 100644 src/Flypaper.Http/TrapMatch.cs create mode 100644 src/Flypaper.Http/TrapMatcher.cs create mode 100644 src/Flypaper.Storage/ChannelTrapEventSink.cs create mode 100644 src/Flypaper.Storage/Flypaper.Storage.csproj create mode 100644 src/Flypaper.Storage/FlypaperDbContext.cs create mode 100644 src/Flypaper.Storage/FlypaperStorageExtensions.cs create mode 100644 src/Flypaper.Storage/TrapEventEntity.cs create mode 100644 src/Flypaper.Storage/TrapEventWriter.cs create mode 100644 src/Flypaper.Web/Components/App.razor create mode 100644 src/Flypaper.Web/Components/Layout/MainLayout.razor create mode 100644 src/Flypaper.Web/Components/Layout/MainLayout.razor.css create mode 100644 src/Flypaper.Web/Components/Pages/Error.razor create mode 100644 src/Flypaper.Web/Components/Pages/Home.razor create mode 100644 src/Flypaper.Web/Components/Pages/NotFound.razor create mode 100644 src/Flypaper.Web/Components/Routes.razor create mode 100644 src/Flypaper.Web/Components/_Imports.razor create mode 100644 src/Flypaper.Web/Flypaper.Web.csproj create mode 100644 src/Flypaper.Web/Program.cs create mode 100644 src/Flypaper.Web/Properties/launchSettings.json create mode 100644 src/Flypaper.Web/appsettings.Development.json create mode 100644 src/Flypaper.Web/appsettings.json create mode 100644 src/Flypaper.Web/wwwroot/app.css create mode 100644 test/Flypaper.Tests/ConnectionGovernorTests.cs create mode 100644 test/Flypaper.Tests/DripStrategyTests.cs create mode 100644 test/Flypaper.Tests/FakeTrapChannel.cs create mode 100644 test/Flypaper.Tests/Flypaper.Tests.csproj create mode 100644 test/Flypaper.Tests/TrapMatcherTests.cs create mode 100644 test/Flypaper.Tests/TrapRunnerTests.cs diff --git a/.gitignore b/.gitignore index ed6d1d2..2cbab93 100644 --- a/.gitignore +++ b/.gitignore @@ -400,3 +400,9 @@ FodyWeavers.xsd # JetBrains Rider *.sln.iml + +# Flypaper +*.db +*.db-shm +*.db-wal +.idea/ diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..a7782a4 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,8 @@ + + + net10.0 + enable + enable + true + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..ae460e4 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,20 @@ + + + true + true + + + + + + + + + + + + + + + + diff --git a/Flypaper.slnx b/Flypaper.slnx new file mode 100644 index 0000000..4b09619 --- /dev/null +++ b/Flypaper.slnx @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/Flypaper.Core/ConnectionGovernor.cs b/src/Flypaper.Core/ConnectionGovernor.cs new file mode 100644 index 0000000..8820ab5 --- /dev/null +++ b/src/Flypaper.Core/ConnectionGovernor.cs @@ -0,0 +1,72 @@ +using System.Diagnostics.CodeAnalysis; +using System.Net; +using Microsoft.Extensions.Options; + +namespace Flypaper.Core; + +public sealed class ConnectionGovernor(IOptions options) : IConnectionGovernor +{ + private readonly Lock _gate = new(); + private readonly Dictionary _perIp = []; + private int _total; + + public int ActiveConnections + { + get + { + lock (_gate) + { + return _total; + } + } + } + + public bool TryAcquire(TrapSession session, [NotNullWhen(true)] out IDisposable? lease) + { + var ip = Normalize(session.RemoteIp); + var limits = options.Value; + + lock (_gate) + { + _perIp.TryGetValue(ip, out var count); + if (_total >= limits.MaxConnections || count >= limits.MaxConnectionsPerIp) + { + lease = null; + return false; + } + + _total++; + _perIp[ip] = count + 1; + } + + lease = new Lease(this, ip); + return true; + } + + private void Release(IPAddress ip) + { + lock (_gate) + { + _total--; + if (--_perIp[ip] == 0) + { + _perIp.Remove(ip); + } + } + } + + private static IPAddress Normalize(IPAddress ip) => ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip; + + private sealed class Lease(ConnectionGovernor owner, IPAddress ip) : IDisposable + { + private int _disposed; + + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 0) + { + owner.Release(ip); + } + } + } +} diff --git a/src/Flypaper.Core/CountingTrapChannel.cs b/src/Flypaper.Core/CountingTrapChannel.cs new file mode 100644 index 0000000..ff655a9 --- /dev/null +++ b/src/Flypaper.Core/CountingTrapChannel.cs @@ -0,0 +1,16 @@ +namespace Flypaper.Core; + +internal sealed class CountingTrapChannel(ITrapChannel inner) : ITrapChannel +{ + private long _bytesSent; + + public TrapSession Session => inner.Session; + + public long BytesSent => Interlocked.Read(ref _bytesSent); + + public async ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken ct) + { + await inner.WriteAsync(data, ct); + Interlocked.Add(ref _bytesSent, data.Length); + } +} diff --git a/src/Flypaper.Core/Flypaper.Core.csproj b/src/Flypaper.Core/Flypaper.Core.csproj new file mode 100644 index 0000000..937e5ee --- /dev/null +++ b/src/Flypaper.Core/Flypaper.Core.csproj @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/Flypaper.Core/FlypaperOptions.cs b/src/Flypaper.Core/FlypaperOptions.cs new file mode 100644 index 0000000..9673b79 --- /dev/null +++ b/src/Flypaper.Core/FlypaperOptions.cs @@ -0,0 +1,12 @@ +namespace Flypaper.Core; + +public sealed class FlypaperOptions +{ + public const string SectionName = "Flypaper"; + + public int MaxConnections { get; set; } = 1000; + + public int MaxConnectionsPerIp { get; set; } = 10; + + public TimeSpan MaxHoldDuration { get; set; } = TimeSpan.FromHours(1); +} diff --git a/src/Flypaper.Core/IConnectionGovernor.cs b/src/Flypaper.Core/IConnectionGovernor.cs new file mode 100644 index 0000000..3d3d254 --- /dev/null +++ b/src/Flypaper.Core/IConnectionGovernor.cs @@ -0,0 +1,8 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Flypaper.Core; + +public interface IConnectionGovernor +{ + bool TryAcquire(TrapSession session, [NotNullWhen(true)] out IDisposable? lease); +} diff --git a/src/Flypaper.Core/ITarpitStrategy.cs b/src/Flypaper.Core/ITarpitStrategy.cs new file mode 100644 index 0000000..a5dd7b0 --- /dev/null +++ b/src/Flypaper.Core/ITarpitStrategy.cs @@ -0,0 +1,10 @@ +namespace Flypaper.Core; + +public interface ITarpitStrategy +{ + string Name { get; } + + bool Supports(TrapProtocol protocol); + + Task RunAsync(ITrapChannel channel, CancellationToken ct); +} diff --git a/src/Flypaper.Core/ITrapChannel.cs b/src/Flypaper.Core/ITrapChannel.cs new file mode 100644 index 0000000..2262e99 --- /dev/null +++ b/src/Flypaper.Core/ITrapChannel.cs @@ -0,0 +1,8 @@ +namespace Flypaper.Core; + +public interface ITrapChannel +{ + TrapSession Session { get; } + + ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken ct); +} diff --git a/src/Flypaper.Core/ITrapEventSink.cs b/src/Flypaper.Core/ITrapEventSink.cs new file mode 100644 index 0000000..ecaa48c --- /dev/null +++ b/src/Flypaper.Core/ITrapEventSink.cs @@ -0,0 +1,6 @@ +namespace Flypaper.Core; + +public interface ITrapEventSink +{ + void Publish(TrapEvent trapEvent); +} diff --git a/src/Flypaper.Core/ServiceCollectionExtensions.cs b/src/Flypaper.Core/ServiceCollectionExtensions.cs new file mode 100644 index 0000000..d16f46a --- /dev/null +++ b/src/Flypaper.Core/ServiceCollectionExtensions.cs @@ -0,0 +1,22 @@ +using Flypaper.Core.Strategies; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace Flypaper.Core; + +public static class ServiceCollectionExtensions +{ + public static IServiceCollection AddFlypaperCore(this IServiceCollection services, IConfiguration configuration) + { + services.Configure(configuration.GetSection(FlypaperOptions.SectionName)); + services.Configure(configuration.GetSection(DripOptions.SectionName)); + + services.TryAddSingleton(TimeProvider.System); + services.TryAddSingleton(); + services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.TryAddSingleton(); + + return services; + } +} diff --git a/src/Flypaper.Core/Strategies/DripOptions.cs b/src/Flypaper.Core/Strategies/DripOptions.cs new file mode 100644 index 0000000..62dd692 --- /dev/null +++ b/src/Flypaper.Core/Strategies/DripOptions.cs @@ -0,0 +1,8 @@ +namespace Flypaper.Core.Strategies; + +public sealed class DripOptions +{ + public const string SectionName = "Flypaper:Drip"; + + public TimeSpan Interval { get; set; } = TimeSpan.FromSeconds(10); +} diff --git a/src/Flypaper.Core/Strategies/DripStrategy.cs b/src/Flypaper.Core/Strategies/DripStrategy.cs new file mode 100644 index 0000000..3dd650d --- /dev/null +++ b/src/Flypaper.Core/Strategies/DripStrategy.cs @@ -0,0 +1,24 @@ +using Microsoft.Extensions.Options; + +namespace Flypaper.Core.Strategies; + +public sealed class DripStrategy(IOptions options, TimeProvider timeProvider) : ITarpitStrategy +{ + private static readonly byte[] Alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"u8.ToArray(); + + public string Name => "drip"; + + public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http; + + public async Task RunAsync(ITrapChannel channel, CancellationToken ct) + { + var buffer = new byte[1]; + while (true) + { + ct.ThrowIfCancellationRequested(); + buffer[0] = Alphabet[Random.Shared.Next(Alphabet.Length)]; + await channel.WriteAsync(buffer, ct); + await Task.Delay(options.Value.Interval, timeProvider, ct); + } + } +} diff --git a/src/Flypaper.Core/TrapContext.cs b/src/Flypaper.Core/TrapContext.cs new file mode 100644 index 0000000..ad08e12 --- /dev/null +++ b/src/Flypaper.Core/TrapContext.cs @@ -0,0 +1,3 @@ +namespace Flypaper.Core; + +public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null); diff --git a/src/Flypaper.Core/TrapEvent.cs b/src/Flypaper.Core/TrapEvent.cs new file mode 100644 index 0000000..f1f9a34 --- /dev/null +++ b/src/Flypaper.Core/TrapEvent.cs @@ -0,0 +1,18 @@ +using System.Net; + +namespace Flypaper.Core; + +public sealed record TrapEvent( + Guid SessionId, + TrapProtocol Protocol, + IPAddress RemoteIp, + string Strategy, + DateTimeOffset StartedAt, + DateTimeOffset EndedAt, + long BytesSent, + TrapOutcome Outcome, + string? Target = null, + string? ClientInfo = null) +{ + public TimeSpan Duration => EndedAt - StartedAt; +} diff --git a/src/Flypaper.Core/TrapOutcome.cs b/src/Flypaper.Core/TrapOutcome.cs new file mode 100644 index 0000000..fc8418a --- /dev/null +++ b/src/Flypaper.Core/TrapOutcome.cs @@ -0,0 +1,9 @@ +namespace Flypaper.Core; + +public enum TrapOutcome +{ + ClientAborted, + Timeout, + Rejected, + Completed +} diff --git a/src/Flypaper.Core/TrapProtocol.cs b/src/Flypaper.Core/TrapProtocol.cs new file mode 100644 index 0000000..f0da43a --- /dev/null +++ b/src/Flypaper.Core/TrapProtocol.cs @@ -0,0 +1,7 @@ +namespace Flypaper.Core; + +public enum TrapProtocol +{ + Http, + Ssh +} diff --git a/src/Flypaper.Core/TrapRunner.cs b/src/Flypaper.Core/TrapRunner.cs new file mode 100644 index 0000000..db621aa --- /dev/null +++ b/src/Flypaper.Core/TrapRunner.cs @@ -0,0 +1,67 @@ +using Microsoft.Extensions.Options; + +namespace Flypaper.Core; + +public sealed class TrapRunner( + IConnectionGovernor governor, + IEnumerable strategies, + ITrapEventSink sink, + IOptions options, + TimeProvider timeProvider) +{ + public async Task RunAsync( + TrapContext context, + Func> openChannel, + CancellationToken ct) + { + var session = context.Session; + var strategy = strategies.FirstOrDefault(s => s.Supports(session.Protocol)); + + if (strategy is null || !governor.TryAcquire(session, out var lease)) + { + Publish(context, strategy?.Name ?? "none", 0, TrapOutcome.Rejected); + return TrapOutcome.Rejected; + } + + using var _ = lease; + using var hold = new CancellationTokenSource(options.Value.MaxHoldDuration, timeProvider); + using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, hold.Token); + + CountingTrapChannel? channel = null; + var outcome = TrapOutcome.Completed; + try + { + channel = new CountingTrapChannel(await openChannel(linked.Token)); + await strategy.RunAsync(channel, linked.Token); + } + catch (OperationCanceledException) when (linked.IsCancellationRequested) + { + outcome = hold.IsCancellationRequested && !ct.IsCancellationRequested + ? TrapOutcome.Timeout + : TrapOutcome.ClientAborted; + } + catch (IOException) + { + outcome = TrapOutcome.ClientAborted; + } + + Publish(context, strategy.Name, channel?.BytesSent ?? 0, outcome); + return outcome; + } + + private void Publish(TrapContext context, string strategy, long bytesSent, TrapOutcome outcome) + { + var session = context.Session; + sink.Publish(new TrapEvent( + session.Id, + session.Protocol, + session.RemoteIp, + strategy, + session.StartedAt, + timeProvider.GetUtcNow(), + bytesSent, + outcome, + context.Target, + context.ClientInfo)); + } +} diff --git a/src/Flypaper.Core/TrapSession.cs b/src/Flypaper.Core/TrapSession.cs new file mode 100644 index 0000000..d08892d --- /dev/null +++ b/src/Flypaper.Core/TrapSession.cs @@ -0,0 +1,5 @@ +using System.Net; + +namespace Flypaper.Core; + +public sealed record TrapSession(Guid Id, TrapProtocol Protocol, IPAddress RemoteIp, DateTimeOffset StartedAt); diff --git a/src/Flypaper.Http/Flypaper.Http.csproj b/src/Flypaper.Http/Flypaper.Http.csproj new file mode 100644 index 0000000..7a11c47 --- /dev/null +++ b/src/Flypaper.Http/Flypaper.Http.csproj @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/src/Flypaper.Http/FlypaperHttpExtensions.cs b/src/Flypaper.Http/FlypaperHttpExtensions.cs new file mode 100644 index 0000000..0cf5184 --- /dev/null +++ b/src/Flypaper.Http/FlypaperHttpExtensions.cs @@ -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(configuration.GetSection(HttpTrapOptions.SectionName)); + services.TryAddSingleton(); + + services.AddOptions() + .Configure>((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(); + app.UseMiddleware(); + return app; + } + + private static int HostBits(string address) => + IPAddress.Parse(address).AddressFamily == AddressFamily.InterNetworkV6 ? 128 : 32; +} diff --git a/src/Flypaper.Http/FlypaperMiddleware.cs b/src/Flypaper.Http/FlypaperMiddleware.cs new file mode 100644 index 0000000..813e1f8 --- /dev/null +++ b/src/Flypaper.Http/FlypaperMiddleware.cs @@ -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 OpenChannelAsync( + HttpContext context, + TrapSession session, + CancellationToken ct) + { + var minDataRate = context.Features.Get(); + if (minDataRate is not null) + { + minDataRate.MinDataRate = null; + } + + context.Features.Get()?.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); + } +} diff --git a/src/Flypaper.Http/HttpTrapChannel.cs b/src/Flypaper.Http/HttpTrapChannel.cs new file mode 100644 index 0000000..1c481fd --- /dev/null +++ b/src/Flypaper.Http/HttpTrapChannel.cs @@ -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 data, CancellationToken ct) + { + await response.Body.WriteAsync(data, ct); + await response.Body.FlushAsync(ct); + } +} diff --git a/src/Flypaper.Http/HttpTrapOptions.cs b/src/Flypaper.Http/HttpTrapOptions.cs new file mode 100644 index 0000000..9f7554b --- /dev/null +++ b/src/Flypaper.Http/HttpTrapOptions.cs @@ -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; } = []; +} diff --git a/src/Flypaper.Http/RealIpMiddleware.cs b/src/Flypaper.Http/RealIpMiddleware.cs new file mode 100644 index 0000000..e69b97c --- /dev/null +++ b/src/Flypaper.Http/RealIpMiddleware.cs @@ -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 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)); + } +} diff --git a/src/Flypaper.Http/TrapMatch.cs b/src/Flypaper.Http/TrapMatch.cs new file mode 100644 index 0000000..65044b3 --- /dev/null +++ b/src/Flypaper.Http/TrapMatch.cs @@ -0,0 +1,8 @@ +namespace Flypaper.Http; + +public enum TrapMatch +{ + None, + UnknownHost, + TrapPath +} diff --git a/src/Flypaper.Http/TrapMatcher.cs b/src/Flypaper.Http/TrapMatcher.cs new file mode 100644 index 0000000..dc95e78 --- /dev/null +++ b/src/Flypaper.Http/TrapMatcher.cs @@ -0,0 +1,59 @@ +using Microsoft.Extensions.Options; + +namespace Flypaper.Http; + +public sealed class TrapMatcher +{ + private readonly HashSet _hosts = new(StringComparer.OrdinalIgnoreCase); + private readonly List _hostSuffixes = []; + private readonly HashSet _paths = new(StringComparer.OrdinalIgnoreCase); + private readonly List _pathPrefixes = []; + + public TrapMatcher(IOptions 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; +} diff --git a/src/Flypaper.Storage/ChannelTrapEventSink.cs b/src/Flypaper.Storage/ChannelTrapEventSink.cs new file mode 100644 index 0000000..eb9e4e7 --- /dev/null +++ b/src/Flypaper.Storage/ChannelTrapEventSink.cs @@ -0,0 +1,20 @@ +using System.Threading.Channels; +using Flypaper.Core; + +namespace Flypaper.Storage; + +public sealed class ChannelTrapEventSink : ITrapEventSink +{ + private const int Capacity = 10_000; + + private readonly Channel _channel = Channel.CreateBounded( + new BoundedChannelOptions(Capacity) + { + FullMode = BoundedChannelFullMode.DropOldest, + SingleReader = true + }); + + public ChannelReader Reader => _channel.Reader; + + public void Publish(TrapEvent trapEvent) => _channel.Writer.TryWrite(trapEvent); +} diff --git a/src/Flypaper.Storage/Flypaper.Storage.csproj b/src/Flypaper.Storage/Flypaper.Storage.csproj new file mode 100644 index 0000000..21647ea --- /dev/null +++ b/src/Flypaper.Storage/Flypaper.Storage.csproj @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/Flypaper.Storage/FlypaperDbContext.cs b/src/Flypaper.Storage/FlypaperDbContext.cs new file mode 100644 index 0000000..9c31a60 --- /dev/null +++ b/src/Flypaper.Storage/FlypaperDbContext.cs @@ -0,0 +1,23 @@ +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage; + +public sealed class FlypaperDbContext(DbContextOptions options) : DbContext(options) +{ + internal const int MaxTextLength = 2048; + + public DbSet TrapEvents => Set(); + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + var trapEvent = modelBuilder.Entity(); + trapEvent.Property(e => e.Protocol).HasConversion().HasMaxLength(16); + trapEvent.Property(e => e.Outcome).HasConversion().HasMaxLength(16); + trapEvent.Property(e => e.RemoteIp).HasMaxLength(64); + trapEvent.Property(e => e.Strategy).HasMaxLength(64); + trapEvent.Property(e => e.Target).HasMaxLength(MaxTextLength); + trapEvent.Property(e => e.ClientInfo).HasMaxLength(MaxTextLength); + trapEvent.HasIndex(e => e.StartedAt); + trapEvent.HasIndex(e => e.RemoteIp); + } +} diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs new file mode 100644 index 0000000..c227a7b --- /dev/null +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -0,0 +1,17 @@ +using Flypaper.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; + +namespace Flypaper.Storage; + +public static class FlypaperStorageExtensions +{ + public static IServiceCollection AddFlypaperStorage(this IServiceCollection services, string connectionString) + { + services.AddDbContextFactory(options => options.UseSqlite(connectionString)); + services.AddSingleton(); + services.AddSingleton(sp => sp.GetRequiredService()); + services.AddHostedService(); + return services; + } +} diff --git a/src/Flypaper.Storage/TrapEventEntity.cs b/src/Flypaper.Storage/TrapEventEntity.cs new file mode 100644 index 0000000..70bc75b --- /dev/null +++ b/src/Flypaper.Storage/TrapEventEntity.cs @@ -0,0 +1,48 @@ +using Flypaper.Core; + +namespace Flypaper.Storage; + +public sealed class TrapEventEntity +{ + public long Id { get; set; } + + public Guid SessionId { get; set; } + + public TrapProtocol Protocol { get; set; } + + public required string RemoteIp { get; set; } + + public required string Strategy { get; set; } + + public DateTime StartedAt { get; set; } + + public DateTime EndedAt { get; set; } + + public long DurationMs { get; set; } + + public long BytesSent { get; set; } + + public TrapOutcome Outcome { get; set; } + + public string? Target { get; set; } + + public string? ClientInfo { get; set; } + + public static TrapEventEntity From(TrapEvent trapEvent) => new() + { + SessionId = trapEvent.SessionId, + Protocol = trapEvent.Protocol, + RemoteIp = trapEvent.RemoteIp.ToString(), + Strategy = trapEvent.Strategy, + StartedAt = trapEvent.StartedAt.UtcDateTime, + EndedAt = trapEvent.EndedAt.UtcDateTime, + DurationMs = (long)trapEvent.Duration.TotalMilliseconds, + BytesSent = trapEvent.BytesSent, + Outcome = trapEvent.Outcome, + Target = Truncate(trapEvent.Target, FlypaperDbContext.MaxTextLength), + ClientInfo = Truncate(trapEvent.ClientInfo, FlypaperDbContext.MaxTextLength) + }; + + private static string? Truncate(string? value, int maxLength) => + value is { Length: > 0 } && value.Length > maxLength ? value[..maxLength] : value; +} diff --git a/src/Flypaper.Storage/TrapEventWriter.cs b/src/Flypaper.Storage/TrapEventWriter.cs new file mode 100644 index 0000000..a2317ef --- /dev/null +++ b/src/Flypaper.Storage/TrapEventWriter.cs @@ -0,0 +1,44 @@ +using Flypaper.Core; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; + +namespace Flypaper.Storage; + +internal sealed class TrapEventWriter( + ChannelTrapEventSink sink, + IDbContextFactory dbContextFactory, + ILogger logger) : BackgroundService +{ + private const int MaxBatchSize = 100; + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + await using (var db = await dbContextFactory.CreateDbContextAsync(stoppingToken)) + { + await db.Database.EnsureCreatedAsync(stoppingToken); + } + + var batch = new List(MaxBatchSize); + while (await sink.Reader.WaitToReadAsync(stoppingToken)) + { + while (batch.Count < MaxBatchSize && sink.Reader.TryRead(out var trapEvent)) + { + batch.Add(trapEvent); + } + + try + { + await using var db = await dbContextFactory.CreateDbContextAsync(stoppingToken); + db.TrapEvents.AddRange(batch.Select(TrapEventEntity.From)); + await db.SaveChangesAsync(stoppingToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + logger.LogError(ex, "Failed to persist {Count} trap events", batch.Count); + } + + batch.Clear(); + } + } +} diff --git a/src/Flypaper.Web/Components/App.razor b/src/Flypaper.Web/Components/App.razor new file mode 100644 index 0000000..ce1943c --- /dev/null +++ b/src/Flypaper.Web/Components/App.razor @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor b/src/Flypaper.Web/Components/Layout/MainLayout.razor new file mode 100644 index 0000000..e1a9a75 --- /dev/null +++ b/src/Flypaper.Web/Components/Layout/MainLayout.razor @@ -0,0 +1,3 @@ +@inherits LayoutComponentBase + +@Body diff --git a/src/Flypaper.Web/Components/Layout/MainLayout.razor.css b/src/Flypaper.Web/Components/Layout/MainLayout.razor.css new file mode 100644 index 0000000..60cec92 --- /dev/null +++ b/src/Flypaper.Web/Components/Layout/MainLayout.razor.css @@ -0,0 +1,20 @@ +#blazor-error-ui { + color-scheme: light only; + background: lightyellow; + bottom: 0; + box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); + box-sizing: border-box; + display: none; + left: 0; + padding: 0.6rem 1.25rem 0.7rem 1.25rem; + position: fixed; + width: 100%; + z-index: 1000; +} + + #blazor-error-ui .dismiss { + cursor: pointer; + position: absolute; + right: 0.75rem; + top: 0.5rem; + } diff --git a/src/Flypaper.Web/Components/Pages/Error.razor b/src/Flypaper.Web/Components/Pages/Error.razor new file mode 100644 index 0000000..576cc2d --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Error.razor @@ -0,0 +1,36 @@ +@page "/Error" +@using System.Diagnostics + +Error + +

Error.

+

An error occurred while processing your request.

+ +@if (ShowRequestId) +{ +

+ Request ID: @RequestId +

+} + +

Development Mode

+

+ Swapping to Development environment will display more detailed information about the error that occurred. +

+

+ The Development environment shouldn't be enabled for deployed applications. + It can result in displaying sensitive information from exceptions to end users. + For local debugging, enable the Development environment by setting the ASPNETCORE_ENVIRONMENT environment variable to Development + and restarting the app. +

+ +@code{ + [CascadingParameter] + private HttpContext? HttpContext { get; set; } + + private string? RequestId { get; set; } + private bool ShowRequestId => !string.IsNullOrEmpty(RequestId); + + protected override void OnInitialized() => + RequestId = Activity.Current?.Id ?? HttpContext?.TraceIdentifier; +} diff --git a/src/Flypaper.Web/Components/Pages/Home.razor b/src/Flypaper.Web/Components/Pages/Home.razor new file mode 100644 index 0000000..2bbee2a --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Home.razor @@ -0,0 +1,7 @@ +@page "/" + +Flypaper + +

Flypaper

+ +

Dashboard folgt.

diff --git a/src/Flypaper.Web/Components/Pages/NotFound.razor b/src/Flypaper.Web/Components/Pages/NotFound.razor new file mode 100644 index 0000000..917ada1 --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/NotFound.razor @@ -0,0 +1,5 @@ +@page "/not-found" +@layout MainLayout + +

Not Found

+

Sorry, the content you are looking for does not exist.

\ No newline at end of file diff --git a/src/Flypaper.Web/Components/Routes.razor b/src/Flypaper.Web/Components/Routes.razor new file mode 100644 index 0000000..105855d --- /dev/null +++ b/src/Flypaper.Web/Components/Routes.razor @@ -0,0 +1,6 @@ + + + + + + diff --git a/src/Flypaper.Web/Components/_Imports.razor b/src/Flypaper.Web/Components/_Imports.razor new file mode 100644 index 0000000..3a3a828 --- /dev/null +++ b/src/Flypaper.Web/Components/_Imports.razor @@ -0,0 +1,11 @@ +@using System.Net.Http +@using System.Net.Http.Json +@using Microsoft.AspNetCore.Components.Forms +@using Microsoft.AspNetCore.Components.Routing +@using Microsoft.AspNetCore.Components.Web +@using static Microsoft.AspNetCore.Components.Web.RenderMode +@using Microsoft.AspNetCore.Components.Web.Virtualization +@using Microsoft.JSInterop +@using Flypaper.Web +@using Flypaper.Web.Components +@using Flypaper.Web.Components.Layout diff --git a/src/Flypaper.Web/Flypaper.Web.csproj b/src/Flypaper.Web/Flypaper.Web.csproj new file mode 100644 index 0000000..680b0db --- /dev/null +++ b/src/Flypaper.Web/Flypaper.Web.csproj @@ -0,0 +1,12 @@ + + + + true + + + + + + + + diff --git a/src/Flypaper.Web/Program.cs b/src/Flypaper.Web/Program.cs new file mode 100644 index 0000000..c7c4189 --- /dev/null +++ b/src/Flypaper.Web/Program.cs @@ -0,0 +1,30 @@ +using Flypaper.Core; +using Flypaper.Http; +using Flypaper.Storage; +using Flypaper.Web.Components; + +var builder = WebApplication.CreateBuilder(args); + +builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false); + +builder.Services.AddRazorComponents(); +builder.Services.AddFlypaperCore(builder.Configuration); +builder.Services.AddFlypaperHttp(builder.Configuration); +builder.Services.AddFlypaperStorage(builder.Configuration.GetConnectionString("Flypaper") ?? "Data Source=flypaper.db"); + +var app = builder.Build(); + +app.UseFlypaper(); + +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Error", createScopeForErrors: true); +} +app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true); + +app.UseAntiforgery(); + +app.MapStaticAssets(); +app.MapRazorComponents(); + +app.Run(); diff --git a/src/Flypaper.Web/Properties/launchSettings.json b/src/Flypaper.Web/Properties/launchSettings.json new file mode 100644 index 0000000..6ddff38 --- /dev/null +++ b/src/Flypaper.Web/Properties/launchSettings.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://localhost:5248", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://localhost:7142;http://localhost:5248", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } + } diff --git a/src/Flypaper.Web/appsettings.Development.json b/src/Flypaper.Web/appsettings.Development.json new file mode 100644 index 0000000..5d3801e --- /dev/null +++ b/src/Flypaper.Web/appsettings.Development.json @@ -0,0 +1,16 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "Flypaper": { + "Drip": { + "Interval": "00:00:01" + }, + "Http": { + "KnownHosts": [ "localhost" ] + } + } +} diff --git a/src/Flypaper.Web/appsettings.json b/src/Flypaper.Web/appsettings.json new file mode 100644 index 0000000..2bb83b4 --- /dev/null +++ b/src/Flypaper.Web/appsettings.json @@ -0,0 +1,40 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*", + "ConnectionStrings": { + "Flypaper": "Data Source=flypaper.db" + }, + "Flypaper": { + "MaxConnections": 1000, + "MaxConnectionsPerIp": 10, + "MaxHoldDuration": "01:00:00", + "Drip": { + "Interval": "00:00:10" + }, + "Http": { + "KnownHosts": [], + "TrustedProxies": [], + "TrapPaths": [ + "/.env", + "/.env.*", + "/.git/*", + "/.aws/*", + "/.DS_Store", + "/wp-login.php", + "/wp-admin/*", + "/xmlrpc.php", + "/phpmyadmin/*", + "/vendor/phpunit/*", + "/server-status", + "/actuator/*", + "/cgi-bin/*", + "/boaform/*" + ] + } + } +} diff --git a/src/Flypaper.Web/wwwroot/app.css b/src/Flypaper.Web/wwwroot/app.css new file mode 100644 index 0000000..5388357 --- /dev/null +++ b/src/Flypaper.Web/wwwroot/app.css @@ -0,0 +1,38 @@ +h1:focus { + outline: none; +} + +.valid.modified:not([type=checkbox]) { + outline: 1px solid #26b050; +} + +.invalid { + outline: 1px solid #e50000; +} + +.validation-message { + color: #e50000; +} + +.blazor-error-boundary { + background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; + padding: 1rem 1rem 1rem 3.7rem; + color: white; +} + + .blazor-error-boundary::after { + content: "An error has occurred." + } + +.darker-border-checkbox.form-check-input { + border-color: #929292; +} + +.form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder { + color: var(--bs-secondary-color); + text-align: end; +} + +.form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder { + text-align: start; +} \ No newline at end of file diff --git a/test/Flypaper.Tests/ConnectionGovernorTests.cs b/test/Flypaper.Tests/ConnectionGovernorTests.cs new file mode 100644 index 0000000..8a035d3 --- /dev/null +++ b/test/Flypaper.Tests/ConnectionGovernorTests.cs @@ -0,0 +1,76 @@ +using System.Net; +using Flypaper.Core; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace Flypaper.Tests; + +public sealed class ConnectionGovernorTests +{ + private static readonly IPAddress IpA = IPAddress.Parse("203.0.113.1"); + private static readonly IPAddress IpB = IPAddress.Parse("203.0.113.2"); + + [Fact] + public void Rejects_when_per_ip_limit_reached() + { + var governor = CreateGovernor(maxConnections: 10, maxPerIp: 2); + + governor.TryAcquire(Session(IpA), out _).ShouldBeTrue(); + governor.TryAcquire(Session(IpA), out _).ShouldBeTrue(); + governor.TryAcquire(Session(IpA), out var lease).ShouldBeFalse(); + lease.ShouldBeNull(); + + governor.TryAcquire(Session(IpB), out _).ShouldBeTrue(); + } + + [Fact] + public void Rejects_when_total_limit_reached() + { + var governor = CreateGovernor(maxConnections: 2, maxPerIp: 10); + + governor.TryAcquire(Session(IpA), out _).ShouldBeTrue(); + governor.TryAcquire(Session(IpB), out _).ShouldBeTrue(); + governor.TryAcquire(Session(IPAddress.Parse("203.0.113.3")), out _).ShouldBeFalse(); + } + + [Fact] + public void Disposing_lease_frees_slot() + { + var governor = CreateGovernor(maxConnections: 1, maxPerIp: 1); + + governor.TryAcquire(Session(IpA), out var lease).ShouldBeTrue(); + governor.TryAcquire(Session(IpA), out _).ShouldBeFalse(); + + lease.Dispose(); + + governor.ActiveConnections.ShouldBe(0); + governor.TryAcquire(Session(IpA), out _).ShouldBeTrue(); + } + + [Fact] + public void Disposing_lease_twice_releases_once() + { + var governor = CreateGovernor(maxConnections: 10, maxPerIp: 10); + governor.TryAcquire(Session(IpA), out var first).ShouldBeTrue(); + governor.TryAcquire(Session(IpA), out _).ShouldBeTrue(); + + first.Dispose(); + first.Dispose(); + + governor.ActiveConnections.ShouldBe(1); + } + + [Fact] + public void Treats_ipv4_mapped_ipv6_as_same_ip() + { + var governor = CreateGovernor(maxConnections: 10, maxPerIp: 1); + + governor.TryAcquire(Session(IpA), out _).ShouldBeTrue(); + governor.TryAcquire(Session(IpA.MapToIPv6()), out _).ShouldBeFalse(); + } + + private static ConnectionGovernor CreateGovernor(int maxConnections, int maxPerIp) => + new(Options.Create(new FlypaperOptions { MaxConnections = maxConnections, MaxConnectionsPerIp = maxPerIp })); + + private static TrapSession Session(IPAddress ip) => new(Guid.NewGuid(), TrapProtocol.Http, ip, DateTimeOffset.UtcNow); +} diff --git a/test/Flypaper.Tests/DripStrategyTests.cs b/test/Flypaper.Tests/DripStrategyTests.cs new file mode 100644 index 0000000..ffa4209 --- /dev/null +++ b/test/Flypaper.Tests/DripStrategyTests.cs @@ -0,0 +1,43 @@ +using Flypaper.Core; +using Flypaper.Core.Strategies; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace Flypaper.Tests; + +public sealed class DripStrategyTests +{ + [Fact] + public async Task Drips_single_bytes_until_cancelled() + { + var strategy = CreateStrategy(TimeSpan.FromMilliseconds(20)); + var channel = new FakeTrapChannel(); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); + + await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token)); + + channel.Writes.Count.ShouldBeInRange(3, 20); + channel.Writes.ShouldAllBe(write => write.Length == 1); + } + + [Fact] + public async Task Writes_first_byte_immediately() + { + var strategy = CreateStrategy(TimeSpan.FromMinutes(1)); + var channel = new FakeTrapChannel(); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + + await Should.ThrowAsync(() => strategy.RunAsync(channel, cts.Token)); + + channel.Writes.Count.ShouldBe(1); + } + + [Theory] + [InlineData(TrapProtocol.Http, true)] + [InlineData(TrapProtocol.Ssh, false)] + public void Supports_only_http(TrapProtocol protocol, bool expected) => + CreateStrategy(TimeSpan.FromSeconds(1)).Supports(protocol).ShouldBe(expected); + + private static DripStrategy CreateStrategy(TimeSpan interval) => + new(Options.Create(new DripOptions { Interval = interval }), TimeProvider.System); +} diff --git a/test/Flypaper.Tests/FakeTrapChannel.cs b/test/Flypaper.Tests/FakeTrapChannel.cs new file mode 100644 index 0000000..7d50060 --- /dev/null +++ b/test/Flypaper.Tests/FakeTrapChannel.cs @@ -0,0 +1,19 @@ +using System.Collections.Concurrent; +using System.Net; +using Flypaper.Core; + +namespace Flypaper.Tests; + +internal sealed class FakeTrapChannel : ITrapChannel +{ + public TrapSession Session { get; } = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Loopback, DateTimeOffset.UtcNow); + + public ConcurrentQueue Writes { get; } = new(); + + public ValueTask WriteAsync(ReadOnlyMemory data, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + Writes.Enqueue(data.ToArray()); + return ValueTask.CompletedTask; + } +} diff --git a/test/Flypaper.Tests/Flypaper.Tests.csproj b/test/Flypaper.Tests/Flypaper.Tests.csproj new file mode 100644 index 0000000..06e2909 --- /dev/null +++ b/test/Flypaper.Tests/Flypaper.Tests.csproj @@ -0,0 +1,25 @@ + + + + false + + + + + + + + + + + + + + + + + + + + + diff --git a/test/Flypaper.Tests/TrapMatcherTests.cs b/test/Flypaper.Tests/TrapMatcherTests.cs new file mode 100644 index 0000000..bb873d1 --- /dev/null +++ b/test/Flypaper.Tests/TrapMatcherTests.cs @@ -0,0 +1,41 @@ +using Flypaper.Http; +using Microsoft.Extensions.Options; +using Shouldly; + +namespace Flypaper.Tests; + +public sealed class TrapMatcherTests +{ + private readonly TrapMatcher _matcher = new(Options.Create(new HttpTrapOptions + { + KnownHosts = ["example.com", "*.example.org"], + TrapPaths = ["/.env", "/.git/*", "/wp-login.php"] + })); + + [Theory] + [InlineData("example.com", "/")] + [InlineData("EXAMPLE.com", "/index.html")] + [InlineData("app.example.org", "/api/items")] + [InlineData("example.com", "/.envelope")] + [InlineData("example.com", "/.git")] + public void Lets_normal_requests_pass(string host, string path) => + _matcher.Match(host, path).ShouldBe(TrapMatch.None); + + [Theory] + [InlineData("example.com", "/.env")] + [InlineData("example.com", "/.ENV")] + [InlineData("example.com", "/.env/")] + [InlineData("example.com", "/.git/config")] + [InlineData("app.example.org", "/wp-login.php")] + public void Traps_configured_paths(string host, string path) => + _matcher.Match(host, path).ShouldBe(TrapMatch.TrapPath); + + [Theory] + [InlineData("unknown.net", "/")] + [InlineData("203.0.113.7", "/")] + [InlineData("example.org", "/")] + [InlineData("", "/")] + [InlineData(null, "/")] + public void Traps_unknown_hosts(string? host, string path) => + _matcher.Match(host, path).ShouldBe(TrapMatch.UnknownHost); +} diff --git a/test/Flypaper.Tests/TrapRunnerTests.cs b/test/Flypaper.Tests/TrapRunnerTests.cs new file mode 100644 index 0000000..97230e1 --- /dev/null +++ b/test/Flypaper.Tests/TrapRunnerTests.cs @@ -0,0 +1,88 @@ +using System.Net; +using Flypaper.Core; +using Flypaper.Core.Strategies; +using Microsoft.Extensions.Options; +using NSubstitute; +using Shouldly; + +namespace Flypaper.Tests; + +public sealed class TrapRunnerTests +{ + private readonly IConnectionGovernor _governor = Substitute.For(); + private readonly ITrapEventSink _sink = Substitute.For(); + private readonly FakeTrapChannel _channel = new(); + + [Fact] + public async Task Rejects_without_opening_channel_when_governor_is_full() + { + _governor.TryAcquire(Arg.Any(), out Arg.Any()).Returns(false); + var opened = false; + + var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync( + Context(), + _ => + { + opened = true; + return ValueTask.FromResult(_channel); + }, + CancellationToken.None); + + outcome.ShouldBe(TrapOutcome.Rejected); + opened.ShouldBeFalse(); + _sink.Received(1).Publish(Arg.Is(e => e.Outcome == TrapOutcome.Rejected && e.BytesSent == 0)); + } + + [Fact] + public async Task Times_out_after_max_hold_duration_and_releases_lease() + { + var lease = AllowAcquire(); + + var outcome = await CreateRunner(TimeSpan.FromMilliseconds(200)).RunAsync(Context(), Open, CancellationToken.None); + + outcome.ShouldBe(TrapOutcome.Timeout); + lease.Received(1).Dispose(); + _sink.Received(1).Publish(Arg.Is(e => + e.Outcome == TrapOutcome.Timeout && e.BytesSent == _channel.Writes.Count && e.BytesSent > 0)); + } + + [Fact] + public async Task Reports_client_abort_when_caller_cancels() + { + AllowAcquire(); + using var cts = new CancellationTokenSource(TimeSpan.FromMilliseconds(100)); + + var outcome = await CreateRunner(TimeSpan.FromMinutes(1)).RunAsync(Context(), Open, cts.Token); + + outcome.ShouldBe(TrapOutcome.ClientAborted); + _sink.Received(1).Publish(Arg.Is(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "drip")); + } + + private IDisposable AllowAcquire() + { + var lease = Substitute.For(); + _governor.TryAcquire(Arg.Any(), out Arg.Any()) + .Returns(call => + { + call[1] = lease; + return true; + }); + return lease; + } + + private ValueTask Open(CancellationToken ct) => ValueTask.FromResult(_channel); + + private TrapRunner CreateRunner(TimeSpan maxHoldDuration) + { + var drip = new DripStrategy(Options.Create(new DripOptions { Interval = TimeSpan.FromMilliseconds(20) }), TimeProvider.System); + return new TrapRunner( + _governor, + [drip], + _sink, + Options.Create(new FlypaperOptions { MaxHoldDuration = maxHoldDuration }), + TimeProvider.System); + } + + private static TrapContext Context() => + new(new TrapSession(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow), "GET /.env"); +}