diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 6b4df41..bb69892 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -111,15 +111,15 @@ jobs: docker compose -f deploy/unraid/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. + # checked from inside proxynet on both ports: 8080 is the trap, reached the + # same way NPM reaches it (the probe comes from a private address, so /health + # is exempt from the trap), 8081 is the dashboard. 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 + if docker run --rm --network proxynet busybox:1.37 sh -c \ + 'wget -qO- http://flypaper:8080/health && wget -qO- http://flypaper:8081/health'; then exit 0 fi sleep 2 diff --git a/Dockerfile b/Dockerfile index 300ab08..86fdc19 100644 --- a/Dockerfile +++ b/Dockerfile @@ -17,7 +17,7 @@ WORKDIR /app RUN mkdir /data && chown $APP_UID /data -ENV ASPNETCORE_HTTP_PORTS=8080 \ +ENV ASPNETCORE_HTTP_PORTS= \ ConnectionStrings__Flypaper="Data Source=/data/flypaper.db" \ Flypaper__DataProtection__KeysPath=/data/keys \ Flypaper__GeoIp__Directory=/data/geoip @@ -25,7 +25,7 @@ ENV ASPNETCORE_HTTP_PORTS=8080 \ COPY --from=build /app . USER $APP_UID -EXPOSE 8080 +EXPOSE 8080 8081 VOLUME /data ENTRYPOINT ["dotnet", "Flypaper.Web.dll"] diff --git a/README.md b/README.md index 9804293..8d688e6 100644 --- a/README.md +++ b/README.md @@ -18,14 +18,14 @@ flowchart LR proxy -->|"unknown host or trap path
+ X-Real-IP"| flypaper["Flypaper"] flypaper -.->|"endless HTML,
a few bytes at a time"| bot flypaper --> db[("SQLite:
catches, settings")] - you["You (LAN)"] -->|"dashboard host"| flypaper + you["You (LAN)"] -->|"dashboard, port 8081"| flypaper ``` 1. Your reverse proxy keeps serving your real sites. Everything it has no site for (the default/catch-all server) goes to Flypaper, optionally also a few bait paths on your real domains. -2. Flypaper looks at the `Host` header. A request for a host it doesn't know, or for a trap path, - is caught. Requests for a known host (the dashboard's) pass through to the dashboard. +2. Flypaper listens on two ports. Port `8080` is the trap: everything that arrives there is + caught. Port `8081` serves the dashboard and never traps; keep it inside your LAN. 3. A caught request gets `200 OK` and an endless, plausible-looking HTML page: random chunks of 1 to 64 bytes with random pauses of 50 ms to 1 s in between. 4. A connection governor caps the number of catches overall and per IP and ends every catch @@ -48,19 +48,26 @@ flowchart LR - **Retention**: old catches are deleted daily (90 days by default); catches from private networks are not stored by default; buttons to delete private or all catches - **One log line per catch**, so `docker logs` alone shows whether the trap works -- **Health endpoint** `/health` for container health checks (answers only to private - addresses) +- **Health endpoint** `/health` for container health checks (on the trap port it answers only + to private addresses) +- **No configuration needed to start**: one volume, two ports, the admin password is set on + first visit ## Quick start -There is no public image; build it from source. +There is no public image yet; build it from source. No environment variable is required. ```bash git clone flypaper cd flypaper +docker build -t flypaper . +docker run -d --name flypaper --restart unless-stopped \ + -p 8080:8080 -p 127.0.0.1:8081:8081 \ + -v flypaper-data:/data \ + flypaper ``` -Create a `compose.yaml` next to the `Dockerfile`: +Or with Compose, in a `compose.yaml` next to the `Dockerfile`: ```yaml services: @@ -70,14 +77,8 @@ services: container_name: flypaper restart: unless-stopped ports: - - "8080:8080" - environment: - TZ: Europe/Berlin - # Host names that reach the dashboard. Every other Host header is trapped. - Flypaper__Http__KnownHosts__0: localhost - # The reverse proxy that sets X-Real-IP (IP or CIDR), see below. - Flypaper__Http__TrustedProxies__0: 172.16.0.0/12 - Flypaper__Admin__Password: ${FLYPAPER_ADMIN_PASSWORD:?set FLYPAPER_ADMIN_PASSWORD} + - "8080:8080" # trap: point your reverse proxy here + - "127.0.0.1:8081:8081" # dashboard: LAN or localhost only volumes: - flypaper-data:/data @@ -85,15 +86,12 @@ volumes: flypaper-data: ``` -```bash -FLYPAPER_ADMIN_PASSWORD='a-long-random-password' docker compose up -d --build -``` - -- Dashboard: , log in with the password. -- See the trap in action (any unknown host works): +- Dashboard: . On the first visit Flypaper asks you to set the admin + password; afterwards you log in with it and can change it on the settings page. +- See the trap in action: ```bash - curl -N -H "Host: example.invalid" http://localhost:8080/ + curl -N http://localhost:8080/ ``` This catch comes from a private address and is therefore not stored; the log line ends with @@ -109,13 +107,16 @@ needed to run Flypaper. ## Behind a reverse proxy -Flypaper is meant to sit behind the reverse proxy that already owns ports 80/443. Two rules +Flypaper is meant to sit behind the reverse proxy that already owns ports 80/443. The proxy +forwards to the trap port `8080`; the dashboard port `8081` is never forwarded. Two rules apply to every proxy: - **Set `X-Real-IP`** (and `X-Forwarded-For`) to the client address. -- **Trust the proxy in Flypaper**: `Flypaper__Http__TrustedProxies__0` must contain the - proxy's IP or subnet. Headers from anyone else are ignored, so bots can't fake their - address. For a Docker network: +- **Flypaper must trust the proxy.** By default it trusts every private network (`10/8`, + `172.16/12`, `192.168/16`, loopback, `fc00::/7`), which covers a proxy in a Docker network + or on the LAN. Headers from public addresses are ignored, so bots can't fake their address. + To narrow it down, set `Flypaper__Http__TrustedProxies__0` to the proxy's IP or subnet, e.g. + the Docker network's subnet: ```bash docker network inspect -f '{{(index .IPAM.Config 0).Subnet}}' @@ -129,11 +130,14 @@ bot never sees it. Flypaper sends `X-Accel-Buffering: no`, which nginx honors. - **The catch-all server.** Requests for hosts you don't serve (mostly the bare IP) go to Flypaper. This is where almost all scanners end up. - **Optionally, trap paths on your real domains.** Forward only the bait paths, e.g. `/.env` - or `/wp-login.php`, from your real sites to Flypaper. Your domains are unknown to Flypaper, - so these requests are caught as well. + or `/wp-login.php`, from your real sites to Flypaper. Every request on the trap port is + caught, so nothing else is needed. -Never forward a whole domain that is listed as a known host: its other paths would show the -dashboard login. +*Known hosts* (optional) change this for hosts you list: on the trap port, a known host is +caught only on the configured trap paths, and its other paths get a plain `404` without being +logged. That is useful if your proxy forwards more than the bait paths of a real domain, for +example a whole location. Unknown hosts are always caught. The dashboard is never reachable +on the trap port. ### Nginx Proxy Manager @@ -210,7 +214,7 @@ server { } ``` -With Flypaper on the same host, `TrustedProxies` can stay empty: loopback is trusted by default. +With Flypaper on the same host, nothing else is needed: loopback is trusted by default. ### Caddy @@ -256,13 +260,14 @@ labels: ### Environment variables -Read at startup. List entries need an index (`__0`, `__1`, ...). +All optional. Read at startup; list entries need an index (`__0`, `__1`, ...). | Variable | Purpose | Default | |---|---|---| -| `Flypaper__Http__KnownHosts__0` | Host names that reach the dashboard (`*.example.com` allowed). Every other host is trapped. | none | -| `Flypaper__Http__TrustedProxies__0` | IP or CIDR of the reverse proxy allowed to set `X-Real-IP` / `X-Forwarded-For` | loopback only | -| `Flypaper__Admin__Password` | Dashboard password. Without it the dashboard stays locked. | none | +| `Flypaper__Admin__Password` | Fixes the dashboard password and disables the first-visit setup and the password change | set on first visit | +| `Flypaper__Http__TrustedProxies__0` | IP or CIDR of the reverse proxy allowed to set `X-Real-IP` / `X-Forwarded-For`; replaces the default | private networks | +| `Flypaper__Http__KnownHosts__0` | Hosts that are caught only on trap paths (`*.example.com` allowed), see above | none | +| `Flypaper__Ports__Trap` / `Flypaper__Ports__Dashboard` | Container ports | `8080` / `8081` | | `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` | | `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` | | `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` | @@ -290,10 +295,13 @@ reset button removes all saved values. ## Security notes -- **Keep the dashboard internal.** Only list internal names or LAN addresses as known hosts - and never route a known host through your public proxy. -- **Use a strong admin password.** The login runs over plain HTTP unless you put the - dashboard behind TLS yourself. +- **Keep the dashboard internal.** Publish port `8081` only to your LAN or to localhost and + never forward it from your public proxy. +- **Finish the setup before the dashboard is reachable by anyone else.** Until a password is + set, whoever opens the dashboard first can set it. The setup page disappears once a password + exists. +- **Use a strong admin password** (at least 12 characters). Only a salted hash is stored. The + login runs over plain HTTP unless you put the dashboard behind TLS yourself. - **The limits protect you, not the bots.** Every catch holds a socket in Flypaper and in your proxy for up to the maximum hold time. Keep `MaxConnections` well below what your proxy can handle (nginx: `worker_connections`), and keep the per-IP limit low so a single scanner @@ -315,7 +323,7 @@ dotnet run --project src/Flypaper.Web ``` `dotnet run` starts in the Development environment: the dashboard is at - (known host `localhost`, password `dev`), the database is + (password `dev`), the trap at , the database is `src/Flypaper.Web/flypaper.db`, and GeoIP is off unless `Flypaper__GeoIp__Directory` is set. `docker build -t flypaper .` builds the image. diff --git a/deploy/unraid/README.md b/deploy/unraid/README.md index af94492..8309a95 100644 --- a/deploy/unraid/README.md +++ b/deploy/unraid/README.md @@ -32,11 +32,12 @@ 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. +- Dashboard: `http://192.168.1.14:44307` → container port `8081` (LAN only, login with + `FLYPAPER_ADMIN_PASSWORD`) +- Trap: NPM forwards to `flypaper:8080` over `proxynet`. Everything on that port is + trapped. +- `/health` on `8080` answers only to private addresses; from public addresses it is a trap + like any other path. On `8081` it always answers. ## Rollback diff --git a/deploy/unraid/compose.yaml b/deploy/unraid/compose.yaml index 0985765..65e1d20 100644 --- a/deploy/unraid/compose.yaml +++ b/deploy/unraid/compose.yaml @@ -3,8 +3,8 @@ # .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. +# site for unknown hosts, trap paths on the real domains). The dashboard has its own +# port 8081, published only to the LAN: 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 @@ -18,11 +18,9 @@ services: container_name: flypaper restart: always ports: - - "44307:8080" + - "44307:8081" 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. @@ -34,9 +32,9 @@ services: 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 '"] + # The image has neither curl nor wget; bash's /dev/tcp does the request + # against the dashboard port. + test: ["CMD", "bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/8081 && 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 diff --git a/src/Flypaper.Http/FlypaperHttpExtensions.cs b/src/Flypaper.Http/FlypaperHttpExtensions.cs index 50d3294..bd3a156 100644 --- a/src/Flypaper.Http/FlypaperHttpExtensions.cs +++ b/src/Flypaper.Http/FlypaperHttpExtensions.cs @@ -14,9 +14,12 @@ namespace Flypaper.Http; public static class FlypaperHttpExtensions { + private static readonly string[] DefaultTrustedProxies = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; + public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration) { services.Configure(configuration.GetSection(HttpTrapOptions.SectionName)); + services.Configure(configuration.GetSection(PortOptions.SectionName)); services.PostConfigure(options => { if (options.TrapPathsOverride is not null) @@ -33,7 +36,9 @@ public static class FlypaperHttpExtensions { forwarded.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; forwarded.ForwardLimit = 1; - foreach (var proxy in trap.Value.TrustedProxies) + var configured = trap.Value.TrustedProxies.Where(proxy => !string.IsNullOrWhiteSpace(proxy)).ToArray(); + var proxies = configured.Length > 0 ? configured : DefaultTrustedProxies; + foreach (var proxy in proxies) { forwarded.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(proxy.Contains('/') ? proxy : $"{proxy}/{HostBits(proxy)}")); } diff --git a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs index 89a0383..b46afdf 100644 --- a/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs +++ b/src/Flypaper.Http/Middleware/FlypaperMiddleware.cs @@ -7,6 +7,7 @@ using Flypaper.Http.Matching; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Features; +using Microsoft.Extensions.Options; namespace Flypaper.Http.Middleware; @@ -14,17 +15,24 @@ internal sealed class FlypaperMiddleware( RequestDelegate next, TrapMatcher matcher, TrapRunner runner, + IOptions ports, TimeProvider timeProvider) { public async Task InvokeAsync(HttpContext context) { - var request = context.Request; - if (IsInternalHealthProbe(context) || matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None) + if (context.Connection.LocalPort == ports.Value.Dashboard || IsInternalHealthProbe(context)) { await next(context); return; } + var request = context.Request; + if (matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None) + { + context.Response.StatusCode = StatusCodes.Status404NotFound; + return; + } + var session = new TrapSession( Guid.NewGuid(), TrapProtocol.Http, diff --git a/src/Flypaper.Http/PortOptions.cs b/src/Flypaper.Http/PortOptions.cs new file mode 100644 index 0000000..f94cf81 --- /dev/null +++ b/src/Flypaper.Http/PortOptions.cs @@ -0,0 +1,10 @@ +namespace Flypaper.Http; + +public sealed class PortOptions +{ + public const string SectionName = "Flypaper:Ports"; + + public int Trap { get; set; } = 8080; + + public int Dashboard { get; set; } = 8081; +} diff --git a/src/Flypaper.Storage/FlypaperStorageExtensions.cs b/src/Flypaper.Storage/FlypaperStorageExtensions.cs index ba3182e..498b88e 100644 --- a/src/Flypaper.Storage/FlypaperStorageExtensions.cs +++ b/src/Flypaper.Storage/FlypaperStorageExtensions.cs @@ -20,6 +20,7 @@ public static class FlypaperStorageExtensions builder.Configuration.Add(source); builder.Services.AddSingleton(source); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.Configure(builder.Configuration.GetSection(RetentionOptions.SectionName)); builder.Services.AddFlypaperStorage(connectionString); diff --git a/src/Flypaper.Storage/Settings/AdminCredentialStore.cs b/src/Flypaper.Storage/Settings/AdminCredentialStore.cs new file mode 100644 index 0000000..4ac5054 --- /dev/null +++ b/src/Flypaper.Storage/Settings/AdminCredentialStore.cs @@ -0,0 +1,43 @@ +using Flypaper.Storage.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Flypaper.Storage.Settings; + +public sealed class AdminCredentialStore(IDbContextFactory dbContextFactory) +{ + private const string PasswordHashKey = "Flypaper:Admin:PasswordHash"; + + public async Task GetPasswordHashAsync(CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + return await db.Settings.Where(s => s.Key == PasswordHashKey).Select(s => s.Value).SingleOrDefaultAsync(ct); + } + + public async Task TryCreatePasswordHashAsync(string hash, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + db.Settings.Add(new SettingEntity { Key = PasswordHashKey, Value = hash }); + try + { + await db.SaveChangesAsync(ct); + return true; + } + catch (DbUpdateException) + { + return false; + } + } + + public async Task UpdatePasswordHashAsync(string hash, CancellationToken ct = default) + { + await using var db = await dbContextFactory.CreateDbContextAsync(ct); + var updated = await db.Settings + .Where(s => s.Key == PasswordHashKey) + .ExecuteUpdateAsync(setters => setters.SetProperty(s => s.Value, hash), ct); + if (updated == 0) + { + db.Settings.Add(new SettingEntity { Key = PasswordHashKey, Value = hash }); + await db.SaveChangesAsync(ct); + } + } +} diff --git a/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs b/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs index b6416b4..0cf03aa 100644 --- a/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs +++ b/src/Flypaper.Storage/Settings/RuntimeSettingsStore.cs @@ -10,11 +10,13 @@ public sealed partial class RuntimeSettingsStore( DbConfigurationSource source, ILogger logger) { + private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray(); + public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var transaction = await db.Database.BeginTransactionAsync(ct); - await db.Settings.ExecuteDeleteAsync(ct); + await RuntimeSettings(db).ExecuteDeleteAsync(ct); db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value })); await db.SaveChangesAsync(ct); await transaction.CommitAsync(ct); @@ -24,16 +26,19 @@ public sealed partial class RuntimeSettingsStore( public async Task ResetAsync(CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); - await db.Settings.ExecuteDeleteAsync(ct); + await RuntimeSettings(db).ExecuteDeleteAsync(ct); Reload(); } public async Task HasOverridesAsync(CancellationToken ct = default) { await using var db = await dbContextFactory.CreateDbContextAsync(ct); - return await db.Settings.AnyAsync(ct); + return await RuntimeSettings(db).AnyAsync(ct); } + private static IQueryable RuntimeSettings(FlypaperDbContext db) => + db.Settings.Where(setting => RuntimeKeys.Contains(setting.Key)); + private void Reload() { if (!source.TryReload()) diff --git a/src/Flypaper.Web/Auth/AdminAuthenticator.cs b/src/Flypaper.Web/Auth/AdminAuthenticator.cs index c0edb8d..5718606 100644 --- a/src/Flypaper.Web/Auth/AdminAuthenticator.cs +++ b/src/Flypaper.Web/Auth/AdminAuthenticator.cs @@ -1,22 +1,64 @@ using System.Security.Cryptography; using System.Text; +using Flypaper.Storage.Settings; +using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.Options; namespace Flypaper.Web.Auth; -public sealed class AdminAuthenticator(IOptions options) +public sealed class AdminAuthenticator(IOptions options, AdminCredentialStore store) { - public bool IsConfigured => !string.IsNullOrEmpty(options.Value.Password); + public const int MinimumPasswordLength = 12; - public bool Verify(string? candidate) + private static readonly PasswordHasher Hasher = new(); + private static readonly AdminAccount Account = new(); + + public bool UsesEnvironmentPassword => !string.IsNullOrEmpty(options.Value.Password); + + public async Task IsConfiguredAsync(CancellationToken ct = default) => + UsesEnvironmentPassword || await store.GetPasswordHashAsync(ct) is not null; + + public async Task VerifyAsync(string? candidate, CancellationToken ct = default) { - if (!IsConfigured || string.IsNullOrEmpty(candidate)) + if (string.IsNullOrEmpty(candidate)) { return false; } - return CryptographicOperations.FixedTimeEquals(Hash(candidate), Hash(options.Value.Password!)); + if (UsesEnvironmentPassword) + { + return CryptographicOperations.FixedTimeEquals(Sha256(candidate), Sha256(options.Value.Password!)); + } + + return await store.GetPasswordHashAsync(ct) is { } hash + && Hasher.VerifyHashedPassword(Account, hash, candidate) != PasswordVerificationResult.Failed; } - private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value)); + public async Task TrySetInitialPasswordAsync(string password, CancellationToken ct = default) => + !UsesEnvironmentPassword && await store.TryCreatePasswordHashAsync(Hasher.HashPassword(Account, password), ct); + + public async Task TryChangePasswordAsync(string currentPassword, string newPassword, CancellationToken ct = default) + { + if (UsesEnvironmentPassword || !await VerifyAsync(currentPassword, ct)) + { + return false; + } + + await store.UpdatePasswordHashAsync(Hasher.HashPassword(Account, newPassword), ct); + return true; + } + + public static string? ValidateNewPassword(string? password, string? confirmation) + { + if (string.IsNullOrEmpty(password) || password.Length < MinimumPasswordLength) + { + return $"Mindestens {MinimumPasswordLength} Zeichen."; + } + + return password == confirmation ? null : "Die Passwörter stimmen nicht überein."; + } + + private static byte[] Sha256(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value)); + + public sealed class AdminAccount; } diff --git a/src/Flypaper.Web/Auth/AuthEndpoints.cs b/src/Flypaper.Web/Auth/AuthEndpoints.cs index c0b092c..5aa4696 100644 --- a/src/Flypaper.Web/Auth/AuthEndpoints.cs +++ b/src/Flypaper.Web/Auth/AuthEndpoints.cs @@ -18,17 +18,41 @@ public static class AuthEndpoints { var target = IsLocalPath(returnUrl) ? returnUrl! : "/"; - if (!admin.Verify(password)) + if (!await admin.VerifyAsync(password, context.RequestAborted)) { await Task.Delay(750, context.RequestAborted); return Results.LocalRedirect($"/login?error=1&returnUrl={Uri.EscapeDataString(target)}"); } - var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], CookieAuthenticationDefaults.AuthenticationScheme); - await context.SignInAsync(new ClaimsPrincipal(identity)); + await SignInAsync(context); return Results.LocalRedirect(target); }).AllowAnonymous(); + app.MapPost("/auth/setup", async ( + HttpContext context, + AdminAuthenticator admin, + [FromForm] string? password, + [FromForm] string? confirmation) => + { + if (await admin.IsConfiguredAsync(context.RequestAborted)) + { + return Results.LocalRedirect("/login"); + } + + if (AdminAuthenticator.ValidateNewPassword(password, confirmation) is { } error) + { + return Results.LocalRedirect($"/setup?error={Uri.EscapeDataString(error)}"); + } + + if (!await admin.TrySetInitialPasswordAsync(password!, context.RequestAborted)) + { + return Results.LocalRedirect("/login"); + } + + await SignInAsync(context); + return Results.LocalRedirect("/"); + }).AllowAnonymous(); + app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) => { if (!await antiforgery.IsRequestValidAsync(context)) @@ -43,6 +67,12 @@ public static class AuthEndpoints return app; } + private static Task SignInAsync(HttpContext context) + { + var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], CookieAuthenticationDefaults.AuthenticationScheme); + return context.SignInAsync(new ClaimsPrincipal(identity)); + } + private static bool IsLocalPath(string? url) => !string.IsNullOrEmpty(url) && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\')); } diff --git a/src/Flypaper.Web/Components/Pages/Login.razor b/src/Flypaper.Web/Components/Pages/Login.razor index 54b17e3..de7b714 100644 --- a/src/Flypaper.Web/Components/Pages/Login.razor +++ b/src/Flypaper.Web/Components/Pages/Login.razor @@ -3,35 +3,34 @@ @attribute [AllowAnonymous] @using Flypaper.Web.Auth @inject AdminAuthenticator Admin +@inject NavigationManager Navigation Flypaper · Anmelden

