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(security): honour the failed-login time window (#180)

Max Freedom Pollard3de85c2a17ce
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fc27411a..27e2f9df 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -96,6 +96,11 @@ release history; historical `agent-v*` tags are not panel releases.
Scanner custom-path scan, #144). Blueprint registration now waives Flask's
setup guard for the duration of the call, which is safe in the panel's
single-worker threaded deployment.
+- Count only the requested window in the failed-login check. The Security →
+ Events card "Failed login attempts (24h)" and its alert counted every
+ failure still in the auth log, which under the usual weekly log rotation is
+ up to a week of SSH attempts, so the number was inflated and the alert kept
+ firing on old attempts.
## [1.11.4] - 2026-09-12
diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.py
index 59f72c69..fc2db6a1 100644
--- a/backend/app/services/security_service.py
+++ b/backend/app/services/security_service.py
@@ -15,6 +15,7 @@ serverkit-image-scan.
"""
import os
+import re
import json
import shlex
import hashlib
@@ -30,6 +31,19 @@ from app.utils.system import (
run_privileged,
)
+# The two stamps an auth log line starts with. RFC 3339 is rsyslog's
+# high-precision format, the default on recent Ubuntu releases:
+# "2026-10-22T09:15:02.123456+02:00". The traditional BSD stamp, still written
+# on Debian and the RHEL family and by syslog-ng, is local time with no year:
+# "Oct 2 09:15:02". Its month names are English whatever the locale, so they
+# are matched by hand rather than through strptime's %b.
+_RFC3339_STAMP_RE = re.compile(r'^(\d{4}-\d{2}-\d{2}T\S+)\s')
+_BSD_STAMP_RE = re.compile(r'^([A-Z][a-z]{2}) {1,2}(\d{1,2}) (\d{2}):(\d{2}):(\d{2})\s')
+_SYSLOG_MONTHS = {m: i for i, m in enumerate(
+ ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'), start=1)}
+
+
class SecurityService:
"""Service for security scanning and monitoring."""
@@ -38,6 +52,8 @@ class SecurityService:
INTEGRITY_DB = os.path.join(CONFIG_DIR, 'file_integrity.json')
SCAN_LOG = os.path.join(paths.SERVERKIT_LOG_DIR, 'security_scans.log')
ALERTS_LOG = os.path.join(paths.SERVERKIT_LOG_DIR, 'security_alerts.log')
+ # Where sshd/PAM failures land: Debian family, then the RHEL family.
+ AUTH_LOGS = ('/var/log/auth.log', '/var/log/secure')
# Scan status tracking
_current_scan = None
@@ -227,14 +243,42 @@ class SecurityService:
# ==========================================
# SUSPICIOUS ACTIVITY DETECTION
# ==========================================
+ @staticmethod
+ def _auth_log_time(line: str, now: datetime) -> Optional[datetime]:
+ """When an auth log line was written, as naive local time, or None
+ when its stamp is neither of the two rsyslog writes by default.
+
+ The BSD stamp has no year, so it takes ``now``'s and steps back one
+ when that would put the line more than a day in the future, as a
+ December line read in January would be.
+ """
+ match = _RFC3339_STAMP_RE.match(line)
+ if match:
+ try:
+ stamp = datetime.fromisoformat(match.group(1))
+ except ValueError:
+ return None
+ return stamp.astimezone().replace(tzinfo=None)
+
+ match = _BSD_STAMP_RE.match(line)
+ if not match or match.group(1) not in _SYSLOG_MONTHS:
+ return None
+ month = _SYSLOG_MONTHS[match.group(1)]
+ day, hour, minute, second = (int(part) for part in match.groups()[1:])
+ try:
+ stamp = datetime(now.year, month, day, hour, minute, second)
+ if stamp > now + timedelta(days=1):
+ stamp = stamp.replace(year=now.year - 1)
+ except ValueError: # Feb 29 outside a leap year, or a garbled stamp
+ return None
+ return stamp
+
@classmethod
def check_failed_logins(cls, since_hours: int = 24) -> Dict:
- """Check for failed login attempts."""
+ """Count failed logins in the auth log over the last ``since_hours``."""
try:
- # Check auth.log or secure log
- log_files = ['/var/log/auth.log', '/var/log/secure']
log_file = None
- for lf in log_files:
+ for lf in cls.AUTH_LOGS:
if os.path.exists(lf):
log_file = lf
break
@@ -242,13 +286,19 @@ class SecurityService:
if not log_file:
return {'success': False, 'error': 'Auth log not found'}
- cutoff_time = datetime.now() - timedelta(hours=since_hours)
+ now = datetime.now()
+ cutoff_time = now - timedelta(hours=since_hours)
failed_attempts = []
with open(log_file, 'r') as f:
for line in f:
if 'Failed password' in line or 'authentication failure' in line.lower():
- # Parse the log line to extract IP and user
+ # A line whose stamp cannot be read is kept rather
+ # than dropped: it may be recent, and leaving it out
+ # would hide failures instead of counting them.
+ written = cls._auth_log_time(line, now)
+ if written is not None and written < cutoff_time:
+ continue
failed_attempts.append(line.strip())
config = cls.get_config()
diff --git a/backend/tests/test_failed_logins_window.py b/backend/tests/test_failed_logins_window.py
new file mode 100644
index 00000000..f8eb2ae3
--- /dev/null
+++ b/backend/tests/test_failed_logins_window.py
@@ -0,0 +1,132 @@
+"""SecurityService.check_failed_logins must count only its time window.
+
+The Security -> Events tab asks for the last 24 hours of failed logins
+(``GET /api/v1/security/failed-logins?hours=24``), shows the number under
+"Failed login attempts (24h)", and alerts with "... in the last 24 hours"
+once it reaches the threshold. check_failed_logins computed the cutoff for
+that window and never used it, so every failure still in the current auth
+log was counted: on a stock weekly logrotate that is up to a week of SSH
+noise, which keeps the alert firing on old attempts.
+
+These tests write a throwaway auth log with failures on both sides of the
+cutoff, in the two timestamp formats rsyslog writes, and point the service
+at it.
+"""
+from datetime import datetime, timedelta
+
+import pytest
+
+from app.services.security_service import SecurityService
+
+MONTHS = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
+
+
+def bsd_stamp(when):
+ """Traditional syslog stamp, local time and no year: 'Oct 2 09:15:02'.
+
+ Built by hand because strftime's %b follows the locale and syslog's
+ month names do not."""
+ return f'{MONTHS[when.month - 1]} {when.day:2d} {when:%H:%M:%S}'
+
+
+def rfc3339_stamp(when):
+ """rsyslog's high-precision stamp: '2026-10-22T09:15:02.123456+02:00'."""
+ return when.astimezone().isoformat(timespec='microseconds')
+
+
+def failure(stamp, n):
+ return (f'{stamp} web1 sshd[{1000 + n}]: Failed password for root '
+ f'from 203.0.113.{n} port {40000 + n} ssh2')
+
+
+def auth_log(tmp_path, monkeypatch):
+ """A temp auth log the service reads instead of the host's, the default
+ security config (threshold 5), and alerts captured instead of sent."""
+ path = tmp_path / 'auth.log'
+ monkeypatch.setattr(SecurityService, 'AUTH_LOGS', (str(path),))
+ monkeypatch.setattr(SecurityService, 'SECURITY_CONFIG',
+ str(tmp_path / 'security.json'))
+ sent = []
+ monkeypatch.setattr(
+ SecurityService, '_send_security_notification',
+ classmethod(lambda cls, *args, **kwargs: sent.append((args, kwargs))))
+
+ def write(lines):
+ path.write_text('\n'.join(lines) + '\n')
+
+ write.sent = sent
+ return write
+
+
[email protected]('stamp', [bsd_stamp, rfc3339_stamp],
+ ids=['bsd', 'rfc3339'])
+def test_failures_older_than_the_window_are_not_counted(auth_log, stamp):
+ now = datetime.now()
+ stale = [failure(stamp(now - timedelta(days=days)), n)
+ for n, days in enumerate((5, 3, 2), start=1)]
+ recent = [failure(stamp(now - timedelta(hours=hours)), n)
+ for n, hours in enumerate((2, 1), start=4)]
+ auth_log(stale + recent)
+
+ result = SecurityService.check_failed_logins(24)
+
+ assert result['success'] is True
+ assert result['failed_attempts'] == 2
+ assert result['recent_failures'] == recent
+ # Two failures sit under the default threshold of 5. All five lines
+ # together reach it, which is what used to raise the alert.
+ assert result['alert_triggered'] is False
+ assert auth_log.sent == []
+
+
+def test_the_window_follows_the_hours_requested(auth_log):
+ now = datetime.now()
+ auth_log([failure(bsd_stamp(now - timedelta(hours=hours)), n)
+ for n, hours in enumerate((100, 50, 5), start=1)])
+
+ assert SecurityService.check_failed_logins(24)['failed_attempts'] == 1
+ assert SecurityService.check_failed_logins(72)['failed_attempts'] == 2
+ assert SecurityService.check_failed_logins(168)['failed_attempts'] == 3
+
+
+def test_the_alert_reports_the_count_inside_the_window(auth_log):
+ now = datetime.now()
+ stale = [failure(bsd_stamp(now - timedelta(days=3)), n)
+ for n in range(1, 21)]
+ recent = [failure(bsd_stamp(now - timedelta(minutes=10 * n)), n)
+ for n in range(21, 27)]
+ auth_log(stale + recent)
+
+ result = SecurityService.check_failed_logins(24)
+
+ assert result['failed_attempts'] == 6
+ assert result['alert_triggered'] is True
+ [(args, kwargs)] = auth_log.sent
+ assert args == ('failed_logins',
+ 'High number of failed login attempts: 6 in the last 24 hours')
+ assert kwargs['details'] == {'count': 6}
+
+
+def test_a_december_stamp_read_in_january_is_from_last_year():
+ """The traditional stamp has no year. Taking the current one would put
+ New Year's Eve failures eleven months in the future."""
+ new_year = datetime(2027, 1, 1, 0, 30)
+
+ assert SecurityService._auth_log_time(
+ failure('Dec 31 23:50:07', 1), new_year) == datetime(2026, 12, 31, 23, 50, 7)
+ assert SecurityService._auth_log_time(
+ failure('Jan 1 00:10:00', 2), new_year) == datetime(2027, 1, 1, 0, 10)
+
+
+def test_a_line_without_a_recognisable_stamp_is_still_counted(auth_log):
+ """A custom rsyslog template the parser does not know cannot be placed
+ in time. Counting it keeps the alert from going quiet on such a host."""
+ line = 'web1 sshd[1001]: Failed password for root from 203.0.113.1 port 40001 ssh2'
+ auth_log([line])
+
+ result = SecurityService.check_failed_logins(24)
+
+ assert result['failed_attempts'] == 1
+ assert result['recent_failures'] == [line]