TExcelTAD
Home › Cybersecurity › Mini Project: Login Guard

Mini Project: Login Guard

In this project you'll build Login Guard, a small defensive toolkit for a web shop's login system. It brings together several lessons of the course:

  • a password-policy checker that rejects weak passwords at sign-up (Password Policy),
  • safe password storage with a slow, salted KDF (Password Storage),
  • structured security logging of every login attempt (Logging & Detection),
  • an anomaly detector that turns the login log into prioritised alerts (Logging, SOC).

Every step is a complete program you can run and change. The "users" and "attackers" are simulated with fixed data and fixed timestamps, so the output is always the same.

Step 1: The password policy

Following modern guidance, the policy checks length, a blocklist of common passwords (also with trailing digits and symbols removed), and context (no username or shop name inside the password). It returns a list of reasons, so the sign-up form can tell the user exactly what to change.

python · try it yourself
import unicodedata

BLOCKLIST = {"password", "123456", "12345678", "qwerty", "letmein", "welcome",
             "iloveyou", "admin", "monkey", "football", "dragon", "sunshine"}
SITE = "tadshop"
MIN_LEN, MAX_LEN = 12, 128

def policy_problems(password, username):
    pw = unicodedata.normalize("NFKC", password)
    lowered = pw.lower()
    core = lowered.rstrip("0123456789!@#$%^&*?.")
    problems = []
    if len(pw) < MIN_LEN:
        problems.append(f"at least {MIN_LEN} characters")
    if len(pw) > MAX_LEN:
        problems.append(f"at most {MAX_LEN} characters")
    if lowered in BLOCKLIST or core in BLOCKLIST:
        problems.append("too common")
    if username.lower() in lowered:
        problems.append("contains your username")
    if SITE in lowered:
        problems.append("contains the shop name")
    if len(set(lowered)) < 4:
        problems.append("too few different characters")
    return problems

candidates = [
    ("ana", "sunshine2026!"),
    ("ben", "ben-likes-tea"),
    ("chi", "tadshop-summer"),
    ("dan", "zzzzzzzzzzzzzz"),
    ("eva", "lantern copper meadow"),
]
for user, pw in candidates:
    problems = policy_problems(pw, user)
    print(f"{user}: {'accepted' if not problems else 'rejected (' + ', '.join(problems) + ')'}")
ana: rejected (too common)
ben: rejected (contains your username)
chi: rejected (contains the shop name)
dan: rejected (too few different characters)
eva: accepted

Step 2: Registering accounts with scrypt

Accepted passwords are stored as scrypt hashes with a random salt per user, in a self-describing format (scrypt$n$r$p$salt$hash). The salts are random, so we never print them; we print only what is deterministic. The cost n = 2**12 keeps this demo quick in the browser; production systems tune it higher (for example 2**15 or more, around 50–100 ms per hash).

python · try it yourself
import base64
import os
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.exceptions import InvalidKey

N, R, P = 2**12, 8, 1          # demo cost: tune higher in production

def hash_password(password):
    salt = os.urandom(16)
    key = Scrypt(salt=salt, length=32, n=N, r=R, p=P).derive(password.encode())
    return "
quot;.join(["scrypt", str(N), str(R), str(P), base64.b64encode(salt).decode(), base64.b64encode(key).decode()]) def check_password(password, record): _, n, r, p, salt, key = record.split("
quot;) kdf = Scrypt(salt=base64.b64decode(salt), length=32, n=int(n), r=int(r), p=int(p)) try: kdf.verify(password.encode(), base64.b64decode(key)) return True except InvalidKey: return False accounts = {} for user, pw in [("eva", "lantern copper meadow"), ("fay", "orbit velvet kettle 42")]: accounts[user] = hash_password(pw) print("stored fields:", accounts["eva"].split("
quot;)[:4], "+ salt + hash") print("eva correct:", check_password("lantern copper meadow", accounts["eva"])) print("eva wrong: ", check_password("lantern copper meadows", accounts["eva"])) print("unique salts:", accounts["eva"].split("
quot;)[4] != accounts["fay"].split("
quot;)[4])
stored fields: ['scrypt', '4096', '8', '1'] + salt + hash
eva correct: True
eva wrong:   False
unique salts: True

