4 Commits
Author SHA1 Message Date
TomandClaude Opus 5.5 4168e9990b Add Unraid template, icon and privilege-dropping entrypoint
Build and deploy / build (push) Successful in 1m32s
Build and deploy / deploy (push) Successful in 22s
Release / image (push) Successful in 1m57s
Release / release (push) Successful in 7s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:35:46 +01:00
TomandClaude Opus 5.5 0984af25bc Build multi-arch release images without emulation
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:31:06 +01:00
TomandClaude Opus 5.5 7c3657d015 Add versioning, release workflow and changelog
Build and deploy / build (push) Successful in 1m56s
Build and deploy / deploy (push) Successful in 22s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:25:11 +01:00
TomandClaude Opus 5.5 c22d452720 Separate dashboard port, first-run password setup and default trusted proxies
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 17:21:49 +01:00
35 changed files with 1001 additions and 116 deletions

No files matched your search

+2
View File
@@ -7,3 +7,5 @@
.idea/ .idea/
test/ test/
.gitea/ .gitea/
unraid/
deploy/
+16 -10
View File
@@ -1,6 +1,7 @@
# Builds the image on every push to main, pushes it to the Gitea registry (tagged # 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 # :main AND the short commit SHA, for rollback) and deploys the stack on Unraid
# from deploy/unraid/compose.yaml (Tom's personal Unraid setup). # from deploy/unraid/compose.yaml (Tom's personal Unraid setup). Releases (:latest,
# :X.Y.Z) come from version tags in release.yml and are never deployed here.
# #
# The deploy works because the act_runner runs ON Unraid and hands its Docker # 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 # socket to the job: every `docker` command here talks to the Unraid daemon, so
@@ -58,13 +59,18 @@ jobs:
id: sha id: sha
run: echo "short=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT" run: echo "short=$(git rev-parse --short HEAD)" >> "$GITHUB_OUTPUT"
- name: Build and push (:latest and :<sha>) # amd64 only: these builds exist for the Unraid deploy (x86_64), and a
# single platform keeps every push fast. Releases are multi-arch.
- name: Build and push (:main and :<sha>)
uses: docker/build-push-action@v6 uses: docker/build-push-action@v6
with: with:
context: . context: .
platforms: linux/amd64
push: true push: true
build-args: |
VERSION=0.0.0-dev+${{ steps.sha.outputs.short }}
tags: | tags: |
${{ env.IMAGE }}:latest ${{ env.IMAGE }}:main
${{ env.IMAGE }}:${{ steps.sha.outputs.short }} ${{ env.IMAGE }}:${{ steps.sha.outputs.short }}
deploy: deploy:
@@ -111,15 +117,15 @@ jobs:
docker compose -f deploy/unraid/compose.yaml up -d --wait --remove-orphans 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 # /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 # checked from inside proxynet on both ports: 8080 is the trap, reached the
# comes from a private address, so /health is exempt from the trap even # same way NPM reaches it (the probe comes from a private address, so /health
# though the Host header (flypaper) is unknown. A failure marks the run red; # is exempt from the trap), 8081 is the dashboard. A failure marks the run
# the rollback stays a deliberate step. # red; the rollback stays a deliberate step.
- name: Health gate - name: Health gate
run: | run: |
for attempt in $(seq 1 30); do for attempt in $(seq 1 30); do
if docker run --rm --network proxynet busybox:1.37 \ if docker run --rm --network proxynet busybox:1.37 sh -c \
wget -qO- http://flypaper:8080/health; then 'wget -qO- http://flypaper:8080/health && wget -qO- http://flypaper:8081/health'; then
exit 0 exit 0
fi fi
sleep 2 sleep 2
+115
View File
@@ -0,0 +1,115 @@
# Builds a release when a version tag (vX.Y.Z) is pushed: a multi-arch image
# (linux/amd64, linux/arm64) is tagged :X.Y.Z, :X.Y, :X and :latest in the Gitea
# registry, and a Gitea release is created with the matching section of
# CHANGELOG.md as notes. Nothing is deployed; Tom's Unraid follows :main through
# deploy.yml.
#
# A pre-release tag such as v0.2.0-rc.1 only gets its own :0.2.0-rc.1 tag and a
# release marked as pre-release; :latest and the short tags stay on the last
# stable version.
#
# Required repository secrets: REGISTRY_USER, REGISTRY_TOKEN (see deploy.yml).
# The release itself uses the job's built-in token.
name: Release
on:
push:
tags: ["v*"]
env:
IMAGE: gitea.anticarnist.de/tom/flypaper
jobs:
image:
runs-on: ubuntu-latest
outputs:
version: ${{ steps.version.outputs.version }}
prerelease: ${{ steps.version.outputs.prerelease }}
steps:
- name: Check out the source
uses: actions/checkout@v4
- name: Read the version from the tag
id: version
run: |
version="${GITHUB_REF_NAME#v}"
if ! echo "$version" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$'; then
echo "Tag $GITHUB_REF_NAME is not vX.Y.Z" >&2
exit 1
fi
echo "version=$version" >> "$GITHUB_OUTPUT"
{
echo "tags<<EOF"
echo "$IMAGE:$version"
case "$version" in
*-*) ;;
*)
echo "$IMAGE:${version%.*}"
echo "$IMAGE:${version%%.*}"
echo "$IMAGE:latest"
;;
esac
echo "EOF"
} >> "$GITHUB_OUTPUT"
case "$version" in
*-*) echo "prerelease=true" >> "$GITHUB_OUTPUT" ;;
*) echo "prerelease=false" >> "$GITHUB_OUTPUT" ;;
esac
- 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 }}
# No QEMU: the Dockerfile compiles natively on the runner and cross-publishes
# for each architecture; the arm64 runtime stage only copies files. Setting
# up QEMU would also register binfmt handlers on the Unraid host kernel.
- name: Build and push the release tags
uses: docker/build-push-action@v6
with:
context: .
platforms: linux/amd64,linux/arm64
push: true
build-args: |
VERSION=${{ steps.version.outputs.version }}
tags: ${{ steps.version.outputs.tags }}
release:
needs: image
runs-on: ubuntu-latest
steps:
- name: Check out the source
uses: actions/checkout@v4
# The notes are the CHANGELOG.md section of this version, from its heading
# up to the next one. If the API call fails, the images are still pushed;
# the release can then be created by hand (deploy/unraid/README.md).
- name: Create the Gitea release
env:
VERSION: ${{ needs.image.outputs.version }}
PRERELEASE: ${{ needs.image.outputs.prerelease }}
TOKEN: ${{ github.token }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}/releases
run: |
notes=$(awk -v version="$VERSION" '
/^## \[/ { if (found) exit; if (index($0, "[" version "]")) { found = 1; next } }
/^\[[^]]+\]: / { if (found) exit }
found { print }
' CHANGELOG.md)
[ -n "$notes" ] || notes="See CHANGELOG.md."
jq -n \
--arg tag "$GITHUB_REF_NAME" \
--arg name "Flypaper $VERSION" \
--arg body "$notes" \
--argjson prerelease "$PRERELEASE" \
'{tag_name: $tag, name: $name, body: $body, prerelease: $prerelease}' > release.json
curl -fsS -X POST "$API" \
-H "Authorization: token $TOKEN" \
-H "Content-Type: application/json" \
--data @release.json
+36
View File
@@ -0,0 +1,36 @@
# Changelog
All notable changes to Flypaper are documented in this file. The format follows
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.1.0] - 2026-11-14
First release.
### Added
- HTTP tarpit on its own port (8080): every request is caught and answered with endless,
plausible HTML in random chunks of 1–64 bytes with random pauses of 50 ms–1 s.
- Connection governor with limits overall and per IP and a maximum hold time; requests
without a free slot get a quick 404.
- Optional known hosts that are caught only on configurable trap paths.
- Client IP from `X-Real-IP` / `X-Forwarded-For`, trusting private networks by default.
- One log line per catch and storage in SQLite, enriched with country, city and ASN from the
DB-IP Lite databases (downloaded and refreshed monthly, existing catches backfilled).
- Dashboard on its own port (8081): totals, world map, top countries, providers, IPs and
paths, latest catches with expandable rows.
- Settings page for trap paths, known hosts, limits, retention and the private-network filter,
effective without a restart; deleting private or all catches.
- Admin password set on first visit (stored as a salted hash) and changeable later, or fixed
with `Flypaper__Admin__Password`.
- Daily retention cleanup (90 days by default), `/health` endpoint, Docker image running as
non-root with all data under `/data`.
- Public images for `linux/amd64` and `linux/arm64` in the Gitea registry.
- Unraid Docker template; when started as root, the container hands `/data` to its app user
and drops privileges.
[Unreleased]: https://gitea.anticarnist.de/Tom/Flypaper/compare/v0.1.0...main
[0.1.0]: https://gitea.anticarnist.de/Tom/Flypaper/releases/tag/v0.1.0
+1
View File
@@ -4,5 +4,6 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors> <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>0.0.0-dev</Version>
</PropertyGroup> </PropertyGroup>
</Project> </Project>
+20 -7
View File
@@ -1,4 +1,8 @@
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build # The SDK stage runs natively on the build machine and cross-publishes for the
# target architecture. The runtime stage only copies files and sets metadata, so a
# multi-arch build needs no QEMU emulation at all.
FROM --platform=$BUILDPLATFORM mcr.microsoft.com/dotnet/sdk:10.0 AS build
ARG TARGETARCH
WORKDIR /src WORKDIR /src
COPY Directory.Build.props Directory.Packages.props ./ COPY Directory.Build.props Directory.Packages.props ./
@@ -7,25 +11,34 @@ COPY src/Flypaper.GeoIp/Flypaper.GeoIp.csproj src/Flypaper.GeoIp/
COPY src/Flypaper.Http/Flypaper.Http.csproj src/Flypaper.Http/ COPY src/Flypaper.Http/Flypaper.Http.csproj src/Flypaper.Http/
COPY src/Flypaper.Storage/Flypaper.Storage.csproj src/Flypaper.Storage/ COPY src/Flypaper.Storage/Flypaper.Storage.csproj src/Flypaper.Storage/
COPY src/Flypaper.Web/Flypaper.Web.csproj src/Flypaper.Web/ COPY src/Flypaper.Web/Flypaper.Web.csproj src/Flypaper.Web/
RUN dotnet restore src/Flypaper.Web/Flypaper.Web.csproj RUN dotnet restore src/Flypaper.Web/Flypaper.Web.csproj -a $TARGETARCH
COPY src/ src/ COPY src/ src/
RUN dotnet publish src/Flypaper.Web/Flypaper.Web.csproj -c Release -o /app --no-restore ARG VERSION=0.0.0-dev
RUN dotnet publish src/Flypaper.Web/Flypaper.Web.csproj -c Release -a $TARGETARCH -o /app --no-restore -p:Version=$VERSION \
&& mkdir /data
FROM mcr.microsoft.com/dotnet/aspnet:10.0 FROM mcr.microsoft.com/dotnet/aspnet:10.0
ARG VERSION=0.0.0-dev
WORKDIR /app WORKDIR /app
RUN mkdir /data && chown $APP_UID /data LABEL org.opencontainers.image.title="Flypaper" \
org.opencontainers.image.description="Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis." \
org.opencontainers.image.source="https://gitea.anticarnist.de/Tom/Flypaper" \
org.opencontainers.image.licenses="MIT" \
org.opencontainers.image.version=$VERSION
ENV ASPNETCORE_HTTP_PORTS=8080 \ ENV ASPNETCORE_HTTP_PORTS= \
ConnectionStrings__Flypaper="Data Source=/data/flypaper.db" \ ConnectionStrings__Flypaper="Data Source=/data/flypaper.db" \
Flypaper__DataProtection__KeysPath=/data/keys \ Flypaper__DataProtection__KeysPath=/data/keys \
Flypaper__GeoIp__Directory=/data/geoip Flypaper__GeoIp__Directory=/data/geoip
COPY --from=build --chown=1654:1654 /data /data
COPY --from=build /app . COPY --from=build /app .
COPY --chmod=755 docker-entrypoint.sh /usr/local/bin/flypaper-entrypoint
USER $APP_UID USER $APP_UID
EXPOSE 8080 EXPOSE 8080 8081
VOLUME /data VOLUME /data
ENTRYPOINT ["dotnet", "Flypaper.Web.dll"] ENTRYPOINT ["flypaper-entrypoint"]
+112 -43
View File
@@ -18,14 +18,14 @@ flowchart LR
proxy -->|"unknown host or trap path<br/>+ X-Real-IP"| flypaper["Flypaper"] proxy -->|"unknown host or trap path<br/>+ X-Real-IP"| flypaper["Flypaper"]
flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot flypaper -.->|"endless HTML,<br/>a few bytes at a time"| bot
flypaper --> db[("SQLite:<br/>catches, settings")] flypaper --> db[("SQLite:<br/>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 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 default/catch-all server) goes to Flypaper, optionally also a few bait paths on your real
domains. domains.
2. Flypaper looks at the `Host` header. A request for a host it doesn't know, or for a trap path, 2. Flypaper listens on two ports. Port `8080` is the trap: everything that arrives there is
is caught. Requests for a known host (the dashboard's) pass through to the dashboard. 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 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. 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 4. A connection governor caps the number of catches overall and per IP and ends every catch
@@ -48,36 +48,35 @@ flowchart LR
- **Retention**: old catches are deleted daily (90 days by default); catches from private - **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 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 - **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 - **Health endpoint** `/health` for container health checks (on the trap port it answers only
addresses) to private addresses)
- **No configuration needed to start**: one volume, two ports, the admin password is set on
first visit
## Quick start ## Quick start
There is no public image; build it from source. Images for `linux/amd64` and `linux/arm64` (e.g. Raspberry Pi 4/5 with a 64-bit OS) are
published in the author's Gitea registry; no login is needed to pull. No environment variable
is required.
```bash ```bash
git clone <repository-url> flypaper docker run -d --name flypaper --restart unless-stopped \
cd flypaper -p 8080:8080 -p 127.0.0.1:8081:8081 \
-v flypaper-data:/data \
gitea.anticarnist.de/tom/flypaper:latest
``` ```
Create a `compose.yaml` next to the `Dockerfile`: Or with Compose:
```yaml ```yaml
services: services:
flypaper: flypaper:
build: . image: gitea.anticarnist.de/tom/flypaper:latest
image: flypaper:local
container_name: flypaper container_name: flypaper
restart: unless-stopped restart: unless-stopped
ports: ports:
- "8080:8080" - "8080:8080" # trap: point your reverse proxy here
environment: - "127.0.0.1:8081:8081" # dashboard: LAN or localhost only
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}
volumes: volumes:
- flypaper-data:/data - flypaper-data:/data
@@ -85,15 +84,15 @@ volumes:
flypaper-data: flypaper-data:
``` ```
```bash You can also build the image yourself: clone the repository and replace the `image:` line with
FLYPAPER_ADMIN_PASSWORD='a-long-random-password' docker compose up -d --build `build: .`, or run `docker build -t flypaper .`.
```
- Dashboard: <http://localhost:8080>, log in with the password. - Dashboard: <http://localhost:8081>. On the first visit Flypaper asks you to set the admin
- See the trap in action (any unknown host works): password; afterwards you log in with it and can change it on the settings page.
- See the trap in action:
```bash ```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 This catch comes from a private address and is therefore not stored; the log line ends with
@@ -107,15 +106,78 @@ The files in [`deploy/unraid/`](deploy/unraid) and `.gitea/workflows/deploy.yml`
author's personal deployment (Gitea Actions to Unraid). They are an example only and not author's personal deployment (Gitea Actions to Unraid). They are an example only and not
needed to run Flypaper. needed to run Flypaper.
## Unraid
[`unraid/flypaper.xml`](unraid/flypaper.xml) is a Docker template for Unraid. It sets up both
ports, the appdata folder `/mnt/user/appdata/flypaper` and the optional variables (under
*Show more settings*).
1. Copy the template to the flash drive, in the Unraid terminal:
```bash
wget -O /boot/config/plugins/dockerMan/templates-user/my-Flypaper.xml \
https://gitea.anticarnist.de/Tom/Flypaper/raw/branch/main/unraid/flypaper.xml
```
2. **Docker → Add Container**, pick *Flypaper* under the user templates, choose free host ports
(8080 is often taken on Unraid) and **Apply**.
3. Open the WebUI (the dashboard port) and set the admin password.
Unraid can also read templates from a *template repository* (Docker tab, Advanced View), but
that feature is built around GitHub repositories and may not accept this Gitea URL; the manual
copy above always works.
The template starts the container as root (`--user 0:0`) only so it can hand the appdata folder
to its app user; Flypaper then drops to UID 1654 for good. Without it, a freshly created appdata
folder belongs to root and the database cannot be created.
**Connecting Nginx Proxy Manager:** follow the [NPM section](#nginx-proxy-manager) below. If NPM
runs in a user-defined Docker network (e.g. `proxynet`), put Flypaper into the same network
(*Network Type* in the template) and use `http://Flypaper:8080` as the target. If NPM can't
share a network with it, forward to `http://<unraid-ip>:<trap-port>` instead. Either way the
request comes from a private address, which Flypaper trusts by default.
The template is not part of the official Community Applications yet; that needs a separate
submission.
## Versions and updates
Flypaper follows [Semantic Versioning](https://semver.org); every release is listed in
[CHANGELOG.md](CHANGELOG.md). The running version is shown in the dashboard footer and in the
first log line.
| Image tag | Meaning |
|---|---|
| `:latest` | The newest release. The right choice for most setups. |
| `:X.Y.Z` | A fixed release, e.g. `:0.1.0`. Pin it if you update deliberately. |
| `:X.Y`, `:X` | The newest release of that minor or major line. |
| `:main` | Development build of every commit on `main`. May break. |
Pull a fixed version with `docker pull gitea.anticarnist.de/tom/flypaper:0.1.0`. To build a
specific release from source instead:
```bash
git checkout v0.1.0
docker build --build-arg VERSION=0.1.0 -t flypaper:0.1.0 .
```
To update, pull or rebuild the image and recreate the container
(`docker compose pull && docker compose up -d`). The database is migrated automatically on
start; back up the `/data` volume first. Before 1.0, a minor version may contain breaking
changes, so read the changelog.
## Behind a reverse proxy ## 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: apply to every proxy:
- **Set `X-Real-IP`** (and `X-Forwarded-For`) to the client address. - **Set `X-Real-IP`** (and `X-Forwarded-For`) to the client address.
- **Trust the proxy in Flypaper**: `Flypaper__Http__TrustedProxies__0` must contain the - **Flypaper must trust the proxy.** By default it trusts every private network (`10/8`,
proxy's IP or subnet. Headers from anyone else are ignored, so bots can't fake their `172.16/12`, `192.168/16`, loopback, `fc00::/7`), which covers a proxy in a Docker network
address. For 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 ```bash
docker network inspect <network> -f '{{(index .IPAM.Config 0).Subnet}}' docker network inspect <network> -f '{{(index .IPAM.Config 0).Subnet}}'
@@ -129,11 +191,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 - **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. Flypaper. This is where almost all scanners end up.
- **Optionally, trap paths on your real domains.** Forward only the bait paths, e.g. `/.env` - **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, or `/wp-login.php`, from your real sites to Flypaper. Every request on the trap port is
so these requests are caught as well. caught, so nothing else is needed.
Never forward a whole domain that is listed as a known host: its other paths would show the *Known hosts* (optional) change this for hosts you list: on the trap port, a known host is
dashboard login. 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 ### Nginx Proxy Manager
@@ -210,7 +275,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 ### Caddy
@@ -256,13 +321,14 @@ labels:
### Environment variables ### 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 | | Variable | Purpose | Default |
|---|---|---| |---|---|---|
| `Flypaper__Http__KnownHosts__0` | Host names that reach the dashboard (`*.example.com` allowed). Every other host is trapped. | 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` | loopback only | | `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__Admin__Password` | Dashboard password. Without it the dashboard stays locked. | none | | `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` | | `ConnectionStrings__Flypaper` | SQLite database | `Data Source=/data/flypaper.db` |
| `Flypaper__DataProtection__KeysPath` | Keys for login cookies and forms | `/data/keys` | | `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` | | `Flypaper__GeoIp__Directory` | Folder for the DB-IP databases; empty disables GeoIP | `/data/geoip` |
@@ -290,10 +356,13 @@ reset button removes all saved values.
## Security notes ## Security notes
- **Keep the dashboard internal.** Only list internal names or LAN addresses as known hosts - **Keep the dashboard internal.** Publish port `8081` only to your LAN or to localhost and
and never route a known host through your public proxy. never forward it from your public proxy.
- **Use a strong admin password.** The login runs over plain HTTP unless you put the - **Finish the setup before the dashboard is reachable by anyone else.** Until a password is
dashboard behind TLS yourself. 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 - **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 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 handle (nginx: `worker_connections`), and keep the per-IP limit low so a single scanner
@@ -315,7 +384,7 @@ dotnet run --project src/Flypaper.Web
``` ```
`dotnet run` starts in the Development environment: the dashboard is at `dotnet run` starts in the Development environment: the dashboard is at
<http://localhost:5248> (known host `localhost`, password `dev`), the database is <http://localhost:5248> (password `dev`), the trap at <http://localhost:5247>, the database is
`src/Flypaper.Web/flypaper.db`, and GeoIP is off unless `Flypaper__GeoIp__Directory` is set. `src/Flypaper.Web/flypaper.db`, and GeoIP is off unless `Flypaper__GeoIp__Directory` is set.
`docker build -t flypaper .` builds the image. `docker build -t flypaper .` builds the image.
+36 -9
View File
@@ -5,9 +5,35 @@ describes a generic installation.
Every push to `main` (except docs and `.md` files) runs `.gitea/workflows/deploy.yml` on the 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 act_runner on Unraid: it builds the image, pushes it to
`gitea.anticarnist.de/tom/flypaper` (`:latest` and `:<short-sha>`), deploys `gitea.anticarnist.de/tom/flypaper` (`:main` and `:<short-sha>`), deploys
`deploy/unraid/compose.yaml` and waits for `/health`. A manual run is possible from the Actions `deploy/unraid/compose.yaml` and waits for `/health`. A manual run is possible from the Actions
tab (`workflow_dispatch`). tab (`workflow_dispatch`). The stack follows `:main`, not the releases.
## Releases
A version tag runs `.gitea/workflows/release.yml`: it builds the image with that version,
pushes `:X.Y.Z`, `:X.Y`, `:X` and `:latest` (a pre-release such as `v0.2.0-rc.1` gets only
its own tag) and creates a Gitea release with the version's section of `CHANGELOG.md` as
notes. Nothing is deployed.
1. Move the entries under `[Unreleased]` in `CHANGELOG.md` into a new version section with
today's date, update the links at the bottom, commit and push.
2. Tag and push:
```bash
git tag -a v0.1.0 -m "Flypaper 0.1.0"
git push origin v0.1.0
```
The registry serves the images to anyone because the `Tom` account is public; packages
inherit the visibility of their owner, not of the repository. To show the package on the
repository page, link it once: Gitea → Tom → Packages → `flypaper` → Settings → Link to
repository `Flypaper` (or `POST /api/v1/packages/Tom/container/flypaper/-/link/Flypaper` with
a token that has `write:package`).
If the release step fails (e.g. the built-in token may not create releases), the images are
already pushed. Create the release by hand: Gitea → repo → Releases → New Release, pick the
tag, title `Flypaper X.Y.Z`, paste the changelog section.
## Secrets ## Secrets
@@ -32,13 +58,14 @@ deploy.
## Access ## Access
- Dashboard: `http://192.168.1.14:44307` (LAN only, login with `FLYPAPER_ADMIN_PASSWORD`) - Dashboard: `http://192.168.1.14:44307` → container port `8081` (LAN only, login with
- Trap: NPM forwards to `flypaper:8080` over `proxynet`. Every Host header other than the `FLYPAPER_ADMIN_PASSWORD`)
dashboard host lands in the trap, as do the trap paths on known hosts. - Trap: NPM forwards to `flypaper:8080` over `proxynet`. Everything on that port is
- `/health` answers only to private addresses; from public addresses it is a trap like any trapped.
other path. - `/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 ## Rollback
Pin the image in `compose.yaml` to a previous `:<short-sha>` and push, or deploy that tag Pin the image in `compose.yaml` to a previous `:<short-sha>` or a release `:X.Y.Z` and push,
manually on Unraid. or deploy that tag manually on Unraid.
+8 -9
View File
@@ -3,8 +3,8 @@
# .gitea/workflows/deploy.yml, not pasted into the Compose Manager. # .gitea/workflows/deploy.yml, not pasted into the Compose Manager.
# #
# NPM reaches the trap as flypaper:8080 over the external network proxynet (default # 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 # site for unknown hosts, trap paths on the real domains). The dashboard has its own
# from the LAN on the host port: http://192.168.1.14:44307. # port 8081, published only to the LAN: http://192.168.1.14:44307.
# #
# `restart: always`, not `unless-stopped`: Unraid stops every container explicitly # `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 # when Docker or the array goes down, and `unless-stopped` treats that as a manual
@@ -14,15 +14,14 @@ name: flypaper
services: services:
flypaper: flypaper:
image: gitea.anticarnist.de/tom/flypaper:latest # :main follows every push to main; releases are tagged :X.Y.Z and :latest.
image: gitea.anticarnist.de/tom/flypaper:main
container_name: flypaper container_name: flypaper
restart: always restart: always
ports: ports:
- "44307:8080" - "44307:8081"
environment: environment:
TZ: Europe/Berlin 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. # Subnet of proxynet: only NPM may set X-Forwarded-For / X-Real-IP.
Flypaper__Http__TrustedProxies__0: 172.19.0.0/16 Flypaper__Http__TrustedProxies__0: 172.19.0.0/16
# From the repository secret, never in the repo. # From the repository secret, never in the repo.
@@ -34,9 +33,9 @@ services:
networks: networks:
- proxynet - proxynet
healthcheck: healthcheck:
# The image has neither curl nor wget; bash's /dev/tcp does the request. # The image has neither curl nor wget; bash's /dev/tcp does the request
# /health from loopback is exempt from the trap. # against the dashboard port.
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 '"] 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 interval: 30s
timeout: 5s timeout: 5s
start_period: 10s start_period: 10s
+11
View File
@@ -0,0 +1,11 @@
#!/bin/sh
set -e
# Started as root (e.g. by the Unraid template): hand /data to the app user, which a
# freshly created host folder is not, then drop privileges for good.
if [ "$(id -u)" = "0" ]; then
chown -R "$APP_UID:$APP_UID" /data
exec setpriv --reuid="$APP_UID" --regid="$APP_UID" --clear-groups dotnet /app/Flypaper.Web.dll "$@"
fi
exec dotnet /app/Flypaper.Web.dll "$@"
+6 -1
View File
@@ -14,9 +14,12 @@ namespace Flypaper.Http;
public static class FlypaperHttpExtensions 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) public static IServiceCollection AddFlypaperHttp(this IServiceCollection services, IConfiguration configuration)
{ {
services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName)); services.Configure<HttpTrapOptions>(configuration.GetSection(HttpTrapOptions.SectionName));
services.Configure<PortOptions>(configuration.GetSection(PortOptions.SectionName));
services.PostConfigure<HttpTrapOptions>(options => services.PostConfigure<HttpTrapOptions>(options =>
{ {
if (options.TrapPathsOverride is not null) if (options.TrapPathsOverride is not null)
@@ -33,7 +36,9 @@ public static class FlypaperHttpExtensions
{ {
forwarded.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; forwarded.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
forwarded.ForwardLimit = 1; 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)}")); forwarded.KnownIPNetworks.Add(System.Net.IPNetwork.Parse(proxy.Contains('/') ? proxy : $"{proxy}/{HostBits(proxy)}"));
} }
@@ -7,6 +7,7 @@ using Flypaper.Http.Matching;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Features; using Microsoft.AspNetCore.Server.Kestrel.Core.Features;
using Microsoft.Extensions.Options;
namespace Flypaper.Http.Middleware; namespace Flypaper.Http.Middleware;
@@ -14,17 +15,24 @@ internal sealed class FlypaperMiddleware(
RequestDelegate next, RequestDelegate next,
TrapMatcher matcher, TrapMatcher matcher,
TrapRunner runner, TrapRunner runner,
IOptions<PortOptions> ports,
TimeProvider timeProvider) TimeProvider timeProvider)
{ {
public async Task InvokeAsync(HttpContext context) public async Task InvokeAsync(HttpContext context)
{ {
var request = context.Request; if (context.Connection.LocalPort == ports.Value.Dashboard || IsInternalHealthProbe(context))
if (IsInternalHealthProbe(context) || matcher.Match(request.Host.Host, request.Path.Value) == TrapMatch.None)
{ {
await next(context); await next(context);
return; 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( var session = new TrapSession(
Guid.NewGuid(), Guid.NewGuid(),
TrapProtocol.Http, TrapProtocol.Http,
+10
View File
@@ -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;
}
@@ -20,6 +20,7 @@ public static class FlypaperStorageExtensions
builder.Configuration.Add(source); builder.Configuration.Add(source);
builder.Services.AddSingleton(source); builder.Services.AddSingleton(source);
builder.Services.AddSingleton<RuntimeSettingsStore>(); builder.Services.AddSingleton<RuntimeSettingsStore>();
builder.Services.AddSingleton<AdminCredentialStore>();
builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName)); builder.Services.Configure<RetentionOptions>(builder.Configuration.GetSection(RetentionOptions.SectionName));
builder.Services.AddFlypaperStorage(connectionString); builder.Services.AddFlypaperStorage(connectionString);
@@ -0,0 +1,43 @@
using Flypaper.Storage.Entities;
using Microsoft.EntityFrameworkCore;
namespace Flypaper.Storage.Settings;
public sealed class AdminCredentialStore(IDbContextFactory<FlypaperDbContext> dbContextFactory)
{
private const string PasswordHashKey = "Flypaper:Admin:PasswordHash";
public async Task<string?> 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<bool> 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);
}
}
}
@@ -10,11 +10,13 @@ public sealed partial class RuntimeSettingsStore(
DbConfigurationSource source, DbConfigurationSource source,
ILogger<RuntimeSettingsStore> logger) ILogger<RuntimeSettingsStore> logger)
{ {
private static readonly string[] RuntimeKeys = SettingKeys.All.ToArray();
public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default) public async Task SaveAsync(RuntimeSettings settings, CancellationToken ct = default)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var db = await dbContextFactory.CreateDbContextAsync(ct);
await using var transaction = await db.Database.BeginTransactionAsync(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 })); db.Settings.AddRange(settings.ToConfiguration().Select(pair => new SettingEntity { Key = pair.Key, Value = pair.Value }));
await db.SaveChangesAsync(ct); await db.SaveChangesAsync(ct);
await transaction.CommitAsync(ct); await transaction.CommitAsync(ct);
@@ -24,16 +26,19 @@ public sealed partial class RuntimeSettingsStore(
public async Task ResetAsync(CancellationToken ct = default) public async Task ResetAsync(CancellationToken ct = default)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var db = await dbContextFactory.CreateDbContextAsync(ct);
await db.Settings.ExecuteDeleteAsync(ct); await RuntimeSettings(db).ExecuteDeleteAsync(ct);
Reload(); Reload();
} }
public async Task<bool> HasOverridesAsync(CancellationToken ct = default) public async Task<bool> HasOverridesAsync(CancellationToken ct = default)
{ {
await using var db = await dbContextFactory.CreateDbContextAsync(ct); await using var db = await dbContextFactory.CreateDbContextAsync(ct);
return await db.Settings.AnyAsync(ct); return await RuntimeSettings(db).AnyAsync(ct);
} }
private static IQueryable<SettingEntity> RuntimeSettings(FlypaperDbContext db) =>
db.Settings.Where(setting => RuntimeKeys.Contains(setting.Key));
private void Reload() private void Reload()
{ {
if (!source.TryReload()) if (!source.TryReload())
+15
View File
@@ -0,0 +1,15 @@
using System.Reflection;
namespace Flypaper.Web;
public static class AppVersion
{
public static string Current { get; } = Read();
private static string Read()
{
var version = typeof(AppVersion).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "0.0.0-dev";
var plus = version.IndexOf('+');
return plus >= 0 && version.Length > plus + 8 ? version[..(plus + 8)] : version;
}
}
+48 -6
View File
@@ -1,22 +1,64 @@
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Text; using System.Text;
using Flypaper.Storage.Settings;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
namespace Flypaper.Web.Auth; namespace Flypaper.Web.Auth;
public sealed class AdminAuthenticator(IOptions<AdminOptions> options) public sealed class AdminAuthenticator(IOptions<AdminOptions> 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<AdminAccount> Hasher = new();
private static readonly AdminAccount Account = new();
public bool UsesEnvironmentPassword => !string.IsNullOrEmpty(options.Value.Password);
public async Task<bool> IsConfiguredAsync(CancellationToken ct = default) =>
UsesEnvironmentPassword || await store.GetPasswordHashAsync(ct) is not null;
public async Task<bool> VerifyAsync(string? candidate, CancellationToken ct = default)
{ {
if (!IsConfigured || string.IsNullOrEmpty(candidate)) if (string.IsNullOrEmpty(candidate))
{ {
return false; return false;
} }
return CryptographicOperations.FixedTimeEquals(Hash(candidate), Hash(options.Value.Password!)); if (UsesEnvironmentPassword)
{
return CryptographicOperations.FixedTimeEquals(Sha256(candidate), Sha256(options.Value.Password!));
} }
private static byte[] Hash(string value) => SHA256.HashData(Encoding.UTF8.GetBytes(value)); return await store.GetPasswordHashAsync(ct) is { } hash
&& Hasher.VerifyHashedPassword(Account, hash, candidate) != PasswordVerificationResult.Failed;
}
public async Task<bool> TrySetInitialPasswordAsync(string password, CancellationToken ct = default) =>
!UsesEnvironmentPassword && await store.TryCreatePasswordHashAsync(Hasher.HashPassword(Account, password), ct);
public async Task<bool> 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;
} }
+33 -3
View File
@@ -18,17 +18,41 @@ public static class AuthEndpoints
{ {
var target = IsLocalPath(returnUrl) ? returnUrl! : "/"; var target = IsLocalPath(returnUrl) ? returnUrl! : "/";
if (!admin.Verify(password)) if (!await admin.VerifyAsync(password, context.RequestAborted))
{ {
await Task.Delay(750, context.RequestAborted); await Task.Delay(750, context.RequestAborted);
return Results.LocalRedirect($"/login?error=1&returnUrl={Uri.EscapeDataString(target)}"); return Results.LocalRedirect($"/login?error=1&returnUrl={Uri.EscapeDataString(target)}");
} }
var identity = new ClaimsIdentity([new Claim(ClaimTypes.Name, "admin")], CookieAuthenticationDefaults.AuthenticationScheme); await SignInAsync(context);
await context.SignInAsync(new ClaimsPrincipal(identity));
return Results.LocalRedirect(target); return Results.LocalRedirect(target);
}).AllowAnonymous(); }).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) => app.MapPost("/auth/logout", async (HttpContext context, IAntiforgery antiforgery) =>
{ {
if (!await antiforgery.IsRequestValidAsync(context)) if (!await antiforgery.IsRequestValidAsync(context))
@@ -43,6 +67,12 @@ public static class AuthEndpoints
return app; 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) => private static bool IsLocalPath(string? url) =>
!string.IsNullOrEmpty(url) && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\')); !string.IsNullOrEmpty(url) && url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'));
} }
@@ -11,6 +11,6 @@
</nav> </nav>
@Body @Body
<footer class="footer"> <footer class="footer">
<a href="https://db-ip.com">IP Geolocation by DB-IP</a> (CC BY 4.0) · Kartendaten: Natural Earth Flypaper @AppVersion.Current · <a href="https://db-ip.com">IP Geolocation by DB-IP</a> (CC BY 4.0) · Kartendaten: Natural Earth
</footer> </footer>
</main> </main>
+9 -10
View File
@@ -3,20 +3,12 @@
@attribute [AllowAnonymous] @attribute [AllowAnonymous]
@using Flypaper.Web.Auth @using Flypaper.Web.Auth
@inject AdminAuthenticator Admin @inject AdminAuthenticator Admin
@inject NavigationManager Navigation
<PageTitle>Flypaper · Anmelden</PageTitle> <PageTitle>Flypaper · Anmelden</PageTitle>
<h1 class="login-title">Flypaper</h1> <h1 class="login-title">Flypaper</h1>
@if (!Admin.IsConfigured)
{
<div class="banner bad">
<strong>Zugang gesperrt.</strong>
Es ist kein Admin-Passwort gesetzt. Setze die Umgebungsvariable <code>Flypaper__Admin__Password</code> und starte den Container neu.
</div>
}
else
{
<form method="post" action="/auth/login" class="card form"> <form method="post" action="/auth/login" class="card form">
<AntiforgeryToken /> <AntiforgeryToken />
<input type="hidden" name="returnUrl" value="@ReturnUrl" /> <input type="hidden" name="returnUrl" value="@ReturnUrl" />
@@ -28,10 +20,17 @@ else
} }
<button type="submit">Anmelden</button> <button type="submit">Anmelden</button>
</form> </form>
}
@code { @code {
[SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; } [SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; }
[SupplyParameterFromQuery(Name = "returnUrl")] private string? ReturnUrl { get; set; } [SupplyParameterFromQuery(Name = "returnUrl")] private string? ReturnUrl { get; set; }
protected override async Task OnInitializedAsync()
{
if (!await Admin.IsConfiguredAsync())
{
Navigation.NavigateTo("/setup");
}
}
} }
@@ -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; }
}
@@ -0,0 +1,63 @@
@using Flypaper.Web.Auth
@inject AdminAuthenticator Admin
@inject NavigationManager Navigation
<section class="card form">
<h2>Admin-Passwort</h2>
@if (Changed == "changed")
{
<div class="banner ok">Passwort geändert.</div>
}
@if (Admin.UsesEnvironmentPassword)
{
<p class="muted">Das Passwort kommt aus der Umgebungsvariable <code>Flypaper__Admin__Password</code> und lässt sich nur dort ändern.</p>
}
else
{
<EditForm Model="Model" FormName="password" OnSubmit="ChangeAsync" action="/settings" class="form">
<label for="current-password">Aktuelles Passwort</label>
<InputText id="current-password" type="password" autocomplete="current-password" @bind-Value="Model!.Current" />
<FieldError Errors="_errors" Field="@nameof(PasswordModel.Current)" />
<label for="new-password">Neues Passwort <span class="muted">(mindestens @AdminAuthenticator.MinimumPasswordLength Zeichen)</span></label>
<InputText id="new-password" type="password" autocomplete="new-password" @bind-Value="Model!.New" />
<label for="confirm-password">Neues Passwort wiederholen</label>
<InputText id="confirm-password" type="password" autocomplete="new-password" @bind-Value="Model!.Confirmation" />
<FieldError Errors="_errors" Field="@nameof(PasswordModel.New)" />
<div class="actions">
<button type="submit">Passwort ändern</button>
</div>
</EditForm>
}
</section>
@code {
private readonly Dictionary<string, string> _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");
}
}
@@ -14,6 +14,7 @@
@inject IConfiguration Configuration @inject IConfiguration Configuration
@inject RuntimeSettingsStore Store @inject RuntimeSettingsStore Store
@inject AdminAuthenticator Admin @inject AdminAuthenticator Admin
@inject IOptions<PortOptions> Ports
@inject NavigationManager Navigation @inject NavigationManager Navigation
<PageTitle>Flypaper · Einstellungen</PageTitle> <PageTitle>Flypaper · Einstellungen</PageTitle>
@@ -42,7 +43,7 @@ else if (Saved == "reset")
<InputTextArea id="trap-paths" @bind-Value="Model!.TrapPaths" rows="10" class="mono" /> <InputTextArea id="trap-paths" @bind-Value="Model!.TrapPaths" rows="10" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.TrapPaths)" /> <FieldError Errors="_errors" Field="@nameof(SettingsModel.TrapPaths)" />
<label for="hosts">Zusätzliche bekannte Hosts <span class="muted">(einer pro Zeile, z. B. beispiel.de oder *.beispiel.de)</span></label> <label for="hosts">Bekannte Hosts <span class="muted">(einer pro Zeile, z. B. beispiel.de oder *.beispiel.de; werden auf dem Fallen-Port nur bei Fallenpfaden gefangen, sonst 404)</span></label>
<InputTextArea id="hosts" @bind-Value="Model!.ExtraKnownHosts" rows="4" class="mono" /> <InputTextArea id="hosts" @bind-Value="Model!.ExtraKnownHosts" rows="4" class="mono" />
<FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" /> <FieldError Errors="_errors" Field="@nameof(SettingsModel.ExtraKnownHosts)" />
@@ -89,6 +90,8 @@ else if (Saved == "reset")
<TrapDataSection /> <TrapDataSection />
<PasswordSection />
<section class="card"> <section class="card">
<h2>Nur per Umgebungsvariable</h2> <h2>Nur per Umgebungsvariable</h2>
<p class="muted">Gelten ab Containerstart und lassen sich hier nicht ändern.</p> <p class="muted">Gelten ab Containerstart und lassen sich hier nicht ändern.</p>
@@ -97,7 +100,8 @@ else if (Saved == "reset")
<tr><th>Datenbank</th><td class="mono">@DatabasePath</td></tr> <tr><th>Datenbank</th><td class="mono">@DatabasePath</td></tr>
<tr><th>Bekannte Hosts</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:KnownHosts").Get<string[]>())</td></tr> <tr><th>Bekannte Hosts</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:KnownHosts").Get<string[]>())</td></tr>
<tr><th>Vertrauenswürdige Proxies</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get<string[]>())</td></tr> <tr><th>Vertrauenswürdige Proxies</th><td class="mono">@Format(Configuration.GetSection("Flypaper:Http:TrustedProxies").Get<string[]>())</td></tr>
<tr><th>Admin-Passwort</th><td>@(Admin.IsConfigured ? "gesetzt" : "nicht gesetzt")</td></tr> <tr><th>Admin-Passwort</th><td>@(Admin.UsesEnvironmentPassword ? "per Umgebungsvariable" : "im Dashboard festgelegt")</td></tr>
<tr><th>Ports</th><td class="mono">Falle @Ports.Value.Trap, Dashboard @Ports.Value.Dashboard</td></tr>
</tbody> </tbody>
</table> </table>
</section> </section>
@@ -0,0 +1,36 @@
@page "/setup"
@layout EmptyLayout
@attribute [AllowAnonymous]
@using Flypaper.Web.Auth
@inject AdminAuthenticator Admin
@inject NavigationManager Navigation
<PageTitle>Flypaper · Einrichten</PageTitle>
<h1 class="login-title">Flypaper einrichten</h1>
<form method="post" action="/auth/setup" class="card form">
<AntiforgeryToken />
<p class="muted">Lege das Admin-Passwort für das Dashboard fest. Diese Seite ist nur erreichbar, solange noch kein Passwort existiert.</p>
<label for="password">Passwort <span class="muted">(mindestens @AdminAuthenticator.MinimumPasswordLength Zeichen)</span></label>
<input id="password" name="password" type="password" autocomplete="new-password" minlength="@AdminAuthenticator.MinimumPasswordLength" autofocus required />
<label for="confirmation">Passwort wiederholen</label>
<input id="confirmation" name="confirmation" type="password" autocomplete="new-password" required />
@if (Error is not null)
{
<p class="error">@Error</p>
}
<button type="submit">Passwort festlegen</button>
</form>
@code {
[SupplyParameterFromQuery(Name = "error")] private string? Error { get; set; }
protected override async Task OnInitializedAsync()
{
if (await Admin.IsConfiguredAsync())
{
Navigation.NavigateTo("/login");
}
}
}
+9 -1
View File
@@ -2,6 +2,7 @@ using Flypaper.Core;
using Flypaper.GeoIp; using Flypaper.GeoIp;
using Flypaper.Http; using Flypaper.Http;
using Flypaper.Storage; using Flypaper.Storage;
using Flypaper.Web;
using Flypaper.Web.Auth; using Flypaper.Web.Auth;
using Flypaper.Web.Components; using Flypaper.Web.Components;
using Flypaper.Web.Health; using Flypaper.Web.Health;
@@ -11,7 +12,13 @@ using Microsoft.AspNetCore.DataProtection;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options => options.AddServerHeader = false); var ports = builder.Configuration.GetSection(PortOptions.SectionName).Get<PortOptions>() ?? new PortOptions();
builder.WebHost.ConfigureKestrel(options =>
{
options.AddServerHeader = false;
options.ListenAnyIP(ports.Trap);
options.ListenAnyIP(ports.Dashboard);
});
builder.AddFlypaperStorage(); builder.AddFlypaperStorage();
builder.Services.AddRazorComponents(); builder.Services.AddRazorComponents();
@@ -44,6 +51,7 @@ builder.Services.AddAuthorizationBuilder()
var app = builder.Build(); var app = builder.Build();
app.Logger.LogInformation("Flypaper {Version} starting", AppVersion.Current);
await app.Services.MigrateFlypaperDatabaseAsync(); await app.Services.MigrateFlypaperDatabaseAsync();
app.UseFlypaper(); app.UseFlypaper();
@@ -6,13 +6,12 @@
} }
}, },
"Flypaper": { "Flypaper": {
"Http": {
"KnownHosts": [
"localhost"
]
},
"Admin": { "Admin": {
"Password": "dev" "Password": "dev"
},
"Ports": {
"Trap": 5247,
"Dashboard": 5248
} }
} }
} }
@@ -50,13 +50,38 @@ public sealed class ForwardedHeadersTests
ip.ShouldBe(sender); ip.ShouldBe(sender);
} }
private static async Task<IPAddress?> 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<IPAddress?> SendAsync(IPAddress remoteIp, params (string Name, string Value)[] headers) =>
SendAsync(remoteIp, "172.18.0.0/16", headers);
private static async Task<IPAddress?> SendAsync(IPAddress remoteIp, string? trustedProxy, params (string Name, string Value)[] headers)
{ {
var configuration = new ConfigurationBuilder() var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string?> .AddInMemoryCollection(new Dictionary<string, string?>
{ {
["Flypaper:Http:KnownHosts:0"] = "dashboard.lan", ["Flypaper:Http:TrustedProxies:0"] = trustedProxy
["Flypaper:Http:TrustedProxies:0"] = "172.18.0.0/16"
}) })
.Build(); .Build();
@@ -78,6 +103,7 @@ public sealed class ForwardedHeadersTests
var httpContext = new DefaultHttpContext { RequestServices = services }; var httpContext = new DefaultHttpContext { RequestServices = services };
httpContext.Connection.RemoteIpAddress = remoteIp; httpContext.Connection.RemoteIpAddress = remoteIp;
httpContext.Connection.LocalPort = 8081;
httpContext.Request.Host = new HostString("dashboard.lan"); httpContext.Request.Host = new HostString("dashboard.lan");
httpContext.Request.Path = "/"; httpContext.Request.Path = "/";
foreach (var (name, value) in headers) foreach (var (name, value) in headers)
@@ -71,6 +71,7 @@ public sealed class HealthProbeTests
var httpContext = new DefaultHttpContext { RequestServices = services }; var httpContext = new DefaultHttpContext { RequestServices = services };
httpContext.Connection.RemoteIpAddress = remoteIp; httpContext.Connection.RemoteIpAddress = remoteIp;
httpContext.Connection.LocalPort = 8080;
httpContext.Request.Host = new HostString("flypaper:8080"); httpContext.Request.Host = new HostString("flypaper:8080");
httpContext.Request.Path = path; httpContext.Request.Path = path;
@@ -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<ITrapEventSink>();
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<string, string?>
{
["Flypaper:MaxConnections"] = "0",
["Flypaper:Http:KnownHosts:0"] = "example.com",
["Flypaper:Http:TrapPaths:0"] = "/.env"
})
.Build();
var services = new ServiceCollection()
.AddLogging()
.AddSingleton(sink ?? Substitute.For<ITrapEventSink>())
.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);
}
}
+156
View File
@@ -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<WebApplicationFactory<Program>> _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<AdminAuthenticator>();
(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<AdminAuthenticator>().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<AdminAuthenticator>();
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<AdminAuthenticator>();
(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<Program>().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<HttpResponseMessage> 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<string> 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);
}
}
}
@@ -15,7 +15,7 @@ public sealed class HealthEndpointTests : IDisposable
_factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder => _factory = new WebApplicationFactory<Program>().WithWebHostBuilder(builder =>
{ {
builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}"); builder.UseSetting("ConnectionStrings:Flypaper", $"Data Source={_dbPath}");
builder.UseSetting("Flypaper:Http:KnownHosts:0", "localhost"); builder.UseSetting("Flypaper:Ports:Dashboard", "0");
}); });
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

