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.

22.1 KB
Raw Blame
"""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 (ServiceControl, is_command_available,
                             run_checked, run_privileged, write_privileged_file)
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 = {port}
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_for_key(cls, key):
        """``serverkit-<key>`` jail name for any sanitized key (site name, game
        server id, …). The generic naming primitive under jail_name(app)."""
        return cls.JAIL_PREFIX + cls._sanitize(key)

    @classmethod
    def jail_name(cls, app):
        """``serverkit-<key>`` jail name for an application."""
        return cls.jail_name_for_key(getattr(app, 'name', None))

    @classmethod
    def _jail_path_for_name(cls, jail):
        """Absolute path of a jail file by full jail name, guarded so it can only
        ever be a ServerKit-owned file inside JAIL_DIR."""
        filename = f'{jail}.conf'
        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)

    @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)."""
        return cls._jail_path_for_name(cls.jail_name(app))

    # ---------- 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 — the shared door."""
        return write_privileged_file(path, content)

    @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, filter_name=None, filter_content=None):
        """Write a ServerKit-owned Fail2ban filter if missing or out of date.

        Generic: any vertical can supply its own ``serverkit-*`` filter (e.g. a
        game-server console-login filter). Defaults to the WordPress login/xmlrpc
        filter for back-compat. Ownership-guarded — the name must be a
        ``serverkit-`` filter, so this never touches an operator's own filters."""
        if not cls.available():
            return cls._unavailable()
        filter_name = filter_name or cls.WP_FILTER
        filter_content = filter_content if filter_content is not None else cls.FILTER_CONTENT
        if not filter_name.startswith(cls.JAIL_PREFIX):
            return {'success': False,
                    'error': f'filter name must start with {cls.JAIL_PREFIX!r}'}
        safe = cls._sanitize(filter_name)
        path = os.path.join(cls.FILTER_DIR, f'{safe}.conf')
        existing = cls._read_text(path)
        if existing is not None and existing.strip() == filter_content.strip():
            return {'success': True, 'path': path, 'changed': False}
        res = cls._write_file(path, filter_content)
        if not res.get('success'):
            return res
        return {'success': True, 'path': path, 'changed': True}

    # ---------- jail lifecycle ----------

    @classmethod
    def _render_jail_config(cls, *, jail, site, filter_name, logpath,
                            maxretry, findtime, bantime, port='http,https'):
        return cls.JAIL_TEMPLATE.format(
            jail=jail, site=site, filter=filter_name, logpath=logpath,
            maxretry=maxretry or cls.MAXRETRY,
            findtime=findtime or cls.FINDTIME,
            bantime=bantime or cls.BANTIME,
            port=port,
        )

    @classmethod
    def _render_jail(cls, app, logpath, maxretry, findtime, bantime):
        """WP-flavored back-compat renderer (serverkit-wp-login filter, web ports)."""
        return cls._render_jail_config(
            jail=cls.jail_name(app), site=getattr(app, 'name', ''),
            filter_name=cls.WP_FILTER, logpath=logpath,
            maxretry=maxretry, findtime=findtime, bantime=bantime, port='http,https')

    @classmethod
    def enable_jail(cls, key, *, filter_name, filter_content, logpath,
                    maxretry=None, findtime=None, bantime=None,
                    port='http,https', site_label=None):
        """Create/refresh an arbitrary ServerKit-owned brute-force jail; reload.

        The generic engine behind enable_wp_jail, reusable by other verticals
        (e.g. a game-server login/RCON jail). ``key`` names the jail
        (``serverkit-<sanitized key>``); ``filter_name``/``filter_content`` define
        the ``serverkit-*`` filter to (re)write; ``logpath`` is the log to watch;
        ``port`` sets the jail's ports. Idempotent and best-effort: returns a
        ``skipped`` descriptor when fail2ban is unavailable rather than raising."""
        if not cls.available():
            return cls._unavailable()
        if not key:
            return {'success': False, 'error': 'jail key is required'}

        flt = cls.ensure_filter(filter_name, filter_content)
        if not flt.get('success'):
            return flt

        cls._ensure_logpath(logpath)
        jail = cls.jail_name_for_key(key)
        try:
            jail_path = cls._jail_path_for_name(jail)
        except ValueError as e:
            return {'success': False, 'error': str(e)}

        written = cls._write_file(jail_path, cls._render_jail_config(
            jail=jail, site=site_label or key, filter_name=cls._sanitize(filter_name),
            logpath=logpath, maxretry=maxretry, findtime=findtime, bantime=bantime,
            port=port))
        if not written.get('success'):
            return written

        reloaded = cls.reload()
        return {
            'success': True, 'enabled': True, 'jail': jail,
            'path': jail_path, 'logpath': logpath,
            'reloaded': reloaded.get('success'), 'reload_message': reloaded.get('message'),
        }

    @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.

        Thin wrapper over the generic enable_jail engine with the WordPress
        login/xmlrpc filter and the site's nginx access log."""
        if not cls.available():
            return cls._unavailable()
        if not getattr(app, 'name', None):
            return {'success': False, 'error': 'application has no name'}
        logpath = NginxService.site_access_log_path(app.name)
        return cls.enable_jail(
            app.name, filter_name=cls.WP_FILTER, filter_content=cls.FILTER_CONTENT,
            logpath=logpath, maxretry=maxretry, findtime=findtime, bantime=bantime,
            port='http,https', site_label=app.name)

    @classmethod
    def remove_jail(cls, key):
        """Remove a ServerKit jail by key and reload fail2ban. No-op (success)
        when the jail does not exist or fail2ban is unavailable."""
        if not cls.available():
            return cls._unavailable()
        jail = cls.jail_name_for_key(key)
        try:
            jail_path = cls._jail_path_for_name(jail)
        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': jail,
                'reloaded': reloaded.get('success')}

    @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.

        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
        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

        f2b = cls.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 = cls.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."""
        if not cls.available():
            return cls._unavailable()
        return cls.unban_ip(ip, cls.jail_name(app))

    # ------------------------------------------------------------------
    # Fail2ban status probing + unban (inversion). These are
    # the read/undo half core keeps when the management surface moves to
    # the serverkit-fail2ban extension: Setup Health, the security audit
    # and the per-site jail status above all probe through here, and the
    # extension's routes delegate here too. Pure fail2ban-client probes —
    # they work whenever the host tool exists, extension installed or not.
    # ------------------------------------------------------------------
    @classmethod
    def get_fail2ban_status(cls):
        """Get Fail2ban installation and service status."""
        result = {
            'installed': False,
            'service_running': False,
            'version': None,
            'jails': []
        }

        try:
            version_output = run_checked(['fail2ban-client', '--version'], timeout=10)
            if version_output['success']:
                result['installed'] = True
                result['version'] = version_output['output'].strip().split('\n')[0]
        except Exception:  # noqa: BLE001 - probe only; absence is the answer
            pass

        if result['installed']:
            try:
                result['service_running'] = ServiceControl.is_active('fail2ban')
            except Exception:
                pass

            if result['service_running']:
                try:
                    jails_output = run_checked(['fail2ban-client', 'status'], timeout=10)
                    if jails_output['success']:
                        for line in jails_output['output'].split('\n'):
                            if 'Jail list:' in line:
                                jails_str = line.split(':')[1].strip()
                                if jails_str:
                                    result['jails'] = [j.strip() for j in jails_str.split(',')]
                except Exception:
                    pass

        return result

    @classmethod
    def get_fail2ban_jail_status(cls, jail):
        """Get status of a specific Fail2ban jail."""
        try:
            result = run_checked(['fail2ban-client', 'status', jail], timeout=10)

            if not result['success']:
                return {'success': False, 'error': f'Jail {jail} not found'}

            status = {
                'jail': jail,
                'currently_banned': 0,
                'total_banned': 0,
                'banned_ips': [],
                'currently_failed': 0,
                'total_failed': 0
            }

            for line in result['output'].split('\n'):
                line = line.strip()
                if 'Currently banned:' in line:
                    status['currently_banned'] = int(line.split(':')[1].strip())
                elif 'Total banned:' in line:
                    status['total_banned'] = int(line.split(':')[1].strip())
                elif 'Banned IP list:' in line:
                    ips_str = line.split(':')[1].strip()
                    if ips_str:
                        status['banned_ips'] = ips_str.split()
                elif 'Currently failed:' in line:
                    status['currently_failed'] = int(line.split(':')[1].strip())
                elif 'Total failed:' in line:
                    status['total_failed'] = int(line.split(':')[1].strip())

            return {'success': True, **status}

        except Exception as e:
            return {'success': False, 'error': str(e)}

    @classmethod
    def unban_ip(cls, ip, jail=None):
        """Unban an IP from Fail2ban."""
        try:
            if jail:
                result = run_checked(['fail2ban-client', 'set', jail, 'unbanip', ip],
                                     timeout=10)
            else:
                result = run_checked(['fail2ban-client', 'unban', ip], timeout=10)

            if result['success']:
                return {'success': True, 'message': f'IP {ip} unbanned'}
            return {'success': False, 'error': result['error'] or 'Failed to unban IP'}

        except Exception as e:
            return {'success': False, 'error': str(e)}