Roadmaps / Cybersecurity / Lab 3

Lab 3 of 8 · Logs and detection (SOC basics)

Log a login service and write a brute-force detection

Run a small login service that writes JSON security logs, then write and test a rule that alerts on 5 failed logins from one address within 60 seconds.

Time
60–90 minutes
Cost
Free.

What you learn

A security operations centre (SOC) watches logs for signs of attack. A detection rule turns "something looks wrong" into an alert someone can act on. This is the core of a SOC analyst job.

  • What good security logs contain
  • Writing a detection rule with a threshold and a time window
  • Testing a rule before you trust it
  • How SIEM tools (Splunk, Microsoft Sentinel, Elastic) run rules at scale

In the AI era: SOCs now use AI to summarise alerts and suggest next steps, but the alerts come from rules like the one you write here, and analysts still judge them.

Before you start

  • Finish lab 2 (you need the virtual environment).

Step by step

  1. 1 Write the login service

    Every login attempt writes one JSON line to logs/auth.log with the time, result, user and address.

    File: login_app.py
    """A tiny login service that writes security logs, for practising detection.
    Demo only: real apps store password hashes, not passwords."""
    import json
    import logging
    import os
    from datetime import datetime, timezone
    from pathlib import Path
    
    from flask import Flask, jsonify, request
    
    app = Flask(__name__)
    Path("logs").mkdir(exist_ok=True)
    log = logging.getLogger("auth")
    log.setLevel(logging.INFO)
    log.addHandler(logging.FileHandler("logs/auth.log"))
    
    USERS = {"alex": "correct-horse-battery-staple"}
    BLOCKED_IPS = {ip for ip in os.getenv("BLOCKED_IPS", "").split(",") if ip}
    
    
    def record(event: str, user: str, ip: str) -> None:
        log.info(json.dumps({
            "time": datetime.now(timezone.utc).isoformat(),
            "event": event,
            "user": user,
            "ip": ip,
        }))
    
    
    @app.post("/login")
    def login():
        # Lab only: trusting X-Forwarded-For lets us pretend to be other IPs.
        # A real app trusts it only from its own proxy.
        ip = request.headers.get("X-Forwarded-For", request.remote_addr or "unknown")
        body = request.get_json(silent=True) or {}
        user = str(body.get("user", ""))[:64]
        if ip in BLOCKED_IPS:
            record("blocked", user, ip)
            return jsonify(error="blocked"), 403
        if USERS.get(user) == body.get("password"):
            record("login_success", user, ip)
            return jsonify(ok=True)
        record("login_failure", user, ip)
        return jsonify(error="invalid credentials"), 401
    
  2. 2 Run it and log in once

    Start the service in one terminal and keep it running. In a second terminal (with the virtual environment active), log in correctly.

    Run this
    flask --app login_app run --port 5001
    # in a second terminal:
    curl -s -X POST http://127.0.0.1:5001/login -H "content-type: application/json" -d '{"user": "alex", "password": "correct-horse-battery-staple"}'
    tail -n 1 logs/auth.log
    You should see:

    {"ok":true} and a login_success log line.

  3. 3 Write the detection rule

    The rule keeps a sliding 60-second window of failures per address and raises one alert when an address reaches 5.

    File: detect.py
    """Detection rule: 5 or more failed logins from one IP within 60 seconds."""
    import json
    from collections import defaultdict, deque
    from datetime import datetime, timedelta
    from pathlib import Path
    
    WINDOW = timedelta(seconds=60)
    THRESHOLD = 5
    
    
    def detect(lines: list[str]) -> list[dict]:
        recent: dict[str, deque] = defaultdict(deque)
        alerted: set[str] = set()
        alerts = []
        for line in lines:
            if not line.strip():
                continue
            entry = json.loads(line)
            if entry["event"] != "login_failure":
                continue
            when = datetime.fromisoformat(entry["time"])
            times = recent[entry["ip"]]
            times.append(when)
            while when - times[0] > WINDOW:
                times.popleft()
            if len(times) >= THRESHOLD and entry["ip"] not in alerted:
                alerted.add(entry["ip"])
                alerts.append({
                    "rule": "brute_force_login",
                    "severity": "high",
                    "ip": entry["ip"],
                    "user": entry["user"],
                    "failures_in_window": len(times),
                    "first_seen": times[0].isoformat(),
                    "alert_time": entry["time"],
                })
        return alerts
    
    
    if __name__ == "__main__":
        for alert in detect(Path("logs/auth.log").read_text().splitlines()):
            print(json.dumps(alert))
    
  4. 4 Test the rule

    A rule that has never been tested will either miss attacks or flood you with false alarms. These tests check both.

    File: tests/test_detect.py
    import json
    
    from detect import detect
    
    
    def line(seconds: int, ip: str, event: str = "login_failure") -> str:
        return json.dumps({"time": f"2026-01-01T10:00:{seconds:02d}+00:00", "event": event, "user": "alex", "ip": ip})
    
    
    def test_five_quick_failures_raise_one_alert() -> None:
        alerts = detect([line(s, "203.0.113.50") for s in range(0, 12, 2)])
        assert len(alerts) == 1
        assert alerts[0]["ip"] == "203.0.113.50"
    
    
    def test_slow_failures_do_not_alert() -> None:
        lines = [json.dumps({"time": f"2026-01-01T10:{m:02d}:00+00:00", "event": "login_failure", "user": "alex", "ip": "198.51.100.7"}) for m in range(6)]
        assert detect(lines) == []
    
    
    def test_successful_logins_are_ignored() -> None:
        assert detect([line(s, "192.0.2.1", "login_success") for s in range(10)]) == []
    
  5. 5 Run the tests

    The empty files let pytest import your modules.

    Run this
    touch tests/__init__.py conftest.py
    python -m pytest -q
    You should see:

    3 passed.

  6. 6 Commit and push

    Your logs folder is ignored by Git: logs can contain personal data and do not belong in a repository.

    Run this
    git add login_app.py detect.py tests conftest.py
    git commit -m "Add login service with security logs and a brute-force detection"
    git push

You are done when

  • Every login attempt appears in logs/auth.log as JSON.

  • Three tests prove the rule alerts on fast failures and ignores slow ones.

  • You can name the threshold and window and explain the trade-off between missed attacks and false alarms.

Finished? Get your proof page

We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.