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
Add per-site Fail2ban jail and UI for WP brute-force protection
Juan Denis76ded002da3f
diff --git a/backend/app/api/wordpress.py b/backend/app/api/wordpress.pyindex 39c0f54a..4b270616 100644--- a/backend/app/api/wordpress.py+++ b/backend/app/api/wordpress.py@@ -701,6 +701,54 @@ def set_site_cron(app_id):return jsonify(WpSecurityService.set_cron_disabled(app.root_path, disabled)), 200+@wordpress_bp.route('/sites/<int:app_id>/security/bruteforce', methods=['GET'])+@jwt_required()+def get_site_bruteforce(app_id):+ """Per-site login brute-force status: fail2ban availability, jail on/off, bans."""+ from app.services.wp_security_service import WpSecurityService+ app, err = _owner_or_admin_app(app_id)+ if err:+ return err+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if not wp_site:+ return jsonify({'error': 'Not a WordPress site'}), 400+ return jsonify(WpSecurityService.get_brute_force(wp_site)), 200+++@wordpress_bp.route('/sites/<int:app_id>/security/bruteforce', methods=['POST'])+@jwt_required()+@admin_required+def set_site_bruteforce(app_id):+ """Enable/disable the site's WP-login brute-force jail."""+ from app.services.wp_security_service import WpSecurityService+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if not wp_site:+ return jsonify({'error': 'Not a WordPress site'}), 400+ enabled = bool((request.get_json() or {}).get('enabled'))+ return jsonify(WpSecurityService.set_brute_force(wp_site, enabled)), 200+++@wordpress_bp.route('/sites/<int:app_id>/security/bruteforce/unban', methods=['POST'])+@jwt_required()+@admin_required+def unban_site_bruteforce(app_id):+ """Unban an IP from the site's brute-force jail."""+ from app.services.wp_security_service import WpSecurityService+ app = _resolve_app(app_id)+ if not app:+ return jsonify({'error': 'Application not found'}), 404+ wp_site = WordPressSite.query.filter_by(application_id=app.id).first()+ if not wp_site:+ return jsonify({'error': 'Not a WordPress site'}), 400+ ip = ((request.get_json() or {}).get('ip') or '').strip()+ if not ip:+ return jsonify({'error': 'ip is required'}), 400+ return jsonify(WpSecurityService.unban_brute_force(wp_site, ip)), 200++# ---- Safe update manager (#29): run history, on-demand safe update, schedule ----@wordpress_bp.route('/sites/<int:app_id>/updates', methods=['GET'])diff --git a/backend/app/services/fail2ban_jail_service.py b/backend/app/services/fail2ban_jail_service.pynew file mode 100644index 00000000..fa139778--- /dev/null+++ b/backend/app/services/fail2ban_jail_service.py@@ -0,0 +1,313 @@+"""Per-site brute-force jail management on top of the reverse-proxy/log layer.++ServerKit's read-only Fail2ban integration (``SecurityService``) can list and+ban/unban, but it cannot *create* jails. This service is the write half: it+generates ServerKit-owned Fail2ban filter + per-site jail configs that watch a+managed site's nginx access log and ban IPs that hammer the WordPress login.++This is what redeems the ``WpSecurityService`` deferral: a managed WordPress site+already gets a per-site nginx vhost whose access log+(``NginxService.site_access_log_path``) records ``POST /wp-login.php`` /+``POST /xmlrpc.php`` with the *real* client IP (nginx is the edge listener, so the+log's remote address is the client, not a proxy). A jail pointed at that log is+therefore a real per-site brute-force jail.++Design:+* **Ownership-guarded** — only ever writes/reads/removes files named+ ``serverkit-*`` under ``filter.d/`` and ``jail.d/``; an operator's own jails are+ never touched. The per-site jail filename is sanitised to ``[a-z0-9_-]`` so it+ can never escape the jail directory.+* **Best-effort, never raises; Linux-only** — on Windows (dev) or when Fail2ban+ is absent, every mutating call returns a ``skipped`` descriptor instead of+ failing, so site creation degrades gracefully and the UI can surface "fail2ban+ not available".+* **Config files are the source of truth** — a site is protected iff its+ ``jail.d/serverkit-<key>.conf`` exists (same model nginx sites use); there is no+ parallel DB state to drift.+"""+import os+import re+import logging++from app.utils.system import run_privileged, is_command_available, ServiceControl+from app.services.nginx_service import NginxService++logger = logging.getLogger(__name__)+++class Fail2banJailService:+ FILTER_DIR = '/etc/fail2ban/filter.d'+ JAIL_DIR = '/etc/fail2ban/jail.d'++ # ServerKit-owned filter name (filter.d/serverkit-wp-login.conf).+ WP_FILTER = 'serverkit-wp-login'+ # Every ServerKit jail file + jail name carries this prefix — both the+ # ownership marker and the namespace that keeps us off operator jails.+ JAIL_PREFIX = 'serverkit-'++ # Default thresholds: 5 login POSTs within 10 min -> 1 hour ban.+ MAXRETRY = 5+ FINDTIME = 600+ BANTIME = 3600++ # WordPress login / XML-RPC brute-force filter. Raw string: the regex needs a+ # literal backslash-dot. <HOST> is Fail2ban's IP capture; for the nginx+ # combined log line "<ip> - - [time] \"POST /wp-login.php ...\"" it captures the+ # real client IP. Date is auto-detected by Fail2ban for the common log format.+ FILTER_CONTENT = r'''# ServerKit-managed Fail2ban filter: WordPress login / XML-RPC brute force.+# Matches POSTs to wp-login.php and xmlrpc.php in the nginx combined access log.+# nginx is the edge listener, so <HOST> (the log's remote address) is the real+# client IP. Generated by Fail2banJailService - do not edit by hand (regenerated).+[Definition]+failregex = ^<HOST> -.*"POST /wp-login\.php+ ^<HOST> -.*"POST /xmlrpc\.php+ignoreregex =+'''++ JAIL_TEMPLATE = '''# ServerKit-managed brute-force jail for site "{site}".+# Generated by Fail2banJailService - do not edit by hand (regenerated on change).+[{jail}]+enabled = true+filter = {filter}+logpath = {logpath}+port = http,https+maxretry = {maxretry}+findtime = {findtime}+bantime = {bantime}+'''++ # ---------- availability ----------++ @classmethod+ def available(cls):+ """True only on a Linux host where the fail2ban client is installed."""+ if os.name == 'nt':+ return False+ return is_command_available('fail2ban-client')++ @staticmethod+ def _unavailable():+ return {+ 'success': True, 'skipped': True, 'available': False, 'reason': 'unavailable',+ 'message': 'fail2ban is not available on this host; brute-force protection is inactive.',+ }++ # ---------- naming (pure, filesystem-free) ----------++ @staticmethod+ def _sanitize(name):+ """Reduce a site name to a Fail2ban/filename-safe key (``[a-z0-9_-]``).++ Strips everything else — so path separators and dots can't survive — which+ is what makes the derived jail filename traversal-proof."""+ return re.sub(r'[^a-zA-Z0-9_-]', '-', (name or '')).strip('-') or 'site'++ @classmethod+ def jail_name(cls, app):+ """``serverkit-<key>`` jail name for an application."""+ return cls.JAIL_PREFIX + cls._sanitize(getattr(app, 'name', None))++ @classmethod+ def _jail_filename(cls, app):+ return f'{cls.jail_name(app)}.conf'++ @classmethod+ def _jail_path(cls, app):+ """Absolute path of the per-site jail file, guarded so it can only ever be+ a ServerKit-owned file inside JAIL_DIR."""+ filename = cls._jail_filename(app)+ if (not filename.startswith(cls.JAIL_PREFIX)+ or '/' in filename or '\\' in filename or '..' in filename):+ # Unreachable given _sanitize, but refuse rather than risk a stray path.+ raise ValueError(f'refusing to target non-ServerKit jail file: {filename!r}')+ return os.path.join(cls.JAIL_DIR, filename)++ # ---------- file helpers ----------++ @staticmethod+ def _read_text(path):+ try:+ with open(path, 'r') as fh:+ return fh.read()+ except Exception:+ return None++ @staticmethod+ def _write_file(path, content):+ """Write *content* to *path* with privilege (sudo tee), like NginxService."""+ try:+ proc = run_privileged(['tee', path], input=content)+ if proc.returncode != 0:+ return {'success': False, 'error': (proc.stderr or 'write failed').strip()}+ return {'success': True, 'path': path}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ @staticmethod+ def _ensure_logpath(logpath):+ """Make sure the access log exists before the jail references it — a jail+ whose logpath is missing fails to start. nginx creates the file on reload;+ this is belt-and-suspenders for the race where the site has had no hits."""+ try:+ run_privileged(['touch', logpath])+ except Exception:+ pass++ # ---------- filter ----------++ @classmethod+ def ensure_filter(cls):+ """Write the ServerKit WP-login filter if missing or out of date."""+ if not cls.available():+ return cls._unavailable()+ path = os.path.join(cls.FILTER_DIR, f'{cls.WP_FILTER}.conf')+ existing = cls._read_text(path)+ if existing is not None and existing.strip() == cls.FILTER_CONTENT.strip():+ return {'success': True, 'path': path, 'changed': False}+ res = cls._write_file(path, cls.FILTER_CONTENT)+ if not res.get('success'):+ return res+ return {'success': True, 'path': path, 'changed': True}++ # ---------- jail lifecycle ----------++ @classmethod+ def _render_jail(cls, app, logpath, maxretry, findtime, bantime):+ return cls.JAIL_TEMPLATE.format(+ jail=cls.jail_name(app), site=getattr(app, 'name', ''), filter=cls.WP_FILTER,+ logpath=logpath,+ maxretry=maxretry or cls.MAXRETRY,+ findtime=findtime or cls.FINDTIME,+ bantime=bantime or cls.BANTIME,+ )++ @classmethod+ def enable_wp_jail(cls, app, *, maxretry=None, findtime=None, bantime=None):+ """Create/refresh a WP brute-force jail for *app* and reload fail2ban.++ Idempotent (regenerates the jail file). Best-effort: returns a ``skipped``+ descriptor when fail2ban is unavailable rather than raising, so callers in+ the site-create path never fail because of it."""+ if not cls.available():+ return cls._unavailable()+ if not getattr(app, 'name', None):+ return {'success': False, 'error': 'application has no name'}++ flt = cls.ensure_filter()+ if not flt.get('success'):+ return flt++ logpath = NginxService.site_access_log_path(app.name)+ cls._ensure_logpath(logpath)++ try:+ jail_path = cls._jail_path(app)+ except ValueError as e:+ return {'success': False, 'error': str(e)}++ written = cls._write_file(jail_path, cls._render_jail(+ app, logpath, maxretry, findtime, bantime))+ if not written.get('success'):+ return written++ reloaded = cls.reload()+ return {+ 'success': True, 'enabled': True, 'jail': cls.jail_name(app),+ 'path': jail_path, 'logpath': logpath,+ 'reloaded': reloaded.get('success'), 'reload_message': reloaded.get('message'),+ }++ @classmethod+ def disable_jail(cls, app):+ """Remove a site's ServerKit jail file and reload fail2ban. No-op (success)+ when the jail does not exist or fail2ban is unavailable."""+ if not cls.available():+ return cls._unavailable()+ try:+ jail_path = cls._jail_path(app)+ except ValueError as e:+ return {'success': False, 'error': str(e)}++ if not os.path.exists(jail_path):+ return {'success': True, 'removed': False, 'message': 'no jail to remove'}+ try:+ proc = run_privileged(['rm', '-f', jail_path])+ if proc.returncode != 0:+ return {'success': False, 'error': (proc.stderr or 'remove failed').strip()}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ reloaded = cls.reload()+ return {'success': True, 'removed': True, 'jail': cls.jail_name(app),+ 'reloaded': reloaded.get('success')}++ @classmethod+ def reload(cls):+ """``fail2ban-client reload`` (keeps existing bans), falling back to a+ service restart if the client call fails."""+ if not cls.available():+ return cls._unavailable()+ try:+ proc = run_privileged(['fail2ban-client', 'reload'], timeout=30)+ if proc.returncode == 0:+ return {'success': True, 'message': 'fail2ban reloaded'}+ except Exception:+ pass+ try:+ res = ServiceControl.restart('fail2ban', timeout=30)+ return {'success': res.returncode == 0,+ 'message': 'fail2ban restarted' if res.returncode == 0+ else (res.stderr or 'reload failed')}+ except Exception as e:+ return {'success': False, 'error': str(e)}++ # ---------- status / actions ----------++ @classmethod+ def get_status(cls, app):+ """Per-site brute-force status: availability, whether the jail exists, the+ active thresholds, and (when fail2ban is running) live ban counts."""+ info = {+ 'available': cls.available(),+ 'enabled': False,+ 'jail': cls.jail_name(app),+ 'thresholds': {'maxretry': cls.MAXRETRY, 'findtime': cls.FINDTIME,+ 'bantime': cls.BANTIME},+ 'fail2ban_installed': False,+ 'fail2ban_running': False,+ 'currently_banned': 0,+ 'total_banned': 0,+ 'currently_failed': 0,+ 'banned_ips': [],+ }+ if not cls.available():+ return info++ try:+ info['enabled'] = os.path.exists(cls._jail_path(app))+ except ValueError:+ info['enabled'] = False++ from app.services.security_service import SecurityService+ f2b = SecurityService.get_fail2ban_status()+ info['fail2ban_installed'] = bool(f2b.get('installed'))+ info['fail2ban_running'] = bool(f2b.get('service_running'))++ if info['enabled'] and info['fail2ban_running']:+ js = SecurityService.get_fail2ban_jail_status(info['jail'])+ if js.get('success'):+ info.update({+ 'currently_banned': js.get('currently_banned', 0),+ 'total_banned': js.get('total_banned', 0),+ 'currently_failed': js.get('currently_failed', 0),+ 'banned_ips': js.get('banned_ips', []),+ })+ return info++ @classmethod+ def unban(cls, app, ip):+ """Unban *ip* from this site's jail (thin wrapper over SecurityService)."""+ if not cls.available():+ return cls._unavailable()+ from app.services.security_service import SecurityService+ return SecurityService.unban_ip(ip, cls.jail_name(app))diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex cc558ae1..f278bb2c 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -29,6 +29,11 @@ class NginxService:SITES_ENABLED = os.path.join(NGINX_CONF_DIR, 'sites-enabled')NGINX_BIN = os.environ.get('NGINX_BIN', '/usr/sbin/nginx')LOCATIONS_DIR = os.path.join(NGINX_CONF_DIR, 'serverkit-locations')+ # Per-site log directory. Must stay in sync with the access_log/error_log+ # paths hard-coded in the site templates below. site_access_log_path() is the+ # single source of truth consumers should use (e.g. the fail2ban jail layer+ # watches this exact file), so the path can never drift from what nginx writes.+ LOG_DIR = '/var/log/nginx'# TemplatesPHP_SITE_TEMPLATE = '''server {{@@ -531,6 +536,21 @@ location /p/ {{redirect = cls.SSL_REDIRECT_TEMPLATE.format(domains=domains)return redirect + '\n' + https_config+ @classmethod+ def site_access_log_path(cls, name: str) -> str:+ """Path of the per-site nginx access log for site ``name`` — the same+ ``/var/log/nginx/{name}.access.log`` the site templates write. This is the+ canonical accessor so consumers (e.g. the fail2ban brute-force jail) never+ hard-code the path and it can't drift from the generated vhost. Always a+ POSIX path (these are Linux server logs), independent of the panel's OS."""+ return f'{cls.LOG_DIR}/{name}.access.log'++ @classmethod+ def site_error_log_path(cls, name: str) -> str:+ """Path of the per-site nginx error log for site ``name`` (companion to+ :meth:`site_access_log_path`)."""+ return f'{cls.LOG_DIR}/{name}.error.log'+@classmethoddef enable_site(cls, name: str) -> Dict:"""Enable a site by creating symlink in sites-enabled."""diff --git a/backend/app/services/wordpress_service.py b/backend/app/services/wordpress_service.pyindex 58901f9f..b7348b88 100644--- a/backend/app/services/wordpress_service.py+++ b/backend/app/services/wordpress_service.py@@ -2128,6 +2128,20 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]v = cls._write_app_vhost(app)if v.get('warning'):warning = (warning + '; ' + v['warning']) if warning else v['warning']++ # Brute-force protection is on by default: now that the per-site vhost (and+ # therefore its access log) exists, stand up the WP-login Fail2ban jail.+ # Best-effort and never fatal — a host without fail2ban (e.g. Windows dev)+ # is silently skipped; only a real failure (e.g. reload error) warns.+ try:+ from app.services.fail2ban_jail_service import Fail2banJailService+ jail = Fail2banJailService.enable_wp_jail(app)+ except Exception as e:+ jail = {'success': False, 'error': str(e)}+ if jail and not jail.get('success') and not jail.get('skipped') and jail.get('error'):+ msg = f"brute-force jail: {jail['error']}"+ warning = (warning + '; ' + msg) if warning else msg+return {'domain': site_host, 'nginx': v.get('nginx'), 'warning': warning}@classmethod@@ -2541,6 +2555,13 @@ RewriteRule ^wp-content/uploads/.*\\.php$ - [F]NginxService.delete_site(wp_site.application.name)except Exception:pass+ # Remove the per-site brute-force jail too, so a deleted site leaves no+ # dangling Fail2ban config. Best-effort (no-op without fail2ban).+ try:+ from app.services.fail2ban_jail_service import Fail2banJailService+ Fail2banJailService.disable_jail(wp_site.application)+ except Exception:+ passdb.session.delete(wp_site.application)db.session.delete(wp_site)diff --git a/backend/app/services/wp_security_service.py b/backend/app/services/wp_security_service.pyindex 3032519b..370ac8ff 100644--- a/backend/app/services/wp_security_service.py+++ b/backend/app/services/wp_security_service.py@@ -5,10 +5,12 @@ WP-CLI bridge (WordPressService.wp_cli), so containerized sites work.Integrity runs in a background thread (verify-checksums fetches from wordpress.organd can be slow) so the single worker never blocks; debug/cron are quick.-Deferred (needs infra absent in the Docker-localhost model): a per-site-wp-login/xmlrpc brute-force rate-limit jail (Fail2ban / nginx limit_req). Managed-sites are localhost:PORT apache containers with no host-side per-site access log-for a jail to watch; revisit once a per-site reverse-proxy/log layer exists.+Brute-force protection (shipped): each managed site already has a per-site nginx+reverse-proxy vhost whose access log records wp-login/xmlrpc hits with the real+client IP, so a per-site Fail2ban jail can watch it. ``get_brute_force`` /+``set_brute_force`` here are a thin WordPress-facing wrapper over+``Fail2banJailService`` (the jail-management layer); the jail is enabled by default+when a site is created and torn down when it is deleted."""import json@@ -164,3 +166,36 @@ class WpSecurityService:if not res.get('success'):return {'success': False, 'error': res.get('error')}return cls.get_cron(path)++ # ---------- brute-force protection (per-site Fail2ban jail) ----------++ @classmethod+ def get_brute_force(cls, site):+ """Per-site login brute-force status (availability, on/off, live bans).++ Returns the jail layer's status verbatim, plus a ``no_application`` flag for+ the (unexpected) case of a site with no linked application."""+ from app.services.fail2ban_jail_service import Fail2banJailService+ app = getattr(site, 'application', None)+ if not app:+ return {'available': False, 'enabled': False, 'no_application': True}+ return Fail2banJailService.get_status(app)++ @classmethod+ def set_brute_force(cls, site, enabled):+ """Enable or disable the site's WP-login brute-force jail."""+ from app.services.fail2ban_jail_service import Fail2banJailService+ app = getattr(site, 'application', None)+ if not app:+ return {'success': False, 'error': 'Site has no linked application'}+ return (Fail2banJailService.enable_wp_jail(app) if enabled+ else Fail2banJailService.disable_jail(app))++ @classmethod+ def unban_brute_force(cls, site, ip):+ """Unban an IP from this site's brute-force jail."""+ from app.services.fail2ban_jail_service import Fail2banJailService+ app = getattr(site, 'application', None)+ if not app:+ return {'success': False, 'error': 'Site has no linked application'}+ return Fail2banJailService.unban(app, ip)diff --git a/backend/tests/test_fail2ban_jail_service.py b/backend/tests/test_fail2ban_jail_service.pynew file mode 100644index 00000000..3b076118--- /dev/null+++ b/backend/tests/test_fail2ban_jail_service.py@@ -0,0 +1,191 @@+"""Per-site brute-force jail layer (Fail2banJailService) — pure unit tests.++No real fail2ban or filesystem: privileged writes/reads and os.path.exists are+mocked, so these assert the *rendered* filter/jail configs, the ownership ++traversal guards, and graceful degradation — the same style as+test_nginx_remote_upstream (assert the generated config, not a live daemon).+"""+import os+import types+from unittest.mock import patch, MagicMock++import pytest++from app.services.fail2ban_jail_service import Fail2banJailService as F2B+from app.services.nginx_service import NginxService+++def _app(name='myblog'):+ return types.SimpleNamespace(name=name, port=8300)+++def _ok(stdout='', stderr=''):+ """CompletedProcess-like stub for run_privileged."""+ return types.SimpleNamespace(returncode=0, stdout=stdout, stderr=stderr)+++# ---------- rendered configs ----------++def test_filter_targets_wp_login_and_xmlrpc():+ c = F2B.FILTER_CONTENT+ assert '[Definition]' in c+ assert '<HOST>' in c # fail2ban IP capture present+ assert r'wp-login\.php' in c+ assert r'xmlrpc\.php' in c+++def test_jail_render_uses_nginx_log_path_and_thresholds():+ logpath = NginxService.site_access_log_path('myblog')+ jail = F2B._render_jail(_app('myblog'), logpath, None, None, None)+ assert '[serverkit-myblog]' in jail+ assert 'enabled = true' in jail+ assert 'filter = serverkit-wp-login' in jail+ assert f'logpath = {logpath}' in jail+ assert f'maxretry = {F2B.MAXRETRY}' in jail+ assert f'findtime = {F2B.FINDTIME}' in jail+ assert f'bantime = {F2B.BANTIME}' in jail+ # the jail watches the exact file nginx writes for the site+ assert logpath == '/var/log/nginx/myblog.access.log'+++def test_jail_render_honours_threshold_overrides():+ jail = F2B._render_jail(_app(), '/var/log/nginx/x.access.log', 3, 120, 900)+ assert 'maxretry = 3' in jail+ assert 'findtime = 120' in jail+ assert 'bantime = 900' in jail+++# ---------- naming / ownership / traversal guards ----------+[email protected]('raw,expected', [+ ('myblog', 'serverkit-myblog'),+ ('My Blog!', 'serverkit-My-Blog'),+ ('../../etc/passwd', 'serverkit-etc-passwd'),+ ('a.b.c', 'serverkit-a-b-c'),+ ('', 'serverkit-site'),+])+def test_jail_name_is_sanitized_and_prefixed(raw, expected):+ name = F2B.jail_name(_app(raw))+ assert name == expected+ # never contains a path separator or traversal sequence+ assert '/' not in name and '\\' not in name and '..' not in name+++def test_jail_path_cannot_escape_jail_dir():+ # Even a traversal-style name resolves to a serverkit-owned file *inside*+ # JAIL_DIR — this is the structural ownership guard.+ p = F2B._jail_path(_app('../../evil'))+ assert os.path.dirname(p) == F2B.JAIL_DIR+ assert os.path.basename(p).startswith('serverkit-')+ assert os.path.basename(p).endswith('.conf')+++# ---------- graceful degradation (Windows / no fail2ban) ----------++def test_enable_and_disable_skip_when_unavailable():+ with patch.object(F2B, 'available', return_value=False):+ en = F2B.enable_wp_jail(_app())+ dis = F2B.disable_jail(_app())+ for res in (en, dis):+ assert res['success'] is True+ assert res['skipped'] is True+ assert res['available'] is False+++def test_enable_requires_app_name():+ with patch.object(F2B, 'available', return_value=True):+ res = F2B.enable_wp_jail(types.SimpleNamespace(name=''))+ assert res['success'] is False+++# ---------- lifecycle (mocked privileged calls) ----------++def test_enable_writes_filter_and_jail_then_reloads():+ writes = {}++ def fake_run(cmd, **kwargs):+ if cmd[:1] == ['tee'] and 'input' in kwargs:+ writes[cmd[1]] = kwargs['input']+ return _ok()++ with patch.object(F2B, 'available', return_value=True), \+ patch.object(F2B, '_read_text', return_value=None), \+ patch('app.services.fail2ban_jail_service.run_privileged', side_effect=fake_run) as rp:+ res = F2B.enable_wp_jail(_app('myblog'))++ assert res['success'] is True and res['enabled'] is True+ assert res['jail'] == 'serverkit-myblog'++ filter_path = os.path.join(F2B.FILTER_DIR, 'serverkit-wp-login.conf')+ jail_path = os.path.join(F2B.JAIL_DIR, 'serverkit-myblog.conf')+ assert filter_path in writes and r'wp-login\.php' in writes[filter_path]+ assert jail_path in writes+ assert 'logpath = /var/log/nginx/myblog.access.log' in writes[jail_path]++ # the logpath was touched, and fail2ban was reloaded (not restarted)+ cmds = [c.args[0] for c in rp.call_args_list]+ assert ['touch', '/var/log/nginx/myblog.access.log'] in cmds+ assert ['fail2ban-client', 'reload'] in cmds+++def test_disable_removes_only_serverkit_jail_file():+ removed = {}++ def fake_run(cmd, **kwargs):+ if cmd[:1] == ['rm']:+ removed['path'] = cmd[-1]+ return _ok()++ with patch.object(F2B, 'available', return_value=True), \+ patch('app.services.fail2ban_jail_service.os.path.exists', return_value=True), \+ patch('app.services.fail2ban_jail_service.run_privileged', side_effect=fake_run):+ res = F2B.disable_jail(_app('myblog'))++ assert res['success'] is True and res['removed'] is True+ assert removed['path'] == os.path.join(F2B.JAIL_DIR, 'serverkit-myblog.conf')+ assert os.path.basename(removed['path']).startswith('serverkit-')+++def test_disable_is_noop_when_no_jail_file():+ with patch.object(F2B, 'available', return_value=True), \+ patch('app.services.fail2ban_jail_service.os.path.exists', return_value=False), \+ patch('app.services.fail2ban_jail_service.run_privileged') as rp:+ res = F2B.disable_jail(_app('myblog'))+ assert res['success'] is True and res['removed'] is False+ rp.assert_not_called()+++def test_get_status_shape_when_jail_absent():+ sec = MagicMock()+ sec.get_fail2ban_status.return_value = {'installed': True, 'service_running': False}+ with patch.object(F2B, 'available', return_value=True), \+ patch('app.services.fail2ban_jail_service.os.path.exists', return_value=False), \+ patch('app.services.security_service.SecurityService', sec):+ st = F2B.get_status(_app('myblog'))+ assert st['available'] is True+ assert st['enabled'] is False+ assert st['jail'] == 'serverkit-myblog'+ assert st['thresholds']['maxretry'] == F2B.MAXRETRY+ assert st['fail2ban_running'] is False+++# ---------- WpSecurityService wrapper ----------++def test_wp_security_set_brute_force_delegates_to_jail_service():+ from app.services.wp_security_service import WpSecurityService+ app = _app('myblog')+ site = types.SimpleNamespace(application=app)+ with patch.object(F2B, 'enable_wp_jail', return_value={'success': True}) as en, \+ patch.object(F2B, 'disable_jail', return_value={'success': True}) as dis:+ r_on = WpSecurityService.set_brute_force(site, True)+ r_off = WpSecurityService.set_brute_force(site, False)+ en.assert_called_once_with(app)+ dis.assert_called_once_with(app)+ assert r_on['success'] and r_off['success']+++def test_wp_security_brute_force_handles_missing_application():+ from app.services.wp_security_service import WpSecurityService+ site = types.SimpleNamespace(application=None)+ assert WpSecurityService.set_brute_force(site, True)['success'] is False+ assert WpSecurityService.get_brute_force(site)['no_application'] is Truediff --git a/docs/WORDPRESS_ROADMAP.md b/docs/WORDPRESS_ROADMAP.mdindex 1b2b2a44..6b23f2ac 100644--- a/docs/WORDPRESS_ROADMAP.md+++ b/docs/WORDPRESS_ROADMAP.md@@ -273,12 +273,13 @@ Highest-effort, broadest surface — but by now the `WordPressSite` is a first-c- **Done when:** Updates run on a schedule, staging-first, with backup + auto-rollback and a report.- **Landed:** New `WpUpdateService.start_update` runs a **background safe update** (Docker-correct, all via `wp_cli`): record pre-update versions → `wp db export` a DB snapshot (a generous **600s** timeout — added a `timeout` param to `wp_cli` — so a large DB is never truncated; **aborts if the snapshot fails** — no net, no update) → apply updates only to components with an available update **minus an exclusion list** → a **quiet, side-effect-free** health probe (`wp eval` + the HTTP probe; deliberately does NOT call `check_health`, so an auto-rollback never fires spurious #27 down/up pages) → if the update **regressed a previously-healthy site** (now unhealthy/degraded), **AUTO-ROLLBACK**: version-pin each updated component back (`wp <type> update --version=<old> --force --skip-plugins --skip-themes`, so it runs even on a fatally-broken site) + re-import the snapshot → re-check → persist a `WordPressUpdateRun` **report**. The snapshot is **kept for manual restore** whenever the site doesn't end verified-healthy; deleted only on success. A per-site cron **schedule** + exclusion list is driven by a new daemon-thread scheduler **bounded by a concurrency semaphore** (a shared 3am cron can't stampede the host). New model `WordPressUpdateRun` + 2 columns (Alembic **012**); a new **Updates tab** (run-now, schedule, exclusions, run-history). **Also fixed a latent #26/#27 bug** surfaced by the review: `EnvironmentHealthService.check_health` returned `unknown` for *every* production site (its `_get_compose_path` needs a `container_prefix` production sites lack), making uptime/incidents/alerts inert for the primary site type — now falls back to the Application `root_path` compose so production health actually works. *(Deferred: **staging-first** promotion — update a staging env via the promote pipeline, validate, then promote to prod — needs a staging env + full env-pipeline orchestration; revisit on #15/#18.)* Verified: backend `py_compile`, frontend lint-clean (full build was blocked only by a concurrent agent's unrelated in-progress AI import, not #29 code), 2-lens adversarial review (blockers fixed: production-site health gating + DB-import timeout; majors fixed: scheduler stampede, snapshot-abort). Not runtime-exercised on a real host.-### #30 — Per-site security depth `[L]` 🟡 — ✅ Done (file integrity + WP_DEBUG toggle + WP-Cron, Docker-correct; brute-force rate-limit jail deferred)+### #30 — Per-site security depth `[L]` 🟡 — ✅ Done (file integrity + WP_DEBUG toggle + WP-Cron + brute-force jail, Docker-correct)- **Today:** ClamAV + file-integrity scan host paths (`/var/www`, `/home`, `/etc`) and can't reach Docker WP volumes; nothing resolves a site to a scannable docroot; integrity never calls `wp ... verify-checksums`; no `wp-login.php`/`xmlrpc` rate-limit jail.- **Do:** Per-site scan-target resolution; file integrity via `wp core/plugin/theme verify-checksums`; a Fail2ban jail/filter (or nginx `limit_req` zone) targeting each site's access log for `wp-login.php`/`xmlrpc.php`; per-site `WP_DEBUG`/`SCRIPT_DEBUG` toggle and WP-Cron list/run/disable.- **Reuse:** `security_service` (Fail2ban jails), `wp_cli`, `cron_service`, `nginx_service` WP template.- **Done when:** A site can be scanned, checksum-verified, brute-force-protected, and debug-toggled.- **Landed:** New `WpSecurityService` + a per-site **Security tab** (Docker-correct, all via the WP-CLI bridge): **(1) File integrity** — a background `wp core verify-checksums` + `wp plugin verify-checksums --all` (in-container, so it reaches the volume; runs off the request thread and the UI polls), flagging tampered/unexpected files. **(2) Debug toggle** — sets `WP_DEBUG`/`SCRIPT_DEBUG` with `WP_DEBUG_DISPLAY=false` and, crucially, **`WP_DEBUG_LOG=/tmp/wp-debug.log`** — *outside* the web root, so the log is never publicly fetchable (the default `wp-content/debug.log` is apache-served — a real info leak this avoids); the write is gated so a read-only/stopped site reports an honest failure. **(3) WP-Cron** — `DISABLE_WP_CRON` status + due-event list, run-due-now, and enable/disable (with a clear "needs a real system cron" warning). Routes mirror the established per-site pattern (owner-or-admin GET, `@admin_required` mutations). *(Deferred — the brute-force `wp-login`/`xmlrpc` **rate-limit jail**: Fail2ban/nginx `limit_req` both need a host-side per-site access log to watch, which the `localhost:PORT` apache-container model doesn't expose — the same per-site reverse-proxy/log gap as #21/#25/#8-backend. A WP-level login-limiter plugin is the Docker-correct alternative, deferred to honour the WP-CLI-over-plugin thesis.)* Verified: backend `py_compile`, frontend lint-clean + build, focused security review (debug-log web-exposure caught + fixed). Not runtime-exercised on a real host.+- **Update — brute-force jail shipped:** the deferral above is now redeemed. Every managed site already has a per-site nginx reverse-proxy vhost whose access log (`NginxService.site_access_log_path`) records `wp-login.php`/`xmlrpc.php` hits with the **real client IP** (nginx is the edge listener), so there *is* a host-side per-site log for a jail to watch. New `Fail2banJailService` (the write half of the previously read-only Fail2ban integration) generates a ServerKit-owned filter + per-site jail (`jail.d/serverkit-<app>.conf`, ownership-guarded, Linux-only, best-effort). Protection is **on by default**: the jail is created when a WP site is created (after its vhost, so the log exists) and removed on delete; a per-site **Brute-force protection** card in the Security tab toggles it, shows live bans, and unbans (5 login POSTs / 10 min → 1 h ban). Degrades gracefully where Fail2ban is absent (e.g. Windows dev → "fail2ban not available"). Verified: 17 new unit tests (rendered filter/jail, ownership/traversal guards, graceful skip) + full backend suite green + frontend build. Not runtime-exercised on a real host.### #31 — Selective push UI `[S]` 🟡 — ✅ Done (specific-tables selectors added; files-only/db-only/specific-folders already existed)- **Today:** The dump layer already supports table filters / files-only / db-only; `PromoteModal` exposes only coarse code/db/full.diff --git a/frontend/src/pages/WordPressDetail.jsx b/frontend/src/pages/WordPressDetail.jsxindex bf7ab474..78a45612 100644--- a/frontend/src/pages/WordPressDetail.jsx+++ b/frontend/src/pages/WordPressDetail.jsx@@ -1065,18 +1065,20 @@ const SecurityTab = ({ siteId }) => {const [debug, setDebug] = useState(null);const [cron, setCron] = useState(null);const [vulns, setVulns] = useState(null);+ const [brute, setBrute] = useState(null);const [loading, setLoading] = useState(true);const [busy, setBusy] = useState(false);const loadAll = React.useCallback(async () => {try {- const [i, d, c, v] = await Promise.all([+ const [i, d, c, v, b] = await Promise.all([wordpressApi.getIntegrity(siteId).catch(() => null),wordpressApi.getDebug(siteId).catch(() => null),wordpressApi.getCron(siteId).catch(() => null),wordpressApi.getVulnerabilities(siteId).catch(() => null),+ wordpressApi.getBruteForce(siteId).catch(() => null),]);- setIntegrity(i); setDebug(d); setCron(c); setVulns(v);+ setIntegrity(i); setDebug(d); setCron(c); setVulns(v); setBrute(b);} finally {setLoading(false);}@@ -1122,6 +1124,26 @@ const SecurityTab = ({ siteId }) => {catch (err) { toast.error(err.message || 'Failed to update WP-Cron'); }finally { setBusy(false); }}+ async function toggleBrute() {+ const wasEnabled = brute?.enabled;+ setBusy(true);+ try {+ const res = await wordpressApi.setBruteForce(siteId, !wasEnabled);+ if (res.success === false) { toast.error(res.error || 'Failed to update protection'); return; }+ setBrute(await wordpressApi.getBruteForce(siteId));+ toast.success(wasEnabled ? 'Brute-force protection disabled' : 'Brute-force protection enabled');+ } catch (err) { toast.error(err.message || 'Failed to update protection'); }+ finally { setBusy(false); }+ }+ async function unbanIp(ip) {+ setBusy(true);+ try {+ const res = await wordpressApi.unbanBruteForceIp(siteId, ip);+ toast[res.success ? 'success' : 'error'](res.success ? `Unbanned ${ip}` : (res.error || 'Failed to unban'));+ setBrute(await wordpressApi.getBruteForce(siteId));+ } catch (err) { toast.error(err.message || 'Failed to unban'); }+ finally { setBusy(false); }+ }if (loading) return <OverviewGridSkeleton panels={2} />;@@ -1151,6 +1173,11 @@ const SecurityTab = ({ siteId }) => {? `${(vsum.critical ?? 0) + (vsum.high ?? 0)} found`: 'no scan yet',},+ {+ label: 'Login brute-force protection',+ state: brute?.available === false ? 'unknown' : (brute?.enabled ? 'pass' : 'fail'),+ detail: brute?.available === false ? 'fail2ban unavailable' : (brute?.enabled ? 'jail active' : 'not protected'),+ },];const scored = checks.filter(c => c.state !== 'unknown');const score = scored.length ? Math.round(scored.filter(c => c.state === 'pass').length / scored.length * 100) : null;@@ -1230,6 +1257,41 @@ const SecurityTab = ({ siteId }) => {<p className="hint">Disable WP-Cron only if a real system cron hits wp-cron.php — otherwise scheduled tasks (publishing, updates) will not run.</p></div></div>++ <div className="app-panel">+ <div className="app-panel-header">Brute-force protection</div>+ <div className="app-panel-body">+ {brute?.available === false ? (+ <p className="hint">Fail2ban isn’t installed on this server, so login brute-force protection is inactive. Install it from the <strong>Security → Fail2ban</strong> page to enable per-site jails.</p>+ ) : (+ <>+ <div className="app-info-grid">+ <div className="app-info-item"><span className="app-info-label">Login jail</span><span className="app-info-value"><Pill kind={brute?.enabled ? 'green' : 'gray'}>{brute?.enabled ? 'active' : 'off'}</Pill></span></div>+ <div className="app-info-item"><span className="app-info-label">Currently banned</span><span className="app-info-value">{brute?.currently_banned ?? 0}</span></div>+ <div className="app-info-item"><span className="app-info-label">Total bans</span><span className="app-info-value">{brute?.total_banned ?? 0}</span></div>+ </div>+ <div className="app-detail-actions">+ <Button variant="outline" size="sm" onClick={toggleBrute} disabled={busy}>{brute?.enabled ? 'Disable protection' : 'Enable protection'}</Button>+ </div>+ {(brute?.banned_ips?.length > 0) && (+ <div className="wp-banlist">+ {brute.banned_ips.map(ip => (+ <div key={ip} className="wp-banlist__row">+ <span className="wp-banlist__ip">{ip}</span>+ <Button variant="ghost" size="sm" onClick={() => unbanIp(ip)} disabled={busy}>Unban</Button>+ </div>+ ))}+ </div>+ )}+ <p className="hint">+ Bans IPs that repeatedly POST to <code>wp-login.php</code> or <code>xmlrpc.php</code>+ {brute?.thresholds ? ` (${brute.thresholds.maxretry} attempts / ${Math.round(brute.thresholds.findtime / 60)} min → ${Math.round(brute.thresholds.bantime / 60)} min ban)` : ''}.+ {brute?.available && brute?.fail2ban_running === false ? ' Fail2ban is installed but not running — start it on the Security page.' : ''}+ </p>+ </>+ )}+ </div>+ </div></div></div>);diff --git a/frontend/src/services/wordpress.js b/frontend/src/services/wordpress.jsindex 0f8b864a..d9f44f01 100644--- a/frontend/src/services/wordpress.js+++ b/frontend/src/services/wordpress.js@@ -245,6 +245,12 @@ const wordpressApi = {runCron: (siteId) => api.request(`${BASE_PATH}/${siteId}/cron/run`, { method: 'POST' }),setCronDisabled: (siteId, disabled) => api.request(`${BASE_PATH}/${siteId}/cron`, { method: 'POST', body: { disabled } }),+ // Per-site brute-force protection: a WP-login Fail2ban jail watching the+ // site's reverse-proxy access log.+ getBruteForce: (siteId) => api.request(`${BASE_PATH}/${siteId}/security/bruteforce`),+ setBruteForce: (siteId, enabled) => api.request(`${BASE_PATH}/${siteId}/security/bruteforce`, { method: 'POST', body: { enabled } }),+ unbanBruteForceIp: (siteId, ip) => api.request(`${BASE_PATH}/${siteId}/security/bruteforce/unban`, { method: 'POST', body: { ip } }),+// Monthly client reports (#33): persisted per-month uptime/updates/backups/vuln rollupsgetReports: (siteId) => api.request(`${BASE_PATH}/${siteId}/reports`),generateReport: (siteId, body = {}) => api.request(`${BASE_PATH}/${siteId}/reports/generate`, { method: 'POST', body }),diff --git a/frontend/src/styles/pages/_wordpress.scss b/frontend/src/styles/pages/_wordpress.scssindex 0450ac2e..66695993 100644--- a/frontend/src/styles/pages/_wordpress.scss+++ b/frontend/src/styles/pages/_wordpress.scss@@ -1405,6 +1405,30 @@overflow-wrap: anywhere;}+ // ---- Brute-force jail: banned-IP rows with an inline Unban action ----+ .wp-banlist {+ margin-top: $space-3;+ border: 1px solid var(--border-soft);+ border-radius: $radius-md;+ overflow: hidden;+ }+ .wp-banlist__row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: $space-3;+ padding: 8px $space-4;++ & + & {+ border-top: 1px solid var(--border-soft);+ }+ }+ .wp-banlist__ip {+ font-family: var(--mono);+ font-size: 13px;+ color: var(--text-code);+ }+// ---- Run-history / incident rows (Updates + Reports) ----.wp-run-row {display: flex;