Files
BanGUI/Docs/Features.md
Lukas 32aad186c3 TASK-031: Enforce bcrypt 72-byte password limit
Bcrypt silently truncates passwords at 72 bytes, so passwords longer than 72
characters provide no additional security. This commit enforces the 72-byte
maximum across the authentication and setup flows.

Changes:
- Add max_length=72 to LoginRequest.password and SetupRequest.master_password
- Update field validator in SetupRequest to explicitly check max_length
- Add comprehensive tests for password length validation (6 new test cases)
- Document the 72-byte limitation in Features.md (master password options)
- Add new section 12 'Password Hashing' in Backend-Development.md explaining:
  - The bcrypt truncation behavior
  - Why the limit is enforced
  - The validation flow from frontend to backend
  - What happens when passwords exceed the limit

All existing tests pass, no regressions introduced.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-04-26 15:38:20 +02:00

372 lines
23 KiB
Markdown

# BanGUI — Feature List
A web application to monitor, manage, and configure fail2ban from a clean, accessible interface.
---
## 1. Setup Page
- Displayed automatically on first launch when no configuration exists.
- As long as no configuration is saved, every route redirects to the setup page.
- Once setup is complete and a configuration is saved, the setup page redirects to the login page and cannot be used again.
- The `SetupGuard` component checks the setup status on every protected route; if setup is not complete it redirects the user to `/setup`.
- **Security:** The master password is SHA-256 hashed in the browser using the native `SubtleCrypto` API before it is transmitted. The backend then bcrypt-hashes the received hash with an auto-generated salt. The plaintext password never leaves the browser and is never stored.
### Options
- **Master Password** — Set a single global password that protects the entire web interface. Must be between 8 and 72 characters long (72-byte limit is due to bcrypt truncation) and include one uppercase letter, one number, and one special character from `!@#$%^&*()`.
- **Database Path** — Define where the application stores its own SQLite database.
- **fail2ban Connection** — Specify how the application connects to the running fail2ban instance (socket path or related settings).
- **General Preferences** — Any additional application-level settings such as default time zone, date format, or session duration.
---
## 2. Login Page
- A simple password prompt with a single input field and a submit button.
- No username — only the master password set during setup.
- Every page in the application (except the setup page) requires the user to be authenticated.
- If a user is not logged in and tries to access any page, they are automatically redirected to the login page.
- After entering the correct password the user is taken to the page they originally requested.
- A logout option is available from every page so the user can end their session.
### Session Validation on App Load
- On app mount (page reload or initial load), the frontend validates the cached session with the backend by calling `GET /api/auth/session`.
- While the validation check is in flight, a loading spinner is displayed to avoid UI flicker.
- If the backend returns **200**, the session is valid and the app proceeds normally.
- If the backend returns **401**, the session has expired or been revoked (server-side DB deletion, restart, etc.), and the user is logged out and redirected to the login page.
- If a **network error** occurs (backend temporarily unreachable), the user is not logged out — the app assumes the backend will recover and continues with the cached session state. The next API call will trigger a 401 if the session is actually invalid.
### Login Rate Limiting
- The login endpoint (`POST /api/auth/login`) is protected against brute-force attacks with per-IP rate limiting.
- **Rate limit:** 5 login attempts per minute per IP address.
- When the limit is exceeded, the server returns **HTTP 429 Too Many Requests** with a `Retry-After` header indicating when requests will be accepted again.
- Each failed login attempt triggers a 10-second delay on the server side to further slow down attack attempts, on top of the bcrypt password hashing cost.
- The rate limiter tracks attempts in memory per IP, ensuring that rapid-fire attacks from a single source are quickly throttled.
---
## 3. Ban Overview (Dashboard)
The main landing page after login. Shows recent ban activity at a glance.
### Server Status Bar
- A persistent status indicator showing whether the fail2ban server is running or unreachable.
- Displays the fail2ban version, the number of active jails, and total bans across all jails.
- Shows combined statistics: total failures detected and total bans issued since the server started.
### Ban List
- A table displaying all IPs that were banned within a selected time window.
- **Columns:** Time of ban, IP address, requested URL / service, country of origin, target domain, target subdomain.
- Rows are sorted by time, newest first.
- A time-range selector with quick presets:
- Last 24 hours
- Last 7 days (week)
- Last 30 days (month)
- Last 365 days (year)
- **Data source selection:** The "Last 24 hours" preset queries fail2ban's live database directly for real-time accuracy. All longer presets (7 days, 30 days, 365 days) query the BanGUI long-term archive, because fail2ban's own database only retains the last 24 hours by default.
- A **data-source badge** next to the time-range selector indicates whether the current view is showing **Live (fail2ban DB)** or **Archive (BanGUI DB)** data.
---
## 4. World Map View
A geographical overview of ban activity.
### Map
- A full world map rendered with country outlines, showing ban activity through color-coded fills (no satellite imagery).
- **Color coding:** Countries are colored based on their ban count for the selected time range:
- **Red:** High ban count (100+ bans by default)
- **Yellow:** Medium ban count (50 bans by default)
- **Green:** Low ban count (20 bans by default)
- **Transparent (no fill):** Zero bans
- Colors are smoothly interpolated between the thresholds (e.g., 35 bans shows a yellow-green blend)
- The color threshold values are configurable through the application settings
- **Interactive zoom and pan:** Users can zoom in/out using mouse wheel or touch gestures, and pan by clicking and dragging. This allows detailed inspection of densely-affected regions. Zoom controls (zoom in, zoom out, reset view) are provided as overlay buttons in the top-right corner.
- For every country that has bans, the total count is shown only in the country tooltip, not rendered on the map itself.
- Countries with zero banned IPs show no tooltip and remain blank and transparent.
- Clicking a country filters the companion table below to show only bans from that country. When a country is selected the server returns the **complete** list of bans for that country in the chosen time window — the default 200-row companion cap is lifted for filtered queries. Clicking the same country again or using the "Clear filter" button reverts to the standard unfiltered view.
- Time-range selector with the same quick presets:
- Last 24 hours
- Last 7 days
- Last 30 days
- Last 365 days
- **Data source selection:** Same rule as the Dashboard — "Last 24 hours" uses the live fail2ban database; all other ranges use the BanGUI archive.
- A **data-source badge** is displayed alongside the time-range selector indicating **Live (fail2ban DB)** or **Archive (BanGUI DB)**.
### Companion Table
- The column header row is always visible at the top of the scrollable table area (sticky positioning) so column labels remain readable regardless of scroll position.
- The pagination / page-size bar is always visible at the bottom of the scrollable table area (sticky positioning) so the user can navigate pages without scrolling back down.
---
## 5. Jail Management
A dedicated view for managing fail2ban jails and taking manual ban actions.
### Jail Overview
- A list of all jails showing their name, current status (running / stopped / idle), backend type, and key metrics.
- For each jail: number of currently banned IPs, total bans since start, current failures detected, and total failures.
- Quick indicators for the jail's find time, ban time, and max retries.
- A toggle to also show **Inactive Jails** — jails that are defined in fail2ban config files but are not currently running.
- Each inactive jail has an **Activate** button that enables and reloads it immediately, with optional overrides for ban time, find time, max retries, port, and log path.
### Jail Detail
- Selecting a jail opens a detailed view with all of its settings.
- Shows every monitored log file path attached to that jail.
- Shows all fail regex and ignore regex patterns in a readable list.
- Shows the date pattern and log encoding used for parsing.
- Shows all actions attached to the jail and their configuration.
- Shows ban-time escalation settings if incremental banning is enabled (factor, formula, multipliers, max time).
### Jail Controls
- Start or stop individual jails.
- Toggle a jail into idle mode (pauses monitoring without fully stopping it) and back.
- Reload a single jail to pick up configuration changes without restarting the entire server.
- Reload all jails at once.
### Ban an IP
- Input field to enter an IP address.
- Option to select which jail the ban should apply to.
- Confirm and execute the ban.
- Visual feedback confirming the IP has been banned successfully.
### Unban an IP
- Input field to enter an IP address, or select from the list of currently banned IPs.
- Option to select the jail from which the IP should be unbanned, or unban from all jails.
- Option to unban all IPs at once across every jail.
- Confirm and execute the unban.
- Visual feedback confirming the IP has been unbanned successfully.
### Currently Banned IPs
- A quick-reference list of all IPs that are currently banned across all jails.
- Each entry shows the IP, the jail it belongs to, when the ban started, and when it will expire (if applicable).
- Shows how many times this IP has been banned before (ban count / repeat offender indicator).
- Direct unban button next to each entry for convenience.
### IP Lookup
- Enter any IP address to check whether it is currently banned, and if so in which jails.
- Show the ban history for that IP: how many times it was banned, when each ban occurred, and from which jails.
- Display enriched IP information: country, ASN (network operator), and Regional Internet Registry (RIR).
### IP Whitelist (Ignore List)
- View the list of IP addresses or networks that are excluded from banning, per jail and globally.
- Add an IP address or network range to a jail's ignore list so it will never be banned.
- Remove an IP from the ignore list.
- Toggle the "ignore self" option per jail, which automatically excludes the server's own IP addresses.
---
## 6. Configuration View
A page to inspect and modify the fail2ban configuration without leaving the web interface.
### View Configuration
- The **Jails**, **Filters**, and **Actions** tabs each use a **master/detail list layout**:
- A scrollable left pane lists all items (jail names, filter filenames, action filenames).
- Each item displays an **Active** or **Inactive** badge. Active items are sorted to the top; items within each group are sorted alphabetically.
- A jail is "active" if fail2ban reports it as enabled at runtime. A filter or action is "active" if it is referenced by at least one enabled jail.
- Inactive jails (present in config files but not running) are discoverable from the Jails tab. Selecting one shows its config file settings and allows activating it.
- Clicking an item loads its structured configuration form in the right detail pane.
- On narrow screens (< 900 px) the list pane collapses into a dropdown above the detail pane.
- Show global fail2ban settings (ban time, find time, max retries, etc.) on the Global Settings tab.
### Edit Configuration
- Inline editing of jail parameters (ban time, max retries, enabled/disabled, etc.).
- Inline editing of filter regex patterns.
- Add or remove fail regex and ignore regex patterns per jail.
- Edit the prefix regex used for pre-filtering log lines.
- Configure the date pattern and log time zone for each jail.
- Configure DNS resolution mode per jail (resolve all hostnames, IP only, etc.).
- Configure ban-time escalation: enable incremental banning and set factor, formula, multipliers, maximum ban time, and random jitter.
- Save changes and optionally reload fail2ban to apply them immediately.
- Validation feedback if a regex pattern or setting value is invalid before saving.
- **Activate** an inactive jail directly from the Jails tab detail pane, with optional parameter overrides.
- **Deactivate** a running jail from the Jails tab; writes ``enabled = false`` to a local override file and reloads fail2ban.
### Raw Configuration Editing
- Every jail, filter, and action detail pane includes a collapsible **Raw Configuration** section at the bottom.
- The section shows the complete raw text of the config file (`.conf`) in an editable monospace textarea.
- The user can edit the raw text directly and click **Save Raw** to overwrite the file on disk.
- The textarea loads lazily — the raw file content is only fetched when the section is first expanded.
- A save-state indicator shows idle / saving / saved / error feedback after each save attempt.
### Add Log Observation
- Option to register additional log files that fail2ban should monitor.
- For each new log, specify:
- The path to the log file (must be within allowed directories to prevent unauthorized access to sensitive files).
- One or more regex patterns that define what constitutes a failure.
- The jail name and basic jail settings (ban time, retries, etc.).
- Choose whether the file should be read from the beginning or only new lines (head vs. tail).
- Preview matching lines from the log against the provided regex before saving, so the user can verify the pattern works.
- **Log Path Security:** Added log paths must resolve to locations within a configured allowlist of safe directories (default: `/var/log` and `/config/log`). This prevents authenticated users from instructing fail2ban to monitor sensitive system files. Paths containing symlinks are resolved to their canonical targets before validation.
### Regex Tester
- Paste or type a sample log line into a text field.
- Enter a fail regex pattern.
- Immediately see whether the pattern matches the sample, with the matched groups highlighted.
- Useful for crafting and debugging new filter rules before applying them to a live jail.
### Server Settings
- View and change the fail2ban log level using valid values: `CRITICAL`, `ERROR`, `WARNING`, `NOTICE`, `INFO`, `DEBUG`.
- View and change the log target, which can be:
- Special values: `STDOUT`, `STDERR`, `SYSLOG`
- A file path that resolves to one of the configured safe log directories (default: `/var/log` and `/config/log`). Symlinks are resolved to their canonical targets before validation.
- View and change the syslog socket if syslog is used.
- Flush and re-open log files (useful after log rotation).
- View and change the fail2ban database file location.
- Set the database purge age — how long historical ban records are kept before automatic cleanup.
- Set the maximum number of log-line matches stored per ban record in the database.
### Map Settings
- Configure the three color thresholds that determine how countries are colored on the World Map view based on their ban count:
- **Low Threshold (Green):** Ban count at which the color transitions from light green to full green (default: 20).
- **Medium Threshold (Yellow):** Ban count at which the color transitions from green to yellow (default: 50).
- **High Threshold (Red):** Ban count at which the color transitions from yellow to red (default: 100).
- Countries with ban counts between thresholds display smoothly interpolated colors.
- Countries with zero bans remain transparent (no fill).
- Changes take effect immediately on the World Map view without requiring a page reload.
### Log
- A dedicated **Log** tab on the Configuration page shows fail2ban service health and a live log viewer in one place.
- **Service Health panel** (always visible):
- Online/offline **badge** (Running / Offline).
- When online: version, active jail count, currently banned IPs, and currently failed attempts as stat cards.
- Log level and log target displayed as meta labels.
- Warning banner when fail2ban is offline, prompting the user to check the server and socket configuration.
- **Log Viewer** (shown when fail2ban logs to a file):
- Displays the tail of the fail2ban log file in a scrollable monospace container.
- Log lines are **color-coded by severity**: errors and critical messages in red, warnings in yellow, debug lines in grey, and informational lines in the default color.
- Toolbar controls:
- **Filter** — substring input with 300 ms debounce; only lines containing the filter text are shown.
- **Lines** — selector for how many tail lines to fetch (100 / 200 / 500 / 1000).
- **Refresh** button for an on-demand reload.
- **Auto-refresh** toggle with interval selector (5 s / 10 s / 30 s) for live monitoring.
- Truncation notice when the total log file line count exceeds the requested tail limit.
- Container automatically scrolls to the bottom after each data update.
- When fail2ban is configured to log to a non-file target (`STDOUT`, `STDERR`, or `SYSLOG`), an informational banner explains that file-based log viewing is unavailable.
- Log file paths are validated against a configurable allowlist of safe directories on the backend to prevent unauthorized reads of sensitive system files.
---
## 7. Ban History
A view for exploring historical ban data stored in the BanGUI long-term archive.
### History Table
- Browse all past bans across all jails, not just the currently active ones.
- **Columns:** Time of ban, IP address, jail, ban duration, ban count (how many times this IP was banned), country.
- Filter by jail, by IP address, or by time range.
- The default time range on first load is **Last 7 days** and the data source is always the **BanGUI archive**, ensuring the full retention window is visible regardless of fail2ban's `dbpurgeage` setting.
- A **data-source badge** is displayed indicating **Archive (BanGUI DB)**.
- See at a glance which IPs are repeat offenders (high ban count).
### Per-IP History
- Select any IP to see its full ban timeline: every ban event, which jail triggered it, when it started, and how long it lasted.
- Merged view showing total failures and matched log lines aggregated across all bans for that IP.
### Persistent Historical Archive
- BanGUI stores a separate long-term historical ban archive in its own application database, independent from fail2ban's database retention settings.
- On each configured sync cycle (default every 5 minutes), BanGUI reads latest entries from fail2ban `bans` table and appends any new events to BanGUI history storage.
- Supports both `ban` and `unban` events; audit record includes: `timestamp`, `ip`, `jail`, `action`, `duration`, `origin` (manual, auto, blocklist, etc.), `failures`, `matches`, and optional `country` / `ASN` enrichment.
- Includes incremental import logic with dedupe: using unique constraint on (ip, jail, action, timeofban) to prevent duplication across sync cycles.
- Provides backfill mode for initial startup: import the last 7.5 days of existing fail2ban history into BanGUI to avoid dark gaps after restart. Requires fail2ban's `dbpurgeage` to be set to at least `648000` (7.5 days) — BanGUI ships with this value pre-configured in its Docker setup.
- Includes configurable archive purge policy in BanGUI (default 365 days), separate from fail2ban `dbpurgeage`, to keep app storage bounded while preserving audit data.
- Expose API endpoints for querying persistent history, with filters for timeframe, jail, origin, IP, and current ban status.
- On fail2ban connectivity failure, BanGUI continues serving historical data; next successful sync resumes ingestion without data loss.
---
## 8. External Blocklist Importer
Automated downloading and applying of external IP blocklists to block known malicious IPs on a recurring schedule.
### Blocklist Sources
- Manage a list of external blocklist URLs (e.g. `https://lists.blocklist.de/lists/all.txt`).
- Add, edit, or remove blocklist source URLs through the web interface.
- Each source has a name, URL, and an enabled/disabled toggle.
- Support for plain-text lists with one IP address per line.
- Preview the contents of a blocklist URL before enabling it (download and display a sample of entries).
#### URL Validation & Security
- **Scheme restriction:** Only `http://` and `https://` schemes are accepted. `file://`, `ftp://`, and other schemes are rejected.
- **Hostname validation:** The hostname is resolved via DNS and the resulting IP address is validated to prevent SSRF attacks:
- Private IP ranges (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`) are rejected.
- Loopback addresses (`127.0.0.1`, `::1`) are rejected.
- Link-local addresses (`169.254.0.0/16`, `fe80::/10`) are rejected.
- Reserved and multicast addresses are rejected.
- **Error handling:** If a URL fails validation (invalid scheme, unresolvable hostname, or resolves to a private IP), the API returns a `400 Bad Request` with a descriptive error message.
- **Ports:** URLs may specify custom ports (e.g. `https://example.com:8443/list.txt`), but the hostname must still resolve to a public IP address.
### Schedule
- Configure when the blocklist import runs using a simple time-and-frequency picker (no raw cron syntax required).
- Default schedule: daily at 03:00 (server local time).
- Available frequency presets:
- Every X hours
- Daily at a specific time
- Weekly on a specific day and time
- Option to run an import manually at any time via a "Run Now" button.
- Show the date and time of the last successful import and the next scheduled run.
### Import Behaviour
- On each scheduled run, download all enabled blocklist sources.
- Validate that each downloaded entry is a well-formed IP address or CIDR range before applying it.
- Apply downloaded IPs as bans through fail2ban (preferred) or directly via an iptables chain, depending on configuration.
- If using an iptables chain: flush the chain before re-populating it so stale entries are removed automatically.
- If using fail2ban: ban each IP in a dedicated jail created for blocklist imports so they are tracked separately from regular bans.
- Skip empty lines and malformed entries gracefully instead of aborting the entire import.
- Clean up temporary downloaded files after processing.
### Import Log
- Keep a log of every import run: timestamp, source URL, number of IPs imported, number of entries skipped (invalid), and any errors.
- Display the import log in the web interface, filterable by source and date range.
- Show a warning badge in the navigation if the most recent import encountered errors.
### Error Handling
- If a blocklist URL is unreachable, log the error and continue with remaining sources.
- If curl (or the download mechanism) is unavailable, surface a clear error in the import log.
- Notify the user (via the UI status bar) when a scheduled import fails so it does not go unnoticed.
---
## 9. General Behaviour
- **Responsive layout** — Usable on desktop and tablet screens.
- **Session persistence** — The user stays logged in until they explicitly log out or the session expires.
- **Consistent navigation** — A sidebar or top navigation bar is visible on every page, providing quick access to all sections: Dashboard, World Map, Jails, Configuration, History, and Logout.
- **Time zone awareness** — All displayed times respect the time zone configured during setup.
- **Connection health** — The application continuously checks whether the fail2ban server is reachable and shows a clear warning when the connection is lost.