Step 3: Logging every login attempt

The login function returns a result and writes a structured event (a dict, which would be one JSON line in a real log). It records time, user, source IP, country (from a GeoIP lookup in real life) and outcome, and it never logs the password. Unknown users get the same generic answer as wrong passwords, so attackers can't learn which usernames exist.

python · try it yourself
import json

USERS = {"eva": "pw-eva", "fay": "pw-fay", "gus": "pw-gus"}   # stand-in for hashed records
LOG = []

def login(t, user, password, ip, country):
    ok = user in USERS and USERS[user] == password      # real code: check_password()
    LOG.append({"t": t, "user": user, "ip": ip, "country": country,
                "outcome": "success" if ok else "failure"})
    return "welcome" if ok else "invalid username or password"

print(login(1000, "eva", "pw-eva", "198.51.100.10", "VN"))
print(login(1010, "eva", "oops", "198.51.100.10", "VN"))
print(login(1020, "nobody", "x", "203.0.113.66", "NL"))
for event in LOG:
    print(json.dumps(event))
welcome
invalid username or password
invalid username or password
{"t": 1000, "user": "eva", "ip": "198.51.100.10", "country": "VN", "outcome": "success"}
{"t": 1010, "user": "eva", "ip": "198.51.100.10", "country": "VN", "outcome": "failure"}
{"t": 1020, "user": "nobody", "ip": "203.0.113.66", "country": "NL", "outcome": "failure"}

Step 4: Detection rules

Now the detector. It reads the event log and applies four rules, each producing an alert with a severity:

Rule Signal Severity
Brute force ≥ 5 failures from one IP within 5 minutes medium
Credential stuffing ≥ 4 different usernames failing from one IP high
Success after failures a login succeeds from an IP that brute-forced or stuffed critical
New country a user logs in from a country never seen for them before low
python · try it yourself
from collections import defaultdict

def detect(log, burst=5, window=300, stuffing_users=4):
    alerts = []
    fails_by_ip = defaultdict(list)
    for e in log:
        if e["outcome"] == "failure":
            fails_by_ip[e["ip"]].append(e)

    suspicious_ips = {}
    for ip, fails in fails_by_ip.items():
        times = [e["t"] for e in fails]
        if any(times[i + burst - 1] - times[i] <= window for i in range(len(times) - burst + 1)):
            alerts.append(("medium", f"brute force from {ip}: {len(fails)} failures"))
            suspicious_ips[ip] = "brute force"
        users = sorted({e["user"] for e in fails})
        if len(users) >= stuffing_users:
            alerts.append(("high", f"credential stuffing from {ip}: {len(users)} usernames"))
            suspicious_ips[ip] = "credential stuffing"

    seen_countries = defaultdict(list)
    for e in log:
        if e["outcome"] != "success":
            continue
        if e["ip"] in suspicious_ips:
            alerts.append(("critical", f"{e['user']} logged in from {e['ip']} after {suspicious_ips[e['ip']]}"))
        known = seen_countries[e["user"]]
        if known and e["country"] not in known:
            alerts.append(("low", f"{e['user']} logged in from new country {e['country']}"))
        if e["country"] not in known:
            known.append(e["country"])
    return alerts

sample = [
    {"t": 0,   "user": "eva", "ip": "198.51.100.10", "country": "VN", "outcome": "success"},
    {"t": 50,  "user": "gus", "ip": "203.0.113.66", "country": "NL", "outcome": "failure"},
    {"t": 60,  "user": "gus", "ip": "203.0.113.66", "country": "NL", "outcome": "failure"},
    {"t": 70,  "user": "gus", "ip": "203.0.113.66", "country": "NL", "outcome": "failure"},
    {"t": 80,  "user": "gus", "ip": "203.0.113.66", "country": "NL", "outcome": "failure"},
    {"t": 90,  "user": "gus", "ip": "203.0.113.66", "country": "NL", "outcome": "failure"},
    {"t": 95,  "user": "gus", "ip": "203.0.113.66", "country": "NL", "outcome": "success"},
    {"t": 400, "user": "eva", "ip": "192.0.2.80", "country": "DE", "outcome": "success"},
]
for severity, message in detect(sample):
    print(f"[{severity}] {message}")
