Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

Reading Sign-In Logs for Identity Attacks

Generate a seeded sign-in log with normal traffic, a password-spraying burst, an MFA-fatigue sequence that ends in an approval and a stolen session reused from a new device, write detections that find each one while staying quiet on shared NAT addresses and network changes, and choose containment steps mapped to MITRE ATT&CK.

Contentsand lesson path

What you will learn

  • Recognise identity attack patterns such as password spraying, MFA fatigue and session token theft in sign-in logs and recommend containment.

01. Goal and setup

Identity attacks leave traces in the identity provider's sign-in log: one record per password attempt, MFA prompt or session use, with the user, source IP address, network owner and device. In this lab you generate one day of synthetic log for 60 users, then write detections for three attacks hidden in it. You also check each detection against normal events that look similar, because a rule that fires on Monday-morning typos gets switched off.

You need: Python 3.12, standard library only. The generator uses a fixed random seed, so with the same Python version your log and outputs match the ones shown. The IP addresses come from the ranges reserved for documentation (192.0.2.0/24, 198.51.100.0/24 and 203.0.113.0/24), and the network numbers from the private ASN range. An ASN (autonomous system number) identifies the network that owns an address, such as an internet provider or a hosting company. Work in a new folder called signin-lab.

02. Three patterns and their shapes

Three attack patterns are in the log. Each one leaves a different shape.

Password spraying (ATT&CK T1110.003) tries one or two common passwords against many accounts, slowly enough that no single account locks. Its shape is many distinct accounts failing, few attempts per account, often from one hosting network with rotating addresses. It differs from password guessing (T1110.001: many passwords against one account) and credential stuffing (T1110.004: username and password pairs leaked from another site, so each account gets its own guess and the success rate is higher).

MFA request flooding (T1621), often called MFA fatigue, needs the password first. The attacker starts sign-in after sign-in, and the user's phone shows prompt after prompt until the user approves one. Its shape is a burst of denied or timed-out prompts for one user, then an approval, all from a network the user does not normally use.

Session token reuse follows theft of a session cookie or token (T1539 Steal Web Session Cookie), for example by infostealer malware on the user's device or by an adversary-in-the-middle phishing kit. The attacker then presents it (T1550.004). No password or MFA is needed, so there is no failed sign-in to see. Its shape is a session that was created on one device and is suddenly used from another device and network, with no new sign-in.

03. Step 1: Generate the sign-in log

Save the generator as gen_signins.py and run it. Read the comments first: they say which users are attacked and which harmless events were added to tempt your rules into false positives.

Python · signin-lab/gen_signins.py
"""Writes signins.jsonl: one lab day of synthetic sign-in events (seeded)."""
import json
import random
from datetime import datetime, timedelta

rng = random.Random(7)
DAY = datetime(2026, 11, 10)
USERS = [f"u{n:03d}" for n in range(1, 61)]
OFFICE = ("198.51.100.10", 64496)            # NAT: many staff share this IP
events = []


def emit(t, event, user, ip, asn, device, result, session=None):
    events.append({"ts": t.isoformat() + "Z", "event": event, "user": user,
                   "ip": ip, "asn": asn, "device": device, "result": result,
                   "session": session})


def good_login(t, user, ip, asn, device):
    emit(t, "signin", user, ip, asn, device, "success")
    sid = f"s-{user}-{t:%H%M}"
    emit(t + timedelta(seconds=8), "mfa", user, ip, asn, device, "approved", sid)
    return sid


# Normal day: everyone signs in from the office or home, some mistype first.
for user in USERS:
    t = DAY + timedelta(hours=8, minutes=rng.randrange(0, 90))
    ip, asn = OFFICE if rng.random() < 0.6 else (
        f"192.0.2.{rng.randrange(2, 250)}", 64497)
    if rng.random() < 0.15:                  # typo, then success
        emit(t - timedelta(seconds=20), "signin", user, ip, asn, f"d-{user}",
             "failure")
    sid = good_login(t, user, ip, asn, f"d-{user}")
    emit(t + timedelta(minutes=30), "session", user, ip, asn, f"d-{user}", "ok", sid)

# u021 changes network mid-session: same laptop, phone hotspot (not an attack).
emit(DAY + timedelta(hours=11), "session", "u021", "192.0.2.201", 64499,
     "d-u021", "ok", next(e["session"] for e in events
                          if e["user"] == "u021" and e["session"]))
