diff --git a/.dockerignore b/.dockerignore index a41540f..c72c465 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,3 +6,4 @@ .git/ .idea/ test/ +.gitea/ diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml new file mode 100644 index 0000000..223c8e7 --- /dev/null +++ b/.gitea/workflows/deploy.yml @@ -0,0 +1,134 @@ +# Builds the image on every push to main, pushes it to the Gitea registry (tagged +# :latest AND the short commit SHA, for rollback) and deploys the stack on Unraid +# from the repo's compose.yaml. +# +# The deploy works because the act_runner runs ON Unraid and hands its Docker +# socket to the job: every `docker` command here talks to the Unraid daemon, so +# absolute paths in compose.yaml (the /data bind mount) are host paths. +# +# Required repository secrets (Gitea -> repo -> Settings -> Actions -> Secrets): +# REGISTRY_USER the registry username (e.g. Tom) +# REGISTRY_TOKEN a Gitea access token with package:write -- NOT the password +# FLYPAPER_ADMIN_PASSWORD the dashboard login password + +name: Build and deploy + +on: + push: + branches: [main] + # Docs alone change neither the image nor the stack. + paths-ignore: + - "docs/**" + - "**/*.md" + # Manual run from Gitea (Actions tab), e.g. to redeploy after a server restart. + workflow_dispatch: + +# Two quick pushes must not deploy over each other; the later one waits. +concurrency: + group: deploy-flypaper + cancel-in-progress: false + +env: + IMAGE: gitea.anticarnist.de/tom/flypaper + COMPOSE_VERSION: v2.39.4 + # Host folder of the /data volume and the UID of the image's app user. + DATA_DIR: /mnt/user/appdata/flypaper + APP_UID: "1654" + +jobs: + build: + runs-on: ubuntu-latest + steps: + - name: Check out the source + uses: actions/checkout@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to the Gitea registry + uses: docker/login-action@v3 + with: + registry: gitea.anticarnist.de + username: ${{ secrets.REGISTRY_USER }} + password: ${{ secrets.REGISTRY_TOKEN }} + + # The short SHA names the image content unambiguously and never moves, + # so it is the stable handle for a rollback. + - name: Compute the short commit SHA + id: sha + run: echo "short=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT" + + - name: Build and push (:latest and :) + uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: | + ${{ env.IMAGE }}:latest + ${{ env.IMAGE }}:${{ steps.sha.outputs.short }} + + deploy: + needs: build + runs-on: ubuntu-latest + steps: + - name: Check out the source + uses: actions/checkout@v4 + + # The job image ships the Docker CLI (the build needs it) but not + # necessarily the compose plugin; install a pinned one if it is missing. + - name: Ensure docker compose + run: | + docker compose version && exit 0 + mkdir -p ~/.docker/cli-plugins + curl -fsSL -o ~/.docker/cli-plugins/docker-compose \ + "https://github.com/docker/compose/releases/download/${COMPOSE_VERSION}/docker-compose-linux-x86_64" + chmod +x ~/.docker/cli-plugins/docker-compose + docker compose version + + # The container runs as the image's app user, not as root. The folder lives + # on the host, so a throwaway container creates it there and hands it to that + # user -- on every deploy, so a reset by Unraid's "New Permissions" heals itself. + - name: Prepare the data folder + run: | + docker run --rm -v "${DATA_DIR}:/data" busybox:1.37 \ + chown -R "${APP_UID}:${APP_UID}" /data + + # The image is private; the pull below runs with this job's login. + - name: Log in to the Gitea registry + uses: docker/login-action@v3 + with: + registry: gitea.anticarnist.de + username: ${{ secrets.REGISTRY_USER }} + password: ${{ secrets.REGISTRY_TOKEN }} + + # An explicit pull: `up` alone keeps a local :latest and would not notice + # the image the build job just pushed. + - name: Pull and start the stack + env: + FLYPAPER_ADMIN_PASSWORD: ${{ secrets.FLYPAPER_ADMIN_PASSWORD }} + run: | + docker compose -f compose.yaml pull + docker compose -f compose.yaml up -d --wait --remove-orphans + + # /health answers 200 only when the app runs AND reads its database. It is + # checked from inside proxynet, the same way NPM reaches the app. The probe + # comes from a private address, so /health is exempt from the trap even + # though the Host header (flypaper) is unknown. A failure marks the run red; + # the rollback stays a deliberate step. + - name: Health gate + run: | + for attempt in $(seq 1 30); do + if docker run --rm --network proxynet busybox:1.37 \ + wget -qO- http://flypaper:8080/health; then + exit 0 + fi + sleep 2 + done + echo "flypaper did not report healthy within 60 seconds." >&2 + docker logs --tail 50 flypaper >&2 + exit 1 + + # Every deploy leaves the previous :latest behind as an untagged image. Only + # untagged images go; a rollback pulls its : from the registry anyway. + - name: Remove untagged images + run: docker image prune -f diff --git a/Directory.Packages.props b/Directory.Packages.props index 7b0a3f4..cb92b60 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -14,6 +14,7 @@ + diff --git a/README.md b/README.md index db31841..6e1e64d 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,43 @@ # Flypaper -Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis. \ No newline at end of file +Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis. + +## Deployment + +Every push to `main` (except docs and `.md` files) runs `.gitea/workflows/deploy.yml` on the +act_runner on Unraid: it builds the image, pushes it to +`gitea.anticarnist.de/tom/flypaper` (`:latest` and `:`), deploys `compose.yaml` +and waits for `/health`. A manual run is possible from the Actions tab (`workflow_dispatch`). + +### Secrets + +Gitea → repo → Settings → Actions → Secrets: + +| Secret | Purpose | +|---|---| +| `REGISTRY_USER` | Registry username | +| `REGISTRY_TOKEN` | Gitea access token with `package:write` (not the password) | +| `FLYPAPER_ADMIN_PASSWORD` | Dashboard login password | + +### Data + +`/mnt/user/appdata/flypaper` on Unraid, mounted as `/data`: + +- `flypaper.db`: trap events and the settings saved in the dashboard +- `keys/`: Data Protection keys, so logins survive a restart + +The container runs as UID 1654. The workflow creates the folder and sets its owner on +every deploy. + +### Access + +- Dashboard: `http://192.168.1.14:44307` (LAN only, login with `FLYPAPER_ADMIN_PASSWORD`) +- Trap: NPM forwards to `flypaper:8080` over `proxynet`. Every Host header other than the + dashboard host lands in the trap, as do the trap paths on known hosts. +- `/health` answers only to private addresses; from public addresses it is a trap like any + other path. + +### Rollback + +Pin the image in `compose.yaml` to a previous `:` and push, or deploy that tag +manually on Unraid. diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..ba15c5c --- /dev/null +++ b/compose.yaml @@ -0,0 +1,47 @@ +# Production stack on Unraid. Deployed as is by .gitea/workflows/deploy.yml, not +# pasted into the Compose Manager. +# +# NPM reaches the trap as flypaper:8080 over the external network proxynet (default +# site for unknown hosts, trap paths on the real domains). The dashboard is reached +# from the LAN on the host port: http://192.168.1.14:44307. +# +# `restart: always`, not `unless-stopped`: Unraid stops every container explicitly +# when Docker or the array goes down, and `unless-stopped` treats that as a manual +# stop -- the trap would stay down after a reboot. + +name: flypaper + +services: + flypaper: + image: gitea.anticarnist.de/tom/flypaper:latest + container_name: flypaper + restart: always + ports: + - "44307:8080" + environment: + TZ: Europe/Berlin + # The dashboard host. Every other Host header lands in the trap. + Flypaper__Http__KnownHosts__0: 192.168.1.14 + # Subnet of proxynet: only NPM may set X-Forwarded-For / X-Real-IP. + Flypaper__Http__TrustedProxies__0: 172.19.0.0/16 + # From the repository secret, never in the repo. + Flypaper__Admin__Password: ${FLYPAPER_ADMIN_PASSWORD:?FLYPAPER_ADMIN_PASSWORD is not set} + volumes: + # SQLite database and Data Protection keys. Owned by the image's app user + # (UID 1654); the deploy workflow creates the folder and sets the owner. + - /mnt/user/appdata/flypaper:/data + networks: + - proxynet + healthcheck: + # The image has neither curl nor wget; bash's /dev/tcp does the request. + # /health from loopback is exempt from the trap. + test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/8080 && printf 'GET /health HTTP/1.0\\r\\nHost: localhost\\r\\n\\r\\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"] + interval: 30s + timeout: 5s + start_period: 10s + retries: 3 + +networks: + proxynet: + # Created once on Unraid and shared with NPM. + external: true diff --git a/src/Flypaper.Http/HttpTrapOptions.cs b/src/Flypaper.Http/HttpTrapOptions.cs index 19f07d2..acc09fc 100644 --- a/src/Flypaper.Http/HttpTrapOptions.cs +++ b/src/Flypaper.Http/HttpTrapOptions.cs @@ -4,6 +4,8 @@ public sealed class HttpTrapOptions { public const string SectionName = "Flypaper:Http"; + public const string HealthPath = "/health"; + public string[] KnownHosts { get; set; } = []; public string[] TrapPaths { get; set; } = []; diff --git a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs index 3419d66..569e3b7 100644 --- a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs +++ b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs @@ -18,7 +18,7 @@ internal sealed class FlypaperMiddleware( public async Task InvokeAsync(HttpContext context) { var request = context.Request; - if (matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None) + if (IsInternalHealthProbe(context) || matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None) { await next(context); return; @@ -46,6 +46,11 @@ internal sealed class FlypaperMiddleware( } } + private static bool IsInternalHealthProbe(HttpContext context) => + context.Request.Path.Equals(HttpTrapOptions.HealthPath, StringComparison.OrdinalIgnoreCase) + && context.Connection.RemoteIpAddress is { } remoteIp + && PrivateNetworks.Contains(remoteIp); + private static async ValueTask OpenChannelAsync( HttpContext context, TrapSession session, diff --git a/src/Flypaper.Http/Middleware/PrivateNetworks.cs b/src/Flypaper.Http/Middleware/PrivateNetworks.cs new file mode 100644 index 0000000..3282c0c --- /dev/null +++ b/src/Flypaper.Http/Middleware/PrivateNetworks.cs @@ -0,0 +1,22 @@ +using System.Net; + +namespace Flypaper.Http.Middleware; + +internal static class PrivateNetworks +{ + private static readonly IPNetwork[] Networks = + [ + IPNetwork.Parse("127.0.0.0/8"), + IPNetwork.Parse("10.0.0.0/8"), + IPNetwork.Parse("172.16.0.0/12"), + IPNetwork.Parse("192.168.0.0/16"), + IPNetwork.Parse("::1/128"), + IPNetwork.Parse("fc00::/7") + ]; + + public static bool Contains(IPAddress address) + { + var ip = address.IsIPv4MappedToIPv6 ? address.MapToIPv4() : address; + return Networks.Any(network => network.Contains(ip)); + } +} diff --git a/src/Flypaper.Web/Health/HealthEndpoints.cs b/src/Flypaper.Web/Health/HealthEndpoints.cs new file mode 100644 index 0000000..c342a52 --- /dev/null +++ b/src/Flypaper.Web/Health/HealthEndpoints.cs @@ -0,0 +1,28 @@ +using Flypaper.Http; +using Flypaper.Storage; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Web.Health; + +public static class HealthEndpoints +{ + public static IEndpointRouteBuilder MapHealthEndpoint(this IEndpointRouteBuilder app) + { + app.MapGet(HttpTrapOptions.HealthPath, async (IDbContextFactory dbContextFactory, CancellationToken ct) => + { + try + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + await db.Settings.AnyAsync(ct); + return Results.Text("healthy", "text/plain; charset=utf-8"); + } + catch (SqliteException) + { + return Results.Text("database unavailable", "text/plain; charset=utf-8", statusCode: StatusCodes.Status503ServiceUnavailable); + } + }).AllowAnonymous(); + + return app; + } +} diff --git a/src/Flypaper.Web/Program.cs b/src/Flypaper.Web/Program.cs index 65d51b8..a69e428 100644 --- a/src/Flypaper.Web/Program.cs +++ b/src/Flypaper.Web/Program.cs @@ -3,6 +3,7 @@ using Flypaper.Http; using Flypaper.Storage; using Flypaper.Web.Auth; using Flypaper.Web.Components; +using Flypaper.Web.Health; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; @@ -57,6 +58,9 @@ app.UseAntiforgery(); app.MapStaticAssets().AllowAnonymous(); app.MapAuthEndpoints(); +app.MapHealthEndpoint(); app.MapRazorComponents(); await app.RunAsync(); + +public partial class Program; diff --git a/test/Flypaper.Tests/Flypaper.Tests.csproj b/test/Flypaper.Tests/Flypaper.Tests.csproj index 06e2909..5974501 100644 --- a/test/Flypaper.Tests/Flypaper.Tests.csproj +++ b/test/Flypaper.Tests/Flypaper.Tests.csproj @@ -6,6 +6,7 @@ + @@ -16,6 +17,7 @@ + diff --git a/test/Flypaper.Tests/Http/HealthProbeTests.cs b/test/Flypaper.Tests/Http/HealthProbeTests.cs new file mode 100644 index 0000000..f6d6ebd --- /dev/null +++ b/test/Flypaper.Tests/Http/HealthProbeTests.cs @@ -0,0 +1,80 @@ +using System.Net; +using Flypaper.Core; +using Flypaper.Core.Abstractions; +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 HealthProbeTests +{ + [Theory] + [InlineData("172.19.0.7")] + [InlineData("127.0.0.1")] + [InlineData("192.168.1.20")] + [InlineData("::1")] + public async Task Lets_health_probe_from_private_network_pass_with_unknown_host(string remoteIp) + { + var (reachedApp, status) = await SendAsync(IPAddress.Parse(remoteIp), "/health"); + + reachedApp.ShouldBeTrue(); + status.ShouldBe(StatusCodes.Status200OK); + } + + [Fact] + public async Task Traps_health_path_from_public_ip() + { + var (reachedApp, status) = await SendAsync(IPAddress.Parse("203.0.113.9"), "/health"); + + reachedApp.ShouldBeFalse(); + status.ShouldBe(StatusCodes.Status404NotFound); + } + + [Fact] + public async Task Traps_other_paths_from_private_network_with_unknown_host() + { + var (reachedApp, _) = await SendAsync(IPAddress.Parse("172.19.0.7"), "/status"); + + reachedApp.ShouldBeFalse(); + } + + private static async Task<(bool ReachedApp, int Status)> SendAsync(IPAddress remoteIp, string path) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Flypaper:MaxConnections"] = "0", + ["Flypaper:Http:KnownHosts:0"] = "dashboard.lan" + }) + .Build(); + + var services = new ServiceCollection() + .AddLogging() + .AddSingleton(Substitute.For()) + .AddFlypaperCore(configuration) + .AddFlypaperHttp(configuration) + .BuildServiceProvider(); + + var reachedApp = false; + var app = new ApplicationBuilder(services); + app.UseFlypaper(); + app.Run(_ => + { + reachedApp = true; + return Task.CompletedTask; + }); + + var httpContext = new DefaultHttpContext { RequestServices = services }; + httpContext.Connection.RemoteIpAddress = remoteIp; + httpContext.Request.Host = new HostString("flypaper:8080"); + httpContext.Request.Path = path; + + await app.Build()(httpContext); + return (reachedApp, httpContext.Response.StatusCode); + } +} diff --git a/test/Flypaper.Tests/Web/HealthEndpointTests.cs b/test/Flypaper.Tests/Web/HealthEndpointTests.cs new file mode 100644 index 0000000..153d866 --- /dev/null +++ b/test/Flypaper.Tests/Web/HealthEndpointTests.cs @@ -0,0 +1,53 @@ +using System.Net; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Data.Sqlite; +using Shouldly; + +namespace Flypaper.Tests.Web; + +public sealed class HealthEndpointTests : IDisposable +{ + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-health-{Guid.NewGuid():N}.db"); + private readonly WebApplicationFactory _factory; + + public HealthEndpointTests() + { + _factory = new WebApplicationFactory().WithWebHostBuilder(builder => + { + builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}"); + builder.UseSetting("Flypaper:Http:KnownHosts:0", "localhost"); + }); + } + + [Fact] + public async Task Reports_healthy_without_login() + { + using var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + + var response = await client.GetAsync("/health"); + + response.StatusCode.ShouldBe(HttpStatusCode.OK); + (await response.Content.ReadAsStringAsync()).ShouldBe("healthy"); + } + + [Fact] + public async Task Keeps_dashboard_behind_login() + { + using var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + + var response = await client.GetAsync("/"); + + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location!.OriginalString.ShouldStartWith("http://localhost/login"); + } + + public void Dispose() + { + _factory.Dispose(); + SqliteConnection.ClearAllPools(); + foreach (var suffix in new[] { "", "-wal", "-shm" }) + { + File.Delete(_dbPath + suffix); + } + } +}