Flypaper

-@if (!Admin.IsConfigured) -{ - -} -else -{ -
- - - - - @if (Error is not null) - { -

Passwort falsch.

- } - - -} +
+ + + + + @if (Error is not null) + { +

Passwort falsch.

+ } + + @code { [SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; } [SupplyParameterFromQuery(Name = "returnUrl")] private string? ReturnUrl { get; set; } + + protected override async Task OnInitializedAsync() + { + if (!await Admin.IsConfiguredAsync()) + { + Navigation.NavigateTo("/setup"); + } + } } diff --git a/src/Flypaper.Web/Components/Pages/Settings/PasswordModel.cs b/src/Flypaper.Web/Components/Pages/Settings/PasswordModel.cs new file mode 100644 index 0000000..adf4655 --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Settings/PasswordModel.cs @@ -0,0 +1,10 @@ +namespace Flypaper.Web.Components.Pages.Settings; + +public sealed class PasswordModel +{ + public string? Current { get; set; } + + public string? New { get; set; } + + public string? Confirmation { get; set; } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/PasswordSection.razor b/src/Flypaper.Web/Components/Pages/Settings/PasswordSection.razor new file mode 100644 index 0000000..ff5cf44 --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Settings/PasswordSection.razor @@ -0,0 +1,63 @@ +@using Flypaper.Web.Auth +@inject AdminAuthenticator Admin +@inject NavigationManager Navigation + +
+

Admin-Passwort

+ + @if (Changed == "changed") + { + + } + + @if (Admin.UsesEnvironmentPassword) + { +

Das Passwort kommt aus der Umgebungsvariable Flypaper__Admin__Password und lässt sich nur dort ändern.

+ } + else + { + + + + + + + + + + + + +
+ +
+
+ } +
+ +@code { + private readonly Dictionary _errors = []; + + [SupplyParameterFromForm(FormName = "password")] private PasswordModel? Model { get; set; } + + [SupplyParameterFromQuery(Name = "password")] private string? Changed { get; set; } + + protected override void OnInitialized() => Model ??= new PasswordModel(); + + private async Task ChangeAsync() + { + if (AdminAuthenticator.ValidateNewPassword(Model!.New, Model.Confirmation) is { } error) + { + _errors[nameof(PasswordModel.New)] = error; + return; + } + + if (!await Admin.TryChangePasswordAsync(Model.Current ?? "", Model.New!)) + { + _errors[nameof(PasswordModel.Current)] = "Aktuelles Passwort falsch."; + return; + } + + Navigation.NavigateTo("/settings?password=changed"); + } +} diff --git a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor index 7265507..fd5cefe 100644 --- a/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor +++ b/src/Flypaper.Web/Components/Pages/Settings/SettingsPage.razor @@ -14,6 +14,7 @@ @inject IConfiguration Configuration @inject RuntimeSettingsStore Store @inject AdminAuthenticator Admin +@inject IOptions Ports @inject NavigationManager Navigation Flypaper · Einstellungen @@ -42,7 +43,7 @@ else if (Saved == "reset") - + @@ -89,6 +90,8 @@ else if (Saved == "reset") + +

Nur per Umgebungsvariable

Gelten ab Containerstart und lassen sich hier nicht ändern.

@@ -97,7 +100,8 @@ else if (Saved == "reset") Datenbank@DatabasePath Bekannte Hosts@Format(Configuration.GetSection("Flypaper:Http:KnownHosts").Get()) Vertrauenswürdige Proxies@Format(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get()) - Admin-Passwort@(Admin.IsConfigured ? "gesetzt" : "nicht gesetzt") + Admin-Passwort@(Admin.UsesEnvironmentPassword ? "per Umgebungsvariable" : "im Dashboard festgelegt") + PortsFalle @Ports.Value.Trap, Dashboard @Ports.Value.Dashboard
diff --git a/src/Flypaper.Web/Components/Pages/Setup.razor b/src/Flypaper.Web/Components/Pages/Setup.razor new file mode 100644 index 0000000..baae71a --- /dev/null +++ b/src/Flypaper.Web/Components/Pages/Setup.razor @@ -0,0 +1,36 @@ +@page "/setup" +@layout EmptyLayout +@attribute [AllowAnonymous] +@using Flypaper.Web.Auth +@inject AdminAuthenticator Admin +@inject NavigationManager Navigation + +Flypaper · Einrichten + +

Flypaper einrichten

+ +
+ +

Lege das Admin-Passwort für das Dashboard fest. Diese Seite ist nur erreichbar, solange noch kein Passwort existiert.

+ + + + + @if (Error is not null) + { +

@Error

+ } + + + +@code { + [SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; } + + protected override async Task OnInitializedAsync() + { + if (await Admin.IsConfiguredAsync()) + { + Navigation.NavigateTo("/login"); + } + } +} diff --git a/src/Flypaper.Web/Program.cs b/src/Flypaper.Web/Program.cs index 8d8fdd8..14953a4 100644 --- a/src/Flypaper.Web/Program.cs +++ b/src/Flypaper.Web/Program.cs @@ -11,7 +11,13 @@ using Microsoft.AspNetCore.DataProtection; var builder = WebApplication.CreateBuilder(args); -builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false); +var ports = builder.Configuration.GetSection(PortOptions.SectionName).Get() ?? new PortOptions(); +builder.WebHost.ConfigureKestrel(options => +{ + options.AddServerHeader = false; + options.ListenAnyIP(ports.Trap); + options.ListenAnyIP(ports.Dashboard); +}); builder.AddFlypaperStorage(); builder.Services.AddRazorComponents(); diff --git a/src/Flypaper.Web/appsettings.Development.json b/src/Flypaper.Web/appsettings.Development.json index 24b82b8..9d136b0 100644 --- a/src/Flypaper.Web/appsettings.Development.json +++ b/src/Flypaper.Web/appsettings.Development.json @@ -6,13 +6,12 @@ } }, "Flypaper": { - "Http": { - "KnownHosts": [ - "localhost" - ] - }, "Admin": { "Password": "dev" + }, + "Ports": { + "Trap": 5247, + "Dashboard": 5248 } } } diff --git a/test/Flypaper.Tests/Http/ForwardedHeadersTests.cs b/test/Flypaper.Tests/Http/ForwardedHeadersTests.cs index c761a3f..954d287 100644 --- a/test/Flypaper.Tests/Http/ForwardedHeadersTests.cs +++ b/test/Flypaper.Tests/Http/ForwardedHeadersTests.cs @@ -50,13 +50,38 @@ public sealed class ForwardedHeadersTests ip.ShouldBe(sender); } - private static async Task SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers) + [Theory] + [InlineData("172.19.0.3")] + [InlineData("10.1.2.3")] + [InlineData("192.168.1.2")] + [InlineData("127.0.0.1")] + [InlineData("fd00::2")] + public async Task Trusts_private_networks_by_default(string proxy) + { + var ip = await SendAsync(IPAddress.Parse(proxy), trustedProxy: null, ("X-Real-IP", Client)); + + ip.ShouldBe(IPAddress.Parse(Client)); + } + + [Fact] + public async Task Configured_proxies_replace_the_default_networks() + { + var sender = IPAddress.Parse("192.168.1.2"); + + var ip = await SendAsync(sender, ("X-Real-IP", Client)); + + ip.ShouldBe(sender); + } + + private static Task SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers) => + SendAsync(remoteIp, "172.18.0.0/16", headers); + + private static async Task SendAsync(IPAddress remoteIp, string? trustedProxy, params (string Name, string Value)[] headers) { var configuration = new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { - ["Flypaper:Http:KnownHosts:0"] = "dashboard.lan", - ["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16" + ["Flypaper:Http:TrustedProxies:0"] = trustedProxy }) .Build(); @@ -78,6 +103,7 @@ public sealed class ForwardedHeadersTests var httpContext = new DefaultHttpContext { RequestServices = services }; httpContext.Connection.RemoteIpAddress = remoteIp; + httpContext.Connection.LocalPort = 8081; httpContext.Request.Host = new HostString("dashboard.lan"); httpContext.Request.Path = "/"; foreach (var (name, value) in headers) diff --git a/test/Flypaper.Tests/Http/HealthProbeTests.cs b/test/Flypaper.Tests/Http/HealthProbeTests.cs index f6d6ebd..3210231 100644 --- a/test/Flypaper.Tests/Http/HealthProbeTests.cs +++ b/test/Flypaper.Tests/Http/HealthProbeTests.cs @@ -71,6 +71,7 @@ public sealed class HealthProbeTests var httpContext = new DefaultHttpContext { RequestServices = services }; httpContext.Connection.RemoteIpAddress = remoteIp; + httpContext.Connection.LocalPort = 8080; httpContext.Request.Host = new HostString("flypaper:8080"); httpContext.Request.Path = path; diff --git a/test/Flypaper.Tests/Http/PortSeparationTests.cs b/test/Flypaper.Tests/Http/PortSeparationTests.cs new file mode 100644 index 0000000..1bdcc05 --- /dev/null +++ b/test/Flypaper.Tests/Http/PortSeparationTests.cs @@ -0,0 +1,94 @@ +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 PortSeparationTests +{ + private const int TrapPort = 8080; + private const int DashboardPort = 8081; + private static readonly IPAddress PublicIp = IPAddress.Parse("203.0.113.9"); + + [Theory] + [InlineData("unknown.example", "/")] + [InlineData("unknown.example", "/.env")] + [InlineData("203.0.113.7", "/wp-login.php")] + public async Task Dashboard_port_never_traps(string host, string path) + { + var (reachedApp, _) = await SendAsync(DashboardPort, host, path); + + reachedApp.ShouldBeTrue(); + } + + [Theory] + [InlineData("unknown.example", "/")] + [InlineData("203.0.113.7", "/settings")] + [InlineData("example.com", "/.env")] + public async Task Trap_port_traps_unknown_hosts_and_trap_paths(string host, string path) + { + var (reachedApp, status) = await SendAsync(TrapPort, host, path); + + reachedApp.ShouldBeFalse(); + status.ShouldBe(StatusCodes.Status404NotFound); + } + + [Theory] + [InlineData("/")] + [InlineData("/settings")] + [InlineData("/login")] + public async Task Trap_port_answers_other_paths_of_known_hosts_with_plain_404(string path) + { + var sink = Substitute.For(); + + var (reachedApp, status) = await SendAsync(TrapPort, "example.com", path, sink); + + reachedApp.ShouldBeFalse(); + status.ShouldBe(StatusCodes.Status404NotFound); + sink.DidNotReceiveWithAnyArgs().Publish(default!); + } + + private static async Task<(bool ReachedApp, int Status)> SendAsync(int localPort, string host, string path, ITrapEventSink? sink = null) + { + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Flypaper:MaxConnections"] = "0", + ["Flypaper:Http:KnownHosts:0"] = "example.com", + ["Flypaper:Http:TrapPaths:0"] = "/.env" + }) + .Build(); + + var services = new ServiceCollection() + .AddLogging() + .AddSingleton(sink ?? 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 = PublicIp; + httpContext.Connection.LocalPort = localPort; + httpContext.Request.Host = new HostString(host); + httpContext.Request.Path = path; + + await app.Build()(httpContext); + return (reachedApp, httpContext.Response.StatusCode); + } +} diff --git a/test/Flypaper.Tests/Web/AdminSetupTests.cs b/test/Flypaper.Tests/Web/AdminSetupTests.cs new file mode 100644 index 0000000..df683e7 --- /dev/null +++ b/test/Flypaper.Tests/Web/AdminSetupTests.cs @@ -0,0 +1,156 @@ +using System.Net; +using System.Text.RegularExpressions; +using Flypaper.Web.Auth; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Data.Sqlite; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; + +namespace Flypaper.Tests.Web; + +public sealed partial class AdminSetupTests : IDisposable +{ + private const string Password = "correct-horse-battery"; + + private readonly string _dbPath = Path.Combine(Path.GetTempPath(), $"flypaper-setup-{Guid.NewGuid():N}.db"); + private readonly List> _factories = []; + + [Fact] + public async Task Without_password_login_leads_to_setup() + { + using var client = CreateClient(environmentPassword: null); + + var response = await client.GetAsync("/login"); + + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location!.OriginalString.ShouldEndWith("/setup"); + (await client.GetAsync("/setup")).StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task Setup_sets_password_signs_in_and_closes_itself() + { + using var client = CreateClient(environmentPassword: null); + + var response = await PostFormAsync(client, "/setup", "/auth/setup", ("password", Password), ("confirmation", Password)); + + response.StatusCode.ShouldBe(HttpStatusCode.Redirect); + response.Headers.Location!.OriginalString.ShouldBe("/"); + (await client.GetAsync("/")).StatusCode.ShouldBe(HttpStatusCode.OK); + + var setupAgain = await client.GetAsync("/setup"); + setupAgain.StatusCode.ShouldBe(HttpStatusCode.Redirect); + setupAgain.Headers.Location!.OriginalString.ShouldEndWith("/login"); + } + + [Fact] + public async Task Second_setup_cannot_replace_the_password() + { + using var first = CreateClient(environmentPassword: null); + await PostFormAsync(first, "/setup", "/auth/setup", ("password", Password), ("confirmation", Password)); + + using var attacker = CreateClient(environmentPassword: null); + var token = await AntiforgeryTokenAsync(attacker, "/login"); + var response = await attacker.PostAsync("/auth/setup", Form(token, ("password", "attacker-password-1"), ("confirmation", "attacker-password-1"))); + + response.Headers.Location!.OriginalString.ShouldBe("/login"); + var admin = _factories[0].Services.GetRequiredService(); + (await admin.VerifyAsync(Password)).ShouldBeTrue(); + (await admin.VerifyAsync("attacker-password-1")).ShouldBeFalse(); + } + + [Theory] + [InlineData("short", "short")] + [InlineData("long-enough-password", "other-long-password")] + public async Task Setup_rejects_weak_or_mismatched_passwords(string password, string confirmation) + { + using var client = CreateClient(environmentPassword: null); + + var response = await PostFormAsync(client, "/setup", "/auth/setup", ("password", password), ("confirmation", confirmation)); + + response.Headers.Location!.OriginalString.ShouldStartWith("/setup?error="); + (await _factories[0].Services.GetRequiredService().IsConfiguredAsync()).ShouldBeFalse(); + } + + [Fact] + public async Task Environment_password_overrides_setup() + { + using var client = CreateClient(environmentPassword: Password); + + var setup = await client.GetAsync("/setup"); + setup.StatusCode.ShouldBe(HttpStatusCode.Redirect); + setup.Headers.Location!.OriginalString.ShouldEndWith("/login"); + + var login = await PostFormAsync(client, "/login", "/auth/login", ("password", Password)); + login.Headers.Location!.OriginalString.ShouldBe("/"); + + var admin = _factories[0].Services.GetRequiredService(); + admin.UsesEnvironmentPassword.ShouldBeTrue(); + (await admin.TrySetInitialPasswordAsync("another-long-password")).ShouldBeFalse(); + (await admin.TryChangePasswordAsync(Password, "another-long-password")).ShouldBeFalse(); + } + + [Fact] + public async Task Password_can_be_changed_with_the_current_one() + { + using var client = CreateClient(environmentPassword: null); + var admin = _factories[0].Services.GetRequiredService(); + (await admin.TrySetInitialPasswordAsync(Password)).ShouldBeTrue(); + + (await admin.TryChangePasswordAsync("wrong-current-pw", "new-password-12345")).ShouldBeFalse(); + (await admin.TryChangePasswordAsync(Password, "new-password-12345")).ShouldBeTrue(); + + (await admin.VerifyAsync(Password)).ShouldBeFalse(); + (await admin.VerifyAsync("new-password-12345")).ShouldBeTrue(); + } + + private HttpClient CreateClient(string? environmentPassword) + { + var factory = _factories.FirstOrDefault() ?? new WebApplicationFactory().WithWebHostBuilder(builder => + { + builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}"); + builder.UseSetting("Flypaper:Ports:Dashboard", "0"); + builder.UseSetting("Flypaper:Admin:Password", environmentPassword ?? ""); + }); + + if (_factories.Count == 0) + { + _factories.Add(factory); + } + + return factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + } + + private static async Task PostFormAsync( + HttpClient client, + string formPage, + string action, + params (string Name, string Value)[] fields) => + await client.PostAsync(action, Form(await AntiforgeryTokenAsync(client, formPage), fields)); + + private static async Task AntiforgeryTokenAsync(HttpClient client, string page) + { + var html = await client.GetStringAsync(page); + return TokenPattern().Match(html).Groups[1].Value; + } + + private static FormUrlEncodedContent Form(string token, params (string Name, string Value)[] fields) => + new(fields.Select(f => KeyValuePair.Create(f.Name, f.Value)).Append(KeyValuePair.Create("__RequestVerificationToken", token))); + + [GeneratedRegex("name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"")] + private static partial Regex TokenPattern(); + + public void Dispose() + { + foreach (var factory in _factories) + { + factory.Dispose(); + } + + SqliteConnection.ClearAllPools(); + foreach (var suffix in new[] { "", "-wal", "-shm" }) + { + File.Delete(_dbPath + suffix); + } + } +} diff --git a/test/Flypaper.Tests/Web/HealthEndpointTests.cs b/test/Flypaper.Tests/Web/HealthEndpointTests.cs index 153d866..1eb81e3 100644 --- a/test/Flypaper.Tests/Web/HealthEndpointTests.cs +++ b/test/Flypaper.Tests/Web/HealthEndpointTests.cs @@ -15,7 +15,7 @@ public sealed class HealthEndpointTests : IDisposable _factory = new WebApplicationFactory().WithWebHostBuilder(builder => { builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}"); - builder.UseSetting("Flypaper:Http:KnownHosts:0", "localhost"); + builder.UseSetting("Flypaper:Ports:Dashboard", "0"); }); }