[medium] brute force from 203.0.113.66: 5 failures
[critical] gus logged in from 203.0.113.66 after brute force
[low] eva logged in from new country DE

Five failures in 40 seconds against gus, then a success from the same IP: the detector raises the critical alert you'd want to see first. Eva's login from Germany is only "low": it might be travel or a VPN.

Step 5: The full Login Guard run

Finally, put it all together: sign-ups go through the policy, accounts are stored with scrypt, a simulated morning of login traffic (normal users, a typo, a credential-stuffing bot and a brute-force attack) goes through login, and the detector produces a report sorted by severity, with a recommended action for each alert.

python · try it yourself
import base64
import os
import unicodedata
from collections import defaultdict
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
from cryptography.exceptions import InvalidKey

# ---- policy (step 1) ----
BLOCKLIST = {"password", "123456", "qwerty", "letmein", "welcome", "sunshine", "dragon"}
def policy_problems(password, username):
    lowered = unicodedata.normalize("NFKC", password).lower()
    problems = []
    if len(lowered) < 12: problems.append("too short")
    if lowered in BLOCKLIST or lowered.rstrip("0123456789!?.") in BLOCKLIST: problems.append("too common")
    if username.lower() in lowered: problems.append("contains username")
    return problems

# ---- storage (step 2) ----
N = 2**12
def hash_password(pw):
    salt = os.urandom(16)
    key = Scrypt(salt=salt, length=32, n=N, r=8, p=1).derive(pw.encode())
    return salt, key
def check_password(pw, record):
    salt, key = record
    try:
        Scrypt(salt=salt, length=32, n=N, r=8, p=1).verify(pw.encode(), key)
        return True
    except InvalidKey:
        return False

# ---- logging (step 3) ----
ACCOUNTS, LOG = {}, []
def register(user, pw):
    problems = policy_problems(pw, user)
    if problems:
        return f"{user}: rejected ({', '.join(problems)})"
    ACCOUNTS[user] = hash_password(pw)
    return f"{user}: registered"
def login(t, user, pw, ip, country):
    ok = user in ACCOUNTS and check_password(pw, ACCOUNTS[user])
    LOG.append({"t": t, "user": user, "ip": ip, "country": country,
                "outcome": "success" if ok else "failure"})

# ---- detection (step 4) ----
def detect(log, burst=5, window=300, stuffing_users=4):
    alerts, fails_by_ip, suspicious = [], defaultdict(list), {}
    for e in log:
        if e["outcome"] == "failure":
            fails_by_ip[e["ip"]].append(e)
    for ip, fails in fails_by_ip.items():
        times = [e["t"] for e in fails]
        if any(times[i + burst - 1] - times[i] <= window for i in range(len(times) - burst + 1)):
            alerts.append(("medium", "brute force", ip, f"{len(fails)} failures"))
            suspicious[ip] = "brute force"
        users = sorted({e["user"] for e in fails})
        if len(users) >= stuffing_users:
            alerts.append(("high", "credential stuffing", ip, f"{len(users)} usernames"))
            suspicious[ip] = "credential stuffing"
    seen = defaultdict(list)
    for e in log:
        if e["outcome"] != "success":
            continue
        if e["ip"] in suspicious:
            alerts.append(("critical", "success after attack", e["ip"], f"user {e['user']}"))
        if seen[e["user"]] and e["country"] not in seen[e["user"]]:
            alerts.append(("low", "new country", e["ip"], f"user {e['user']} from {e['country']}"))
        if e["country"] not in seen[e["user"]]:
            seen[e["user"]].append(e["country"])
    return alerts

