ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(install): put a default-deny firewall and fail2ban on a stock install
Juan Denis3c30d2f537de
diff --git a/backend/app/services/setup_health_service.py b/backend/app/services/setup_health_service.pyindex 46edf6e6..667d61ed 100644--- a/backend/app/services/setup_health_service.py+++ b/backend/app/services/setup_health_service.py@@ -10,8 +10,10 @@ personal "secure your account" nudge.Severity is graded by Decision 2's *silent-breakage* rule: an item is``critical`` only when leaving it undone silently breaks something the operatoralready set in motion (e.g. per-site DNS mode with no provider/IP — sites won't-resolve). Everything else is ``recommended``. **HTTPS/TLS items are never-critical** — SSL is optional by decree.+resolve; no host firewall — every container port a deploy maps onto the host is+world-reachable and nothing in the UI says so). Everything else is+``recommended``. **HTTPS/TLS items are never critical** — SSL is optional by+decree.Scope is ``panel`` (a whole-instance setting, admin-only) or ``user`` (a personalitem like account 2FA). Panel snoozes live in a SettingsService map; personal@@ -52,11 +54,20 @@ _ITEM_SCOPES = {'setup.email_delivery': 'panel','setup.backup_policy': 'panel','setup.backup_offsite': 'panel',+ 'setup.firewall': 'panel',+ 'setup.fail2ban': 'panel','setup.canonical_domain': 'panel','setup.wildcard_cert': 'panel','setup.account_security': 'user',}+# Where install.sh puts this host's panel config (install.sh CONFIG_DIR). Its+# presence is the marker for "ServerKit was installed onto THIS host", which is+# what makes the host-firewall items applicable at all — see+# SetupHealthService._manages_host_firewall(). Module-level so tests can point+# it somewhere harmless.+HOST_CONFIG_DIR = '/etc/serverkit'+def _link(to):"""A deep-link fix descriptor pointing the operator at where to finish."""@@ -230,6 +241,12 @@ class SetupHealthService:# --- offsite backup ---items.append(cls._backup_offsite_item())+ # --- host hardening (only on a host this panel actually owns) ---+ for probe in (cls._firewall_item, cls._fail2ban_item):+ probed = probe()+ if probed is not None:+ items.append(probed)+# --- canonical panel domain ---canonical = (cls._get('canonical_domain', '') or '').strip()if canonical:@@ -323,6 +340,138 @@ class SetupHealthService:'storage so a backup survives losing the box.', RECOMMENDED,_link('/settings/storage'))+ # ------------------------------------------------------------------ #+ # Host hardening (firewall + fail2ban)+ # ------------------------------------------------------------------ #++ @staticmethod+ def _in_container():+ """True when the panel is running inside a container.++ Mirrors install.sh's ``detect_container``. Inside a container the HOST+ owns netfilter, not this guest, so "no firewall here" says nothing+ about the box's exposure — reporting it would be a false alarm on every+ docker-compose deployment.+ """+ if os.path.exists('/.dockerenv'):+ return True+ probes = (+ ('/proc/1/cgroup', ('docker', 'containerd', 'lxc', 'kubepods')),+ ('/proc/1/environ', ('container=',)),+ )+ for path, needles in probes:+ try:+ with open(path, 'rb') as fh:+ blob = fh.read().decode('utf-8', 'replace').lower()+ except OSError:+ continue+ if any(n in blob for n in needles):+ return True+ return False++ @classmethod+ def _manages_host_firewall(cls):+ """Whether the firewall / fail2ban items apply to this install at all.++ They only mean something on a Linux box that ServerKit was *installed+ onto* and whose inbound traffic this panel is responsible for:++ * **non-Linux** — a dev checkout on Windows/macOS. There is no host to+ judge (the wildcard-cert item guards itself the same way).+ * **containerised** — the host, not this guest, owns the firewall.+ * **no /etc/serverkit** — install.sh never ran here (dev checkout, CI+ runner, an unrelated machine), so a missing UFW is not this install's+ omission and the operator has nothing to act on.++ Failing the test drops the items entirely rather than reporting them+ ``ok``: an item nobody can act on is noise, and a fake ``ok`` would+ inflate the setup score.+ """+ if not sys.platform.startswith('linux'):+ return False+ if not os.path.isdir(HOST_CONFIG_DIR):+ return False+ return not cls._in_container()++ @classmethod+ def _firewall_item(cls):+ """Host firewall — the one setup item that is critical for *security*.++ Critical under the module's silent-breakage rule: ServerKit publishes+ managed apps by mapping container ports onto the host (8001-8999) and+ will happily stand up database containers on their stock ports. With no+ firewall those are reachable from the internet the moment they start.+ The operator set that in motion by deploying, nothing in the UI says the+ port is public, and the failure mode is a compromise rather than an+ error message — silent breakage, exactly what ``critical`` means here.++ (Not an HTTPS/TLS item, so the SSL-optional decree does not apply.)+ """+ if not cls._manages_host_firewall():+ return None+ try:+ from app.services.firewall_service import FirewallService+ status = FirewallService.get_status() or {}+ except Exception: # noqa: BLE001 — a probe must never break the sweep+ return None++ if status.get('any_active'):+ name = status.get('active_firewall') or 'a firewall'+ return _item(+ 'setup.firewall', 'Host firewall', 'ok',+ f'Inbound traffic is filtered by {name}.', RECOMMENDED,+ _link('/security/firewall'))+ return _item(+ 'setup.firewall', 'Host firewall', 'fail',+ 'No firewall is active on this server, so every port a managed app '+ 'or database container maps onto the host is reachable from the '+ 'internet. Turn on UFW (or firewalld) with default-deny inbound, '+ 'allowing only SSH, 80 and 443. Snooze this item if your firewall '+ 'lives at the provider edge instead.',+ CRITICAL, _link('/security/firewall'))++ @classmethod+ def _fail2ban_item(cls):+ """Brute-force protection.++ Recommended, not critical: the panel already throttles its own logins+ per-IP (``AUTH_IP_MAX_ATTEMPTS``), so a missing fail2ban thins out+ defence in depth rather than silently breaking something the operator+ started — which is the bar ``critical`` has to clear in this registry.+ """+ if not cls._manages_host_firewall():+ return None+ try:+ from app.services.security_service import SecurityService+ status = SecurityService.get_fail2ban_status() or {}+ except Exception: # noqa: BLE001+ return None++ if not status.get('installed'):+ return _item(+ 'setup.fail2ban', 'Brute-force protection', 'warn',+ 'fail2ban is not installed, so repeated SSH login failures are '+ 'never banned at the host level and the panel\'s jail '+ 'management stays inert.', RECOMMENDED,+ _link('/security/fail2ban'))+ if not status.get('service_running'):+ return _item(+ 'setup.fail2ban', 'Brute-force protection', 'warn',+ 'fail2ban is installed but not running, so none of its jails '+ 'are banning anything.', RECOMMENDED, _link('/security/fail2ban'))++ jails = status.get('jails') or []+ if not any('ssh' in str(j).lower() for j in jails):+ return _item(+ 'setup.fail2ban', 'Brute-force protection', 'warn',+ 'fail2ban is running but no SSH jail is enabled — password '+ 'spraying against sshd goes unthrottled.', RECOMMENDED,+ _link('/security/fail2ban'))+ return _item(+ 'setup.fail2ban', 'Brute-force protection', 'ok',+ 'fail2ban is running with an SSH jail.', RECOMMENDED,+ _link('/security/fail2ban'))+@classmethoddef _wildcard_cert_item(cls, base, mode):"""The wildcard-cert item — only applicable once wildcard HTTPS is on fordiff --git a/backend/tests/test_setup_health.py b/backend/tests/test_setup_health.pyindex c2eeab78..29d860f0 100644--- a/backend/tests/test_setup_health.py+++ b/backend/tests/test_setup_health.py@@ -191,6 +191,169 @@ def test_canonical_domain_warn_when_unset(app):assert c['status'] == 'warn'+# --------------------------------------------------------------------------- #+# Host hardening — firewall (critical) + fail2ban (recommended), plan 73 item 8+#+# These items only exist on a Linux host this panel was installed onto (see+# SetupHealthService._manages_host_firewall). Everything below drives that gate+# explicitly so the assertions don't depend on the machine running the suite.+# --------------------------------------------------------------------------- #++def managed_host(monkeypatch):+ """Pretend this panel owns a real Linux host's firewall."""+ from app.services.setup_health_service import SetupHealthService as S+ monkeypatch.setattr(S, '_manages_host_firewall', classmethod(lambda cls: True))+++def fake_firewall(monkeypatch, **status):+ from app.services.firewall_service import FirewallService+ monkeypatch.setattr(FirewallService, 'get_status',+ classmethod(lambda cls: status))+++def fake_fail2ban(monkeypatch, **status):+ from app.services.security_service import SecurityService+ monkeypatch.setattr(SecurityService, 'get_fail2ban_status',+ classmethod(lambda cls: status))+++def test_firewall_item_absent_on_an_unmanaged_host(app):+ """No /etc/serverkit (dev checkout, CI runner) or a container → the items+ drop out entirely rather than reporting a fake 'ok' that would inflate the+ score or a fake 'fail' the operator cannot act on."""+ keys = items_by_key(SetupHealthService.evaluate())+ assert 'setup.firewall' not in keys+ assert 'setup.fail2ban' not in keys+++def test_firewall_critical_when_nothing_is_active(app, managed_host, monkeypatch):+ """The proving assertion: a firewall-less box is flagged CRITICAL."""+ fake_firewall(monkeypatch, any_installed=False, any_active=False,+ active_firewall=None)+ fake_fail2ban(monkeypatch, installed=False)+ c = items_by_key(SetupHealthService.evaluate())['setup.firewall']+ assert c['status'] == 'fail'+ assert c['severity'] == 'critical'+ assert c['fix'] == {'kind': 'link', 'to': '/security/firewall'}+++def test_firewall_ok_when_a_firewall_is_active(app, managed_host, monkeypatch):+ fake_firewall(monkeypatch, any_installed=True, any_active=True,+ active_firewall='ufw')+ fake_fail2ban(monkeypatch, installed=False)+ c = items_by_key(SetupHealthService.evaluate())['setup.firewall']+ assert c['status'] == 'ok'+ assert 'ufw' in c['detail']+++def test_firewall_installed_but_inactive_is_still_critical(app, managed_host, monkeypatch):+ # Installed-and-off filters exactly as much traffic as not installed at all.+ fake_firewall(monkeypatch, any_installed=True, any_active=False,+ active_firewall='ufw')+ fake_fail2ban(monkeypatch, installed=False)+ c = items_by_key(SetupHealthService.evaluate())['setup.firewall']+ assert c['status'] == 'fail'+ assert c['severity'] == 'critical'+++def test_firewall_probe_failure_drops_the_item(app, managed_host, monkeypatch):+ from app.services.firewall_service import FirewallService++ def boom(cls):+ raise OSError('sudo: command not found')++ monkeypatch.setattr(FirewallService, 'get_status', classmethod(boom))+ fake_fail2ban(monkeypatch, installed=False)+ # A probe that cannot answer must never take the whole sweep down, and must+ # never report a firewall it did not observe.+ keys = items_by_key(SetupHealthService.evaluate())+ assert 'setup.firewall' not in keys+++def test_fail2ban_absent_is_recommended_not_critical(app, managed_host, monkeypatch):+ """The panel already throttles its own logins per-IP, so a missing fail2ban+ is defence-in-depth, not silent breakage."""+ fake_firewall(monkeypatch, any_active=True, active_firewall='ufw')+ fake_fail2ban(monkeypatch, installed=False, service_running=False, jails=[])+ c = items_by_key(SetupHealthService.evaluate())['setup.fail2ban']+ assert c['status'] == 'warn'+ assert c['severity'] == 'recommended'+ assert c['fix'] == {'kind': 'link', 'to': '/security/fail2ban'}+++def test_fail2ban_installed_but_stopped_warns(app, managed_host, monkeypatch):+ fake_firewall(monkeypatch, any_active=True, active_firewall='ufw')+ fake_fail2ban(monkeypatch, installed=True, service_running=False, jails=[])+ c = items_by_key(SetupHealthService.evaluate())['setup.fail2ban']+ assert c['status'] == 'warn'+++def test_fail2ban_running_without_an_ssh_jail_warns(app, managed_host, monkeypatch):+ # Running with only a per-site WordPress jail leaves sshd unprotected —+ # which is the jail the installer now writes.+ fake_firewall(monkeypatch, any_active=True, active_firewall='ufw')+ fake_fail2ban(monkeypatch, installed=True, service_running=True,+ jails=['serverkit-blog'])+ c = items_by_key(SetupHealthService.evaluate())['setup.fail2ban']+ assert c['status'] == 'warn'+ assert 'SSH' in c['detail']+++def test_fail2ban_ok_with_the_sshd_jail(app, managed_host, monkeypatch):+ fake_firewall(monkeypatch, any_active=True, active_firewall='ufw')+ fake_fail2ban(monkeypatch, installed=True, service_running=True,+ jails=['sshd', 'serverkit-blog'])+ c = items_by_key(SetupHealthService.evaluate())['setup.fail2ban']+ assert c['status'] == 'ok'+++def test_hardening_items_are_snoozable(app, managed_host, monkeypatch):+ """A box whose firewall lives at the provider edge must be able to mute the+ critical — otherwise the weekly nag becomes permanent noise. Snoozing needs+ the key registered in _ITEM_SCOPES."""+ fake_firewall(monkeypatch, any_active=False, active_firewall=None)+ fake_fail2ban(monkeypatch, installed=False)+ assert SetupHealthService.snooze('setup.firewall', days=30).get('success')+ assert SetupHealthService.snooze('setup.fail2ban', days=30).get('success')+ result = SetupHealthService.evaluate()+ assert items_by_key(result)['setup.firewall']['snoozed'] is True+ assert result['summary']['critical_open'] == 0+++def test_firewall_critical_shows_up_in_the_fingerprint(app, managed_host, monkeypatch):+ """The nag has to be able to see it — a critical that never reaches the+ fingerprint never notifies anyone."""+ fake_firewall(monkeypatch, any_active=False, active_firewall=None)+ fake_fail2ban(monkeypatch, installed=False)+ assert 'setup.firewall' in SetupHealthService.fingerprint()+++def test_manages_host_firewall_gate_is_conservative(app, monkeypatch):+ """The gate itself: Linux + install marker + not a container, all three."""+ import app.services.setup_health_service as m+ S = m.SetupHealthService+ monkeypatch.setattr(m.sys, 'platform', 'linux')+ monkeypatch.setattr(m.os.path, 'isdir', lambda p: p == m.HOST_CONFIG_DIR)++ monkeypatch.setattr(S, '_in_container', staticmethod(lambda: False))+ assert S._manages_host_firewall() is True++ # A container guest does not own the host's netfilter.+ monkeypatch.setattr(S, '_in_container', staticmethod(lambda: True))+ assert S._manages_host_firewall() is False++ # Neither does a dev checkout on Windows/macOS.+ monkeypatch.setattr(S, '_in_container', staticmethod(lambda: False))+ monkeypatch.setattr(m.sys, 'platform', 'win32')+ assert S._manages_host_firewall() is False++ # …nor a Linux box install.sh never touched.+ monkeypatch.setattr(m.sys, 'platform', 'linux')+ monkeypatch.setattr(m.os.path, 'isdir', lambda p: False)+ assert S._manages_host_firewall() is False++# --------------------------------------------------------------------------- ## Severity mapping — HTTPS is NEVER critical (SSL optional by decree)# --------------------------------------------------------------------------- #diff --git a/frontend/src/pages/Dashboard.jsx b/frontend/src/pages/Dashboard.jsxindex 1c80c179..a4ea3502 100644--- a/frontend/src/pages/Dashboard.jsx+++ b/frontend/src/pages/Dashboard.jsx@@ -13,6 +13,7 @@ import { Popover, PopoverTrigger, PopoverContent } from '@/components/ui/popoverimport { SegControl } from '@/components/ds';import EmptyState from '../components/EmptyState';import PluginSlot from '../components/PluginSlot';+import SetupHealthWidget from '../components/dashboard/SetupHealthWidget';import { DashGrid } from '../components/dashboard/grid/DashGrid';import { WidgetLibrary } from '../components/dashboard/grid/WidgetLibrary';import { WidgetEditor } from '../components/dashboard/grid/WidgetEditor';@@ -341,6 +342,13 @@ const Dashboard = () => {{/* Extension slot: widgets contributed to the top of the dashboard */}<PluginSlot name="dashboard.top" />+ {/* Setup health. Deliberately NOT a placeable board widget: an+ unfirewalled box must be visible without the operator first+ opting into a widget, and the card collapses to a single "all+ set" line once everything is done, so it costs nothing when+ clean. Admin-only — the endpoint is too. */}+ {isAdmin && <SetupHealthWidget />}+{/* Board tabs + board-wide controls */}<div className="skw-bar"><div className="skw-tabs">diff --git a/frontend/src/styles/components/_setup-health.scss b/frontend/src/styles/components/_setup-health.scssindex 90104bf6..0cbff3e3 100644--- a/frontend/src/styles/components/_setup-health.scss+++ b/frontend/src/styles/components/_setup-health.scss@@ -1,11 +1,12 @@// ============================================-// SETUP HEALTH — dashboard widget+// SETUP HEALTH — dashboard card// Compact "how set-up is this panel" card: score + top open items, each// deep-linking to its fix. Collapses to a slim "all set" line when clean.+// Sits above the board as a direct child of .dashboard-page (a flex column),+// so vertical rhythm comes from that container's gap — no margin here.// ============================================.setup-health-widget {- grid-column: span 6;display: flex;flex-direction: column;gap: $space-3;@@ -120,10 +121,6 @@}}-@media (max-width: $breakpoint-md) {- .setup-health-widget { grid-column: span 12; }-}-// Per-user "secure your account" nudge banner (dashboard top)..account-security-nudge {display: flex;diff --git a/frontend/src/styles/main.scss b/frontend/src/styles/main.scssindex 1baf22a0..e9c6a4cd 100644--- a/frontend/src/styles/main.scss+++ b/frontend/src/styles/main.scss@@ -74,6 +74,7 @@@import 'components/_design-system'; // redesign shared primitives (sk-* namespace)@import 'components/_datagrid'; // DataGrid list surface (sk-grid*, ds/grid/)@import 'components/_dashboard-widgets'; // configurable dashboard grid (skw-* namespace)+@import 'components/_setup-health'; // dashboard setup-health card + account nudge@import 'components/_widget-editor'; // wide preview+settings widget drawer (skwe-* namespace)@import 'components/_system-notices';@import 'components/_requires-docker';diff --git a/install.sh b/install.shindex e8b5337f..cc442279 100644--- a/install.sh+++ b/install.sh@@ -1388,6 +1388,209 @@ build_frontend() {randomize_favicon}+# ---------------------------------------------------------------------------+# SSH port discovery — the safety interlock in front of default-deny.+#+# Turning on a default-deny firewall without allowing the port sshd actually+# answers on locks the operator out of their own server, over the very SSH+# session running this installer. So: never guess. Ask, in descending order of+# authority, and treat "no answer" as a hard stop rather than "probably 22".+#+# 1. `sshd -T` — the EFFECTIVE config. It resolves Include directives, so it+# sees a port declared in /etc/ssh/sshd_config.d/*.conf that a naive grep+# of sshd_config alone would miss (Ubuntu 22.04+ ships exactly that shape).+# 2. sshd_config + its drop-ins, parsed here. Covers boxes where `sshd -T`+# refuses to run (missing host keys in a fresh image, non-root, ...).+# 3. Whatever sshd is listening on right now, per `ss`. Catches a running+# daemon whose config on disk has drifted from what it was started with.+#+# A config file that names no Port at all means sshd's compiled-in default, so+# that case — and ONLY that case — resolves to 22. If not one of the three+# sources produced anything, the function returns non-zero and the caller must+# not enable a firewall: an exposed box is recoverable, a locked-out one+# usually is not.+#+# Echoes one port per line. SSHD_CONFIG_ROOT overrides /etc/ssh for tests.+# ---------------------------------------------------------------------------+detect_ssh_ports() {+ local etc="${SSHD_CONFIG_ROOT:-/etc/ssh}"+ local main="$etc/sshd_config"+ local raw="" ports="" p have_source=0++ if command -v sshd >/dev/null 2>&1; then+ raw="$(sshd -T 2>/dev/null | awk 'tolower($1) == "port" { print $2 }')" || raw=""+ [ -n "$raw" ] && have_source=1+ fi++ if [ -z "$raw" ] && [ -f "$main" ]; then+ have_source=1+ # Strip comments first so a commented-out "#Port 22" never counts.+ #+ # The `|| true` around cat is load-bearing, not defensive noise: most+ # boxes have no sshd_config.d/*.conf, the unmatched glob makes cat exit+ # non-zero, and under the installer's `set -o pipefail` that failure+ # would wipe a perfectly good answer — falling through to the "22"+ # default below on a box whose sshd is on 2222, and locking the+ # operator out. Exactly the failure this function exists to prevent.+ raw="$( { cat "$main" "$etc"/sshd_config.d/*.conf 2>/dev/null || true; } \+ | sed -e 's/#.*//' \+ | awk 'tolower($1) == "port" { print $2 }' )" || raw=""+ fi++ if [ -z "$raw" ] && command -v ss >/dev/null 2>&1; then+ raw="$(ss -H -tlnp 2>/dev/null | awk '/"sshd"/ { n = split($4, a, ":"); print a[n] }')" || raw=""+ [ -n "$raw" ] && have_source=1+ fi++ # A config that exists but names no Port means the built-in default.+ if [ -z "$raw" ] && [ "$have_source" = "1" ]; then+ raw="22"+ fi++ # Keep only plausible port numbers, de-duplicated, order preserved.+ for p in $raw; do+ case "$p" in+ ''|*[!0-9]*) continue ;;+ esac+ [ "$p" -ge 1 ] && [ "$p" -le 65535 ] || continue+ case " $ports " in+ *" $p "*) continue ;;+ esac+ ports="$ports $p"+ done+ ports="${ports# }"++ [ -n "$ports" ] || return 1+ for p in $ports; do printf '%s\n' "$p"; done+}++# Run a firewall command, or print it under FW_DRY_RUN. Same contract as+# scripts/lib/firewall.sh's _fw_run, kept local so the bootstrap below never+# depends on a private of that lib.+fw_bootstrap_run() {+ if [ "${FW_DRY_RUN:-0}" = "1" ]; then+ printf ' [firewall] would run: %s\n' "$*"+ return 0+ fi+ # Best-effort, like the lib's _fw_run callers: a rule that fails to apply+ # must never abort a `set -e` install. bootstrap_firewall's closing+ # `ufw status` check is what actually decides whether this worked.+ "$@" >/dev/null 2>&1 || true+}++# ---------------------------------------------------------------------------+# Firewall bootstrap: put a default-deny firewall on a box that has none.+#+# The installer used to open 80/443 on whatever firewall it found and shrug+# ("assuming ports 80/443 are already open") when there wasn't one — which is+# the state of a stock Ubuntu/Debian VPS. That box then runs ServerKit with+# every port a deploy maps onto the host (8001-8999, plus database containers)+# facing the internet.+#+# Refuses to act, in this order, when:+# * SERVERKIT_SKIP_FIREWALL=1 — operator said no; never argue.+# * OS_FAMILY is not debian — UFW is Debian/Ubuntu. RHEL-family boxes+# already boot with firewalld ACTIVE, so+# configure_firewall's open step covers+# them. A firewalld default-deny bootstrap+# for the boxes where it is *inactive* is+# a deliberate follow-up: zones/services+# are different enough that copying this+# logic across would be wrong.+# * a firewall is already active — it is the operator's. Opening ports on+# it is fine (next phase); rewriting its+# default policy is not.+# * inside a container — the host owns netfilter; ufw either+# fails outright (no NET_ADMIN) or, worse,+# half-applies.+# * we bootstrapped on a previous run and it is off now — the operator turned+# it off on purpose. A re-run must not+# undo that.+# * the SSH port is unknown — see detect_ssh_ports. Hard stop.+# ---------------------------------------------------------------------------+FIREWALL_BOOTSTRAP_KEY="firewall_bootstrapped"++bootstrap_firewall() {+ if [ "${SERVERKIT_SKIP_FIREWALL:-0}" = "1" ]; then+ good "Skipping firewall setup (SERVERKIT_SKIP_FIREWALL=1)."+ return 0+ fi+ if [ "${OS_FAMILY:-}" != "debian" ]; then+ return 0+ fi+ if [ "$(firewall_detect)" != "none" ]; then+ return 0+ fi++ local ctr+ ctr="$(detect_container)"+ if [ -n "$ctr" ]; then+ warn "Running inside $ctr — leaving the firewall to the host."+ return 0+ fi++ if command -v state_get >/dev/null 2>&1 \+ && [ "$(state_get "$FIREWALL_BOOTSTRAP_KEY" 2>/dev/null || true)" = "1" ]; then+ good "A previous install set up the firewall and it is off now — leaving it alone."+ return 0+ fi++ # ---- the interlock. Nothing below runs without a known SSH port. -------+ local ssh_ports+ if ! ssh_ports="$(detect_ssh_ports)"; then+ warn "Could not determine which port sshd listens on — NOT enabling a firewall."+ warn "Refusing to risk locking you out. Declare 'Port <n>' in /etc/ssh/sshd_config and re-run,"+ warn "or set up UFW yourself: ufw allow <ssh>/tcp && ufw allow 80,443/tcp && ufw enable"+ return 0+ fi++ if ! command -v ufw >/dev/null 2>&1; then+ step "Installing UFW..."+ pkg_add ufw+ fi+ if ! command -v ufw >/dev/null 2>&1; then+ warn "UFW is unavailable — this box is left without a firewall."+ return 0+ fi++ # Order IS the safety property: every allow rule lands BEFORE the+ # default-deny policy, and the policy before the firewall is switched on.+ # `ufw allow` is idempotent ("Skipping adding existing rule"), so a re-run+ # never duplicates anything.+ local port+ for port in $ssh_ports; do+ step "Allowing SSH on ${port}/tcp..."+ fw_bootstrap_run ufw allow "${port}/tcp"+ done+ fw_bootstrap_run ufw allow 80/tcp+ fw_bootstrap_run ufw allow 443/tcp+ # A panel published on a non-standard port needs that port too, or the+ # operator loses the UI the instant default-deny lands.+ case "${PANEL_PORT:-80}" in+ 80|443) : ;;+ *) fw_bootstrap_run ufw allow "${PANEL_PORT}/tcp" ;;+ esac++ fw_bootstrap_run ufw default deny incoming+ fw_bootstrap_run ufw default allow outgoing+ fw_bootstrap_run ufw --force enable++ if [ "${FW_DRY_RUN:-0}" = "1" ]; then+ good "Firewall bootstrap (dry run) complete."+ return 0+ fi++ if ufw status 2>/dev/null | grep -q 'Status: active'; then+ good "UFW enabled: default-deny inbound; SSH ($(printf '%s' "$ssh_ports" | tr '\n' ' ')), 80 and 443 allowed."+ if command -v state_set >/dev/null 2>&1; then+ state_set "$FIREWALL_BOOTSTRAP_KEY" 1 || true+ fi+ else+ warn "UFW did not come up active — this box is still unfirewalled."+ fi+ return 0+}+# ---------------------------------------------------------------------------# Firewall: open 80/443 so the panel is reachable from the outside, and record# exactly what we opened in /etc/serverkit/install-state.json so uninstall can@@ -1403,6 +1606,10 @@ configure_firewall() {fiload_serverkit_lib state.sh || true+ # Stock Debian/Ubuntu ships no firewall at all; put one there before the+ # "no active firewall detected" branch below just shrugs at it.+ bootstrap_firewall+local backendbackend="$(firewall_detect)"if [ "$backend" = "none" ]; then@@ -1470,18 +1677,74 @@ svc_start() {return 0}+# Write the SSH brute-force jail as a jail.d drop-in.+#+# sshd is the one service every box exposes and it is under a password spray+# within minutes of getting a public IP, so this is the jail that matters on a+# fresh VPS. Two things make it correct rather than decorative:+#+# * it watches the SAME port(s) detect_ssh_ports found for the firewall — a+# jail pinned to :22 on a box whose sshd moved to :2222 bans nobody;+# * it declares `backend = systemd` when there is no syslog file to tail+# (Ubuntu 24.04+ and RHEL are journald-only). Without that the jail refuses+# to start with "Have not found any log file for sshd jail" and fail2ban+# looks installed while protecting nothing.+#+# The filename deliberately does NOT start with "serverkit-": that prefix is+# Fail2banJailService's ownership namespace for per-site jails, and this file is+# the installer's. It sorts after Debian's defaults-debian.conf, so jail.d+# ordering makes ours the winner. Regenerated on every run (idempotent).+write_sshd_jail() {+ local jail_dir ports backend_line=""+ jail_dir="${FAIL2BAN_JAIL_DIR:-/etc/fail2ban/jail.d}"++ if ! ports="$(detect_ssh_ports)"; then+ warn "Could not determine the SSH port — leaving fail2ban's sshd jail at its defaults."+ return 0+ fi+ ports="$(printf '%s' "$ports" | tr '\n' ',' | sed 's/,$//')"++ if [ ! -f /var/log/auth.log ] && [ ! -f /var/log/secure ] && svc_has_systemd; then+ backend_line="backend = systemd"+ fi++ mkdir -p "$jail_dir" 2>/dev/null || true+ if ! cat > "$jail_dir/sshd-serverkit.conf" <<F2B_EOF+# ServerKit-managed fail2ban jail: SSH brute force.+# Generated by install.sh - regenerated on every install, do not edit by hand.+[sshd]+enabled = true+port = ${ports}+${backend_line}+maxretry = 5+findtime = 600+bantime = 3600+F2B_EOF+ then+ warn "Could not write the fail2ban sshd jail to $jail_dir."+ return 0+ fi+ good "fail2ban sshd jail watching port(s): ${ports}."+}+provision_hardening() {- # What makes "full" more than "standard".+ # What "standard" and "full" each put on the box.## The panel ships two features that quietly do nothing unless a daemon it- # never installs is present: fail2ban_jail_service manages jails but no- # profile installed fail2ban, and configure_nginx only warns "Install- # certbot and run..." when certbot is missing. Standard leaves both to the- # operator; full is the profile that says "put the whole thing on".+ # never installs is present: fail2ban_jail_service manages jails, and+ # configure_nginx only warns "Install certbot and run..." when certbot is+ # missing.+ #+ # fail2ban is standard-and-up: the small VPS is EXACTLY the box that gets+ # SSH-brute-forced, and leaving it to "full" meant the typical install got+ # neither a firewall nor a jail. certbot stays a "full" extra — HTTPS is+ # optional by decree, so it is a choice, not a baseline.## Every step is warn-and-continue (pkg_add's contract) — a hardening extra# that fails to install must never abort an otherwise good install.- [ "$PROFILE" = "full" ] || return 0+ case "$PROFILE" in+ minimal) return 0 ;;+ esacphase "Hardening"@@ -1492,6 +1755,7 @@ provision_hardening() {pkg_add fail2banfiif command -v fail2ban-server &>/dev/null; then+ write_sshd_jailsvc_enable fail2bansvc_start fail2bangood "fail2ban enabled — manage jails from Security in the panel."@@ -1499,6 +1763,9 @@ provision_hardening() {warn "fail2ban unavailable; the panel's jail management will stay inert."fi+ # Everything below is what makes "full" more than "standard".+ [ "$PROFILE" = "full" ] || return 0+# Certbot only matters when this install is actually attempting HTTPS.if [ "$SERVERKIT_SKIP_SSL" = "1" ]; thengood "Skipping certbot (SERVERKIT_SKIP_SSL=1)."diff --git a/scripts/test/test_install.sh b/scripts/test/test_install.shindex 98439a4b..c0e53a71 100644--- a/scripts/test/test_install.sh+++ b/scripts/test/test_install.sh@@ -1294,14 +1294,29 @@ fi# "full" has to earn its name — it was byte-identical to "standard" until# provision_hardening existed, so the card promised things nothing installed.pkgt="$WORK/t31pkg"; mkdir -p "$pkgt"-out="$( set -Eeuo pipefail; PROFILE=standard; OS_FAMILY=debian; PKG_MGR=apt+out="$( set -Eeuo pipefail; PROFILE=minimal; OS_FAMILY=debian; PKG_MGR=aptSERVERKIT_SKIP_SSL=0pkg_add() { printf 'PKGADD:%s\n' "$*"; }provision_hardening 2>&1 )"if [ -z "$out" ]; then- ok "provision_hardening is a no-op on the standard profile"+ ok "provision_hardening is a no-op on the minimal profile"+else+ bad "provision_hardening ran on minimal: [$out]"+fi++# fail2ban is standard-and-up (plan 73 item 8): the small VPS is exactly the box+# that gets SSH-brute-forced, so leaving it to "full" meant the typical install+# got no jail at all. certbot stays a "full" extra — HTTPS is optional.+out="$( set -Eeuo pipefail; PROFILE=standard; OS_FAMILY=debian; PKG_MGR=apt+ SERVERKIT_SKIP_SSL=0+ pkg_add() { printf 'PKGADD:%s\n' "$*"; }+ svc_enable() { :; }; svc_start() { :; }+ provision_hardening 2>&1 )"+if printf '%s' "$out" | grep -q 'PKGADD:fail2ban' && \+ ! printf '%s' "$out" | grep -q 'PKGADD:certbot'; then+ ok "provision_hardening installs fail2ban (not certbot) on the standard profile"else- bad "provision_hardening ran on standard: [$out]"+ bad "standard profile hardening is wrong: [$(printf '%s' "$out" | tr '\n' ' ')]"fiout="$( set -Eeuo pipefail; PROFILE=full; OS_FAMILY=debian; PKG_MGR=apt@@ -1463,6 +1478,238 @@ elsebad "the source guard no longer short-circuits a source: out=[$out]"fi+# --------------------------------------------------------------------------+# T42 — plan 73 item 8: a stock Debian/Ubuntu box gets a real firewall, and the+# SSH port is discovered BEFORE default-deny is switched on.+#+# This is the single most dangerous thing the installer does: enabling+# default-deny without allowing the port sshd actually answers on locks the+# operator out over the very session running the install. Every case below is a+# lockout-safety assertion.+#+# `sshd` and `ss` are stubbed to fail throughout so detection is forced down to+# the config-file parser and the fixtures decide the answer — otherwise the+# result would depend on whether the CI runner happens to run sshd.+# --------------------------------------------------------------------------+t42="$WORK/t42"; mkdir -p "$t42/bin" "$t42/ssh/sshd_config.d" "$t42/state"+make_stub_exit "$t42/bin" 1 sshd ss++# -- detection: a drop-in Port wins over a commented-out one in the main file.+printf '#Port 22\nPermitRootLogin no\n' > "$t42/ssh/sshd_config"+printf 'Port 2222\n' > "$t42/ssh/sshd_config.d/99-port.conf"+res="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ SSHD_CONFIG_ROOT="$t42/ssh" detect_ssh_ports | tr '\n' ' ' )"+if [ "$res" = "2222 " ]; then+ ok "detect_ssh_ports reads sshd_config.d drop-ins and ignores commented Ports"+else+ bad "detect_ssh_ports got [$res], expected the drop-in's 2222"+fi++# -- detection: several Port lines all come back, de-duplicated.+printf 'Port 22\nPort 2222\nPort 22\n' > "$t42/ssh/sshd_config"+: > "$t42/ssh/sshd_config.d/99-port.conf"+res="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ SSHD_CONFIG_ROOT="$t42/ssh" detect_ssh_ports | tr '\n' ' ' )"+if [ "$res" = "22 2222 " ]; then+ ok "detect_ssh_ports returns every declared port, de-duplicated"+else+ bad "detect_ssh_ports got [$res], expected [22 2222 ]"+fi++# -- detection: NO sshd_config.d directory at all — the common shape, and the+# one that bit hardest. The unmatched glob makes `cat` exit non-zero; under+# the installer's `set -o pipefail` that wiped the parsed answer and the+# function fell through to its "22" default. On a box whose sshd is on 2222+# that means UFW allows the wrong port and locks the operator out. Pinning+# it here because the failure only ever shows up on a real server.+t42b="$WORK/t42b"; mkdir -p "$t42b/ssh"+printf 'Port 2222\n' > "$t42b/ssh/sshd_config"+res="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ SSHD_CONFIG_ROOT="$t42b/ssh" detect_ssh_ports | tr '\n' ' ' )"+if [ "$res" = "2222 " ]; then+ ok "detect_ssh_ports reads sshd_config with no drop-in dir (pipefail regression)"+else+ bad "detect_ssh_ports got [$res] with no sshd_config.d — expected 2222, LOCKOUT RISK"+fi++# -- detection: a config that names no Port means sshd's built-in default.+printf 'PermitRootLogin no\n' > "$t42/ssh/sshd_config"+res="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ SSHD_CONFIG_ROOT="$t42/ssh" detect_ssh_ports | tr '\n' ' ' )"+if [ "$res" = "22 " ]; then+ ok "detect_ssh_ports falls back to 22 when the config names no Port"+else+ bad "detect_ssh_ports got [$res] for a Port-less config, expected 22"+fi++# -- detection: nothing to go on at all → NON-ZERO. This is the fail-safe the+# bootstrap keys off; if it ever starts guessing, the guard is gone.+if ( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ SSHD_CONFIG_ROOT="$t42/nonexistent" detect_ssh_ports >/dev/null 2>&1 ); then+ bad "detect_ssh_ports invented an SSH port with no config, no sshd and no ss"+else+ ok "detect_ssh_ports fails loudly when no source can name a port"+fi++# -- bootstrap: the happy path. Allow rules for SSH/80/443 must all be issued+# BEFORE `ufw default deny incoming`, and default-deny before `ufw enable`.+printf 'Port 2222\n' > "$t42/ssh/sshd_config"+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=debian; PANEL_PORT=80; FW_DRY_RUN=1; FIREWALL_BACKEND=none+ SSHD_CONFIG_ROOT="$t42/ssh"+ detect_container() { printf ''; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ command -v ufw >/dev/null 2>&1 || ufw() { :; }+ bootstrap_firewall 2>&1 )"+allow_ssh_ln="$(printf '%s\n' "$out" | grep -n 'ufw allow 2222/tcp' | head -1 | cut -d: -f1)"+allow_80_ln="$( printf '%s\n' "$out" | grep -n 'ufw allow 80/tcp' | head -1 | cut -d: -f1)"+allow_443_ln="$(printf '%s\n' "$out" | grep -n 'ufw allow 443/tcp' | head -1 | cut -d: -f1)"+deny_ln="$( printf '%s\n' "$out" | grep -n 'ufw default deny incoming' | head -1 | cut -d: -f1)"+enable_ln="$( printf '%s\n' "$out" | grep -n 'ufw --force enable' | head -1 | cut -d: -f1)"+if [ -n "$allow_ssh_ln" ] && [ -n "$allow_80_ln" ] && [ -n "$allow_443_ln" ] \+ && [ -n "$deny_ln" ] && [ -n "$enable_ln" ] \+ && [ "$allow_ssh_ln" -lt "$deny_ln" ] && [ "$allow_80_ln" -lt "$deny_ln" ] \+ && [ "$allow_443_ln" -lt "$deny_ln" ] && [ "$deny_ln" -lt "$enable_ln" ]; then+ ok "bootstrap_firewall allows SSH/80/443 before default-deny, and denies before enabling"+else+ bad "bootstrap_firewall rule ordering is unsafe: [$(printf '%s' "$out" | tr '\n' ' ')]"+fi++# -- bootstrap: the interlock. No discoverable SSH port ⇒ NOTHING is enabled.+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=debian; FW_DRY_RUN=1; FIREWALL_BACKEND=none+ SSHD_CONFIG_ROOT="$t42/nonexistent"+ detect_container() { printf ''; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ command -v ufw >/dev/null 2>&1 || ufw() { :; }+ bootstrap_firewall 2>&1 )"+if ! printf '%s' "$out" | grep -q 'ufw --force enable' \+ && ! printf '%s' "$out" | grep -q 'default deny' \+ && printf '%s' "$out" | grep -qi 'NOT enabling'; then+ ok "bootstrap_firewall refuses to enable a firewall when the SSH port is unknown"+else+ bad "bootstrap_firewall enabled default-deny without knowing the SSH port: [$(printf '%s' "$out" | tr '\n' ' ')]"+fi++# -- bootstrap: a non-standard PANEL_PORT is allowed too, or default-deny takes+# the panel UI down with it.+printf 'Port 22\n' > "$t42/ssh/sshd_config"+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=debian; PANEL_PORT=8443; FW_DRY_RUN=1; FIREWALL_BACKEND=none+ SSHD_CONFIG_ROOT="$t42/ssh"+ detect_container() { printf ''; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ command -v ufw >/dev/null 2>&1 || ufw() { :; }+ bootstrap_firewall 2>&1 )"+if printf '%s' "$out" | grep -q 'ufw allow 8443/tcp'; then+ ok "bootstrap_firewall opens a non-standard PANEL_PORT before default-deny"+else+ bad "bootstrap_firewall would lock the panel out on PANEL_PORT=8443: [$(printf '%s' "$out" | tr '\n' ' ')]"+fi++# -- bootstrap: an ALREADY-ACTIVE firewall is the operator's. Open ports on it+# (configure_firewall's job), never rewrite its default policy.+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=debian; FW_DRY_RUN=1; FIREWALL_BACKEND=firewalld+ SSHD_CONFIG_ROOT="$t42/ssh"+ detect_container() { printf ''; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ bootstrap_firewall 2>&1 )"+if [ -z "$out" ]; then+ ok "bootstrap_firewall leaves an already-active firewall's policy alone"+else+ bad "bootstrap_firewall touched an existing firewall: [$(printf '%s' "$out" | tr '\n' ' ')]"+fi++# -- bootstrap: non-Debian is a no-op (UFW is Debian/Ubuntu; RHEL boots with+# firewalld active and is handled by configure_firewall's open step).+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=rhel; FW_DRY_RUN=1; FIREWALL_BACKEND=none+ SSHD_CONFIG_ROOT="$t42/ssh"+ detect_container() { printf ''; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ bootstrap_firewall 2>&1 )"+if [ -z "$out" ]; then+ ok "bootstrap_firewall is a no-op outside the Debian family"+else+ bad "bootstrap_firewall tried to install UFW on a non-Debian box: [$(printf '%s' "$out" | tr '\n' ' ')]"+fi++# -- bootstrap: SERVERKIT_SKIP_FIREWALL=1 and containers are both hands-off.+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=debian; FW_DRY_RUN=1; FIREWALL_BACKEND=none+ SERVERKIT_SKIP_FIREWALL=1; SSHD_CONFIG_ROOT="$t42/ssh"+ detect_container() { printf ''; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ bootstrap_firewall 2>&1 )"+out2="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=debian; FW_DRY_RUN=1; FIREWALL_BACKEND=none+ SSHD_CONFIG_ROOT="$t42/ssh"+ detect_container() { printf 'lxc'; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ bootstrap_firewall 2>&1 )"+if ! printf '%s' "$out" | grep -q 'ufw' && ! printf '%s' "$out2" | grep -q 'ufw allow'; then+ ok "bootstrap_firewall honours SERVERKIT_SKIP_FIREWALL and skips containers"+else+ bad "bootstrap_firewall ignored an opt-out: [$out] [$out2]"+fi++# -- the re-run guard: we bootstrapped once, the operator switched the firewall+# off, a later install must NOT switch it back on.+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ OS_FAMILY=debian; FW_DRY_RUN=1; FIREWALL_BACKEND=none+ SSHD_CONFIG_ROOT="$t42/ssh"+ detect_container() { printf ''; }+ pkg_add() { :; }+ source "$LIB_DIR/firewall.sh"+ state_get() { [ "$1" = "firewall_bootstrapped" ] && printf '1' || printf ''; }+ bootstrap_firewall 2>&1 )"+if ! printf '%s' "$out" | grep -q 'ufw --force enable'; then+ ok "bootstrap_firewall does not re-enable a firewall the operator turned off"+else+ bad "bootstrap_firewall re-enabled a deliberately disabled firewall: [$(printf '%s' "$out" | tr '\n' ' ')]"+fi++# -- the sshd jail watches the port sshd actually uses, not a hardcoded 22.+printf 'Port 2222\n' > "$t42/ssh/sshd_config"+jail_dir="$t42/jail.d"+out="$( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ SSHD_CONFIG_ROOT="$t42/ssh"; FAIL2BAN_JAIL_DIR="$jail_dir"+ write_sshd_jail 2>&1 )"+if [ -f "$jail_dir/sshd-serverkit.conf" ] \+ && grep -q '^\[sshd\]' "$jail_dir/sshd-serverkit.conf" \+ && grep -q '^enabled = true' "$jail_dir/sshd-serverkit.conf" \+ && grep -q '^port = 2222' "$jail_dir/sshd-serverkit.conf"; then+ ok "write_sshd_jail enables the sshd jail on the detected SSH port"+else+ bad "write_sshd_jail wrote the wrong jail: [$(cat "$jail_dir/sshd-serverkit.conf" 2>/dev/null | tr '\n' ' ')] [$out]"+fi++# Re-running must not append or duplicate — the file is regenerated whole.+( set -Eeuo pipefail; PATH="$t42/bin:$PATH"+ SSHD_CONFIG_ROOT="$t42/ssh"; FAIL2BAN_JAIL_DIR="$jail_dir"+ write_sshd_jail >/dev/null 2>&1 )+if [ "$(grep -c '^\[sshd\]' "$jail_dir/sshd-serverkit.conf")" = "1" ]; then+ ok "write_sshd_jail is idempotent across re-runs"+else+ bad "write_sshd_jail duplicated the jail stanza on a re-run"+fi++# -- static guard: the interlock must stay wired. bootstrap_firewall has to call+# detect_ssh_ports, and the `ufw --force enable` line must live after it.+if awk '/^bootstrap_firewall\(\)/,/^}/' "$INSTALL_SH" | grep -q 'detect_ssh_ports'; then+ ok "bootstrap_firewall still consults detect_ssh_ports before enabling anything"+else+ bad "bootstrap_firewall no longer detects the SSH port — LOCKOUT RISK"+fi+# --------------------------------------------------------------------------printf '\n%d passed, %d failed, %d skipped\n\n' "$PASS" "$FAIL" "$SKIP"[ "$FAIL" -eq 0 ]