+19
View File
@@ -0,0 +1,19 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
<title>Flypaper</title>
<rect width="256" height="256" rx="48" fill="#14171c"/>
<path d="M-38.4,153.1 L290.2,83.3 L303.6,145.9 L-25.1,215.7 Z" fill="#e09a4f"/>
<path d="M-38.4,153.1 L290.2,83.3 L291.5,89.2 L-37.2,159.0 Z" fill="#b5651d"/>
<path d="M-26.3,209.9 L302.3,140.0 L303.6,145.9 L-25.1,215.7 Z" fill="#b5651d"/>
<line x1="116" y1="150" x2="90" y2="168" stroke="#0e1014" stroke-width="6" stroke-linecap="round"/>
<line x1="114" y1="162" x2="88" y2="186" stroke="#0e1014" stroke-width="6" stroke-linecap="round"/>
<line x1="118" y1="172" x2="98" y2="200" stroke="#0e1014" stroke-width="6" stroke-linecap="round"/>
<line x1="140" y1="150" x2="166" y2="168" stroke="#0e1014" stroke-width="6" stroke-linecap="round"/>
<line x1="142" y1="162" x2="168" y2="186" stroke="#0e1014" stroke-width="6" stroke-linecap="round"/>
<line x1="138" y1="172" x2="158" y2="200" stroke="#0e1014" stroke-width="6" stroke-linecap="round"/>
<path d="M135.1,94.2 L135.9,95.5 L136.3,97.0 L136.6,98.6 L136.6,100.3 L136.3,102.1 L135.8,104.1 L135.1,106.1 L134.1,108.3 L132.9,110.4 L131.5,112.7 L129.8,114.9 L128.0,117.2 L126.0,119.4 L123.8,121.6 L121.5,123.8 L119.0,125.9 L116.4,128.0 L113.8,129.9 L111.0,131.8 L108.2,133.5 L105.4,135.1 L102.5,136.5 L99.7,137.8 L96.9,139.0 L94.1,139.9 L91.5,140.7 L88.9,141.3 L86.4,141.6 L84.1,141.8 L81.9,141.8 L79.9,141.6 L78.1,141.2 L76.5,140.7 L75.0,139.9 L73.8,138.9 L72.9,137.8 L72.1,136.5 L71.7,135.0 L71.4,133.4 L71.4,131.7 L71.7,129.9 L72.2,127.9 L72.9,125.9 L73.9,123.7 L75.1,121.6 L76.5,119.3 L78.2,117.1 L80.0,114.8 L82.0,112.6 L84.2,110.4 L86.5,108.2 L89.0,106.1 L91.6,104.0 L94.2,102.1 L97.0,100.2 L99.8,98.5 L102.6,96.9 L105.5,95.5 L108.3,94.2 L111.1,93.0 L113.9,92.1 L116.5,91.3 L119.1,90.7 L121.6,90.4 L123.9,90.2 L126.1,90.2 L128.1,90.4 L129.9,90.8 L131.5,91.3 L133.0,92.1 L134.2,93.1 Z" fill="#e4e7ec" fill-opacity="0.6" stroke="#e4e7ec" stroke-width="2"/>
<path d="M183.1,137.8 L182.2,138.9 L181.0,139.9 L179.5,140.7 L177.9,141.2 L176.1,141.6 L174.1,141.8 L171.9,141.8 L169.6,141.6 L167.1,141.3 L164.5,140.7 L161.9,139.9 L159.1,139.0 L156.3,137.8 L153.5,136.5 L150.6,135.1 L147.8,133.5 L145.0,131.8 L142.2,129.9 L139.6,128.0 L137.0,125.9 L134.5,123.8 L132.2,121.6 L130.0,119.4 L128.0,117.2 L126.2,114.9 L124.5,112.7 L123.1,110.4 L121.9,108.3 L120.9,106.1 L120.2,104.1 L119.7,102.1 L119.4,100.3 L119.4,98.6 L119.7,97.0 L120.1,95.5 L120.9,94.2 L121.8,93.1 L123.0,92.1 L124.5,91.3 L126.1,90.8 L127.9,90.4 L129.9,90.2 L132.1,90.2 L134.4,90.4 L136.9,90.7 L139.5,91.3 L142.1,92.1 L144.9,93.0 L147.7,94.2 L150.5,95.5 L153.4,96.9 L156.2,98.5 L159.0,100.2 L161.8,102.1 L164.4,104.0 L167.0,106.1 L169.5,108.2 L171.8,110.4 L174.0,112.6 L176.0,114.8 L177.8,117.1 L179.5,119.3 L180.9,121.6 L182.1,123.7 L183.1,125.9 L183.8,127.9 L184.3,129.9 L184.6,131.7 L184.6,133.4 L184.3,135.0 L183.9,136.5 Z" fill="#e4e7ec" fill-opacity="0.6" stroke="#e4e7ec" stroke-width="2"/>
<path d="M148.0,152.0 L147.9,155.1 L147.7,158.3 L147.3,161.3 L146.8,164.3 L146.1,167.2 L145.3,170.0 L144.4,172.6 L143.3,175.1 L142.1,177.5 L140.9,179.6 L139.5,181.5 L138.0,183.2 L136.5,184.6 L134.8,185.8 L133.2,186.8 L131.5,187.5 L129.7,187.9 L128.0,188.0 L126.3,187.9 L124.5,187.5 L122.8,186.8 L121.2,185.8 L119.5,184.6 L118.0,183.2 L116.5,181.5 L115.1,179.6 L113.9,177.5 L112.7,175.1 L111.6,172.6 L110.7,170.0 L109.9,167.2 L109.2,164.3 L108.7,161.3 L108.3,158.3 L108.1,155.1 L108.0,152.0 L108.1,148.9 L108.3,145.7 L108.7,142.7 L109.2,139.7 L109.9,136.8 L110.7,134.0 L111.6,131.4 L112.7,128.9 L113.9,126.5 L115.1,124.4 L116.5,122.5 L118.0,120.8 L119.5,119.4 L121.2,118.2 L122.8,117.2 L124.5,116.5 L126.3,116.1 L128.0,116.0 L129.7,116.1 L131.5,116.5 L133.2,117.2 L134.8,118.2 L136.5,119.4 L138.0,120.8 L139.5,122.5 L140.9,124.4 L142.1,126.5 L143.3,128.9 L144.4,131.4 L145.3,134.0 L146.1,136.8 L146.8,139.7 L147.3,142.7 L147.7,145.7 L147.9,148.9 Z" fill="#2a2f38"/>
<path d="M145.0,108.0 L144.9,109.3 L144.7,110.6 L144.4,111.9 L144.0,113.1 L143.4,114.3 L142.7,115.5 L141.9,116.6 L141.0,117.6 L140.0,118.6 L138.9,119.5 L137.8,120.3 L136.5,121.0 L135.2,121.6 L133.8,122.1 L132.4,122.5 L131.0,122.8 L129.5,122.9 L128.0,123.0 L126.5,122.9 L125.0,122.8 L123.6,122.5 L122.2,122.1 L120.8,121.6 L119.5,121.0 L118.2,120.3 L117.1,119.5 L116.0,118.6 L115.0,117.6 L114.1,116.6 L113.3,115.5 L112.6,114.3 L112.0,113.1 L111.6,111.9 L111.3,110.6 L111.1,109.3 L111.0,108.0 L111.1,106.7 L111.3,105.4 L111.6,104.1 L112.0,102.9 L112.6,101.7 L113.3,100.5 L114.1,99.4 L115.0,98.4 L116.0,97.4 L117.1,96.5 L118.2,95.7 L119.5,95.0 L120.8,94.4 L122.2,93.9 L123.6,93.5 L125.0,93.2 L126.5,93.1 L128.0,93.0 L129.5,93.1 L131.0,93.2 L132.4,93.5 L133.8,93.9 L135.2,94.4 L136.5,95.0 L137.8,95.7 L138.9,96.5 L140.0,97.4 L141.0,98.4 L141.9,99.4 L142.7,100.5 L143.4,101.7 L144.0,102.9 L144.4,104.1 L144.7,105.4 L144.9,106.7 Z" fill="#2a2f38"/>
<path d="M125.0,103.0 L125.0,103.7 L124.9,104.4 L124.8,105.1 L124.6,105.7 L124.3,106.4 L124.1,107.0 L123.7,107.6 L123.4,108.1 L122.9,108.7 L122.5,109.1 L122.0,109.6 L121.5,109.9 L121.0,110.3 L120.4,110.5 L119.8,110.7 L119.2,110.9 L118.6,111.0 L118.0,111.0 L117.4,111.0 L116.8,110.9 L116.2,110.7 L115.6,110.5 L115.0,110.3 L114.5,109.9 L114.0,109.6 L113.5,109.1 L113.1,108.7 L112.6,108.1 L112.3,107.6 L111.9,107.0 L111.7,106.4 L111.4,105.7 L111.2,105.1 L111.1,104.4 L111.0,103.7 L111.0,103.0 L111.0,102.3 L111.1,101.6 L111.2,100.9 L111.4,100.3 L111.7,99.6 L111.9,99.0 L112.3,98.4 L112.6,97.9 L113.1,97.3 L113.5,96.9 L114.0,96.4 L114.5,96.1 L115.0,95.7 L115.6,95.5 L116.2,95.3 L116.8,95.1 L117.4,95.0 L118.0,95.0 L118.6,95.0 L119.2,95.1 L119.8,95.3 L120.4,95.5 L121.0,95.7 L121.5,96.1 L122.0,96.4 L122.5,96.9 L122.9,97.3 L123.4,97.9 L123.7,98.4 L124.1,99.0 L124.3,99.6 L124.6,100.3 L124.8,100.9 L124.9,101.6 L125.0,102.3 Z" fill="#b3261e"/>
<path d="M145.0,103.0 L145.0,103.7 L144.9,104.4 L144.8,105.1 L144.6,105.7 L144.3,106.4 L144.1,107.0 L143.7,107.6 L143.4,108.1 L142.9,108.7 L142.5,109.1 L142.0,109.6 L141.5,109.9 L141.0,110.3 L140.4,110.5 L139.8,110.7 L139.2,110.9 L138.6,111.0 L138.0,111.0 L137.4,111.0 L136.8,110.9 L136.2,110.7 L135.6,110.5 L135.0,110.3 L134.5,109.9 L134.0,109.6 L133.5,109.1 L133.1,108.7 L132.6,108.1 L132.3,107.6 L131.9,107.0 L131.7,106.4 L131.4,105.7 L131.2,105.1 L131.1,104.4 L131.0,103.7 L131.0,103.0 L131.0,102.3 L131.1,101.6 L131.2,100.9 L131.4,100.3 L131.7,99.6 L131.9,99.0 L132.3,98.4 L132.6,97.9 L133.1,97.3 L133.5,96.9 L134.0,96.4 L134.5,96.1 L135.0,95.7 L135.6,95.5 L136.2,95.3 L136.8,95.1 L137.4,95.0 L138.0,95.0 L138.6,95.0 L139.2,95.1 L139.8,95.3 L140.4,95.5 L141.0,95.7 L141.5,96.1 L142.0,96.4 L142.5,96.9 L142.9,97.3 L143.4,97.9 L143.7,98.4 L144.1,99.0 L144.3,99.6 L144.6,100.3 L144.8,100.9 L144.9,101.6 L145.0,102.3 Z" fill="#b3261e"/>
</svg>

