diff --git a/docs/configuration.md b/docs/configuration.md index fe2849c..58f694f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -26,6 +26,7 @@ All optional. Read at startup; list entries need an index (`__0`, `__1`, ...). | `Flypaper__Drip__HeadStartSize` | Bytes sent immediately before dripping starts (`0` = off) | `1024` | | `Flypaper__Drip__LinkSpacing` | Link labyrinth: bytes of text between two links in the HTML page (`0` = off, plain `html-drip`) | `160` | | `Flypaper__Drip__BaitPaths` | Comma-separated decoy paths listed in `robots.txt` (max. 8, empty = off); requests to them get `robots-bait` and are held for at least 24 h | `/backup-2024/,/admin-old/,/internal/db-export/,/old-site/` | +| `Flypaper__Drip__Lure` | First visit of an unknown IP to `/` or `/favicon.ico` gets an instant WordPress-looking page or icon (`lure-page`, `lure-icon`) and is not held; every later request is trapped as usual | `true` | | `Flypaper__Drip__MatchPath` | Pick content by request path (`/.env`, `*.json`, `*.xml`, `*.yml`, `*.sql`, `/.git/…`, `/SDK/…`, `/ISAPI/…`, `wp-login.php`) | `true` | | `TZ` | Time zone for the dashboard | UTC | diff --git a/src/Flypaper.Core/Abstractions/IKnownIpLookup.cs b/src/Flypaper.Core/Abstractions/IKnownIpLookup.cs new file mode 100644 index 0000000..4221414 --- /dev/null +++ b/src/Flypaper.Core/Abstractions/IKnownIpLookup.cs @@ -0,0 +1,8 @@ +using System.Net; + +namespace Flypaper.Core.Abstractions; + +public interface IKnownIpLookup +{ + ValueTask HasSeenAsync(IPAddress address, CancellationToken ct); +} diff --git a/src/Flypaper.Core/Abstractions/IResponseHeaders.cs b/src/Flypaper.Core/Abstractions/IResponseHeaders.cs new file mode 100644 index 0000000..106d52c --- /dev/null +++ b/src/Flypaper.Core/Abstractions/IResponseHeaders.cs @@ -0,0 +1,6 @@ +namespace Flypaper.Core.Abstractions; + +public interface IResponseHeaders +{ + IReadOnlyDictionary Headers { get; } +} diff --git a/src/Flypaper.Core/FlypaperCoreExtensions.cs b/src/Flypaper.Core/FlypaperCoreExtensions.cs index 561cbce..6dc52c2 100644 --- a/src/Flypaper.Core/FlypaperCoreExtensions.cs +++ b/src/Flypaper.Core/FlypaperCoreExtensions.cs @@ -22,6 +22,8 @@ public static class FlypaperCoreExtensions services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); services.TryAddEnumerable(ServiceDescriptor.Singleton()); + services.AddSingleton(_ => LureStrategy.Page()); + services.AddSingleton(_ => LureStrategy.Icon()); foreach (var kind in Enum.GetValues()) { services.AddSingleton(provider => new MazeDripStrategy( @@ -44,6 +46,7 @@ public static class FlypaperCoreExtensions services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); return services; } diff --git a/src/Flypaper.Core/Models/TrapContext.cs b/src/Flypaper.Core/Models/TrapContext.cs index edb1915..f0ca1f1 100644 --- a/src/Flypaper.Core/Models/TrapContext.cs +++ b/src/Flypaper.Core/Models/TrapContext.cs @@ -1,3 +1,3 @@ namespace Flypaper.Core.Models; -public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null, string? Path = null); +public sealed record TrapContext(TrapSession Session, string? Target = null, string? ClientInfo = null, string? Path = null, bool IsNewIp = false); diff --git a/src/Flypaper.Core/Networking/NullKnownIpLookup.cs b/src/Flypaper.Core/Networking/NullKnownIpLookup.cs new file mode 100644 index 0000000..cdaa7a8 --- /dev/null +++ b/src/Flypaper.Core/Networking/NullKnownIpLookup.cs @@ -0,0 +1,9 @@ +using System.Net; +using Flypaper.Core.Abstractions; + +namespace Flypaper.Core.Networking; + +internal sealed class NullKnownIpLookup : IKnownIpLookup +{ + public ValueTask HasSeenAsync(IPAddress address, CancellationToken ct) => ValueTask.FromResult(true); +} diff --git a/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs b/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs index 905aa75..04dc430 100644 --- a/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs +++ b/src/Flypaper.Core/Runtime/ConfiguredStrategySelector.cs @@ -19,6 +19,12 @@ public sealed class ConfiguredStrategySelector( return robots; } + if (context.IsNewIp && options.CurrentValue.Lure && LureContent.Handles(context.Path) + && candidates.FirstOrDefault(strategy => strategy.Name == (context.Path == LureContent.PagePath ? LureStrategy.PageName : LureStrategy.IconName)) is { } lure) + { + return lure; + } + if (BaitPaths.Matches(BaitPaths.Parse(options.CurrentValue.BaitPaths), context.Path) && candidates.FirstOrDefault(strategy => strategy.Name == MazeDripStrategy.BaitName) is { } bait) { diff --git a/src/Flypaper.Core/Strategies/DripOptions.cs b/src/Flypaper.Core/Strategies/DripOptions.cs index d5f0da4..59675cd 100644 --- a/src/Flypaper.Core/Strategies/DripOptions.cs +++ b/src/Flypaper.Core/Strategies/DripOptions.cs @@ -20,5 +20,7 @@ public sealed class DripOptions public int LinkSpacing { get; set; } = 160; + public bool Lure { get; set; } = true; + public string BaitPaths { get; set; } = Strategies.BaitPaths.Default; } diff --git a/src/Flypaper.Core/Strategies/LureContent.cs b/src/Flypaper.Core/Strategies/LureContent.cs new file mode 100644 index 0000000..c91cdd2 --- /dev/null +++ b/src/Flypaper.Core/Strategies/LureContent.cs @@ -0,0 +1,90 @@ +using System.Text; + +namespace Flypaper.Core.Strategies; + +public static class LureContent +{ + public const string PagePath = "/"; + + public const string IconPath = "/favicon.ico"; + + public static readonly IReadOnlyDictionary Headers = new Dictionary + { + ["X-Powered-By"] = "PHP/8.1.27", + ["Link"] = "; rel=\"https://api.w.org/\"" + }; + + public static bool Handles(string? path) => + string.Equals(path, PagePath, StringComparison.Ordinal) || string.Equals(path, IconPath, StringComparison.OrdinalIgnoreCase); + + public static byte[] Page() => Encoding.UTF8.GetBytes(""" + + + + + + + Intranet – Just another WordPress site + + + + + + + +

Intranet

Just another WordPress site

+ +

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start writing!

+ + + + """); + + public static byte[] Icon() + { + const int size = 16; + using var stream = new MemoryStream(); + using var writer = new BinaryWriter(stream); + writer.Write((ushort)0); + writer.Write((ushort)1); + writer.Write((ushort)1); + writer.Write((byte)size); + writer.Write((byte)size); + writer.Write((byte)0); + writer.Write((byte)0); + writer.Write((ushort)1); + writer.Write((ushort)32); + var imageSize = 40 + size * size * 4 + size * 4; + writer.Write(imageSize); + writer.Write(22); + writer.Write(40); + writer.Write(size); + writer.Write(size * 2); + writer.Write((ushort)1); + writer.Write((ushort)32); + writer.Write(0); + writer.Write(size * size * 4); + writer.Write(0); + writer.Write(0); + writer.Write(0); + writer.Write(0); + for (var y = 0; y < size; y++) + { + for (var x = 0; x < size; x++) + { + var dx = x - 7.5; + var dy = y - 7.5; + var inside = dx * dx + dy * dy <= 56; + writer.Write(inside ? 0xFF8A5A21u : 0u); + } + } + + writer.Write(new byte[size * 4]); + return stream.ToArray(); + } +} diff --git a/src/Flypaper.Core/Strategies/LureStrategy.cs b/src/Flypaper.Core/Strategies/LureStrategy.cs new file mode 100644 index 0000000..427c91d --- /dev/null +++ b/src/Flypaper.Core/Strategies/LureStrategy.cs @@ -0,0 +1,27 @@ +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; + +namespace Flypaper.Core.Strategies; + +public sealed class LureStrategy(string name, string mediaType, byte[] body) : ITarpitStrategy, IStrategyDetails, IResponseHeaders +{ + public const string PageName = "lure-page"; + + public const string IconName = "lure-icon"; + + public static LureStrategy Page() => new(PageName, "text/html; charset=utf-8", LureContent.Page()); + + public static LureStrategy Icon() => new(IconName, "image/x-icon", LureContent.Icon()); + + public string Name => name; + + public string MediaType => mediaType; + + public IReadOnlyDictionary Headers => LureContent.Headers; + + public bool Supports(TrapProtocol protocol) => protocol == TrapProtocol.Http; + + public string Describe() => Name; + + public async Task RunAsync(ITrapChannel channel, CancellationToken ct) => await channel.WriteAsync(body, ct); +} diff --git a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs index 82f6d27..728704a 100644 --- a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs +++ b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs @@ -3,6 +3,7 @@ using Flypaper.Core.Abstractions; using Flypaper.Core.Models; using Flypaper.Core.Networking; using Flypaper.Core.Runtime; +using Flypaper.Core.Strategies; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Features; @@ -14,6 +15,8 @@ internal sealed class FlypaperMiddleware( RequestDelegate next, TrapRunner runner, IOptions ports, + IKnownIpLookup knownIps, + IOptionsMonitor drip, TimeProvider timeProvider) { public async Task InvokeAsync(HttpContext context) @@ -32,11 +35,17 @@ internal sealed class FlypaperMiddleware( context.Connection.RemoteIpAddress ?? IPAddress.None, timeProvider.GetUtcNow()); + var isNewIp = drip.CurrentValue.Lure + && HttpMethods.IsGet(request.Method) + && LureContent.Handles(request.Path.Value) + && !await knownIps.HasSeenAsync(session.RemoteIp, context.RequestAborted); + var trapContext = new TrapContext( session, $"{request.Method} {StoredHost(request.Host)}{request.Path}{request.QueryString}", request.Headers.UserAgent.ToString(), - request.Path.Value); + request.Path.Value, + isNewIp); var outcome = await runner.RunAsync( trapContext, @@ -77,6 +86,14 @@ internal sealed class FlypaperMiddleware( response.Headers.Server = "nginx"; response.Headers.CacheControl = "no-store"; response.Headers["X-Accel-Buffering"] = "no"; + if (strategy is IResponseHeaders extra) + { + foreach (var (name, value) in extra.Headers) + { + response.Headers[name] = value; + } + } + await response.StartAsync(ct); return new HttpTrapChannel(session, response); diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs index c36d869..4dfcf66 100644 --- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -42,6 +42,7 @@ public static class FlypaperStorageExtensions services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddHostedService(); return services; diff --git a/src/Flypaper.Storage/Queries/KnownIpLookup.cs b/src/Flypaper.Storage/Queries/KnownIpLookup.cs new file mode 100644 index 0000000..3c74b41 --- /dev/null +++ b/src/Flypaper.Storage/Queries/KnownIpLookup.cs @@ -0,0 +1,15 @@ +using System.Net; +using Flypaper.Core.Abstractions; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage.Queries; + +public sealed class KnownIpLookup(IDbContextFactory dbContextFactory) : IKnownIpLookup +{ + public async ValueTask HasSeenAsync(IPAddress address, CancellationToken ct) + { + var ip = address.ToString(); + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await db.TrapEvents.AnyAsync(e => e.RemoteIp == ip, ct); + } +} diff --git a/src/Flypaper.Web/Components/Shared/StrategyNames.cs b/src/Flypaper.Web/Components/Shared/StrategyNames.cs index 0fe65e2..bfbb6ce 100644 --- a/src/Flypaper.Web/Components/Shared/StrategyNames.cs +++ b/src/Flypaper.Web/Components/Shared/StrategyNames.cs @@ -45,6 +45,8 @@ public static partial class StrategyNames ["sql-drip"] = ("Gefälschter Datenbank-Export (SQL)", "Ein erfundener SQL-Dump mit endlos vielen Einträgen. Bots, die nach Datenbank-Backups suchen, laden ihn herunter, solange es geht."), ["hikvision-drip"] = ("Gefälschte Überwachungskamera (Hikvision)", "Die Antwort einer erfundenen Hikvision-Kamera, die nie endet. Bots, die nach angreifbaren Kameras suchen, warten auf die komplette Antwort."), ["wordpress-drip"] = ("Gefälschte WordPress-Anmeldung", "Eine erfundene WordPress-Anmeldeseite, die nie fertig geladen wird. Bots, die Passwörter durchprobieren, kommen nie zum Formular."), + ["lure-page"] = ("Köder-Startseite (WordPress)", "Beim ersten Besuch einer unbekannten IP wird sofort eine kleine WordPress-Seite mit Links geliefert und niemand festgehalten. Wer danach gezielt weitersucht, kommt in die Falle."), + ["lure-icon"] = ("Köder-Favicon (WordPress)", "Beim ersten Besuch einer unbekannten IP wird sofort ein kleines Favicon geliefert und niemand festgehalten."), ["robots-static"] = ("robots.txt (Hinweis an brave Crawler)", "Die robots.txt wird sofort und vollständig geliefert. Sie verbietet alles, brave Crawler bleiben draußen. Es wird bewusst niemand festgehalten."), ["robots-bait"] = ("Köder aus der robots.txt", "Ein Pfad, der in der robots.txt als verboten steht, aber ins Link-Labyrinth führt. Wer dort landet, hat das Verbot gelesen und ignoriert. Er wird mindestens 24 Stunden festgehalten.") }; diff --git a/test/Flypaper.Tests/Core/LureTests.cs b/test/Flypaper.Tests/Core/LureTests.cs new file mode 100644 index 0000000..11a78fd --- /dev/null +++ b/test/Flypaper.Tests/Core/LureTests.cs @@ -0,0 +1,67 @@ +using System.Net; +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; +using Flypaper.Core.Runtime; +using Flypaper.Core.Strategies; +using Flypaper.Tests.Fakes; +using Shouldly; + +namespace Flypaper.Tests.Core; + +public sealed class LureTests +{ + private static readonly TrapSession Session = new(Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("203.0.113.9"), DateTimeOffset.UtcNow); + + [Theory] + [InlineData("/", true, "lure-page")] + [InlineData("/favicon.ico", true, "lure-icon")] + [InlineData("/", false, "html-drip")] + [InlineData("/.env", true, "env-drip")] + [InlineData("/wp-login.php", true, "wordpress-drip")] + public void Lures_only_new_ips_on_start_page_and_favicon(string path, bool isNewIp, string expected) => + Selector(new DripOptions { LinkSpacing = 0 }).Select(new TrapContext(Session, "GET " + path, null, path, isNewIp)).ShouldNotBeNull().Name.ShouldBe(expected); + + [Fact] + public void Switch_turns_the_lure_off() => + Selector(new DripOptions { LinkSpacing = 0, Lure = false }) + .Select(new TrapContext(Session, "GET /", null, "/", true)).ShouldNotBeNull().Name.ShouldBe("html-drip"); + + [Fact] + public async Task Lure_page_is_one_consistent_wordpress_response() + { + var channel = new FakeTrapChannel(); + var strategy = LureStrategy.Page(); + + await strategy.RunAsync(channel, default); + + System.Text.Encoding.UTF8.GetString(channel.Writes.SelectMany(w => w).ToArray()).ShouldContain("WordPress 6.4.3"); + strategy.MediaType.ShouldStartWith("text/html"); + strategy.Headers["X-Powered-By"].ShouldStartWith("PHP/"); + } + + [Fact] + public void Lure_icon_is_a_valid_ico_file() + { + var icon = LureContent.Icon(); + + icon[..4].ShouldBe([0, 0, 1, 0]); + BitConverter.ToInt32(icon, 14).ShouldBe(icon.Length - 22); + LureStrategy.Icon().MediaType.ShouldBe("image/x-icon"); + } + + private static ConfiguredStrategySelector Selector(DripOptions dripOptions) + { + var options = TestOptions.Monitor(dripOptions); + var random = new SeededRandomSource(5); + return new ConfiguredStrategySelector( + [ + new HtmlDripStrategy(options, random, TimeProvider.System), + new FileDripStrategy(FileContent.Profiles.First(p => p.Name == "env-drip"), options, random, TimeProvider.System), + new FileDripStrategy(FileContent.Profiles.First(p => p.Name == "wordpress-drip"), options, random, TimeProvider.System), + LureStrategy.Page(), + LureStrategy.Icon() + ], + options, + random); + } +} diff --git a/test/Flypaper.Tests/Http/LureTests.cs b/test/Flypaper.Tests/Http/LureTests.cs new file mode 100644 index 0000000..e58e74c --- /dev/null +++ b/test/Flypaper.Tests/Http/LureTests.cs @@ -0,0 +1,71 @@ +using System.Net; +using System.Text; +using Flypaper.Core; +using Flypaper.Core.Abstractions; +using Flypaper.Core.Models; +using Flypaper.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Shouldly; + +namespace Flypaper.Tests.Http; + +public sealed class LureTests +{ + [Fact] + public async Task Unknown_ip_gets_the_lure_page_with_matching_headers_and_is_not_held() + { + var (body, headers, sink) = await SendAsync(known: false, "/"); + + body.ShouldContain("WordPress"); + headers["X-Powered-By"].ToString().ShouldStartWith("PHP/"); + headers.Server.ToString().ShouldBe("nginx"); + sink.Received(1).Publish(Arg.Is(e => e.Strategy == "lure-page" && e.Outcome == TrapOutcome.Completed)); + } + + [Fact] + public async Task Known_ip_gets_no_lure() + { + var (_, headers, sink) = await SendAsync(known: true, "/", cancelAfter: TimeSpan.FromMilliseconds(100)); + + headers.ContainsKey("X-Powered-By").ShouldBeFalse(); + sink.Received(1).Publish(Arg.Is(e => e.Strategy != "lure-page")); + } + + private static async Task<(string Body, IHeaderDictionary Headers, ITrapEventSink Sink)> SendAsync(bool known, string path, TimeSpan? cancelAfter = null) + { + var lookup = Substitute.For(); + lookup.HasSeenAsync(Arg.Any(), Arg.Any()).Returns(known); + var sink = Substitute.For(); + var configuration = new ConfigurationBuilder().Build(); + var services = new ServiceCollection() + .AddLogging() + .AddSingleton(sink) + .AddSingleton(lookup) + .AddFlypaperCore(configuration) + .AddFlypaperHttp(configuration) + .BuildServiceProvider(); + + var app = new ApplicationBuilder(services); + app.UseFlypaper(); + var body = new MemoryStream(); + using var cts = new CancellationTokenSource(); + var httpContext = new DefaultHttpContext { RequestServices = services, RequestAborted = cts.Token }; + httpContext.Connection.RemoteIpAddress = IPAddress.Parse("203.0.113.9"); + httpContext.Connection.LocalPort = 8080; + httpContext.Request.Method = "GET"; + httpContext.Request.Host = new HostString("example.com"); + httpContext.Request.Path = path; + httpContext.Response.Body = body; + if (cancelAfter is { } delay) + { + cts.CancelAfter(delay); + } + + await app.Build()(httpContext); + return (Encoding.UTF8.GetString(body.ToArray()), httpContext.Response.Headers, sink); + } +} diff --git a/test/Flypaper.Tests/Storage/KnownIpLookupTests.cs b/test/Flypaper.Tests/Storage/KnownIpLookupTests.cs new file mode 100644 index 0000000..94fd578 --- /dev/null +++ b/test/Flypaper.Tests/Storage/KnownIpLookupTests.cs @@ -0,0 +1,32 @@ +using System.Net; +using Flypaper.Core.Models; +using Flypaper.Storage.Entities; +using Flypaper.Storage.Queries; +using Flypaper.Tests.Mcp; +using Shouldly; + +namespace Flypaper.Tests.Storage; + +public sealed class KnownIpLookupTests : IDisposable +{ + private readonly McpTestData _data = new(); + + [Fact] + public async Task Knows_only_ips_with_a_stored_catch() + { + using (var db = _data.Factory.CreateDbContext()) + { + var started = McpTestData.Now.AddHours(-2); + db.TrapEvents.Add(TrapEventEntity.From(new TrapEvent( + Guid.NewGuid(), TrapProtocol.Http, IPAddress.Parse("2001:db8::7"), "lure-page", started, started.AddSeconds(1), 100, TrapOutcome.Completed, "GET /", null))); + db.SaveChanges(); + } + + var lookup = new KnownIpLookup(_data.Factory); + + (await lookup.HasSeenAsync(IPAddress.Parse("2001:db8::7"), default)).ShouldBeTrue(); + (await lookup.HasSeenAsync(IPAddress.Parse("203.0.113.99"), default)).ShouldBeFalse(); + } + + public void Dispose() => _data.Dispose(); +} diff --git a/test/Flypaper.Tests/Web/StrategyNamesTests.cs b/test/Flypaper.Tests/Web/StrategyNamesTests.cs index 67f1d81..2487d0f 100644 --- a/test/Flypaper.Tests/Web/StrategyNamesTests.cs +++ b/test/Flypaper.Tests/Web/StrategyNamesTests.cs @@ -47,6 +47,7 @@ public sealed class StrategyNamesTests [ MazeDripStrategy.PageName, MazeDripStrategy.ListingName, MazeDripStrategy.BaitName, HtmlDripStrategy.StrategyName, TextDripStrategy.StrategyName, RobotsStaticStrategy.StrategyName, + LureStrategy.PageName, LureStrategy.IconName, .. FileContent.Profiles.Select(profile => profile.Name) ];