# u045 mistypes twice in a row from home, then gets in.
for s in (0, 15):
    emit(DAY + timedelta(hours=19, seconds=s), "signin", "u045", "192.0.2.45",
         64497, "d-u045", "failure")
good_login(DAY + timedelta(hours=19, seconds=40), "u045", "192.0.2.45", 64497,
           "d-u045")

# u052's phone was in a bag: one prompt timed out, the second was approved.
emit(DAY + timedelta(hours=13), "mfa", "u052", "192.0.2.52", 64497, "d-u052",
     "timeout")
emit(DAY + timedelta(hours=13, minutes=1), "signin", "u052", "192.0.2.52", 64497,
     "d-u052", "success")
emit(DAY + timedelta(hours=13, minutes=1, seconds=9), "mfa", "u052", "192.0.2.52",
     64497, "d-u052", "approved", "s-u052-1301")

# Pattern 1: password spraying, one guess per account, rotating IPs, one ASN.
targets = rng.sample([u for u in USERS if u != "u017"], 39) + ["u017"]
rng.shuffle(targets)
for i, user in enumerate(targets):
    t = DAY + timedelta(hours=1, minutes=10, seconds=30 * i)
    ip = f"203.0.113.{10 + i % 5}"
    ok = user == "u017"                       # this user's password was weak
    emit(t, "signin", user, ip, 64510, "d-unknown", "success" if ok else "failure")

# Pattern 2: MFA fatigue against u017, ending in an approval at 02:14.
for k in range(9):
    emit(DAY + timedelta(hours=2, minutes=k * 1.5), "mfa", "u017",
         "203.0.113.12", 64510, "d-unknown", "denied" if k % 2 else "timeout")
emit(DAY + timedelta(hours=2, minutes=14), "mfa", "u017", "203.0.113.12", 64510,
     "d-unknown", "approved", "s-u017-0214")

# Pattern 3: u033's session cookie replayed from a new network and device.
sid = next(e["session"] for e in events if e["user"] == "u033" and e["session"])
emit(DAY + timedelta(hours=10, minutes=5), "session", "u033", "192.0.2.77",
     64511, "d-7f3a", "ok", sid)

events.sort(key=lambda e: e["ts"])
with open("signins.jsonl", "w") as fh:
    fh.writelines(json.dumps(e) + "\n" for e in events)
print(len(events), "events written to signins.jsonl")
Terminal
mkdir -p signin-lab && cd signin-lab   # save gen_signins.py here
python3 gen_signins.py
head -1 signins.jsonl | python3 -m json.tool
Expected output
245 events written to signins.jsonl
{
    "ts": "2026-11-10T01:10:00Z",
    "event": "signin",
    "user": "u023",
    "ip": "203.0.113.10",
    "asn": 64510,
    "device": "d-unknown",
    "result": "failure",
    "session": null
}

Each line of signins.jsonl is one JSON event, a format called JSON Lines. event is signin (password check), mfa (a prompt and its result) or session (a request made with an existing session). Real logs have more fields, such as user agent and risk scores, but these are enough for the three patterns.

04. Step 2: Try a naive rule

Start with the rule many teams write first: alert when three or more accounts fail from the same IP address on the same day.

Python · signin-lab/naive.py
"""A naive rule: alert when 3+ accounts fail from the same IP on the same day."""
import json
from collections import defaultdict

failing = defaultdict(set)
for line in open("signins.jsonl"):
    e = json.loads(line)
    if e["event"] == "signin" and e["result"] == "failure":
        failing[e["ip"]].add(e["user"])
for ip, users in sorted(failing.items()):
    if len(users) >= 3:
        print(f"naive ALERT {ip:15} {len(users)} accounts failed")
Terminal
python3 naive.py
Expected output
naive ALERT 198.51.100.10   4 accounts failed
naive ALERT 203.0.113.10    8 accounts failed
naive ALERT 203.0.113.11    7 accounts failed
naive ALERT 203.0.113.12    8 accounts failed
naive ALERT 203.0.113.13    8 accounts failed
naive ALERT 203.0.113.14    8 accounts failed

This rule gets both cases wrong. The first alert is the office, where many staff share one address through network address translation (NAT), and four of them mistyped a password. The spray is real but split into five alerts of seven or eight accounts each, because the attacker rotated addresses. An analyst sees six alerts that look alike and none that says "39 accounts in 20 minutes".

