Skip to content

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.

fix(fail2ban): make renamed-away jails findable and sweepable

Juan Denis1a27aa784ca3
diff --git a/backend/app/services/fail2ban_jail_service.py b/backend/app/services/fail2ban_jail_service.py
index 4b25705c..67e5d27e 100644
--- a/backend/app/services/fail2ban_jail_service.py
+++ b/backend/app/services/fail2ban_jail_service.py
@@ -293,9 +293,73 @@ bantime = {bantime}
@classmethod
def disable_jail(cls, app):
"""Remove a site's ServerKit jail file and reload fail2ban. Thin wrapper
- over remove_jail keyed by the application name."""
+ over remove_jail keyed by the application name.
+
+ Rename caveat: the jail filename derives from the name at ENABLE time,
+ so a site renamed since then no longer derives its old jail's path —
+ this then returns ``removed: False`` and the stale jail keeps running.
+ Callers should treat ``removed: False`` as "maybe orphaned" and sweep
+ with cleanup_orphans(active_keys)."""
return cls.remove_jail(getattr(app, 'name', None))
+ _SITE_RE = re.compile(
+ r'^# ServerKit-managed brute-force jail for site "(.*)"')
+
+ @classmethod
+ def list_jails(cls):
+ """Every ServerKit-owned jail on disk: [{jail, path, site, logpath}].
+
+ A directory scan, deliberately NOT derived from live site names: jail
+ filenames are keyed by the sanitized site name at enable time, so a
+ site renamed afterwards orphans its jail — still banning against a
+ log nginx no longer writes, invisible to any name-derived lookup.
+ This scan is the only view that still sees those orphans."""
+ jails = []
+ if not os.path.isdir(cls.JAIL_DIR):
+ return jails
+ for name in sorted(os.listdir(cls.JAIL_DIR)):
+ if not name.startswith(cls.JAIL_PREFIX) or not name.endswith('.conf'):
+ continue
+ path = os.path.join(cls.JAIL_DIR, name)
+ content = cls._read_text(path) or ''
+ site_match = cls._SITE_RE.match(content)
+ log_match = re.search(r'^logpath\s*=\s*(.+)$', content, re.MULTILINE)
+ jails.append({
+ 'jail': name[:-len('.conf')],
+ 'path': path,
+ 'site': site_match.group(1) if site_match else None,
+ 'logpath': log_match.group(1).strip() if log_match else None,
+ })
+ return jails
+
+ @classmethod
+ def cleanup_orphans(cls, active_keys):
+ """Remove ServerKit jails no key in *active_keys* derives any more.
+
+ The rename-orphan sweeper: pass every live site name/key; a jail
+ whose filename no longer derives from any of them is deleted, and
+ fail2ban reloads once at the end. Only ``serverkit-*`` files are
+ ever touched (list_jails filters by prefix)."""
+ if not cls.available():
+ return cls._unavailable()
+ keep = {cls.jail_name_for_key(key) for key in active_keys if key}
+ removed, errors = [], []
+ for row in cls.list_jails():
+ if row['jail'] in keep:
+ continue
+ try:
+ proc = run_privileged(['rm', '-f', row['path']])
+ if proc.returncode == 0:
+ removed.append(row['jail'])
+ else:
+ errors.append(f"{row['jail']}: "
+ f"{(proc.stderr or 'remove failed').strip()}")
+ except Exception as e:
+ errors.append(f"{row['jail']}: {e}")
+ reloaded = cls.reload() if removed else {'success': True}
+ return {'success': not errors, 'removed': removed, 'errors': errors,
+ 'reloaded': reloaded.get('success')}
+
@classmethod
def reload(cls):
"""``fail2ban-client reload`` (keeps existing bans), falling back to a
diff --git a/backend/tests/test_fail2ban_jail_service.py b/backend/tests/test_fail2ban_jail_service.py
index 570fe582..3dde28ab 100644
--- a/backend/tests/test_fail2ban_jail_service.py
+++ b/backend/tests/test_fail2ban_jail_service.py
@@ -247,3 +247,87 @@ def test_wp_security_brute_force_handles_missing_application(wp_extension_packag
site = types.SimpleNamespace(application=None)
assert WpSecurityService.set_brute_force(site, True)['success'] is False
assert WpSecurityService.get_brute_force(site)['no_application'] is True
+
+
+# ---------- rename orphans: list_jails + cleanup_orphans (plan 82 §F.2) ----- #
+# The jail filename derives from the site name at ENABLE time. Rename the
+# site and disable_jail() derives a path that no longer exists — it honestly
+# reports removed: False, but the stale jail keeps banning against a log
+# nginx no longer writes. list_jails() (directory scan) + cleanup_orphans()
+# are the recovery path these tests pin.
+
+def _write_jail(jail_dir, key, site=None):
+ jail = F2B.jail_name_for_key(key)
+ content = F2B._render_jail_config(
+ jail=jail, site=site or key, filter_name=F2B._sanitize(F2B.WP_FILTER),
+ logpath=f'/var/log/nginx/{key}.access.log',
+ maxretry=None, findtime=None, bantime=None)
+ (jail_dir / f'{jail}.conf').write_text(content)
+ return jail
+
+
+def test_rename_orphans_jail_and_disable_reports_not_removed(tmp_path, monkeypatch):
+ monkeypatch.setattr(F2B, 'JAIL_DIR', str(tmp_path))
+ _write_jail(tmp_path, 'myshop')
+
+ with patch.object(F2B, 'available', return_value=True):
+ res = F2B.disable_jail(_app('shop')) # renamed since enable
+
+ assert res['success'] is True and res['removed'] is False
+ # ...and the stale jail is still on disk, visible only to the scan:
+ assert [j['jail'] for j in F2B.list_jails()] == ['serverkit-myshop']
+
+
+def test_list_jails_parses_site_and_logpath(tmp_path, monkeypatch):
+ monkeypatch.setattr(F2B, 'JAIL_DIR', str(tmp_path))
+ _write_jail(tmp_path, 'myshop', site='My Shop')
+ (tmp_path / 'operator-own.conf').write_text('[sshd]\n') # not ours: ignored
+
+ jails = F2B.list_jails()
+ assert len(jails) == 1
+ assert jails[0]['site'] == 'My Shop'
+ assert jails[0]['logpath'] == '/var/log/nginx/myshop.access.log'
+
+
+def test_cleanup_orphans_removes_only_derelict_serverkit_jails(tmp_path, monkeypatch):
+ monkeypatch.setattr(F2B, 'JAIL_DIR', str(tmp_path))
+ _write_jail(tmp_path, 'live-site')
+ _write_jail(tmp_path, 'renamed-away')
+ (tmp_path / 'operator-own.conf').write_text('[sshd]\n')
+
+ def fake_rm(cmd, **kwargs):
+ assert cmd[:2] == ['rm', '-f']
+ os.remove(cmd[2])
+ return _ok()
+
+ with patch.object(F2B, 'available', return_value=True), \
+ patch.object(F2B, 'reload', return_value={'success': True}), \
+ patch('app.services.fail2ban_jail_service.run_privileged', side_effect=fake_rm):
+ res = F2B.cleanup_orphans(['live-site', 'other-live'])
+
+ assert res['success'] is True
+ assert res['removed'] == ['serverkit-renamed-away']
+ assert (tmp_path / 'serverkit-live-site.conf').exists()
+ assert (tmp_path / 'operator-own.conf').exists() # never touched
+
+
+def test_cleanup_orphans_no_orphans_no_reload(tmp_path, monkeypatch):
+ monkeypatch.setattr(F2B, 'JAIL_DIR', str(tmp_path))
+ _write_jail(tmp_path, 'live-site')
+
+ with patch.object(F2B, 'available', return_value=True), \
+ patch.object(F2B, 'reload') as rel:
+ res = F2B.cleanup_orphans(['live-site'])
+
+ assert res['success'] is True and res['removed'] == []
+ rel.assert_not_called()
+
+
+def test_sanitize_collision_is_a_shared_jail_documented(tmp_path, monkeypatch):
+ """'my.site' and 'my site' collapse to the same key, so two such sites
+ SHARE one jail file — last enable wins its thresholds/logpath, and
+ disabling either removes the other's protection. Pinned here as known
+ behavior: changing the derivation would orphan every existing install's
+ jail files, so the cure is worse than the disease. Renames/collisions
+ are handled operationally via list_jails + cleanup_orphans."""
+ assert F2B.jail_name_for_key('my.site') == F2B.jail_name_for_key('my site')