Add Flypaper solution skeleton with HTTP tarpit, SQLite event log and tests
This commit is contained in:
1 parent
20314268c6
commit
f9161f48e7
55 files changed
+1331
No files matched your search
@@ -400,3 +400,9 @@ FodyWeavers.xsd
|
|||||||
# JetBrains Rider
|
# JetBrains Rider
|
||||||
*.sln.iml
|
*.sln.iml
|
||||||
|
|
||||||
|
|
||||||
|
# Flypaper
|
||||||
|
*.db
|
||||||
|
*.db-shm
|
||||||
|
*.db-wal
|
||||||
|
.idea/
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
|
<CentralPackageTransitivePinningEnabled>true</CentralPackageTransitivePinningEnabled>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.15" />
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.Hosting.Abstractions" Version="10.0.15" />
|
||||||
|
<PackageVersion Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="10.0.15" />
|
||||||
|
<PackageVersion Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.15" />
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="coverlet.collector" Version="6.0.4" />
|
||||||
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
|
||||||
|
<PackageVersion Include="NSubstitute" Version="5.3.0" />
|
||||||
|
<PackageVersion Include="Shouldly" Version="4.3.0" />
|
||||||
|
<PackageVersion Include="xunit" Version="2.9.3" />
|
||||||
|
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.4" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<Solution>
|
||||||
|
<Folder Name="/src/">
|
||||||
|
<Project Path="src/Flypaper.Core/Flypaper.Core.csproj" />
|
||||||
|
<Project Path="src/Flypaper.Http/Flypaper.Http.csproj" />
|
||||||
|
<Project Path="src/Flypaper.Storage/Flypaper.Storage.csproj" />
|
||||||
|
<Project Path="src/Flypaper.Web/Flypaper.Web.csproj" />
|
||||||
|
</Folder>
|
||||||
|
<Folder Name="/test/">
|
||||||
|
<Project Path="test/Flypaper.Tests/Flypaper.Tests.csproj" />
|
||||||
|
</Folder>
|
||||||
|
</Solution>
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Net;
|
||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public sealed class ConnectionGovernor(IOptions<FlypaperOptions> options) : IConnectionGovernor
|
||||||
|
{
|
||||||
|
private readonly Lock _gate = new();
|
||||||
|
private readonly Dictionary<IPAddress, int> _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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<byte> data, CancellationToken ct)
|
||||||
|
{
|
||||||
|
await inner.WriteAsync(data, ct);
|
||||||
|
Interlocked.Add(ref _bytesSent, data.Length);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<InternalsVisibleTo Include="Flypaper.Tests" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
|
||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public interface IConnectionGovernor
|
||||||
|
{
|
||||||
|
bool TryAcquire(TrapSession session, [NotNullWhen(true)] out IDisposable? lease);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public interface ITarpitStrategy
|
||||||
|
{
|
||||||
|
string Name { get; }
|
||||||
|
|
||||||
|
bool Supports(TrapProtocol protocol);
|
||||||
|
|
||||||
|
Task RunAsync(ITrapChannel channel, CancellationToken ct);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public interface ITrapChannel
|
||||||
|
{
|
||||||
|
TrapSession Session { get; }
|
||||||
|
|
||||||
|
ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public interface ITrapEventSink
|
||||||
|
{
|
||||||
|
void Publish(TrapEvent trapEvent);
|
||||||
|
}
|
||||||
@@ -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<FlypaperOptions>(configuration.GetSection(FlypaperOptions.SectionName));
|
||||||
|
services.Configure<DripOptions>(configuration.GetSection(DripOptions.SectionName));
|
||||||
|
|
||||||
|
services.TryAddSingleton(TimeProvider.System);
|
||||||
|
services.TryAddSingleton<IConnectionGovernor, ConnectionGovernor>();
|
||||||
|
services.TryAddEnumerable(ServiceDescriptor.Singleton<ITarpitStrategy, DripStrategy>());
|
||||||
|
services.TryAddSingleton<TrapRunner>();
|
||||||
|
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Core.Strategies;
|
||||||
|
|
||||||
|
public sealed class DripStrategy(IOptions<DripOptions> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null);
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public enum TrapOutcome
|
||||||
|
{
|
||||||
|
ClientAborted,
|
||||||
|
Timeout,
|
||||||
|
Rejected,
|
||||||
|
Completed
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public enum TrapProtocol
|
||||||
|
{
|
||||||
|
Http,
|
||||||
|
Ssh
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
using Microsoft.Extensions.Options;
|
||||||
|
|
||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public sealed class TrapRunner(
|
||||||
|
IConnectionGovernor governor,
|
||||||
|
IEnumerable<ITarpitStrategy> strategies,
|
||||||
|
ITrapEventSink sink,
|
||||||
|
IOptions<FlypaperOptions> options,
|
||||||
|
TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
public async Task<TrapOutcome> RunAsync(
|
||||||
|
TrapContext context,
|
||||||
|
Func<CancellationToken, ValueTask<ITrapChannel>> 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
using System.Net;
|
||||||
|
|
||||||
|
namespace Flypaper.Core;
|
||||||
|
|
||||||
|
public sealed record TrapSession(Guid Id, TrapProtocol Protocol, IPAddress RemoteIp, DateTimeOffset StartedAt);
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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; } = [];
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
namespace Flypaper.Http;
|
||||||
|
|
||||||
|
public enum TrapMatch
|
||||||
|
{
|
||||||
|
None,
|
||||||
|
UnknownHost,
|
||||||
|
TrapPath
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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<TrapEvent> _channel = Channel.CreateBounded<TrapEvent>(
|
||||||
|
new BoundedChannelOptions(Capacity)
|
||||||
|
{
|
||||||
|
FullMode = BoundedChannelFullMode.DropOldest,
|
||||||
|
SingleReader = true
|
||||||
|
});
|
||||||
|
|
||||||
|
public ChannelReader<TrapEvent> Reader => _channel.Reader;
|
||||||
|
|
||||||
|
public void Publish(TrapEvent trapEvent) => _channel.Writer.TryWrite(trapEvent);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Flypaper.Core\Flypaper.Core.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
|
||||||
|
namespace Flypaper.Storage;
|
||||||
|
|
||||||
|
public sealed class FlypaperDbContext(DbContextOptions<FlypaperDbContext> options) : DbContext(options)
|
||||||
|
{
|
||||||
|
internal const int MaxTextLength = 2048;
|
||||||
|
|
||||||
|
public DbSet<TrapEventEntity> TrapEvents => Set<TrapEventEntity>();
|
||||||
|
|
||||||
|
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||||
|
{
|
||||||
|
var trapEvent = modelBuilder.Entity<TrapEventEntity>();
|
||||||
|
trapEvent.Property(e => e.Protocol).HasConversion<string>().HasMaxLength(16);
|
||||||
|
trapEvent.Property(e => e.Outcome).HasConversion<string>().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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<FlypaperDbContext>(options => options.UseSqlite(connectionString));
|
||||||
|
services.AddSingleton<ChannelTrapEventSink>();
|
||||||
|
services.AddSingleton<ITrapEventSink>(sp => sp.GetRequiredService<ChannelTrapEventSink>());
|
||||||
|
services.AddHostedService<TrapEventWriter>();
|
||||||
|
return services;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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<FlypaperDbContext> dbContextFactory,
|
||||||
|
ILogger<TrapEventWriter> 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<TrapEvent>(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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<base href="/" />
|
||||||
|
<ResourcePreloader />
|
||||||
|
<link rel="stylesheet" href="@Assets["app.css"]" />
|
||||||
|
<link rel="stylesheet" href="@Assets["Flypaper.Web.styles.css"]" />
|
||||||
|
<ImportMap />
|
||||||
|
<HeadOutlet />
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<Routes />
|
||||||
|
<script src="@Assets["_framework/blazor.web.js"]"></script>
|
||||||
|
</body>
|
||||||
|
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
@inherits LayoutComponentBase
|
||||||
|
|
||||||
|
@Body
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
@page "/Error"
|
||||||
|
@using System.Diagnostics
|
||||||
|
|
||||||
|
<PageTitle>Error</PageTitle>
|
||||||
|
|
||||||
|
<h1 class="text-danger">Error.</h1>
|
||||||
|
<h2 class="text-danger">An error occurred while processing your request.</h2>
|
||||||
|
|
||||||
|
@if (ShowRequestId)
|
||||||
|
{
|
||||||
|
<p>
|
||||||
|
<strong>Request ID:</strong> <code>@RequestId</code>
|
||||||
|
</p>
|
||||||
|
}
|
||||||
|
|
||||||
|
<h3>Development Mode</h3>
|
||||||
|
<p>
|
||||||
|
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
|
||||||
|
It can result in displaying sensitive information from exceptions to end users.
|
||||||
|
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
|
||||||
|
and restarting the app.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
@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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
@page "/"
|
||||||
|
|
||||||
|
<PageTitle>Flypaper</PageTitle>
|
||||||
|
|
||||||
|
<h1>Flypaper</h1>
|
||||||
|
|
||||||
|
<p>Dashboard folgt.</p>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
@page "/not-found"
|
||||||
|
@layout MainLayout
|
||||||
|
|
||||||
|
<h3>Not Found</h3>
|
||||||
|
<p>Sorry, the content you are looking for does not exist.</p>
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
<Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
|
||||||
|
<Found Context="routeData">
|
||||||
|
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
|
||||||
|
<FocusOnNavigate RouteData="routeData" Selector="h1" />
|
||||||
|
</Found>
|
||||||
|
</Router>
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\Flypaper.Http\Flypaper.Http.csproj" />
|
||||||
|
<ProjectReference Include="..\Flypaper.Storage\Flypaper.Storage.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -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>();
|
||||||
|
|
||||||
|
app.Run();
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
{
|
||||||
|
"Logging": {
|
||||||
|
"LogLevel": {
|
||||||
|
"Default": "Information",
|
||||||
|
"Microsoft.AspNetCore": "Warning"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"Flypaper": {
|
||||||
|
"Drip": {
|
||||||
|
"Interval": "00:00:01"
|
||||||
|
},
|
||||||
|
"Http": {
|
||||||
|
"KnownHosts": [ "localhost" ]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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/*"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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<OperationCanceledException>(() => 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<OperationCanceledException>(() => 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);
|
||||||
|
}
|
||||||
@@ -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<byte[]> Writes { get; } = new();
|
||||||
|
|
||||||
|
public ValueTask WriteAsync(ReadOnlyMemory<byte> data, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
Writes.Enqueue(data.ToArray());
|
||||||
|
return ValueTask.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="coverlet.collector" />
|
||||||
|
<PackageReference Include="Microsoft.NET.Test.Sdk" />
|
||||||
|
<PackageReference Include="NSubstitute" />
|
||||||
|
<PackageReference Include="Shouldly" />
|
||||||
|
<PackageReference Include="xunit" />
|
||||||
|
<PackageReference Include="xunit.runner.visualstudio" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\Flypaper.Http\Flypaper.Http.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\Flypaper.Storage\Flypaper.Storage.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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<IConnectionGovernor>();
|
||||||
|
private readonly ITrapEventSink _sink = Substitute.For<ITrapEventSink>();
|
||||||
|
private readonly FakeTrapChannel _channel = new();
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Rejects_without_opening_channel_when_governor_is_full()
|
||||||
|
{
|
||||||
|
_governor.TryAcquire(Arg.Any<TrapSession>(), out Arg.Any<IDisposable?>()).Returns(false);
|
||||||
|
var opened = false;
|
||||||
|
|
||||||
|
var outcome = await CreateRunner(TimeSpan.FromSeconds(1)).RunAsync(
|
||||||
|
Context(),
|
||||||
|
_ =>
|
||||||
|
{
|
||||||
|
opened = true;
|
||||||
|
return ValueTask.FromResult<ITrapChannel>(_channel);
|
||||||
|
},
|
||||||
|
CancellationToken.None);
|
||||||
|
|
||||||
|
outcome.ShouldBe(TrapOutcome.Rejected);
|
||||||
|
opened.ShouldBeFalse();
|
||||||
|
_sink.Received(1).Publish(Arg.Is<TrapEvent>(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<TrapEvent>(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<TrapEvent>(e => e.Outcome == TrapOutcome.ClientAborted && e.Strategy == "drip"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private IDisposable AllowAcquire()
|
||||||
|
{
|
||||||
|
var lease = Substitute.For<IDisposable>();
|
||||||
|
_governor.TryAcquire(Arg.Any<TrapSession>(), out Arg.Any<IDisposable?>())
|
||||||
|
.Returns(call =>
|
||||||
|
{
|
||||||
|
call[1] = lease;
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
return lease;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ValueTask<ITrapChannel> Open(CancellationToken ct) => ValueTask.FromResult<ITrapChannel>(_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");
|
||||||
|
}
|
||||||
Reference in new issue
Block a user