05. Step 3: Write the three detections

detect.py holds three rules. Each one prints either an ALERT or an ok line for the near-miss it rules out, so you can see the false-positive check working.

Python · signin-lab/detect.py
"""Three identity detections over signins.jsonl, with false-positive checks."""
import json
from collections import defaultdict
from datetime import datetime, timedelta

SPRAY_WINDOW = timedelta(minutes=30)
SPRAY_MIN_USERS = 10        # distinct accounts failing from one ASN in the window
SPRAY_MAX_PER_USER = 2      # sprayers try few passwords per account
FATIGUE_WINDOW = timedelta(minutes=20)
FATIGUE_MIN_PROMPTS = 5     # unanswered or denied prompts before an approval

events = [json.loads(line) for line in open("signins.jsonl")]
for e in events:
    e["t"] = datetime.fromisoformat(e["ts"].rstrip("Z"))

print("== Password spraying (T1110.003) ==")
by_asn = defaultdict(list)
for e in events:
    if e["event"] == "signin":
        by_asn[e["asn"]].append(e)
for asn, evs in sorted(by_asn.items()):
    fails = [e for e in evs if e["result"] == "failure"]
    for start in fails:
        window = [e for e in evs if start["t"] <= e["t"] < start["t"] + SPRAY_WINDOW]
        bad = defaultdict(int)
        for e in window:
            if e["result"] == "failure":
                bad[e["user"]] += 1
        ok = sorted({e["user"] for e in window if e["result"] == "success"})
        if len(bad) >= SPRAY_MIN_USERS and max(bad.values()) <= SPRAY_MAX_PER_USER \
                and len(ok) < len(bad) / 4:
            ips = {e["ip"] for e in window}
            print(f"ALERT asn {asn} from {start['t']:%H:%M}: {len(bad)} accounts "
                  f"failed from {len(ips)} IPs; succeeded: {', '.join(ok)}")
            break
    else:
        users = {e["user"] for e in fails}
        print(f"ok    asn {asn}: {len(fails)} failures across {len(users)} accounts")

print("== MFA request flooding (T1621) ==")
prompts = defaultdict(list)
for e in events:
    if e["event"] == "mfa":
        prompts[e["user"]].append(e)
for user, evs in sorted(prompts.items()):
    for e in evs:
        if e["result"] != "approved":
            continue
        before = [p for p in evs if e["t"] - FATIGUE_WINDOW <= p["t"] < e["t"]
                  and p["result"] in ("denied", "timeout")]
        if len(before) >= FATIGUE_MIN_PROMPTS:
            print(f"ALERT {user}: {len(before)} denied/timed-out prompts, then "
                  f"approved {e['t']:%H:%M} from asn {e['asn']}")
        elif before:
            print(f"ok    {user}: {len(before)} missed prompt(s) before approval")

print("== Session reuse without sign-in (T1539 / T1550.004) ==")
origin = {}
for e in events:
    if e["event"] == "mfa" and e["result"] == "approved":
        origin[e["session"]] = e
for e in events:
    if e["event"] != "session" or e["session"] not in origin:
        continue
    o = origin[e["session"]]
    if (e["ip"], e["asn"], e["device"]) == (o["ip"], o["asn"], o["device"]):
        continue
    if e["device"] == o["device"]:
        print(f"ok    {e['user']}: network changed to asn {e['asn']}, same device")
    else:
        print(f"ALERT {e['user']}: {e['session']} reused {e['t']:%H:%M} from asn "
              f"{e['asn']}, device {e['device']} (sign-in: {o['device']})")
Terminal
python3 detect.py
Expected output
== Password spraying (T1110.003) ==
ok    asn 64496: 4 failures across 4 accounts
ok    asn 64497: 4 failures across 3 accounts
ALERT asn 64510 from 01:10: 39 accounts failed from 5 IPs; succeeded: u017
== MFA request flooding (T1621) ==
ALERT u017: 9 denied/timed-out prompts, then approved 02:14 from asn 64510
ok    u052: 1 missed prompt(s) before approval
== Session reuse without sign-in (T1539 / T1550.004) ==
ALERT u033: s-u033-0903 reused 10:05 from asn 64511, device d-7f3a (sign-in: d-u033)
ok    u021: network changed to asn 64499, same device