ACTIONS = {
    "success after attack": "lock account, revoke sessions, force reset + MFA",
    "credential stuffing": "block IP at the edge, check for breached passwords",
    "brute force": "rate-limit / temporarily block IP",
    "new country": "ask user to confirm via email",
}
RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3}

# ---- simulation ----
for user, pw in [("eva", "lantern copper meadow"), ("fay", "orbit velvet kettle 42"),
                 ("gus", "sunshine123!"), ("gus", "maple river 1987 ok"), ("hai", "hai-password-1")]:
    print(register(user, pw))

login(0, "eva", "lantern copper meadow", "198.51.100.10", "VN")
login(30, "fay", "orbit velvet kettel 42", "198.51.100.21", "VN")      # typo
login(45, "fay", "orbit velvet kettle 42", "198.51.100.21", "VN")
for i, name in enumerate(["admin", "anna", "bob", "carl", "dina", "eva"]):
    login(100 + i * 3, name, "Winter2025!", "203.0.113.66", "NL")   # stuffing bot
for i in range(6):
    login(200 + i * 10, "gus", f"guess-{i}", "192.0.2.99", "RU")    # brute force
login(270, "gus", "maple river 1987 ok", "192.0.2.99", "RU")        # ...and it got in
login(900, "eva", "lantern copper meadow", "198.51.100.77", "TH")

alerts = sorted(detect(LOG), key=lambda a: RANK[a[0]])
print(f"\n{len(LOG)} login events, {sum(e['outcome'] == 'failure' for e in LOG)} failures, "
      f"{len(alerts)} alerts")
for severity, rule, ip, detail in alerts:
    print(f"[{severity:<8}] {rule:<21} {ip:<15} {detail}")
    print(f"{'':11}-> {ACTIONS[rule]}")
eva: registered
fay: registered
gus: rejected (too common)
gus: registered
hai: rejected (contains username)

17 login events, 13 failures, 5 alerts
[critical] success after attack  192.0.2.99      user gus
           -> lock account, revoke sessions, force reset + MFA
[high    ] credential stuffing   203.0.113.66    6 usernames
           -> block IP at the edge, check for breached passwords
[medium  ] brute force           203.0.113.66    6 failures
           -> rate-limit / temporarily block IP
[medium  ] brute force           192.0.2.99      6 failures
           -> rate-limit / temporarily block IP
[low     ] new country           198.51.100.77   user eva from TH
           -> ask user to confirm via email

The report tells the on-call engineer exactly what to do first: gus's account was taken over after a brute-force run from 192.0.2.99, so lock it and revoke its sessions. Fay's single typo, by contrast, raises nothing. The stuffing bot trips the brute-force rule as well, because its six attempts came within seconds; a real SIEM would group such related alerts into one incident.

Ideas to extend it

  • Add MFA with the TOTP code from the Authentication lesson, and make the critical action "require MFA" instead of a lockout.
  • Rate-limit in login itself: after 5 failures from an IP, refuse further attempts for a few minutes (and log that).
  • Add a pepper (an HMAC key kept outside the account store) before hashing.
  • Detect impossible travel using timestamps and coordinates, as in the Logging lesson.
  • Output alerts as JSON lines that a SIEM could ingest, with a correlation ID per alert.

Go further: How the Projects Work sets out ten larger portfolio projects with a written scope, deliverables and a rubric.

Test yourself

Why does login return the same message for an unknown user and a wrong password?

  1. To save code
  2. So attackers can't use the response to discover which usernames exist
  3. Because the password is hashed
  4. To make logs shorter

Which alert in the final report deserves attention first, and why?

  1. New country, because it is the newest
  2. Success after attack, because an account was probably compromised
  3. Brute force, because it had the most events
  4. Credential stuffing, because many users were involved

What does the stuffing bot's pattern look like in the log?

  1. One user, many passwords
  2. Many different usernames tried once each from the same IP
  3. Logins from many countries
  4. Only successful logins