After

Width:  |  Height:  |  Size: 6.6 KiB

+32
View File
@@ -0,0 +1,32 @@
<?xml version="1.0"?>
<Container version="2">
<Name>Flypaper</Name>
<Repository>gitea.anticarnist.de/tom/flypaper:latest</Repository>
<Registry>https://gitea.anticarnist.de/Tom/-/packages/container/flypaper</Registry>
<Network>bridge</Network>
<MyIP/>
<Shell>bash</Shell>
<Privileged>false</Privileged>
<Support>https://gitea.anticarnist.de/Tom/Flypaper/issues</Support>
<Project>https://gitea.anticarnist.de/Tom/Flypaper</Project>
<Overview>Self-hosted tarpit that traps and slows down scanning bots, with event logging and analysis. Instead of blocking bots, Flypaper answers them with an endless HTML page that trickles in a few bytes at a time, and logs every catch with its country and network provider.[br][br]
The trap port receives everything your reverse proxy has no site for (its catch-all / default server) and, optionally, bait paths such as /.env from your real domains. The dashboard has its own port: keep it inside your LAN. On first visit you set the admin password.[br][br]
The container starts as root only to hand the appdata folder to its app user (UID 1654), then drops privileges for good.</Overview>
<Category>Security: Network:Proxy</Category>
<WebUI>http://[IP]:[PORT:8081]/</WebUI>
<TemplateURL>https://gitea.anticarnist.de/Tom/Flypaper/raw/branch/main/unraid/flypaper.xml</TemplateURL>
<Icon>https://gitea.anticarnist.de/Tom/Flypaper/raw/branch/main/unraid/flypaper.png</Icon>
<ExtraParams>--user 0:0</ExtraParams>
<PostArgs/>
<CPUset/>
<DateInstalled/>
<DonateText/>
<DonateLink/>
<Requires/>
<Config Name="Trap port" Target="8080" Default="8080" Mode="tcp" Description="Point your reverse proxy's catch-all / default server here. Every request on this port is trapped." Type="Port" Display="always" Required="true" Mask="false">8080</Config>
<Config Name="Dashboard port" Target="8081" Default="8081" Mode="tcp" Description="Dashboard and settings. Keep this port inside your LAN and never forward it from your public proxy." Type="Port" Display="always" Required="true" Mask="false">8081</Config>
<Config Name="Data" Target="/data" Default="/mnt/user/appdata/flypaper" Mode="rw" Description="Database, login keys and GeoIP databases." Type="Path" Display="always" Required="true" Mask="false">/mnt/user/appdata/flypaper</Config>
<Config Name="Admin password" Target="Flypaper__Admin__Password" Default="" Mode="" Description="Optional. Fixes the dashboard password and disables the first-visit setup. Leave empty to set it in the dashboard." Type="Variable" Display="advanced" Required="false" Mask="true"/>
<Config Name="Trusted proxy" Target="Flypaper__Http__TrustedProxies__0" Default="" Mode="" Description="Optional. IP or CIDR of the reverse proxy allowed to set X-Real-IP / X-Forwarded-For. Default: all private networks." Type="Variable" Display="advanced" Required="false" Mask="false"/>
<Config Name="Known host" Target="Flypaper__Http__KnownHosts__0" Default="" Mode="" Description="Optional. A host that is caught only on trap paths; its other paths get a plain 404." Type="Variable" Display="advanced" Required="false" Mask="false"/>
</Container>