The spraying rule groups by ASN and looks at a 30-minute window. It needs at least 10 distinct accounts failing, at most 2 failures per account, and successes for fewer than a quarter as many accounts as failed. The office network fails 4 accounts and has dozens of successes, so it stays quiet. The attacker's network fails 39 accounts once each, and the one success, u017, is the most important line in the output: that password worked.

The fatigue rule fires on an approval that follows at least 5 denied or timed-out prompts within 20 minutes. u052 missed one prompt because the phone was in a bag, then approved: one miss is normal. u017 shows the attack completing at 02:14, from the same network that guessed the password at 01:18.

The session rule compares each session event with the approved MFA event that created the session. u021's laptop moved to a phone hotspot: new IP and ASN, same device, so it is reported as ok. u033's session was created on d-u033 in the office and reused from d-7f3a on another network with no sign-in in between. That is the shape of a stolen cookie.

06. Step 4: Thresholds, false positives and evasion

Every number in detect.py is a trade-off, not a standard. A smaller window or higher account count misses slow sprays. A lower one catches the office on a bad morning. Write down why you chose each value and test it against your own normal traffic before you enable it.

These rules can also be evaded. A sprayer who spreads guesses over a week, or across many networks, stays under a 30-minute ASN window. Pair it with a daily per-tenant count of distinct failing accounts. An attacker who sends one prompt every half hour stays under the fatigue window. A count since the user's last successful sign-in catches that, and it is what NIST SP 800-63B-4 asks verifiers to limit. Device IDs come from the client, so an attacker who copies the device fingerprint as well as the cookie can look like the same device. Treat the session rule as one signal among several.

07. Step 5: Contain each pattern

Detection is only useful if someone acts. For each pattern, contain the account first, then the source, then the weakness that made it possible:

  • Spraying (T1110.003). Look for successes from the spraying source: here u017. Treat those accounts as compromised: reset the password, revoke sessions and refresh tokens, and check for new MFA methods or devices the attacker registered (T1098.005). Block the source ASN at the IdP for a while, expecting the attacker to move. Do not lock all 39 targeted accounts: that turns the attack into an outage. Add the guessed password to the banned-password list.
  • MFA fatigue (T1621). The approval means the attacker has the password and a session. Revoke u017's sessions and refresh tokens, reset the password, review what session s-u017-0214 did, and remove any method registered during it. Then limit prompt rates and require a typed number match, or better, move the user to a passkey, which cannot be approved from a fake login.
  • Session reuse (T1539, T1550.004). Revoke u033's sessions and refresh tokens. A password reset alone may leave existing sessions valid, depending on the IdP. Investigate d-u033 for infostealer malware or a recent phishing visit, because that is where the cookie came from. Shorter session lifetimes and policies that tie sessions to compliant devices reduce the value of a stolen cookie.

For all three, preserve the log, record a timeline, and tell the user what happened.

08. Troubleshooting

09. Check your understanding

Practice check · 3 questions

Reading the log

Three questions about the detections you just ran.

Q1. The attacker changes tactics: one push prompt to `u017` every 15 minutes from 01:30, the last at 04:15, then an approval at 04:30. What does `detect.py` print for `u017`, and what would close the gap?
Q2. The session rule sees a live session move from office Wi-Fi to a phone hotspot: new IP and ASN, same device ID, no new sign-in. How does `detect.py` report it?
Q3. How does the log show that `u017`'s approval at 02:14 belonged to the attacker's login rather than to `u017`'s own?
Practice only: not graded, not saved, not evidence.

10. Apply it

For the skill project, turn this into an analysis you can hand to an incident lead:

  • Add a fourth pattern to the generator, such as credential stuffing (many accounts, each with its own leaked password, a higher success rate), and a rule that tells it apart from spraying.
  • Add the daily count and the "prompts since last success" count from the thresholds section, and show that each catches a slower version of its attack.
  • Write a one-page incident note for u017: timeline, evidence lines from the log, ATT&CK techniques, containment done and the change that prevents a repeat.

11. Review prompt

Without looking back, explain: how spraying, password guessing and credential stuffing differ in a log; why grouping by IP split the spray and caught the office; the three conditions of the spraying rule; what makes an MFA approval suspicious; how the session rule tells a moving laptop from a stolen cookie; one way to evade each rule; and the containment steps for each pattern, including why a password reset alone may not end a stolen session.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check